gemi 0.58.0 → 0.58.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-mkfpnymy.js → chunk-01e3gk86.js} +1 -1
- package/dist/{chunk-3aa287k7.js → chunk-4sz6pwtn.js} +2 -2
- package/dist/{chunk-3aa287k7.js.map → chunk-4sz6pwtn.js.map} +1 -1
- package/dist/{chunk-8gew8b9a.js → chunk-vj6f2bmb.js} +1 -1
- package/dist/chunks/{ThemeProvider-li1J_igh.js → ThemeProvider-ByU4BQdL.js} +68 -2
- package/dist/chunks/{ThemeProvider-li1J_igh.js.map → ThemeProvider-ByU4BQdL.js.map} +1 -1
- package/dist/client/ComponentContext.d.ts +46 -0
- package/dist/client/ComponentContext.d.ts.map +1 -1
- package/dist/client/index.js +9 -2
- package/dist/client/index.js.map +1 -1
- package/dist/client/init.d.ts.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/testing/index.js +1 -1
- package/package.json +1 -1
- /package/dist/{chunk-mkfpnymy.js.map → chunk-01e3gk86.js.map} +0 -0
- /package/dist/{chunk-8gew8b9a.js.map → chunk-vj6f2bmb.js.map} +0 -0
package/dist/client/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../client/ServerQueryContext.tsx","../../client/useRouteData.ts","../../client/isPlainObject.ts","../../client/useQuery.ts","../../client/useMutation.ts","../../client/useMutate.ts","../../client/Mutation.tsx","../../client/useIsNavigationPending.ts","../../client/useNavigationProgress.ts","../../client/usePrefetch.ts","../../client/useBreadcrumbs.ts","../../client/Link.tsx","../../client/Redirect.tsx","../../client/Head.tsx","../../utils/partialRender.ts","../../client/helpers/mergeCarriedSegments.ts","../../client/helpers/loadRoutePayload.ts","../../client/ClientRouter.tsx","../../client/init.tsx","../../client/DictionarySinkContext.ts","../../client/createRoot.tsx","../../client/Image.tsx","../../client/auth/useForgotPassword.ts","../../client/auth/useSignIn.tsx","../../client/auth/useSignUp.ts","../../client/auth/useSignOut.ts","../../client/auth/useResetPassword.ts","../../client/auth/useUser.ts","../../client/useFeature.ts","../../utils/parseTranslation.tsx","../../client/useTranslator.ts","../../client/useDictionary.ts","../../i18n/dictionaryShape.ts","../../i18n/defineDictionary.ts","../../client/useLocale.ts","../../client/useSubscription.ts","../../client/useBroadcast.ts","../../client/OpenGraphImage.tsx","../../client/useAppIdMissmatch.ts"],"sourcesContent":["import { createContext } from \"react\";\n\n/**\n * The structural slice of the server's `ServerQueryStore` that `useQuery`\n * needs during a streaming server render. Declared here — not imported from\n * `services/router` — because this file ships in the browser bundle; only the\n * shape crosses over, never the implementation.\n */\nexport interface ServerQueryEntryLike {\n status: \"pending\" | \"resolved\" | \"rejected\";\n data?: any;\n error?: any;\n promise: Promise<void>;\n}\n\nexport interface ServerQueriesLike {\n ensure(\n path: string,\n options?: {\n params?: Record<string, any>;\n search?: Record<string, string | number | boolean | null>;\n },\n source?: \"prefetch\" | \"render\",\n ): ServerQueryEntryLike;\n}\n\n/**\n * Populated only during a streaming server render (`createRoot` threads the\n * request's store through); always `null` in the browser, where suspension\n * runs on `QueryResource` instead.\n */\nexport const ServerQueryContext = createContext<ServerQueriesLike | null>(null);\n","import { useContext } from \"react\";\nimport { RouteStateContext } from \"./RouteStateContext\";\n\nexport function useRouteData() {\n const { data, i18n, prefetchedData, breadcrumbs } =\n useContext(RouteStateContext);\n\n return { data, i18n, prefetchedData, breadcrumbs };\n}\n","export function isPlainObject(\n value: unknown,\n): value is Record<string, unknown> {\n return (\n value !== null &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n","import {\n useCallback,\n useContext,\n useDeferredValue,\n useEffect,\n useRef,\n useSyncExternalStore,\n} from \"react\";\nimport type { RPC } from \"./rpc\";\nimport type { NestedPrettify } from \"../utils/type\";\n\nimport type { ApiRouterHandler } from \"../http/ApiRouter\";\nimport type { UnwrapPromise } from \"../utils/type\";\nimport { QueryConfigContext, QueryManagerContext } from \"./QueryManagerContext\";\nimport { ServerQueryContext } from \"./ServerQueryContext\";\nimport { DEFAULT_STALE_TIME } from \"./QueryResource\";\nimport { applyParams } from \"../utils/applyParams\";\nimport type { UrlParser } from \"./types\";\nimport { toVariantKey } from \"../utils/variantKey\";\nimport { useParams } from \"./useParams\";\nimport { useRouteData } from \"./useRouteData\";\nimport { isPlainObject } from \"./isPlainObject\";\n\ninterface Config<T> {\n fallbackData?: T;\n /**\n * When true (the default), a variant change keeps rendering the previous\n * variant's data while the new one loads. Under suspense this reads through\n * a deferred variant key, so changing `search`/`params` never flashes the\n * segment fallback and needs no `startTransition` at the call site — the\n * pending window is exposed as `loading: true`. Set to `false` to get the\n * suspend-on-variant-change semantics back (e.g. tab-like switches where\n * stale rows would mislead). First mount always suspends either way.\n */\n keepPreviousData?: boolean;\n retryIntervalOnError?: number;\n refreshInterval?: number;\n /**\n * When true, the query revalidates whenever the tab comes back to the\n * foreground. Off by default. `staleTime` still gates it, so a quick\n * tab-out-and-back costs nothing and only data that has actually aged goes\n * back to the wire — silently, keeping what's on screen rendered.\n */\n revalidateOnFocus?: boolean;\n /**\n * Minimum gap between two `revalidateOnFocus` revalidations of the same\n * query, in ms (default 5000). `focus` fires on far more than tab returns —\n * dismissing a file picker, closing a popup, clicking in and out of an\n * embedded iframe — and `staleTime: 0` would otherwise turn each of those\n * into a request per mounted query.\n */\n focusThrottleInterval?: number;\n /** How long cached data stays fresh before a read revalidates it, in ms. */\n staleTime?: number;\n debug?: boolean;\n lazy?: boolean;\n /**\n * When true (the default), a query with no cached data suspends the nearest\n * `Suspense` boundary instead of returning `loading: true`, and an HTTP\n * failure throws into the nearest error boundary. `lazy: true` implies\n * `suspense: false`.\n */\n suspense?: boolean;\n refetchUntil?: (data: T, duration: number) => number;\n}\n\ntype WithOptionalValues<T> = {\n [K in keyof T]: T[K] | null;\n};\n\nconst defaultConfig: Config<any> = {\n fallbackData: null,\n keepPreviousData: true,\n retryIntervalOnError: 10000,\n refreshInterval: 999999,\n revalidateOnFocus: false,\n focusThrottleInterval: 5000,\n staleTime: DEFAULT_STALE_TIME,\n debug: false,\n lazy: false,\n suspense: true,\n};\n\ntype GetRPC = {\n [K in keyof RPC as K extends `GET:${infer P}` ? P : never]: RPC[K];\n};\n\ntype Data<T extends keyof GetRPC> =\n GetRPC[T] extends ApiRouterHandler<any, infer Data, any>\n ? UnwrapPromise<Data>\n : never;\n\ntype Input<T extends keyof GetRPC> =\n GetRPC[T] extends ApiRouterHandler<infer I, any, any> ? I : never;\n\ntype QueryOptions<T extends keyof GetRPC> = {\n search?: Partial<WithOptionalValues<Input<T>>>;\n};\n\ntype Error = Record<string, unknown>;\n\nconst defaultOptions: QueryOptions<any> & { params?: Record<string, any> } = {\n params: {} as Record<string, string>,\n search: {} as Record<string, string>,\n};\n\nexport type QueryResult<T extends keyof GetRPC> = NestedPrettify<Data<T> & {}>;\n\ntype Options<T extends keyof GetRPC> = {\n search?: Record<string, string | number | boolean | null>;\n params?: Partial<UrlParser<`${T & string}`>>;\n};\n\ninterface QueryReturn<T extends keyof GetRPC, D> {\n data: D;\n loading: boolean;\n error: Error;\n mutate: {\n (fn?: NestedPrettify<Data<T>>): void;\n (fn?: (data: NestedPrettify<Data<T>>) => NestedPrettify<Data<T>>): void;\n };\n trigger: () => void;\n prefetch: () => void;\n refetch: () => void;\n version: number;\n}\n\n/**\n * A suspense-enabled query never renders without data, so `data` is\n * non-nullable. Opting out — `suspense: false` or `lazy: true` — brings back\n * the `loading` flag and with it a `data` that can be `undefined`.\n */\ninterface SuspenseConfig<T> extends Omit<Config<T>, \"suspense\" | \"lazy\"> {\n suspense?: true;\n lazy?: false;\n}\n\n/** A per-call `suspense: true` opt-in — wins over an app-wide `suspense: false`. */\ninterface ExplicitSuspenseConfig<T> extends Omit<\n Config<T>,\n \"suspense\" | \"lazy\"\n> {\n suspense: true;\n lazy?: false;\n}\n\n/**\n * The type-level mirror of a provider-level `queryConfig: { suspense: false }`.\n * The `useQuery` overloads reflect the call site only — they cannot see the\n * value threaded through `createRoot` — so an app that turns suspense off\n * app-wide flips the default `data` nullability with the same\n * module-augmentation switch RPC types use:\n *\n * ```ts\n * declare module \"gemi/client\" {\n * interface GemiQueryDefaults {\n * suspense: false;\n * }\n * }\n * ```\n *\n * A per-call `suspense: true` still narrows `data` back to non-nullable.\n */\nexport interface GemiQueryDefaults {}\n\ntype DefaultData<T extends keyof GetRPC> = GemiQueryDefaults extends {\n suspense: false;\n}\n ? NestedPrettify<Data<T>> | undefined\n : NestedPrettify<Data<T>>;\n\nexport function useQuery<T extends keyof GetRPC>(\n url: T,\n options: Options<T> | undefined,\n config: ExplicitSuspenseConfig<Data<T>>,\n): QueryReturn<T, NestedPrettify<Data<T>>>;\nexport function useQuery<T extends keyof GetRPC>(\n url: T,\n options?: Options<T>,\n config?: SuspenseConfig<Data<T>>,\n): QueryReturn<T, DefaultData<T>>;\nexport function useQuery<T extends keyof GetRPC>(\n url: T,\n options?: Options<T>,\n config?: Config<Data<T>>,\n): QueryReturn<T, NestedPrettify<Data<T>> | undefined>;\nexport function useQuery<T extends keyof GetRPC>(\n url: T,\n ...args: [options?: Options<T>, config?: Config<Data<T>>]\n) {\n const [options, config] = args;\n // Resolution order: per-call config → provider `queryConfig` → framework\n // defaults. The first two merge here; `useFrameworkQuery` applies the last.\n // Only *defined* per-call keys participate: a key explicitly set to\n // `undefined` (`{ suspense: cond ? true : undefined }`, forwarding an\n // optional prop) must fall through to the provider default, not clobber it\n // — a plain spread would copy the `undefined` over it. The provider value\n // is already sanitized at the provider (see `QueryManagerProvider`).\n const queryConfig = useContext(QueryConfigContext);\n const merged: Config<Data<T>> = { ...queryConfig };\n if (config) {\n for (const key of Object.keys(config) as Array<keyof Config<Data<T>>>) {\n if (config[key] !== undefined) {\n (merged as Record<string, unknown>)[key] = config[key];\n }\n }\n }\n return useFrameworkQuery(url, options, merged);\n}\n\n/**\n * `useQuery` minus the app's provider-level `queryConfig`: per-call config\n * resolves straight against the framework defaults. Framework-internal hooks\n * (`useUser`'s `suspense: false`, `useSignIn`'s `lazy`) build on this so an\n * app-wide `queryConfig` can never change their semantics. Deliberately not\n * exported from the package root.\n */\nexport function useFrameworkQuery<T extends keyof GetRPC>(\n url: T,\n ...args: [options?: Options<T>, config?: Config<Data<T>>]\n): QueryReturn<T, NestedPrettify<Data<T>> | undefined> {\n const _params = useParams();\n const [_options = defaultOptions, _config = defaultConfig] = args;\n const options = { ...defaultOptions, ..._options };\n const config = { ...defaultConfig, ..._config };\n const suspense = config.suspense !== false && !config.lazy;\n const params =\n \"params\" in options ? { ..._params, ...options.params } : _params;\n const search = \"search\" in options ? (options.search ?? {}) : {};\n const { getResource } = useContext(QueryManagerContext);\n const serverQueries = useContext(ServerQueryContext);\n const currentPath = applyParams(url, params);\n const currentVariantKey = toVariantKey(search);\n // `keepPreviousData` under suspense: read through deferred keys so a\n // variant change never suspends the committed tree. The urgent render keeps\n // showing the previous variant's data; React re-renders in the background\n // with the new keys, suspends *that* attempt only (no fallback flash), and\n // commits when the data lands — no `startTransition` needed at the call\n // site. First mount is unchanged: deferred and current keys are equal, so\n // an uncached query suspends into the segment fallback as today. Both hooks\n // run unconditionally (hook order); the values are only *used* when\n // deferring applies.\n //\n // Deliberate: during the pending window the imperative callbacks\n // (`mutate`/`refetch`/`trigger`/`prefetch`) and the revalidation effects\n // close over the deferred — i.e. *visible* — variant and resource, so they\n // act on the data the user is looking at, not the variant still loading in\n // the background. The window ends when the deferred render commits, at\n // which point they re-bind to the new keys.\n const deferredPath = useDeferredValue(currentPath);\n const deferredVariantKey = useDeferredValue(currentVariantKey);\n const deferVariant = suspense && config.keepPreviousData;\n const normalPath = deferVariant ? deferredPath : currentPath;\n const variantKey = deferVariant ? deferredVariantKey : currentVariantKey;\n // The pending signal for pager UI: true while the visible data belongs to\n // the previous variant and the new one is still loading in the background.\n const isDeferred =\n normalPath !== currentPath || variantKey !== currentVariantKey;\n const { prefetchedData } = useRouteData();\n // `fallbackData` is a single variant's value, so it seeds under this\n // query's variant key; `prefetchedData[normalPath]` is already the full\n // `{ [variantKey]: data }` map the server produced.\n const seed =\n config.fallbackData != null\n ? { [variantKey]: config.fallbackData }\n : prefetchedData?.[normalPath];\n // A memoized map lookup on the provider's ref: stable and cheap, so the\n // resource is derived every render — a params change swaps it in the same\n // render pass instead of flashing through an effect.\n const resource = getResource(normalPath, seed ?? undefined);\n const lazy = config.lazy;\n\n const configRef = useRef(config);\n configRef.current = config;\n\n const refreshIntervalRef = useRef<ReturnType<typeof setInterval> | null>(\n null,\n );\n const retryIntervalRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const retryingMap = useRef<Map<string, boolean>>(new Map());\n const fetchedRef = useRef(!lazy);\n const refetchUntilTimerRef = useRef<ReturnType<typeof setTimeout> | null>(\n null,\n );\n const refetchUntilDurationRef = useRef(0);\n const prefetchedRef = useRef(false);\n // Focus revalidation eligibility, deliberately *not* `fetchedRef`: that one\n // is flipped by `prefetch()` too, and a hover prefetch is documented as\n // \"fetch once\" for data the user may never look at — enrolling it in focus\n // revalidation would keep re-requesting it for the life of the component.\n // Only the reads that put data on screen (`trigger`, `refetch`, `mutate`,\n // or simply not being lazy) count.\n const focusEligibleRef = useRef(!lazy);\n // The away latch: `focus` fires for things that never left the page —\n // dismissing an `alert`, returning from devtools — so a revalidation is only\n // owed when the window actually lost focus or the tab was hidden first.\n const wasAwayRef = useRef(false);\n const lastFocusRevalidationRef = useRef(0);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => resource.store.subscribe(onStoreChange),\n [resource],\n );\n // `peek` hands back the object stored in the map — its identity only\n // changes on a real write, so the snapshot is stable across render\n // attempts. Also the server snapshot: SSR renders whatever the prefetch\n // payload seeded, and never fetches.\n //\n // uSES and transitions: store updates are always urgent, so a write landing\n // mid-transition restarts the pending transition — wasted work, never wrong\n // UI. Exposure is kept small by design: render-phase reads never write the\n // store synchronously (fetches are silent), and a suspended component has no\n // subscription — it is woken by its thrown promise, not the store. The\n // navigation-shaped consequences are pinned in `useQuery.transition.test.tsx`.\n const getSnapshot = useCallback(\n () => resource.peek(variantKey),\n [resource, variantKey],\n );\n const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n // `keepPreviousData`: remember the last snapshot that had data, and show it\n // whenever the current one is loading without data (e.g. a variant change\n // with `suspense: false`). Presence is `hasData`, never `data`'s truthiness\n // — `null`/`0`/`false`/`\"\"` are legitimate response bodies.\n const lastDataRef = useRef(snapshot?.hasData ? snapshot : null);\n useEffect(() => {\n if (snapshot?.hasData) {\n lastDataRef.current = snapshot;\n }\n }, [snapshot]);\n\n let state = snapshot;\n if (\n config.keepPreviousData &&\n !snapshot?.hasData &&\n snapshot?.loading &&\n lastDataRef.current\n ) {\n state = { ...lastDataRef.current, loading: true };\n }\n\n // The render-phase read for the suspense path. Only when there is nothing\n // to show — data in hand always renders, and revalidation stays where it\n // was (the mount effect below). Both reads dedupe across the render\n // attempts React discards, so this is safe to hit on every attempt.\n //\n // On a streaming server render the read goes to the request's\n // `ServerQueryStore` instead of the client resource: a prefetched query is\n // already in flight there and is joined, an undiscovered one starts now\n // (the store logs the late-discovery hint when that cost something).\n let readPromise: Promise<void> | undefined;\n let serverError: unknown;\n if (suspense && !state?.hasData && !state?.error) {\n if (typeof window === \"undefined\") {\n if (serverQueries) {\n const entry = serverQueries.ensure(url, { params, search });\n if (entry.status === \"resolved\") {\n state = {\n loading: false,\n data: entry.data,\n hasData: true,\n error: null,\n version: 0,\n };\n } else if (entry.status === \"rejected\") {\n serverError = entry.error;\n } else {\n readPromise = entry.promise;\n }\n }\n } else {\n readPromise = resource.read(variantKey, config.staleTime).promise;\n }\n }\n\n if (\n suspense &&\n typeof window === \"undefined\" &&\n !serverQueries &&\n !state?.hasData &&\n process.env.NODE_ENV !== \"production\"\n ) {\n const searchHint = variantKey\n ? `, { search: ${JSON.stringify(\n Object.fromEntries(new URLSearchParams(variantKey)),\n )} }`\n : \"\";\n console.warn(\n `[gemi] useQuery(\"${url}\") rendered on the server without data. ` +\n `The server never fetches, so this page ships without it and the ` +\n `client suspends after hydration. Add ` +\n `\\`Query.prefetch(\"${url}\"${searchHint})\\` to the route's view handler.`,\n );\n }\n\n const retry = useCallback(\n (vk: string) => {\n if (!retryingMap.current.get(vk)) {\n if (configRef.current.debug) console.log(\"retrying\", vk);\n retryingMap.current.set(vk, true);\n retryIntervalRef.current = setTimeout(() => {\n resource.getVariant(vk, configRef.current.staleTime);\n retryingMap.current.set(vk, false);\n }, configRef.current.retryIntervalOnError);\n }\n },\n [resource],\n );\n\n // Mount / variant-change revalidation — unchanged semantics: `getVariant`\n // fetches when the variant is missing or stale, and now joins an in-flight\n // render-initiated read instead of racing it.\n useEffect(() => {\n if (fetchedRef.current) {\n resource.getVariant(variantKey, configRef.current.staleTime);\n }\n return () => {\n clearTimeout(retryIntervalRef.current);\n };\n }, [variantKey, resource]);\n\n // With `suspense: false` an error is returned and retried in the\n // background; under suspense it throws below instead.\n useEffect(() => {\n if (!suspense && snapshot?.error) {\n retry(variantKey);\n }\n }, [snapshot, suspense, retry, variantKey]);\n\n useEffect(() => {\n const cfg = configRef.current;\n if (!cfg.refetchUntil) return;\n if (snapshot && !snapshot.loading && snapshot.hasData && !snapshot.error) {\n const nextDuration = cfg.refetchUntil(\n snapshot.data,\n refetchUntilDurationRef.current,\n );\n if (nextDuration > 0) {\n refetchUntilDurationRef.current = nextDuration;\n refetchUntilTimerRef.current = setTimeout(() => {\n resource.refetch(variantKey);\n }, nextDuration);\n } else {\n refetchUntilDurationRef.current = 0;\n }\n }\n return () => {\n if (refetchUntilTimerRef.current) {\n clearTimeout(refetchUntilTimerRef.current);\n }\n };\n }, [snapshot, resource, variantKey]);\n\n const handleReload = useCallback(() => {\n if (configRef.current.debug) {\n console.log(\"Reloading query for\", variantKey);\n }\n const data = resource.getVariant(\n variantKey,\n configRef.current.staleTime,\n ).data;\n resource.mutate(variantKey, () => data);\n }, [variantKey, resource]);\n\n useEffect(() => {\n if (!fetchedRef.current) return;\n refreshIntervalRef.current = setInterval(() => {\n handleReload();\n }, config.refreshInterval);\n\n return () => {\n if (refreshIntervalRef.current) {\n clearInterval(refreshIntervalRef.current);\n }\n };\n }, [config.refreshInterval, handleReload]);\n\n // Revalidate when the tab comes back to the foreground — opt-in via\n // `revalidateOnFocus` (per call or app-wide). `resource.revalidate` applies\n // `staleTime` like the mount effect does, but always fetches silently, so\n // data still inside its freshness window is left alone and anything older\n // is refreshed without what's on screen ever flashing a loading state.\n //\n // Three guards decide whether a return to the foreground is owed a request,\n // because `focus` alone is a poor proxy for one:\n // - eligibility — an untriggered lazy query has nothing on screen;\n // - the away latch — `focus` also fires for a dismissed `alert` or a\n // closed devtools pane, neither of which is a return from anywhere;\n // - the throttle — clicking in and out of an embedded iframe (a payment\n // form, a video) blurs and focuses the window every time, and `focus`\n // runs this for *every* mounted query, so a dashboard would otherwise\n // fire a dozen requests per interaction under `staleTime: 0`.\n //\n // Both events are listened for because neither covers the other: switching\n // between windows fires `focus` while the document stays visible, and\n // switching tabs (or unlocking the device) fires `visibilitychange` without\n // necessarily firing `focus`. They land on one guarded call, so the overlap\n // costs nothing — the latch is already spent by the time the second fires.\n useEffect(() => {\n if (!config.revalidateOnFocus) return;\n const markAway = () => {\n wasAwayRef.current = true;\n };\n const revalidate = () => {\n if (!focusEligibleRef.current) return;\n if (document.visibilityState === \"hidden\") return;\n if (!wasAwayRef.current) return;\n const now = Date.now();\n // Throttled: leave the latch armed so the next return, once the\n // interval has passed, still revalidates.\n if (\n now - lastFocusRevalidationRef.current <\n configRef.current.focusThrottleInterval\n ) {\n return;\n }\n wasAwayRef.current = false;\n lastFocusRevalidationRef.current = now;\n resource.revalidate(variantKey, configRef.current.staleTime);\n };\n const onVisibilityChange = () => {\n if (document.visibilityState === \"hidden\") {\n markAway();\n } else {\n revalidate();\n }\n };\n window.addEventListener(\"blur\", markAway);\n window.addEventListener(\"focus\", revalidate);\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n return () => {\n window.removeEventListener(\"blur\", markAway);\n window.removeEventListener(\"focus\", revalidate);\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n };\n }, [config.revalidateOnFocus, resource, variantKey]);\n\n useEffect(() => {\n // Feature-checked per method: vitest's `import.meta.hot` shim has `on`\n // but not `off`.\n // @ts-ignore\n if (typeof import.meta.hot?.on === \"function\") {\n // @ts-ignore\n import.meta.hot.on(\"http-reload\", handleReload);\n }\n return () => {\n // @ts-ignore\n if (typeof import.meta.hot?.off === \"function\") {\n // @ts-ignore\n import.meta.hot.off(\"http-reload\", handleReload);\n }\n };\n }, [handleReload]);\n\n const trigger = useCallback(() => {\n fetchedRef.current = true;\n focusEligibleRef.current = true;\n const store = resource.store.getValue();\n const variant = store.get(variantKey);\n if (!variant || (!variant.loading && !variant.hasData)) {\n resource.refetch(variantKey);\n }\n }, [resource, variantKey]);\n\n const prefetch = useCallback(() => {\n if (prefetchedRef.current) return;\n prefetchedRef.current = true;\n fetchedRef.current = true;\n // `read`, not `refetch`: a suspending read that follows joins this\n // request instead of racing it, and fresh data is a no-op.\n resource.read(variantKey, configRef.current.staleTime);\n }, [resource, variantKey]);\n\n const refetch = useCallback(() => {\n fetchedRef.current = true;\n focusEligibleRef.current = true;\n resource.refetch(variantKey);\n }, [resource, variantKey]);\n\n function mutate(fn?: NestedPrettify<Data<T>>): void;\n function mutate(\n fn?: (data: NestedPrettify<Data<T>>) => NestedPrettify<Data<T>>,\n ): void;\n function mutate(fn?: any) {\n // Either form ends in a fetch whose result the component renders, so a\n // lazy query mutated by hand is as focus-eligible as a triggered one.\n focusEligibleRef.current = true;\n if (!fn) {\n fetchedRef.current = true;\n resource.refetch(variantKey);\n return;\n }\n return resource.mutate(variantKey, (data: any) => {\n // `null` is a legitimate cached body; only `undefined` means the query\n // hasn't produced anything (and `mutate` refetches instead of calling\n // this in that case).\n if (data === undefined) {\n console.warn(\"Mutate function called before the query.\");\n return data;\n }\n\n // The callback's return value *replaces* the cached data. The type checks\n // below only ensure the shape matches so a stray value can't corrupt the\n // cache; they do not merge or append.\n const updatedData = typeof fn === \"function\" ? fn(data) : fn;\n\n if (isPlainObject(data)) {\n if (isPlainObject(updatedData)) {\n return updatedData;\n }\n throw new Error(\n \"Mutate function must return an object when the current data is an object.\",\n );\n }\n\n if (Array.isArray(data)) {\n if (Array.isArray(updatedData)) {\n return updatedData;\n }\n throw new Error(\n \"Mutate function must return an array when the current data is an array.\",\n );\n }\n\n if (typeof data !== typeof updatedData) {\n throw new Error(\n \"Mutate function must return the same type as the current data.\",\n );\n }\n\n return updatedData;\n });\n }\n\n // Suspend last, after every hook has run: the attempt React discards ran\n // them all, and the retry re-runs them identically. The promise is *thrown*\n // rather than passed to `use()` — the thenable-throw protocol is what\n // React's ping-and-retry machinery is built around (React.lazy, SWR, React\n // Query), whereas `use()` on a client-created promise is documented as\n // unsupported outside a Suspense-compatible framework and React never\n // retries it. A streaming server render takes the same paths: a pending\n // entry suspends (React streams the fallback and resumes on settle), and a\n // rejected one throws so the segment falls back to client rendering, where\n // the browser's own fetch surfaces the error into the boundary.\n if (suspense) {\n if (serverError) {\n throw serverError;\n }\n if (state?.error && !state?.hasData) {\n throw state.error;\n }\n if (!state?.hasData && readPromise) {\n throw readPromise;\n }\n }\n\n return {\n data: state?.data as NestedPrettify<Data<T>>,\n loading: isDeferred || (state?.loading ?? !lazy),\n error: state?.error as Error,\n mutate,\n trigger,\n prefetch,\n refetch,\n version: state?.version as number,\n };\n}\n","import { useContext, useRef, useState } from \"react\";\nimport type { RPC } from \"./rpc\";\nimport type { ApiRouterHandler } from \"../http/ApiRouter\";\nimport type { UnwrapPromise } from \"../utils/type\";\nimport type { UrlParser } from \"./types\";\nimport { useParams } from \"./useParams\";\nimport { ClientRouterContext } from \"./ClientRouterContext\";\n\ntype Methods = {\n POST: {\n [K in keyof RPC as K extends `POST:${infer P}` ? P : never]: RPC[K];\n };\n PUT: {\n [K in keyof RPC as K extends `PUT:${infer P}` ? P : never]: RPC[K];\n };\n PATCH: {\n [K in keyof RPC as K extends `PATCH:${infer P}` ? P : never]: RPC[K];\n };\n DELETE: {\n [K in keyof RPC as K extends `DELETE:${infer P}` ? P : never]: RPC[K];\n };\n};\n\nfunction applyParams(url: string, params: Record<string, any> = {}) {\n let out = url;\n\n for (const [key, value] of Object.entries(params)) {\n out = out.replace(`:${key}?`, value).replace(`:${key}`, value);\n }\n return out;\n}\n\ntype Config<T> = {\n autoInvalidate?: boolean;\n onSuccess: (data: T) => void;\n onError: (error: MutationError) => void;\n onCanceled?: () => void;\n};\n\nconst defaultOptions: Config<any> = {\n autoInvalidate: false,\n onSuccess: () => {},\n onError: (_: MutationError) => {},\n onCanceled: () => {},\n};\n\ntype Data<\n M extends keyof Methods,\n K extends keyof Methods[M],\n> = Methods[M][K] extends ApiRouterHandler<any, infer T, any>\n ? UnwrapPromise<T>\n : never;\n\ntype Body<\n M extends keyof Methods,\n K extends keyof Methods[M],\n> = Methods[M][K] extends ApiRouterHandler<infer T, any, any> ? T : never;\n\ntype MutationError =\n | {\n kind: \"validation_error\";\n messages: Record<string, any>;\n }\n | {\n kind: \"form_error\";\n message: string;\n }\n | {\n kind: \"server_error\";\n message: string;\n }\n | {\n kind: \"not_authorized\";\n message: string;\n }\n | {\n kind: \"insufficient_permissions\";\n message: string;\n };\n\ntype ParseParams<T> = UrlParser<`${T & string}`>;\n\ntype State<T> = {\n data: T | null;\n error: MutationError | null;\n loading: boolean;\n};\n\nexport function useMutation<\n M extends keyof Methods,\n K extends keyof Methods[M],\n T = Data<M, K>,\n U = Body<M, K>,\n>(\n method: M,\n url: K,\n ...args: [\n options?: { params?: Partial<ParseParams<K>>, search?: Record<string, string> },\n config?: Partial<Config<T>>,\n ]\n) {\n const _params = useParams();\n // A write may have moved the data behind any page warmed ahead of a click,\n // and a prefetched payload is committed wholesale — into the query cache too.\n const { clearPrefetchCache } = useContext(ClientRouterContext);\n const [state, setState] = useState<State<T>>({\n data: null,\n error: null,\n loading: false,\n });\n\n const [abortController, setAbortController] = useState(\n () => new AbortController(),\n );\n\n const formData = useRef(new FormData());\n\n async function trigger(input?: U): Promise<T> {\n setState({\n data: state.data,\n error: state.error,\n loading: true,\n });\n const [inputs = {}, options = defaultOptions] = args ?? [];\n const params =\n \"params\" in inputs ? { ..._params, ...inputs.params } : _params;\n const search = \"search\" in inputs ? inputs.search : {};\n const searchParams = new URLSearchParams(search);\n const finalUrl = [applyParams(String(url).replace(`${method}:`, \"\"), params), searchParams.toString()].filter(Boolean).join(\"?\");\n\n let body = null;\n\n const contentType =\n typeof input === \"undefined\" || input instanceof FormData\n ? {}\n : { \"Content-Type\": \"application/json\" };\n\n if (input instanceof FormData) {\n body = input;\n } else if (typeof input === \"undefined\") {\n body = formData.current;\n } else if (input) {\n body = JSON.stringify(input);\n }\n\n try {\n const response = await fetch(`/api${finalUrl}`, {\n method,\n headers: {\n ...contentType,\n },\n ...(body ? { body } : {}),\n signal: abortController.signal,\n });\n\n formData.current = new FormData();\n\n const data = await response.json();\n\n if (!response.ok) {\n setState({\n data: null,\n error: data.error,\n loading: false,\n });\n\n options?.onError?.(data);\n return;\n }\n\n clearPrefetchCache?.();\n options.onSuccess(data);\n\n setState({\n data,\n error: null,\n loading: false,\n });\n\n return data as any;\n } catch (error) {\n formData.current = new FormData();\n options?.onError?.(error);\n setState({\n data: null,\n error,\n loading: false,\n });\n }\n }\n\n trigger.formData = (formData: FormData) => {\n return trigger(formData as U);\n };\n\n return {\n data: state.data as T,\n error: state.error as any,\n loading: state.loading,\n formData: formData.current,\n cancel: () => {\n const [, options = defaultOptions] = args ?? [];\n abortController.abort();\n setAbortController(new AbortController());\n setState({\n data: state.data,\n error: state.error,\n loading: false,\n });\n\n formData.current = new FormData();\n options.onCanceled();\n },\n trigger,\n };\n}\n\nexport function usePost<K extends keyof Methods[\"POST\"], T = Data<\"POST\", K>>(\n url: K,\n ...args: [\n options?: { params?: Partial<ParseParams<K>> },\n config?: Partial<Config<T>>,\n ]\n) {\n return useMutation(\"POST\", url, ...(args as any));\n}\n\nexport function usePut<K extends keyof Methods[\"PUT\"], T = Data<\"PUT\", K>>(\n url: K,\n ...args: [\n options?: { params?: Partial<ParseParams<K>> },\n config?: Partial<Config<T>>,\n ]\n) {\n return useMutation(\"PUT\", url, ...(args as any));\n}\n\nexport function usePatch<\n K extends keyof Methods[\"PATCH\"],\n T = Data<\"PATCH\", K>,\n>(\n url: K,\n ...args: [\n options?: { params?: Partial<ParseParams<K>> },\n config?: Partial<Config<T>>,\n ]\n) {\n return useMutation(\"PATCH\", url, ...(args as any));\n}\n\nexport function useDelete<\n K extends keyof Methods[\"DELETE\"],\n T = Data<\"DELETE\", K>,\n>(\n url: K,\n ...args: [\n options?: { params?: Partial<ParseParams<K>> },\n config?: Partial<Config<T>>,\n ]\n) {\n return useMutation(\"DELETE\", url, ...(args as any));\n}\n\nexport function useUpload<K extends keyof Methods[\"POST\"], T = Data<\"POST\", K>>(\n url: K,\n ...args: [\n options?: { params?: Partial<ParseParams<K>> },\n config?: Partial<Config<T>>,\n ]\n) {\n const [state, setState] = useState<\"idle\" | \"uploading\" | \"done\" | \"error\">(\n \"idle\",\n );\n const [progress, setProgress] = useState(0);\n const _params = useParams();\n const { clearPrefetchCache } = useContext(ClientRouterContext);\n const abortRef = useRef<VoidFunction | null>(null);\n\n const [inputs = {}, options = defaultOptions] = args ?? [];\n\n const cancel = () => {\n if (abortRef.current) {\n abortRef.current();\n options.onCanceled?.();\n setState(\"idle\");\n setProgress(0);\n }\n };\n\n const trigger = async (fileList: FileList | null | File): Promise<T> => {\n if (!fileList) {\n return;\n }\n const params =\n \"params\" in inputs ? { ..._params, ...inputs.params } : _params;\n const finalUrl = applyParams(String(url).replace(\"POST:\", \"\"), params);\n\n const method = \"POST\";\n const action = `/api${finalUrl}`;\n const data = new FormData();\n if (fileList instanceof FileList) {\n for (const file of Array.from(fileList)) {\n data.append(\"file\", file);\n }\n } else {\n data.append(\"file\", fileList);\n }\n const xhr = new XMLHttpRequest();\n abortRef.current = () => {\n xhr.abort();\n };\n\n try {\n const result = await new Promise<Response>((resolve, reject) => {\n xhr.responseType = \"blob\";\n xhr.onreadystatechange = async () => {\n if (xhr.readyState !== 4) {\n // done\n return;\n }\n\n const response = new Response(xhr.response, {\n status: xhr.status,\n statusText: xhr.statusText,\n });\n\n resolve(response);\n };\n\n xhr.addEventListener(\"error\", () => {\n reject(new TypeError(\"Failed to fetch\"));\n });\n\n xhr.upload.addEventListener(\"loadstart\", () => {\n setProgress(0);\n });\n xhr.upload.addEventListener(\"loadend\", () => {\n setProgress(1);\n });\n\n xhr.upload.addEventListener(\"progress\", (event) => {\n setProgress(event.loaded / event.total);\n });\n\n xhr.open(method, action, true);\n xhr.send(data);\n });\n setState(\"uploading\");\n if (!result.ok) {\n let error: MutationError = {\n kind: \"server_error\",\n message: result.statusText,\n };\n try {\n const data = await result.json();\n error = data.error;\n } catch (e) {\n // do nothing\n }\n setState(\"error\");\n options?.onError?.(error);\n return;\n }\n const json = await result.json();\n clearPrefetchCache?.();\n options?.onSuccess?.(json);\n return json;\n } catch (error) {\n setState(\"error\");\n options?.onError?.(error);\n return;\n }\n };\n\n return {\n state,\n progress,\n trigger,\n cancel,\n };\n}\n","import { useContext } from \"react\";\nimport type { ApiRouterHandler } from \"../http/ApiRouter\";\nimport type { NestedPrettify, UnwrapPromise } from \"../utils/type\";\nimport { isPlainObject } from \"./isPlainObject\";\n\nimport type { RPC } from \"./rpc\";\nimport { QueryManagerContext } from \"./QueryManagerContext\";\nimport type { UrlParser } from \"./types\";\nimport { applyParams } from \"../utils/applyParams\";\nimport { toVariantKey } from \"../utils/variantKey\";\ntype GetRPC = {\n [K in keyof RPC as K extends `GET:${infer P}` ? P : never]: RPC[K];\n};\n\ntype Data<T extends keyof GetRPC> =\n GetRPC[T] extends ApiRouterHandler<any, infer Data, any>\n ? UnwrapPromise<Data>\n : never;\n\nexport function useMutate() {\n const { getResource } = useContext(QueryManagerContext);\n return function mutate<T extends keyof GetRPC>(\n options: {\n path: T;\n params?: UrlParser<`${T & string}`>;\n search?: Record<string, any>;\n },\n fn?:\n | ((data: NestedPrettify<Data<T>>) => NestedPrettify<Data<T>>)\n | NestedPrettify<Data<T>>,\n ) {\n const { path, params = {}, search = {} } = options ?? {};\n const normalPath = applyParams(path, params);\n const resource = getResource(normalPath);\n const variantKey = toVariantKey(search);\n return resource.mutate.call(resource, variantKey, (data: any) => {\n if (data === undefined || data === null) {\n console.warn(\"Mutate function called before the query.\");\n return data;\n }\n\n if (!fn) {\n return data;\n }\n\n // The callback's return value *replaces* the cached data. The type checks\n // below only ensure the shape matches; they do not merge or append.\n const updatedData = typeof fn === \"function\" ? fn(data) : fn;\n\n if (isPlainObject(data)) {\n if (isPlainObject(updatedData)) {\n return updatedData;\n }\n throw new Error(\n \"Mutate function must return an object when the current data is an object.\",\n );\n }\n\n if (Array.isArray(data)) {\n if (Array.isArray(updatedData)) {\n return updatedData;\n }\n throw new Error(\n \"Mutate function must return an array when the current data is an array.\",\n );\n }\n\n if (typeof data !== typeof updatedData) {\n throw new Error(\n \"Mutate function must return the same type as the current data.\",\n );\n }\n\n return updatedData;\n });\n };\n}\n","import {\n createContext,\n useContext,\n type ComponentProps,\n type FormEvent,\n useRef,\n useEffect,\n useSyncExternalStore,\n useCallback,\n} from \"react\";\nimport type { RPC } from \"./rpc\";\nimport type { ApiRouterHandler } from \"../http/ApiRouter\";\nimport { useMutation } from \"./useMutation\";\nimport type { UnwrapPromise } from \"../utils/type\";\nimport type { UrlParser } from \"./types\";\nimport { useParams } from \"./useParams\";\nimport { ServerDataContext } from \"./ServerDataProvider\";\nimport { Subject } from \"../utils/Subject\";\n\ntype Any = any;\n\ninterface MutationContextValue {\n isPending: boolean;\n result: null | Any;\n validationErrors: Record<string, string[]>;\n formError: null | string;\n formDataSubject: React.RefObject<Subject<FormData>>;\n}\n\nconst MutationContext = createContext({\n isPending: false,\n result: null,\n} as MutationContextValue);\n\ntype GetResult<T> =\n T extends ApiRouterHandler<Any, infer Result, Any>\n ? UnwrapPromise<Result>\n : never;\n\ntype PostRequests = {\n [K in keyof RPC as K extends `POST:${infer P}` ? P : never]: GetResult<\n RPC[K]\n >;\n};\n\ntype PutRequests = {\n [K in keyof RPC as K extends `PUT:${infer P}` ? P : never]: GetResult<RPC[K]>;\n};\n\ntype DeleteRequests = {\n [K in keyof RPC as K extends `DELETE:${infer P}` ? P : never]: GetResult<\n RPC[K]\n >;\n};\n\ntype PatchRequests = {\n [K in keyof RPC as K extends `PATCH:${infer P}` ? P : never]: GetResult<\n RPC[K]\n >;\n};\n\ntype Methods = {\n POST: PostRequests;\n PUT: PutRequests;\n DELETE: DeleteRequests;\n PATCH: PatchRequests;\n};\n\ninterface FormProps<\n M extends keyof Methods,\n K extends keyof Methods[M],\n> extends Omit<ComponentProps<\"form\">, \"action\" | \"onError\"> {\n method?: M;\n action: K;\n onSuccess?: (result: Methods[M][K], form: HTMLFormElement) => void;\n onError?: (error: Any, form: HTMLFormElement) => void;\n params?: Partial<UrlParser<`${K & string}`>>;\n search?: Record<string, string>;\n dynamicInputs?: (formData: FormData) => Record<string, any>;\n}\n\nexport function Form<\n K extends keyof Methods[T],\n T extends keyof Methods = \"POST\",\n>(props: FormProps<T, K>) {\n const _params = useParams();\n const {\n method = \"POST\",\n action,\n onSuccess = () => {},\n onError = () => {},\n params,\n search = {},\n className,\n dynamicInputs = () => ({}),\n ...formProps\n } = \"params\" in props\n ? { ...props, params: { ..._params, ...props.params } }\n : { ...props, params: _params };\n const formRef = useRef<HTMLFormElement>(null);\n const { __csrf } = useContext(ServerDataContext);\n const formDataSubject = useRef(new Subject(new FormData()));\n\n const updateFormData = useCallback(() => {\n formDataSubject.current.next(new FormData(formRef.current));\n }, []);\n\n useEffect(() => {\n if (!formRef.current) return;\n\n formRef.current.addEventListener(\"input\", updateFormData);\n\n const observer = new MutationObserver(() => {\n const formData = new FormData(formRef.current);\n formDataSubject.current.next(formData);\n });\n\n formRef.current.querySelectorAll(\"input\").forEach((input) =>\n observer.observe(input, {\n attributes: true,\n attributeFilter: [\"value\"],\n }),\n );\n\n formRef.current.querySelectorAll(\"select\").forEach((input) =>\n observer.observe(input, {\n attributes: true,\n attributeFilter: [\"value\"],\n }),\n );\n\n formRef.current.querySelectorAll(\"textarea\").forEach((input) =>\n observer.observe(input, {\n attributes: true,\n attributeFilter: [\"value\"],\n }),\n );\n\n return () => {\n observer.disconnect();\n if (formRef.current) {\n formRef.current.removeEventListener(\"input\", updateFormData);\n }\n };\n }, [updateFormData]);\n\n const { trigger, data, error, loading } = useMutation(\n method,\n String(action) as Any,\n {\n params,\n search,\n } as Any,\n {\n onSuccess: (data) => onSuccess(data as Any, formRef.current),\n onError: (error) => onError(error, formRef.current),\n },\n );\n\n const handleSubmit = async (e: FormEvent) => {\n if (loading) {\n return;\n }\n e.preventDefault();\n if (!formRef.current) {\n return;\n }\n const formData = new FormData(formRef.current);\n for (const [key, value] of Object.entries(dynamicInputs(formData))) {\n formData.append(key, value as any);\n }\n trigger(formData as any);\n };\n\n const validationErrors =\n error?.kind === \"validation_error\" ? error.messages : {};\n\n const formError = error?.kind === \"form_error\" ? error.message : null;\n\n return (\n <MutationContext.Provider\n value={{\n isPending: loading,\n result: data,\n validationErrors,\n formError,\n formDataSubject,\n }}\n >\n <form\n className={[\"group\", className].filter(Boolean).join(\" \")}\n data-loading={loading}\n ref={formRef}\n onSubmit={handleSubmit}\n {...formProps}\n >\n <input type=\"hidden\" name=\"__csrf\" value={__csrf} />\n {props.children}\n </form>\n </MutationContext.Provider>\n );\n}\n\nexport function useMutationStatus() {\n const { isPending } = useContext(MutationContext);\n\n return { isPending };\n}\n\nexport function useFormStatus() {\n const { isPending, validationErrors, formError } =\n useContext(MutationContext);\n\n return { isPending, validationErrors, formError };\n}\n\nexport function useFormData() {\n const context = useContext(MutationContext);\n\n const { formDataSubject } = context;\n\n // Unbound on purpose: `Subject` binds in its constructor, so these are\n // stable across renders. The `.bind` calls that used to be here allocated a\n // fresh `subscribe` every render, which made `useSyncExternalStore` drop and\n // re-add this component's subscription on each pass.\n return useSyncExternalStore(\n formDataSubject.current.subscribe,\n formDataSubject.current.getValue,\n formDataSubject.current.getValue,\n );\n}\n\nexport const ValidationErrors = (props: {\n name: string;\n className?: string;\n render?: (props: ComponentProps<\"div\">) => React.JSX.Element;\n}) => {\n const {\n render = (props: ComponentProps<\"div\">) => <div {...props} />,\n name,\n } = props;\n const { validationErrors } = useContext(MutationContext);\n\n const Comp = render;\n\n if (validationErrors[name]?.length > 0) {\n return (\n <>\n {validationErrors[name].map((error) => {\n return (\n <Comp className={props.className} key={error}>\n {error}\n </Comp>\n );\n })}\n </>\n );\n }\n\n return null;\n};\n\nexport const FormFieldContainer = (\n props: ComponentProps<\"div\"> & { name: string },\n) => {\n const { name, children, ...rest } = props;\n const { validationErrors } = useContext(MutationContext);\n const errors = validationErrors[name] || [];\n return (\n <div data-has-error={errors.length > 0} {...rest}>\n {children}\n </div>\n );\n};\n\nexport const FormError = (props: ComponentProps<\"div\">) => {\n const { formError } = useContext(MutationContext);\n\n if (formError) {\n return <div {...props}>{formError}</div>;\n }\n\n return null;\n};\n","import { useContext, useSyncExternalStore } from \"react\";\nimport { ClientRouterContext } from \"./ClientRouterContext\";\n\nexport function useIsNavigationPending() {\n const { isNavigatingSubject } = useContext(ClientRouterContext);\n // These read `this`, and `useSyncExternalStore` calls whatever it is handed\n // as a plain function — which used to throw `undefined is not an object\n // (evaluating 'this.value')` on the first render of any component calling\n // this hook. `Subject` now binds in its constructor, so the references are\n // both correct and stable across renders; binding here instead would hand\n // uSES a new `subscribe` every render and churn the subscription.\n const isNavigating = useSyncExternalStore(\n isNavigatingSubject.subscribe,\n isNavigatingSubject.getValue,\n isNavigatingSubject.getValue,\n );\n\n return isNavigating;\n}\n","import { useContext, useEffect, useState } from \"react\";\nimport { ClientRouterContext } from \"./ClientRouterContext\";\n\nexport function useNavigationProgress() {\n const { progressManager } = useContext(ClientRouterContext);\n const [progress, setProgress] = useState(progressManager.state.getValue());\n\n useEffect(() => {\n const unsub = progressManager.state.subscribe((p) => setProgress(p));\n return () => {\n unsub();\n };\n }, [progressManager.state]);\n\n return progress;\n}\n","import { useCallback, useContext } from \"react\";\n\nimport { applyParams } from \"../utils/applyParams\";\nimport { ClientRouterContext } from \"./ClientRouterContext\";\nimport { I18nContext } from \"./I18nContext\";\nimport { useLocation } from \"./useLocation\";\nimport type { UrlParser, ViewPaths } from \"./types\";\n\ntype Search = Record<string, string | number | boolean | undefined | null>;\n\n/**\n * A prefetch spends the visitor's data on a page they may never open, so it\n * stands down when they have asked for less of that or the connection cannot\n * spare it. `navigator.connection` only exists in Chromium — everywhere else\n * there is nothing to go on and prefetching proceeds.\n */\nfunction connectionRefusesPrefetch() {\n const connection = (navigator as any)?.connection;\n if (!connection) {\n return false;\n }\n if (connection.saveData) {\n return true;\n }\n return [\"slow-2g\", \"2g\"].includes(connection.effectiveType);\n}\n\ntype Options<T extends ViewPaths> =\n UrlParser<T> extends Record<string, never>\n ? {\n search?: Search;\n locale?: string;\n }\n : {\n search?: Search;\n params: UrlParser<T>;\n locale?: string;\n };\n\n/**\n * Warms a route ahead of the navigation to it: its page data, its stylesheets\n * and its component chunks. A navigation that lands on a prefetched route\n * renders from the cached payload instead of waiting on a request.\n *\n * The URL is built exactly the way `useNavigate` builds it — the prefetch is\n * only ever used by a navigation that asks for the same one.\n */\nexport function usePrefetch() {\n const { prefetchRoute } = useContext(ClientRouterContext);\n const { defaultLocale } = useContext(I18nContext);\n const location = useLocation();\n\n const currentPathname = location.pathname;\n const currentSearch = location.search;\n const currentLocale = location.locale;\n\n return useCallback(\n async <T extends ViewPaths>(\n path: T | (string & {}),\n ...args: UrlParser<T> extends Record<string, never>\n ? [options?: Options<T>]\n : [options: Options<T>]\n ) => {\n if (typeof window === \"undefined\" || !prefetchRoute) {\n return;\n }\n\n if (connectionRefusesPrefetch()) {\n return;\n }\n\n const [options = {}] = args;\n const {\n search = {},\n params = {},\n locale = null,\n } = { params: {}, search: {}, locale: null, ...options };\n\n let localeSegment = locale ?? currentLocale;\n if (localeSegment === defaultLocale) {\n localeSegment = \"\";\n }\n\n const pathname = applyParams(path, params) || \"/\";\n // Matches `useNavigate`, which hands the search object straight to\n // `URLSearchParams` — the query string a click produces has to be the one\n // the payload was cached under.\n const queryString = new URLSearchParams(search as any).toString();\n const searchSegment = queryString.length > 0 ? `?${queryString}` : \"\";\n\n // The route already on screen has nothing to warm, and eagerly prefetched\n // links pointing back at it would just replay the current page's queries.\n if (pathname === currentPathname && searchSegment === currentSearch) {\n return;\n }\n\n await prefetchRoute({\n pathname,\n search: searchSegment,\n localeSegment: localeSegment ? `/${localeSegment}` : \"\",\n });\n },\n [\n prefetchRoute,\n defaultLocale,\n currentLocale,\n currentPathname,\n currentSearch,\n ],\n );\n}\n","import { useContext } from \"react\";\nimport { useRoute } from \"./useRoute\";\nimport { ClientRouterContext } from \"./ClientRouterContext\";\n\nexport type Breadcrumb = {\n label: string;\n href: string;\n};\n\nexport function useBreadcrumbs() {\n const { pathname } = useRoute();\n const { getViewPathsFromPathname, breadcrumbsCache } =\n useContext(ClientRouterContext);\n\n let breadcrumbs: Breadcrumb[] = [];\n const viewPaths = getViewPathsFromPathname(pathname);\n for (const viewPath of viewPaths) {\n if (breadcrumbsCache.has(`${viewPath}:${pathname}`)) {\n breadcrumbs.push(breadcrumbsCache.get(`${viewPath}:${pathname}`));\n }\n }\n\n return breadcrumbs.filter((breadcrumb) => breadcrumb?.label.length > 0);\n}\n","import {\n useCallback,\n useContext,\n useEffect,\n useRef,\n memo,\n type ComponentProps,\n type SyntheticEvent,\n} from \"react\";\n\nimport { applyParams } from \"../utils/applyParams\";\nimport { useLocation } from \"./useLocation\";\nimport type { UrlParser, ViewResult } from \"./types\";\nimport { useNavigate } from \"./useNavigate\";\nimport type { ViewRPC } from \"./rpc\";\nimport type { Prettify } from \"../utils/type\";\nimport { useParams } from \"./useParams\";\nimport { I18nContext } from \"./I18nContext\";\nimport { useRouteTransition } from \"./RouteTransitionProvider\";\nimport { usePrefetch } from \"./usePrefetch\";\n\ntype Views = {\n [K in keyof ViewRPC as K extends `view:${infer P}`\n ? P\n : never]: ViewResult<K>;\n};\n\ntype Search = Record<string, string | number | boolean | undefined | null>;\n\n/**\n * When to warm the target route's data, styles and chunks.\n *\n * - `hover` — the moment the pointer arrives, or on touch or keyboard focus.\n * - `intent` — hover held long enough to read as intent, so a cursor sweeping\n * across a nav bar does not fire a request per link it crosses.\n * - `viewport` — as the link comes into view.\n * - `render` — as soon as the link renders.\n *\n * Several can be combined. The useful pairing is a bulk strategy with an\n * interactive one — `[\"viewport\", \"intent\"]` warms the link on the way past and\n * warms it again on approach if the cached payload has since gone stale.\n * `hover` and `intent` together is just `hover`, since it fires first.\n *\n * Every strategy stands down on metered or very slow connections.\n */\nexport type PrefetchStrategy = \"hover\" | \"intent\" | \"viewport\" | \"render\";\n\n/** How long the pointer has to rest on an `intent` link before it counts. */\nconst INTENT_DELAY = 100;\n\n/** How far ahead of the viewport a `viewport` link starts warming. */\nconst VIEWPORT_MARGIN = \"200px\";\n\ntype LinkBaseProps<T extends keyof Views> = Omit<\n ComponentProps<\"a\">,\n \"href\"\n> & {\n active?: boolean;\n href: T;\n hash?: string;\n /** Off unless set. `false` is accepted so it can be driven by a variable. */\n prefetch?: PrefetchStrategy | readonly PrefetchStrategy[] | false;\n params: UrlParser<T>;\n search?: T extends keyof Views\n ? Views[T][\"input\"] extends Record<string, never>\n ? Search\n : Prettify<Partial<Views[T][\"input\"]> & Search>\n : Search;\n};\n\ntype LinkProps<T extends keyof Views, U = UrlParser<T>> = U extends Record<\n string,\n never\n>\n ? Omit<LinkBaseProps<T>, \"params\">\n : LinkBaseProps<T>;\n\nfunction normalizeSearch(search: Search): Record<string, string> {\n return Object.fromEntries(\n Object.entries(search)\n .filter(([_k, v]) => v !== undefined && v !== null)\n .map(([k, v]) => [k, String(v)]),\n ) as Record<string, string>;\n}\n\nexport const Link = memo(<T extends keyof Views>(props: LinkProps<T>) => {\n const _params = useParams();\n const { isTransitioning, targetPath } = useRouteTransition();\n const {\n href,\n onClick,\n onMouseEnter,\n onMouseLeave,\n onTouchStart,\n onFocus,\n onBlur,\n ref,\n hash = \"\",\n active = false,\n prefetch,\n params = {},\n search = {},\n ...rest\n } = { params: _params, search: {}, ...props };\n const { defaultLocale } = useContext(I18nContext);\n const { push } = useNavigate();\n const location = useLocation();\n const prefetchRoute = usePrefetch();\n const searchParams = new URLSearchParams(normalizeSearch(search));\n\n const path = applyParams(href, params);\n // `applyParams` drops the trailing slash, so the root route comes back empty\n // where every pathname the router reports says `/`.\n const resolvedPath = path || \"/\";\n let urlLocaleSegment = location.locale;\n if (urlLocaleSegment === defaultLocale) {\n urlLocaleSegment = \"\";\n }\n\n const localeSegment = urlLocaleSegment ? `/${urlLocaleSegment}` : \"\";\n\n const targetHref = [\n [`${localeSegment}${path}`, searchParams.toString()]\n .filter((s) => s.length > 0)\n .join(\"?\"),\n hash,\n ].join(\"\");\n\n const currentHref = [location.pathname, location.search, location.hash]\n .filter((item) => !!item)\n .join(\"\");\n\n // Held in a ref because the prefetch callback is rebuilt on every router\n // render — an effect that depended on it would re-fire on renders that have\n // nothing to do with this link.\n const prefetchRouteRef = useRef(prefetchRoute);\n useEffect(() => {\n prefetchRouteRef.current = prefetchRoute;\n });\n\n // Clicking through to the path we are already on is a shallow navigation —\n // it moves the URL without fetching, so there is nothing to warm.\n const isShallowTarget = resolvedPath === location.pathname;\n\n const strategies = !prefetch\n ? []\n : Array.isArray(prefetch)\n ? prefetch\n : [prefetch];\n const uses = (strategy: PrefetchStrategy) => strategies.includes(strategy);\n // Effects below key off the strategies, which arrive as an array literal with\n // a fresh identity on every render. The names are what actually matters.\n const strategyKey = strategies.join(\",\");\n\n // Repeats are the cache's problem, not this component's: it collapses a\n // hover storm into one request and lets a hover past the TTL refresh a\n // payload that has gone stale.\n const runPrefetch = () => {\n if (strategies.length === 0 || isShallowTarget) {\n return;\n }\n prefetchRouteRef.current(href, { params, search } as never);\n };\n\n useEffect(() => {\n if (uses(\"render\")) {\n runPrefetch();\n }\n }, [strategyKey, targetHref]);\n\n const anchorRef = useRef<HTMLAnchorElement | null>(null);\n // A caller's own `ref` still has to reach them — under React 19 it arrives as\n // a plain prop, and the spread below would otherwise hand the element to one\n // of us and null to the other.\n //\n // Memoised because `Link` re-renders on every navigation in the app: a fresh\n // callback identity would have React detach and reattach the element each\n // time, handing a caller's ref callback a null it never asked for.\n const setAnchorRef = useCallback(\n (node: HTMLAnchorElement | null) => {\n anchorRef.current = node;\n if (typeof ref === \"function\") {\n ref(node);\n } else if (ref) {\n ref.current = node;\n }\n },\n [ref],\n );\n\n useEffect(() => {\n if (!uses(\"viewport\")) {\n return;\n }\n const element = anchorRef.current;\n if (!element || typeof IntersectionObserver === \"undefined\") {\n return;\n }\n // One shot: a link scrolled past and back is already warm, and if its entry\n // has expired the next hover or click pays for a fresh one.\n const observer = new IntersectionObserver(\n (entries) => {\n if (entries.some((entry) => entry.isIntersecting)) {\n observer.disconnect();\n runPrefetch();\n }\n },\n { rootMargin: VIEWPORT_MARGIN },\n );\n observer.observe(element);\n return () => observer.disconnect();\n }, [strategyKey, targetHref]);\n\n const intentTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const cancelIntent = () => {\n if (intentTimerRef.current !== null) {\n clearTimeout(intentTimerRef.current);\n intentTimerRef.current = null;\n }\n };\n useEffect(() => cancelIntent, []);\n\n /** A pointer arriving — the one signal `intent` waits on before believing. */\n const pointerArrived = () => {\n if (uses(\"hover\")) {\n runPrefetch();\n } else if (uses(\"intent\")) {\n cancelIntent();\n intentTimerRef.current = setTimeout(runPrefetch, INTENT_DELAY);\n }\n };\n\n /** Focus and touch are deliberate, so neither strategy makes them wait. */\n const linkTargeted = () => {\n if (uses(\"hover\") || uses(\"intent\")) {\n runPrefetch();\n }\n };\n\n /** Runs the caller's own handler first, then the prefetch trigger. */\n const prefetchOn =\n <E extends SyntheticEvent>(\n handler: ((event: E) => void) | undefined,\n trigger: () => void,\n ) =>\n (event: E) => {\n handler?.(event);\n trigger();\n };\n\n return (\n <a\n ref={setAnchorRef}\n data-active={active || currentHref === targetHref}\n // The resolved path, not the template: one template can back a whole list\n // of rows, and only the row that was clicked is heading anywhere.\n data-pending={isTransitioning && resolvedPath === targetPath}\n href={targetHref === '' ? '/' : targetHref}\n onClick={(e) => {\n if (typeof window !== \"undefined\") {\n if (currentHref === targetHref) {\n e.preventDefault();\n return;\n }\n }\n let currentPath = window.location.pathname.replace(localeSegment, \"\");\n currentPath = currentPath === \"\" ? \"/\" : currentPath;\n onClick?.(e);\n\n if (hash === \"\") {\n e.preventDefault();\n }\n push(href, {\n hash,\n search,\n params,\n shallow: path === currentPath,\n } as unknown as never);\n }}\n onMouseEnter={prefetchOn(onMouseEnter, pointerArrived)}\n onMouseLeave={prefetchOn(onMouseLeave, cancelIntent)}\n onTouchStart={prefetchOn(onTouchStart, linkTargeted)}\n onFocus={prefetchOn(onFocus, linkTargeted)}\n onBlur={prefetchOn(onBlur, cancelIntent)}\n {...rest}\n />\n );\n});\n","import { type ComponentProps, useEffect } from \"react\";\nimport type { Link } from \"./Link\";\n\nimport { useNavigate } from \"./useNavigate\";\n\nexport const Redirect = (\n props: ComponentProps<typeof Link> & { action: \"push\" | \"replace\" },\n) => {\n const { href, params = {}, search = {}, action = \"replace\" } = props;\n const { push, replace } = useNavigate();\n\n useEffect(() => {\n if (action === \"replace\") {\n replace(href, { params, search } as any);\n } else {\n push(href, { params, search } as any);\n }\n }, [replace, action, push, params, search, href]);\n\n return <></>;\n};\n","import { type ReactNode, useContext } from \"react\";\nimport { ServerDataContext } from \"./ServerDataProvider\";\n\nexport function updateMeta(meta: any) {\n // A partially rendered response whose segments set no metadata sends none —\n // what is on the page belongs to the segments that were skipped.\n if (!meta) {\n return;\n }\n const { title, description } = meta;\n if (title) {\n document.title = title;\n }\n if (description) {\n const desc = document.querySelector(\"meta[name='description']\");\n if (desc) {\n desc.setAttribute(\"content\", description);\n } else {\n const newDesc = document.createElement(\"meta\");\n newDesc.setAttribute(\"name\", \"description\");\n newDesc.setAttribute(\"content\", description);\n document.head.appendChild(newDesc);\n }\n }\n}\n\nconst OpenGraph = (props: {\n title: string;\n type: string;\n url: string;\n image: string;\n description?: string;\n imageAlt?: string;\n imageWidth?: number;\n imageHeight?: number;\n twitterImage?: string;\n twitterImageAlt?: string;\n twitterImageWidth?: number;\n twitterImageHeight?: number;\n}) => {\n const {\n title,\n description,\n type,\n url,\n image,\n imageAlt,\n imageWidth,\n imageHeight,\n twitterImage,\n twitterImageAlt,\n twitterImageWidth,\n twitterImageHeight,\n } = props;\n\n return (\n <>\n <meta property=\"og:title\" content={title} />\n <meta property=\"og:type\" content={type} />\n <meta property=\"og:url\" content={url} />\n <meta property=\"og:image\" content={image} />\n {description && <meta property=\"og:description\" content={description} />}\n {imageAlt && <meta property=\"og:image:alt\" content={imageAlt} />}\n {imageWidth && (\n <meta property=\"og:image:width\" content={String(imageWidth)} />\n )}\n {imageHeight && (\n <meta property=\"og:image:height\" content={String(imageHeight)} />\n )}\n {twitterImage && (\n <>\n <meta name=\"twitter:image\" content={twitterImage} />\n <meta name=\"twitter:card\" content=\"summary_large_image\" />\n </>\n )}\n {twitterImageAlt && (\n <meta name=\"twitter:image:alt\" content={twitterImageAlt} />\n )}\n {twitterImageWidth && (\n <meta name=\"twitter:image:width\" content={String(twitterImageWidth)} />\n )}\n {twitterImageHeight && (\n <meta\n name=\"twitter:image:height\"\n content={String(twitterImageHeight)}\n />\n )}\n </>\n );\n};\n\nexport const Head = ({\n children = null,\n charSet = \"utf-8\",\n}: { children?: ReactNode; charSet?: string }) => {\n const { meta } = useContext(ServerDataContext);\n return (\n <head>\n <meta charSet={charSet} />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n {/*\n Disable browser auto-translation (Chrome/Google Translate). Gemi apps do\n their own i18n, and a translator that rewrites text nodes *before* React\n hydrates mutates the SSR DOM — which React rejects as a hydration\n mismatch (Minified React error #418) and then regenerates the tree,\n dropping the server-injected <style> and leaving the page unstyled.\n Pair this with `translate=\"no\"` on the <html> element in RootLayout.\n */}\n <meta name=\"google\" content=\"notranslate\" />\n <title>{meta?.title}</title>\n {meta?.description && (\n <meta name=\"description\" content={meta.description} />\n )}\n {meta?.openGraph && <OpenGraph {...meta.openGraph} />}\n {children}\n </head>\n );\n};\n","import { applyParams } from \"./applyParams\";\n\n/**\n * Route the client is currently rendering, sent on `.json` navigations so the\n * server can skip the handlers of the segments that route already has mounted.\n * Value is a locale-less pathname plus search, e.g. `/app/A/chat?tab=2`.\n */\nexport const PARTIAL_RENDER_HEADER = \"x-gemi-from\";\n\n/** What the server reports back about the skip it performed, if any. */\nexport interface PartialRenderInfo {\n /** The `x-gemi-from` value the plan was computed against. */\n from: string;\n /** View paths of the skipped segments, in order. Their data is carried forward. */\n carriedViews: string[];\n}\n\n/**\n * The `x-gemi-from` value for the route the client starts on.\n *\n * On the first render the router's `pathname` is still the route *pattern* the\n * server matched — it only becomes a resolved path once the history listener\n * has run — so this has to apply the params. Sending `/app/:orgId/chat` names\n * no route the server can resolve, and the first navigation after every full\n * page load would skip nothing.\n */\nexport function initialRenderedRoute(route: {\n pathname?: string;\n params?: Record<string, string>;\n search?: string;\n}) {\n // `applyParams` strips the trailing slash, so the root route resolves to the\n // empty string — which the server reads as \"no header\" and renders in full.\n const pathname = applyParams(route.pathname ?? \"/\", route.params ?? {}) || \"/\";\n return `${pathname}${route.search ?? \"\"}`;\n}\n","import type { Breadcrumb } from \"../useBreadcrumbs\";\n\ninterface RouteSnapshot {\n /** Concrete pathname, without the locale segment. */\n pathname: string;\n /** Route pattern the data was produced for — part of every breadcrumb key. */\n routePath: string;\n data: Record<string, any>;\n breadcrumbs: Record<string, Breadcrumb>;\n}\n\n/**\n * A partially rendered response only carries the segments the server actually\n * ran. Everything is keyed by the *new* pathname, so a carried layout would\n * render with empty props unless the data it already had is copied across.\n *\n * Data the server sent always wins: a carried view is only filled in where the\n * response has nothing for it.\n */\nexport function mergeCarriedSegments(\n previous: RouteSnapshot,\n next: RouteSnapshot,\n carriedViews: string[],\n) {\n if (carriedViews.length === 0) {\n return { data: next.data, breadcrumbs: next.breadcrumbs };\n }\n\n // Page data is keyed by the pathname it was fetched for, and a shallow\n // navigation moves the pathname on without fetching — so fall back to the key\n // the data is actually under. The server sends exactly one.\n const previousData = previous.data ?? {};\n const previousViewData =\n previousData[previous.pathname] ?? previousData[Object.keys(previousData)[0]] ?? {};\n const previousBreadcrumbs = previous.breadcrumbs ?? {};\n\n const carriedViewData: Record<string, unknown> = {};\n const carriedBreadcrumbs: Record<string, Breadcrumb> = {};\n\n for (const viewPath of carriedViews) {\n if (viewPath in previousViewData) {\n carriedViewData[viewPath] = previousViewData[viewPath];\n }\n // Breadcrumbs are keyed by route pattern, and that changed even though the\n // segment did not, so they have to be re-keyed rather than copied.\n const previousKey = `${viewPath}:${previous.routePath}`;\n if (previousKey in previousBreadcrumbs) {\n carriedBreadcrumbs[`${viewPath}:${next.routePath}`] = previousBreadcrumbs[previousKey];\n }\n }\n\n // The server sends page data under exactly one key. Take it from the payload\n // rather than recomputing it, so the two never disagree on spelling.\n const [nextKey = next.pathname] = Object.keys(next.data ?? {});\n\n return {\n data: {\n ...next.data,\n [nextKey]: { ...carriedViewData, ...next.data?.[nextKey] },\n },\n breadcrumbs: { ...carriedBreadcrumbs, ...next.breadcrumbs },\n };\n}\n","import {\n PARTIAL_RENDER_HEADER,\n type PartialRenderInfo,\n} from \"../../utils/partialRender\";\nimport { readRoutePayload, type RouteQueryPayload } from \"./readRoutePayload\";\n\ninterface LoadRoutePayloadOptions {\n /** The `.json` URL for the route being navigated to. */\n url: string;\n /** `x-gemi-from` value for the route currently on screen. */\n from: string;\n /** Hands over a payload warmed ahead of this navigation, if there is one. */\n takePrefetched?: (url: string) => Promise<unknown> | null;\n /**\n * The route that is on screen *now*, re-read at the moment a response lands.\n * A navigation that committed while this one was in flight invalidates the\n * partial-render plan the server computed.\n */\n renderedRoute: () => string;\n /**\n * Receives each query result the server streams behind the envelope\n * (#290) — the caller hydrates it into the cache, which settles any\n * segment suspended on that variant.\n */\n onQueryPayload?: (payload: RouteQueryPayload) => void;\n}\n\n/**\n * The page data for a navigation, from whichever source can produce it.\n *\n * A prefetched payload is always a full render, so it can be committed as-is\n * and the `x-gemi-from` round trip skipped entirely. Everything else — no\n * prefetch, a prefetch that failed, a partial response computed against a route\n * that has since been navigated away from — falls through to a request.\n *\n * Returns `null` when nothing usable came back; the caller leaves the current\n * route on screen.\n */\nexport async function loadRoutePayload(\n options: LoadRoutePayloadOptions,\n): Promise<any> {\n const { url, from, takePrefetched, renderedRoute, onQueryPayload } = options;\n\n const prefetched = takePrefetched?.(url);\n if (prefetched) {\n const payload = await prefetched;\n if (payload) {\n return payload;\n }\n }\n\n let response = { ok: false, json: async () => ({}) } as Response;\n try {\n response = await fetch(url, { headers: { [PARTIAL_RENDER_HEADER]: from } });\n } catch (e) {\n console.error(e);\n return null;\n }\n\n if (!response.ok) {\n return null;\n }\n\n // Resolves with the envelope as soon as its line arrives; query results\n // streaming behind it keep draining into `onQueryPayload`.\n const payload = await readRoutePayload(response, onQueryPayload);\n\n // The segments the server carried forward were computed against a route that\n // is no longer on screen. Nothing sound to merge onto — ask for the whole\n // tree instead.\n const claimed: PartialRenderInfo | null = payload?.partial ?? null;\n if (claimed && claimed.from !== renderedRoute()) {\n try {\n const full = await fetch(url);\n if (full.ok) {\n return await readRoutePayload(full, onQueryPayload);\n }\n } catch (e) {\n console.error(e);\n }\n }\n\n return payload;\n}\n","import {\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n StrictMode,\n memo,\n useTransition,\n Suspense,\n useSyncExternalStore,\n} from \"react\";\n\nimport type { PropsWithChildren, ReactNode, ComponentType, lazy } from \"react\";\nimport { ErrorBoundary, type FallbackProps } from \"react-error-boundary\";\n\nimport { ServerDataContext } from \"./ServerDataProvider\";\nimport {\n ClientRouterContext,\n ClientRouterProvider,\n} from \"./ClientRouterContext\";\nimport type { ComponentTree } from \"./types\";\nimport {\n ComponentsContext,\n ComponentsProvider,\n loadViewModule,\n subscribeViewModules,\n} from \"./ComponentContext\";\nimport {\n QueryManagerContext,\n QueryManagerProvider,\n type QueryConfig,\n} from \"./QueryManagerContext\";\nimport { I18nProvider } from \"./I18nContext\";\nimport { WebSocketContextProvider } from \"./WebsocketContext\";\nimport { useNavigate } from \"./useNavigate\";\nimport {\n type PageData,\n type RouteState,\n RouteStateProvider,\n} from \"./RouteStateContext\";\nimport { applyParams } from \"../utils/applyParams\";\nimport { Action } from \"history\";\nimport { useRouteData } from \"./useRouteData\";\nimport { updateMeta } from \"./Head\";\nimport { RouteTransitionProvider } from \"./RouteTransitionProvider\";\nimport { ThemeProvider } from \"./ThemeProvider\";\nimport { initialRenderedRoute } from \"../utils/partialRender\";\nimport { mergeCarriedSegments } from \"./helpers/mergeCarriedSegments\";\nimport { routeDataUrl } from \"./helpers/routeDataUrl\";\nimport { loadRoutePayload } from \"./helpers/loadRoutePayload\";\n\ndeclare global {\n interface Window {\n scrollHistory: Map<string, number>;\n loaders: Record<string, () => void>;\n }\n}\n\nfunction restoreScroll(action: Action | null = null, _pathname = \"no path\") {\n if (action === null) {\n return;\n }\n\n const { pathname, search, hash } = window.location;\n\n const key = [pathname, search, hash].join(\"\");\n const sh = window.scrollHistory;\n\n const scrollPosition = sh?.get(key);\n\n if (action !== Action.Pop) {\n window.scrollTo(0, 0);\n } else {\n // In dev mode the effect runs scroll restoration\n // will be called twice, this if statement prevents\n // scroll to top\n if (!scrollPosition) {\n return;\n }\n window.scrollTo(0, scrollPosition ?? 0);\n }\n\n sh?.delete(key);\n}\n\ninterface RouteProps {\n componentPath: string;\n pathname: string;\n action: Action | null;\n}\n\nconst DefaultQueryErrorFallback = (props: FallbackProps) => {\n return (\n <div role=\"alert\">\n <p>Something went wrong.</p>\n <button type=\"button\" onClick={() => props.resetErrorBoundary()}>\n Try again\n </button>\n </div>\n );\n};\n\nconst Route = memo((props: PropsWithChildren<RouteProps>) => {\n const { componentPath, pathname, action, children } = props;\n const { viewImportMap, getViewModule } = useContext(ComponentsContext);\n const { clearErrors } = useContext(QueryManagerContext);\n const { data } = useRouteData();\n\n // `Loading` / `Error` are optional named exports of the view module,\n // subscribed so a Route that rendered before its chunk arrived re-reads\n // the registry once it lands. On the server `getViewModule` reads the\n // eagerly-loaded modules the http server passed in — a streaming render\n // suspends for real, so the `Loading` fallback it puts in the shell must be\n // the same one the client hydrates.\n const getModule = useCallback(\n () => getViewModule?.(componentPath),\n [getViewModule, componentPath],\n );\n const mod = useSyncExternalStore(subscribeViewModules, getModule, getModule);\n\n const componentData = data?.[pathname]?.[componentPath] ?? {};\n const Component = viewImportMap[componentPath];\n\n useEffect(() => {\n if (!children) {\n restoreScroll(action, componentPath);\n }\n }, [action, children, componentPath]);\n\n if (!Component) {\n const NotFound = viewImportMap[\"404\"];\n return <NotFound />;\n }\n const Loading = mod?.Loading;\n const ErrorFallback = mod?.Error ?? DefaultQueryErrorFallback;\n\n return (\n <ErrorBoundary\n FallbackComponent={ErrorFallback}\n resetKeys={[pathname]}\n onReset={clearErrors}\n >\n <Suspense fallback={Loading ? <Loading /> : null}>\n {/* Keyed by view path so swapping views remounts the view (fresh\n state), while the boundary above — keyed by tree slot in `Tree` —\n stays revealed across the swap. */}\n <Component key={componentPath} {...componentData}>\n {props.children}\n </Component>\n </Suspense>\n </ErrorBoundary>\n );\n});\n\nexport const Tree = memo(\n (props: {\n action: Action;\n tree: ComponentTree;\n entries: string[];\n pathname: string;\n }) => {\n const { entries, tree, pathname, action } = props;\n\n return (\n <>\n {tree\n .filter(([path]) => entries.includes(path))\n .map((node, slot) => {\n const [path, subtree] = node;\n // Keyed by tree SLOT, not by view path: the Suspense/error\n // boundary inside `Route` must survive a sibling swap (Home →\n // Pricing under the same layout), so React treats it as already\n // revealed and a suspending navigation keeps the previous page on\n // screen. A path key would remount the boundary every navigation,\n // and a brand-new boundary commits its fallback the moment any\n // sibling content (the layout's re-rendered chrome) commits —\n // blanking the outgoing page. The view itself still remounts when\n // the path changes: `Route` keys its Component render.\n if (subtree.length > 0) {\n return (\n <Route\n action={action}\n key={`slot-${slot}`}\n componentPath={path}\n pathname={pathname}\n >\n <Tree\n action={action}\n tree={subtree}\n entries={entries}\n pathname={pathname}\n />\n </Route>\n );\n }\n return (\n <Route\n action={action}\n key={`slot-${slot}`}\n componentPath={path}\n pathname={pathname}\n />\n );\n })}\n </>\n );\n },\n);\n\nconst Routes = (props: { componentTree: ComponentTree }) => {\n const { componentTree } = props;\n const [isPending, startTransition] = useTransition();\n const [isFetching, setIsFetching] = useState(false);\n const { routerSubject, fetchRouteCSS, preloadRouteModules, takePrefetched } =\n useContext(ClientRouterContext);\n const { hydrate } = useContext(QueryManagerContext);\n\n const [transitionPath, setTransitionPath] = useState<[string, string]>([\n null,\n routerSubject?.getValue().pathname,\n ]);\n\n const {\n breadcrumbs,\n pageData,\n i18n,\n prefetchedData,\n features,\n appId: currentAppId,\n } = useContext(ServerDataContext);\n\n const [routeState, setRouteState] = useState<RouteState & PageData>({\n params: routerSubject?.getValue().params,\n search: routerSubject?.getValue().search,\n pathname: routerSubject?.getValue().pathname,\n views: routerSubject?.getValue().views,\n action: null,\n hash: routerSubject?.getValue().hash,\n state: routerSubject?.getValue().state,\n routePath: routerSubject?.getValue().routePath,\n locale: routerSubject?.getValue().locale,\n breadcrumbs,\n data: pageData,\n i18n,\n prefetchedData,\n features: features ?? {},\n appId: currentAppId,\n });\n\n const { replace } = useNavigate();\n\n // Adopt what the document was rendered with. Without this the initial payload\n // only ever reaches a component that mounts on the first render, and one that\n // mounts on a later navigation — into a route whose layout has since been\n // carried forward rather than re-run — would fetch it over `/api` instead.\n useEffect(() => {\n hydrate(prefetchedData);\n }, [hydrate, prefetchedData]);\n\n // The route currently on screen, in `x-gemi-from` form. Updated when a\n // response is committed, never when one is merely requested — a navigation\n // that fails must leave the base the server carries segments from intact.\n const renderedRouteRef = useRef(initialRenderedRoute(routeState));\n\n useEffect(() => {\n return routerSubject?.subscribe(async (routerState) => {\n const { pathname, search, state, views } = routerState;\n setTransitionPath((current) => {\n const [, prevTarget] = current;\n return [prevTarget, pathname];\n });\n if (routerState.views.length === 0) {\n // Same reason as the `is404` branch below: the tree about to be mounted\n // carries none of the segments the stale `from` would have the server\n // skip.\n renderedRouteRef.current = \"\";\n setRouteState((routerState) => ({\n ...routerState,\n views: [\"404\"],\n }));\n return;\n }\n\n if (state?.shallow) {\n setRouteState((state) => ({\n ...state,\n ...routerState,\n }));\n return;\n }\n\n const localeSegment = routerState.locale ? `/${routerState.locale}` : \"\";\n\n const url = routeDataUrl({ pathname, search, localeSegment });\n const from = renderedRouteRef.current;\n setIsFetching(true);\n\n // `fetchRouteCSS` keys off the route manifest, so it needs the pattern\n // rather than the concrete path — `/posts/:id`, not `/posts/123`.\n fetchRouteCSS(routerState.routePath).catch((e) => console.error(e));\n // Announced before the imports below start, so each view's own static\n // imports are already in flight rather than discovered one parse at a\n // time once its chunk lands (#352).\n preloadRouteModules(routerState.routePath);\n // Through `loadViewModule` so the module registry — and with it each\n // view's `Loading`/`Error` exports — is populated before the\n // transition commits the new surface.\n for (const component of views) {\n loadViewModule(component);\n }\n\n const payload = await loadRoutePayload({\n url,\n from,\n takePrefetched,\n renderedRoute: () => renderedRouteRef.current,\n // Query results streaming behind the envelope (#290): hydrating each\n // settles the segment suspended on it — the same wake path streamed\n // documents use.\n onQueryPayload: ([path, variantKey, data]) => {\n hydrate({ [path]: { [variantKey]: data } });\n },\n });\n\n if (payload) {\n const {\n data,\n i18n,\n prefetchedData,\n breadcrumbs,\n meta,\n directive = {},\n is404 = false,\n appId,\n features,\n } = payload;\n updateMeta(meta);\n if (directive?.kind === \"Redirect\") {\n if (directive?.path) {\n replace(directive.path, { params: {} } as unknown);\n }\n\n return;\n }\n\n // Returns, rather than falling through. The commit below spreads\n // `routerState`, which carries the *matched* route's views — so without\n // the return this updater's `[\"404\"]` is queued and then overwritten in\n // the same batch, and the route renders its real views with no data.\n //\n // Reachable only since `.feature()`: a path the client cannot match is\n // caught by the `views.length === 0` guard above and never fetched, so\n // `is404` from the server used to imply an empty client `views`. A gated\n // route keeps its manifest entry, which is exactly the case where the\n // server says 404 and the client still knows how to render the page.\n if (is404) {\n // Not `${pathname}${search}`. `x-gemi-from` tells the server which\n // segments are already mounted so it can skip their handlers, and\n // after this commit the mounted tree is `[\"404\"]` — none of the target\n // route's layouts, and none of the previous route's either. The empty\n // string is what the server reads as \"carry nothing\".\n renderedRouteRef.current = \"\";\n startTransition(() => {\n setRouteState((state) => ({\n ...state,\n ...routerState,\n appId,\n i18n,\n features: features ?? state.features,\n // After the spread, deliberately.\n views: [\"404\"],\n }));\n });\n setIsFetching(false);\n return;\n }\n\n const carriedViews: string[] = payload.partial?.carriedViews ?? [];\n renderedRouteRef.current = `${pathname}${search}`;\n\n // Adopt what the server just prefetched before the new surface mounts\n // and its queries read the cache, otherwise they refetch it over /api.\n // Safe here: this callback is async, so we are past the render phase.\n hydrate(prefetchedData);\n\n startTransition(() => {\n setRouteState((state) => ({\n ...routerState,\n appId,\n i18n,\n // `?? state.features` rather than a bare assignment: an error-path\n // or older-server envelope carrying no flags must leave the current\n // values on screen, not blank every flag mid-session.\n features: features ?? state.features,\n prefetchedData,\n ...mergeCarriedSegments(\n state,\n { pathname, routePath: routerState.routePath, data, breadcrumbs },\n carriedViews,\n ),\n }));\n });\n }\n setIsFetching(false);\n });\n }, [\n routerSubject,\n fetchRouteCSS,\n preloadRouteModules,\n takePrefetched,\n replace,\n hydrate,\n ]);\n\n return (\n <RouteTransitionProvider\n isPending={isPending}\n isFetching={isFetching}\n transitionPath={transitionPath}\n >\n <RouteStateProvider state={routeState}>\n <Tree\n action={routeState.action}\n pathname={applyParams(routeState.pathname ?? \"/\", routeState.params)}\n tree={componentTree}\n entries={routeState.pathname ? routeState.views : [\"404\"]}\n />\n </RouteStateProvider>\n </RouteTransitionProvider>\n );\n};\n\nexport const ClientRouter = (props: {\n viewImportMap?: Record<string, ReturnType<typeof lazy>>;\n /** Server only: full view modules for `Loading`/`Error` fallbacks. */\n viewModules?: Record<string, Record<string, any>>;\n RootLayout: ComponentType<{ children: ReactNode; locale: string }>;\n /** App-wide `useQuery` defaults; per-call config always wins. */\n queryConfig?: QueryConfig;\n}) => {\n const { RootLayout } = props;\n const {\n routeManifest,\n router,\n componentTree,\n pageData,\n cssManifest,\n modulePreloadManifest,\n breadcrumbs,\n i18n,\n } = useContext(ServerDataContext);\n\n return (\n <ThemeProvider>\n <I18nProvider>\n <WebSocketContextProvider>\n <QueryManagerProvider queryConfig={props.queryConfig}>\n <ComponentsProvider\n viewImportMap={props.viewImportMap}\n modules={props.viewModules}\n >\n <ClientRouterProvider\n cssManifest={cssManifest}\n modulePreloadManifest={modulePreloadManifest}\n searchParams={router.searchParams}\n params={router.params}\n pageData={pageData}\n is404={router.is404}\n is500={false}\n pathname={router.pathname}\n currentPath={router.currentPath}\n routeManifest={routeManifest}\n breadcrumbs={breadcrumbs}\n urlLocaleSegment={router.urlLocaleSegment}\n >\n <StrictMode>\n <RootLayout locale={i18n.currentLocale}>\n <Routes componentTree={componentTree} />\n </RootLayout>\n </StrictMode>\n </ClientRouterProvider>\n </ComponentsProvider>\n </QueryManagerProvider>\n </WebSocketContextProvider>\n </I18nProvider>\n </ThemeProvider>\n );\n};\n","import { useEffect, type ComponentType } from \"react\";\nimport { hydrateRoot, createRoot } from \"react-dom/client\";\nimport { ServerDataProvider } from \"./ServerDataProvider\";\nimport { ClientRouter } from \"./ClientRouter\";\nimport type { QueryConfig } from \"./QueryManagerContext\";\nimport { ErrorBoundary } from \"react-error-boundary\";\n\nexport interface InitOptions {\n /**\n * App-wide `useQuery` defaults (per-call config always wins). Mirror the\n * value passed to `createRoot` in the view router's service provider so the\n * server render and hydration agree.\n */\n queryConfig?: QueryConfig;\n}\n\nconst StackTrace = () => {\n useEffect(() => {\n window.addEventListener(\"load\", () => {\n const container = document.getElementById(\"overlay\");\n const ErrorOverlay = customElements.get(\"vite-error-overlay\");\n if (ErrorOverlay) {\n const overlay = new ErrorOverlay({\n message: (window as any).error,\n stack: (window as any).stack_trace || \"\",\n });\n container.appendChild(overlay);\n }\n });\n }, []);\n\n return <div id=\"overlay\" />;\n};\n\nexport function init(\n RootLayout: ComponentType<any>,\n options: InitOptions = {},\n) {\n if (typeof window !== \"undefined\" && (window as any).render_error) {\n createRoot(document.body).render(<StackTrace />);\n } else {\n hydrateRoot(\n document,\n <>\n <></>\n <></>\n <ErrorBoundary fallback={<div />}>\n <ServerDataProvider>\n <ClientRouter\n RootLayout={RootLayout}\n queryConfig={options.queryConfig}\n />\n </ServerDataProvider>\n </ErrorBoundary>\n </>,\n {\n onCaughtError: (error) => {\n console.error(error);\n // @ts-ignore\n if (import.meta.env.DEV) {\n const ErrorOverlay = customElements.get(\"vite-error-overlay\");\n if (ErrorOverlay) {\n const overlay = new ErrorOverlay({\n message: (error as any).message,\n stack: (error as any).stack || \"\",\n });\n document.body.appendChild(overlay);\n }\n }\n },\n },\n );\n }\n}\n\nexport function create(\n RootLayout: ComponentType<any>,\n {\n componentTree,\n loaders,\n routeManifest,\n router,\n i18n,\n auth,\n prefetchedData,\n viewImportMap,\n }: any,\n) {\n (window as any).__GEMI_DATA__ = {\n componentTree,\n loaders,\n routeManifest,\n router,\n i18n,\n auth,\n prefetchedData,\n pageData: {},\n };\n createRoot(document.getElementById(\"root\")).render(\n <ServerDataProvider>\n <ClientRouter viewImportMap={viewImportMap} RootLayout={RootLayout} />\n </ServerDataProvider>,\n );\n}\n","import { createContext } from \"react\";\nimport type { DictionarySink } from \"../i18n/dictionarySink\";\n\n/**\n * The SSR-only collector `useDictionary` reports into. `null` in the browser,\n * where nothing needs collecting — the strings are already there.\n *\n * Mirrors `ServerQueryContext`: a server-supplied per-request object handed to\n * the tree by `createRoot`.\n */\nexport const DictionarySinkContext = createContext<DictionarySink | null>(null);\n","import type { ComponentType } from \"react\";\nimport { ClientRouter } from \"./ClientRouter\";\nimport { DictionarySinkContext } from \"./DictionarySinkContext\";\nimport type { QueryConfig } from \"./QueryManagerContext\";\nimport { ServerDataProvider } from \"./ServerDataProvider\";\nimport { ServerQueryContext } from \"./ServerQueryContext\";\n\nexport interface CreateRootOptions {\n /**\n * App-wide `useQuery` defaults (per-call config always wins). Set the same\n * value in the client entry's `init` call so hydration matches the server\n * render.\n */\n queryConfig?: QueryConfig;\n}\n\nexport function createRoot(\n RootLayout: ComponentType<{ children: React.ReactNode; locale: string }>,\n options: CreateRootOptions = {},\n) {\n // `serverQueries`, `viewModules` and `dictionarySink` exist only when the view\n // router renders this on the server — the browser mounts with all three absent.\n return (props: any) => (\n <ServerDataProvider value={props.data}>\n <ServerQueryContext.Provider value={props.serverQueries ?? null}>\n <DictionarySinkContext.Provider value={props.dictionarySink ?? null}>\n <ClientRouter\n RootLayout={RootLayout}\n viewImportMap={props.viewImportMap}\n viewModules={props.viewModules}\n queryConfig={options.queryConfig}\n />\n </DictionarySinkContext.Provider>\n </ServerQueryContext.Provider>\n </ServerDataProvider>\n );\n}\n","import type { ComponentProps } from \"react\";\n\nconst defaultScreen = [390, 768, 1024];\nconst defaultContainer = [100, 100, 100, 100];\n\nfunction generateImageProps(\n src: string,\n width: number,\n container = defaultContainer,\n screen = defaultScreen,\n quality = 80,\n) {\n const baseUrl = src;\n\n const widths = [...container.map((c, i) => (screen[i] * c) / 100), width * 2];\n\n return {\n srcSet: [\n ...screen.map((size, i) => {\n return `/api/__gemi__/services/image/resize?url=${baseUrl}&q=${quality}&w=${widths[i]} ${size}${isNaN(Number(size)) ? \"\" : \"w\"}`;\n }),\n `/api/__gemi__/services/image/resize?url=${baseUrl}&q=${quality}&w=${width * 2} 2x`,\n ].join(\", \"),\n sources: [\n ...container.map((c, i) => {\n if (!screen[i]) {\n return `${c}vw`;\n }\n return `(max-width: ${screen[i]}px) ${c}vw`;\n }),\n ].join(\", \"),\n };\n}\n\nfunction fillRestWithLast<T>(arr: T[], length: number): T[] {\n return [\n ...arr,\n ...Array.from({ length: length - arr.length }).fill(arr[arr.length - 1]),\n ] as T[];\n}\n\ninterface ImageProps {\n src: string;\n width: number;\n container?: number[];\n screen?: number[];\n quality?: number;\n}\n\nexport const Image = (props: ComponentProps<\"img\"> & ImageProps) => {\n const {\n screen = defaultScreen,\n container = defaultContainer,\n src,\n width,\n quality = 80,\n srcSet: __,\n ...rest\n } = props;\n\n if (!src) {\n return null;\n }\n\n const srcProps = generateImageProps(\n src,\n width,\n fillRestWithLast(container, 4),\n screen,\n quality,\n );\n\n return <img {...srcProps} width={width} {...rest} />;\n};\n","import { usePost } from \"../useMutation\";\n\ninterface UseForgotPasswordArgs {\n onSuccess: () => void;\n}\n\nconst defaultArgs: UseForgotPasswordArgs = {\n onSuccess: () => {},\n};\n\nexport function useForgotPassword(args: UseForgotPasswordArgs = defaultArgs) {\n return usePost(\n \"/auth/forgot-password\",\n {},\n {\n onSuccess: () => {\n args.onSuccess();\n },\n },\n );\n}\n","import { usePost } from \"../useMutation\";\nimport { useFrameworkQuery } from \"../useQuery\";\n\ninterface UseSignInArgs {\n onSuccess?: (data: any) => void;\n}\n\nconst defaultArgs: UseSignInArgs = {\n onSuccess: () => {},\n};\n\nexport function useSignIn(args: UseSignInArgs = defaultArgs) {\n // Only here for `mutate` — `lazy` so the sign-in form neither fetches nor\n // suspends on a user it does not have yet. `useFrameworkQuery` keeps that\n // pinned regardless of the app's `queryConfig`.\n const { mutate } = useFrameworkQuery(\"/auth/me\", {}, { lazy: true });\n return usePost(\n \"/auth/sign-in\",\n {},\n {\n onSuccess: (user) => {\n args.onSuccess(user);\n mutate(user as any);\n },\n },\n );\n}\n","import { usePost } from \"../useMutation\";\n\nexport function useSignUp() {\n return usePost(\"/auth/sign-up\");\n}\n","import { useMutate } from \"../useMutate\";\nimport { usePost } from \"../useMutation\";\n\ninterface UseSignOutArgs {\n onSuccess?: () => void;\n}\n\nconst defaultArgs: UseSignOutArgs = {\n onSuccess: () => {},\n};\n\nexport function useSignOut(args: UseSignOutArgs = defaultArgs) {\n const mutator = useMutate();\n return usePost(\n \"/auth/sign-out\",\n {},\n {\n onSuccess: () => {\n args.onSuccess();\n mutator({ path: \"/auth/me\" });\n },\n },\n );\n}\n","import { usePost } from \"../useMutation\";\n\ninterface UseResetPasswordArgs {\n onSuccess: () => void;\n}\n\nconst defaultArgs: UseResetPasswordArgs = {\n onSuccess: () => {},\n};\n\nexport function useResetPassword(args: UseResetPasswordArgs = defaultArgs) {\n return usePost(\n \"/auth/reset-password\",\n {},\n {\n onSuccess: () => {\n args.onSuccess();\n },\n },\n );\n}\n","import { useContext } from \"react\";\nimport { ServerDataContext } from \"../ServerDataProvider\";\nimport { useFrameworkQuery } from \"../useQuery\";\n\nexport function useUser() {\n const { auth } = useContext(ServerDataContext);\n const {\n data: user,\n loading,\n error,\n // `useFrameworkQuery`: the semantics below are pinned, so an app-wide\n // `queryConfig` must not leak in.\n } = useFrameworkQuery(\n \"/auth/me\",\n {},\n {\n fallbackData: auth?.user ? auth.user : null,\n // An anonymous visitor has no `/auth/me` data and never will — this\n // must resolve to `user: null`, not suspend the page behind a 401.\n suspense: false,\n },\n );\n\n if (loading && !user) {\n return { user: null, loading, error };\n }\n\n return { user: user, loading, error };\n}\n","import { useContext } from \"react\";\nimport { RouteStateContext } from \"./RouteStateContext\";\nimport type { ClientFeatureKey } from \"./rpc\";\n\n/**\n * Reads a feature evaluated by the server for this request.\n *\n * ```tsx\n * if (useFeature(\"new-checkout\")) {\n * return <NewCheckout />;\n * }\n * ```\n *\n * Keys are typed against `app/features`, so a typo is a compile error rather\n * than a feature that silently reads as off. Features declared\n * `serverOnly: true` are excluded from that set: they are withheld from the\n * payload on purpose, so reading one here could only ever answer `false`. Use\n * the `Features` facade for those.\n *\n * ## It never fetches\n *\n * The value comes from the payload the server already sent — embedded in the\n * document on first load, and replaced by each navigation's envelope after\n * that. So this is a context read: no request, no suspense, no loading state,\n * and no flash of the wrong branch, which is the failure mode that makes\n * client-evaluated features unusable for anything above the fold.\n *\n * The corollary is that switching a feature on reaches an open page on its next\n * navigation, not instantly.\n *\n * ## Reads route state, not server data\n *\n * `RouteStateContext` is what each navigation replaces — the same reason\n * `useLocale` reads it. Reading `ServerDataContext` instead would pin every\n * feature to the values from the initial document for the life of the session.\n */\nexport function useFeature(key: ClientFeatureKey): boolean {\n // `= {}` because several existing tests provide a bare object as page data,\n // and an error-path envelope may carry no features at all.\n const { features = {} } = useContext(RouteStateContext);\n\n if (process.env.NODE_ENV !== \"production\" && !(key in features)) {\n // Both reasons, because the type system only rules out the second one for a\n // caller whose `gemi.d.ts` resolved — and \"declare it\" is actively wrong\n // advice for the app that already did, then marked it `serverOnly`.\n console.warn(\n `[gemi] Feature \"${String(key)}\" is not in the payload the server sent. Either it is not declared in app/features, or it is declared \\`serverOnly: true\\` and never reaches the browser.`,\n );\n }\n\n // An unknown key reads as off rather than throwing: a feature deleted from the\n // declarations, or a payload that predates one, must not white-screen a page\n // that renders it.\n return features[key as string] === true;\n}\n\n/**\n * Every feature the server sent, for a component that needs to branch on\n * several at once or forward them somewhere.\n */\nexport function useFeatures(): Record<string, boolean> {\n const { features = {} } = useContext(RouteStateContext);\n return features;\n}\n","import { createElement, Fragment, isValidElement, type JSX } from \"react\";\n\ntype TemplateParams = Record<\n string,\n string | ((p: unknown) => string | JSX.Element)\n>;\n\nexport function parseTranslation(template: string, params: TemplateParams) {\n // Check if we have any JSX in our parameters\n const hasJSX = Object.values(params).some(\n (value) =>\n typeof value === \"function\" &&\n isValidElement((value as (p: unknown) => unknown)(\"\")),\n );\n\n // Regular expression to match template variables:\n // {{name}} - simple variable\n // {{name:type}} - variable with type casting\n // {{name:[content]}} - variable with interpolated content\n const regex = /{{([^{}]+?)(?::([^{}\\[\\]]+?))?(?:\\[(.*?)\\])?}}/g;\n\n if (!hasJSX) {\n // Simple string replacement\n const result = template.replace(regex, (match, name, type, content) => {\n // Clean the name part by removing any colon if present\n const cleanName = name.includes(\":\") ? name.split(\":\")[0] : name;\n\n const value = params[cleanName];\n if (value === undefined) {\n return match; // Return original match if no parameter found\n }\n\n if (typeof value === \"function\") {\n // If value is a function, call it with the content if available\n const functionParam = content !== undefined ? content : \"\";\n const functionResult = value(functionParam);\n // Check if function returned JSX - this shouldn't happen in the string branch\n if (isValidElement(functionResult)) {\n throw new Error(\"JSX returned in string context\");\n }\n return String(functionResult);\n }\n\n // Handle type casting if specified\n if (type) {\n switch (type.toLowerCase()) {\n case \"number\":\n return Number(value).toString();\n case \"string\":\n return String(value);\n case \"boolean\":\n return Boolean(value).toString();\n default:\n return String(value);\n }\n }\n return String(value);\n });\n return result as any;\n } else {\n // JSX replacement - we'll split the template into parts\n const parts: Array<string | JSX.Element> = [];\n let lastIndex = 0;\n let match: RegExpExecArray | null = null;\n\n while ((match = regex.exec(template)) !== null) {\n const [fullMatch, name, type, content] = match;\n const matchIndex = match.index;\n\n // Clean the name part by removing any colon if present\n const cleanName = name.includes(\":\") ? name.split(\":\")[0] : name;\n\n // Add text before the match\n if (matchIndex > lastIndex) {\n parts.push(template.substring(lastIndex, matchIndex));\n }\n\n const value = params[cleanName];\n if (value === undefined) {\n // Keep original template variable if no parameter found\n parts.push(fullMatch);\n } else if (typeof value === \"function\") {\n // If value is a function, call it with the content if available\n const functionParam = content !== undefined ? content : \"\";\n const functionResult = value(functionParam);\n parts.push(functionResult);\n } else if (type) {\n // Handle type casting if specified\n switch (type.toLowerCase()) {\n case \"number\":\n parts.push(Number(value).toString());\n break;\n case \"string\":\n parts.push(String(value));\n break;\n case \"boolean\":\n parts.push(Boolean(value).toString());\n break;\n default:\n parts.push(String(value));\n }\n } else {\n parts.push(String(value));\n }\n\n lastIndex = matchIndex + fullMatch.length;\n }\n\n // Add any remaining text\n if (lastIndex < template.length) {\n parts.push(template.substring(lastIndex));\n }\n\n // Convert the parts array to JSX\n return createElement(Fragment, {}, ...parts) as any;\n }\n}\n","import type { I18nDictionary } from \"./rpc\";\nimport type { ParseTranslationParams, Prettify } from \"../utils/type\";\nimport type { JSX } from \"react\";\nimport { parseTranslation } from \"../utils/parseTranslation\";\nimport { useRouteData } from \"./useRouteData\";\n\ntype Parser<T extends Record<string, string>> = Prettify<\n {\n [K in keyof T]: ParseTranslationParams<T[K]>;\n }[keyof T]\n>;\n\ntype ParamsOrNever<T> = T extends Record<string, never>\n ? [params?: never]\n : [params: T];\n\n/**\n * @deprecated Use `useDictionary(dict)` with a `defineDictionary` dictionary\n * declared next to the component. This resolves a dictionary by name through\n * the global `I18nDictionary` interface, which needs a `gemi.d.ts`\n * declaration, a central `app/i18n/index.ts`, and a hand-maintained `prefetch`\n * map naming every route's dictionaries — and it ships whatever that map says\n * whether the page reads it or not. Still supported; see `docs/i18n.md`.\n */\nexport function useTranslator<T extends keyof I18nDictionary>(component: T) {\n const { i18n } = useRouteData();\n\n function parse<\n K extends keyof I18nDictionary[T][\"dictionary\"],\n U extends Record<string, string> = I18nDictionary[T][\"dictionary\"][K],\n >(key: K, ...args: ParamsOrNever<Parser<U>>) {\n try {\n const translations = i18n.dictionary[i18n.currentLocale][component];\n const [params = {}] = args;\n return parseTranslation(translations[key as any], params);\n } catch (err) {\n console.error(\n `Unresolved translation Component:${component} key:${String(key)}`,\n );\n return String(key);\n }\n }\n\n parse.jsx = <\n K extends keyof I18nDictionary[T][\"dictionary\"],\n U extends Record<string, string> = I18nDictionary[T][\"dictionary\"][K],\n >(\n key: K,\n ...args: ParamsOrNever<Parser<U>>\n ) => {\n return parse(key, ...(args as any)) as unknown as JSX.Element;\n };\n\n return parse;\n}\n","import { use, useContext, type JSX } from \"react\";\nimport type { DictionaryHandle } from \"../i18n/defineDictionary\";\nimport { setActiveLocale } from \"../i18n/dictionaryRegistry\";\nimport type { DictionaryTranslations } from \"../i18n/dictionaryShape\";\nimport { parseTranslation } from \"../utils/parseTranslation\";\nimport type { ParseTranslationParams, Prettify } from \"../utils/type\";\nimport { DictionarySinkContext } from \"./DictionarySinkContext\";\nimport { useRouteData } from \"./useRouteData\";\n\ntype Parser<T extends Record<string, string>> = Prettify<\n {\n [K in keyof T]: ParseTranslationParams<T[K]>;\n }[keyof T]\n>;\n\ntype ParamsOrNever<T> = T extends Record<string, never>\n ? [params?: never]\n : [params: T];\n\n/**\n * Read a dictionary declared with `defineDictionary`, next to the component\n * that uses it.\n *\n * ```tsx\n * const t = useDictionary(homeDict);\n * t(\"title\", { name });\n * ```\n *\n * Keys and interpolation params come straight from the literal — there is no\n * name string to keep in sync and no `gemi.d.ts` augmentation.\n *\n * Normally this resolves without suspending: the server seeds the strings it\n * rendered with into the hydration payload, and the router warms a view's\n * dictionaries while it is already loading that view's chunks. It falls back to\n * suspending on the locale's chunk when neither happened — a dictionary inside\n * a `lazy()` subtree, or the first render after a locale switch.\n *\n * Replaces `useTranslator`, which is deprecated.\n */\nexport function useDictionary<const T extends DictionaryTranslations>(\n dictionary: DictionaryHandle<T>,\n) {\n const { i18n } = useRouteData();\n const sink = useContext(DictionarySinkContext);\n // An app with i18n switched off still renders dictionaries — fall back to the\n // source language rather than blowing up on an empty `i18n` payload.\n const locale = i18n?.currentLocale ?? dictionary.locales[0];\n // Tells the view loader which locale's chunks to warm on the next\n // navigation. `__GEMI_DATA__` only knows the locale the document loaded in.\n setActiveLocale(locale);\n\n // `loadForRender`, not the plain loader: a rejected locale chunk must not\n // rethrow out of `use()` and take the route down. It degrades to no strings,\n // and the per-key lookup below falls back to the key — what `useTranslator`\n // did. Called on the handle rather than the registry so a dictionary declared\n // at module scope survives the registry being reset under it.\n const pending = dictionary.loadForRender(locale);\n const strings = pending instanceof Promise ? use(pending) : pending;\n\n // Reported from the render phase, and deliberately so: on the server the\n // strings have to reach the document before the segment that used them is\n // revealed, or hydration would find them missing and refetch. The sink\n // de-duplicates, and it is null in the browser.\n sink?.use(dictionary.id, locale, strings);\n\n // Annotated `string` rather than inferred: `parseTranslation` returns `any`\n // (it hands back a JSX element on the `t.jsx` path), and letting that leak\n // through would silently defeat the key and param checking below — every\n // call site would typecheck against `any`.\n function parse<K extends keyof T & string, U extends T[K] = T[K]>(\n key: K,\n ...args: ParamsOrNever<Parser<U extends Record<string, string> ? U : never>>\n ): string {\n const template = strings[key];\n if (typeof template !== \"string\") {\n console.error(\n `Unresolved translation key:${key} locale:${locale} dictionary:${dictionary.id}`,\n );\n return key;\n }\n const [params = {}] = args;\n return parseTranslation(template, params as any) as string;\n }\n\n parse.jsx = <K extends keyof T & string, U extends T[K] = T[K]>(\n key: K,\n ...args: ParamsOrNever<Parser<U extends Record<string, string> ? U : never>>\n ) => {\n return parse(key, ...(args as any)) as unknown as JSX.Element;\n };\n\n return parse;\n}\n","/**\n * The one implementation of \"what is a dictionary literal, and what is its id\",\n * shared by the runtime (`defineDictionary`) and the Vite plugin.\n *\n * Both sides must agree exactly. A dictionary's id is a hash of its own\n * contents rather than of its file path, so a module that is bundled on one\n * side and evaluated raw on the other still lands on the same id — which is\n * what lets the SSR payload seed the client registry.\n */\n\nexport type DictionaryTranslations = Record<string, Record<string, string>>;\n\nexport type LocaleStrings = Record<string, string>;\n\n/**\n * Locales the dictionary declares, source language first.\n *\n * The order is meaningful: the first locale is the source language, and a key\n * missing from some other locale falls back along this list.\n *\n * `sourceLocale` pins that choice. Without it the source language is whichever\n * locale is seen first while walking the literal, which makes it an emergent\n * property of key order — adding a key at the top of a dictionary whose other\n * keys happen to lack `en-US` would silently re-point every fallback in it. Any\n * dictionary that is not uniformly translated should say which locale it is\n * authored in.\n */\nexport function dictionaryLocales(\n translations: DictionaryTranslations,\n sourceLocale?: string,\n): string[] {\n const locales: string[] = [];\n const seen = new Set<string>();\n if (sourceLocale) {\n seen.add(sourceLocale);\n locales.push(sourceLocale);\n }\n for (const byLocale of Object.values(translations)) {\n for (const locale of Object.keys(byLocale)) {\n if (!seen.has(locale)) {\n seen.add(locale);\n locales.push(locale);\n }\n }\n }\n return locales;\n}\n\n/**\n * Flatten one locale out of a dictionary.\n *\n * A key with no string for `locale` falls back along the declared locale order\n * rather than vanishing, so a half-translated dictionary degrades one string at\n * a time instead of rendering the whole component as raw keys.\n */\nexport function localeStrings(\n translations: DictionaryTranslations,\n locale: string,\n fallbackOrder: string[] = dictionaryLocales(translations),\n): LocaleStrings {\n const out: LocaleStrings = {};\n for (const [key, byLocale] of Object.entries(translations)) {\n let value = byLocale?.[locale];\n if (typeof value !== \"string\") {\n for (const candidate of fallbackOrder) {\n const fallback = byLocale?.[candidate];\n if (typeof fallback === \"string\") {\n value = fallback;\n break;\n }\n }\n }\n if (typeof value === \"string\") {\n out[key] = value;\n }\n }\n return out;\n}\n\nexport interface SourceDisagreement {\n key: string;\n first: string;\n againstKey: string;\n againstFirst: string;\n}\n\n/**\n * Whether the inferred source language survives reordering the literal.\n *\n * `dictionaryLocales` collects locales entry by entry, so `locales[0]` is the\n * first locale of the first entry. That is invariant under key reordering\n * exactly when every entry lists the same locale first — and order-dependent\n * the moment two entries disagree, because then whichever happens to be written\n * first decides what the *whole* dictionary falls back to. Adding one key at\n * the top can flip every other key's fallback language, from a diff that reads\n * as an addition.\n *\n * Returns the disagreement so the build can name both keys; `null` when the\n * inference is stable. `sourceLocale` settles it and makes the question moot.\n */\nexport function findSourceDisagreement(\n translations: DictionaryTranslations,\n): SourceDisagreement | null {\n let againstKey: string | undefined;\n let againstFirst: string | undefined;\n\n for (const [key, byLocale] of Object.entries(translations)) {\n const first = Object.keys(byLocale ?? {})[0];\n // A key with no locales at all is a different problem, reported elsewhere.\n if (first === undefined) continue;\n\n if (againstFirst === undefined) {\n againstFirst = first;\n againstKey = key;\n continue;\n }\n if (first !== againstFirst) {\n return { key, first, againstKey: againstKey!, againstFirst };\n }\n }\n return null;\n}\n\n/**\n * Canonical serialization — key order in the source file must not change the\n * id, or an innocuous reordering would break the payload/registry match.\n */\nexport function canonicalizeDictionary(\n translations: DictionaryTranslations,\n): string {\n const keys = Object.keys(translations).sort();\n const parts = keys.map((key) => {\n const byLocale = translations[key] ?? {};\n const locales = Object.keys(byLocale).sort();\n const inner = locales.map((l) => JSON.stringify([l, byLocale[l]])).join(\",\");\n return `${JSON.stringify(key)}:[${inner}]`;\n });\n return `{${parts.join(\",\")}}`;\n}\n\n/**\n * FNV-1a, run twice with different offsets for a 64-bit-wide id. No crypto\n * import, and it has to work identically in the browser bundle, under Bun on\n * the server, and inside the Vite plugin.\n */\nexport function dictionaryId(translations: DictionaryTranslations): string {\n const input = canonicalizeDictionary(translations);\n let a = 0x811c9dc5;\n let b = 0x01000193;\n for (let i = 0; i < input.length; i++) {\n const c = input.charCodeAt(i);\n a = Math.imul(a ^ c, 0x01000193);\n b = Math.imul(b ^ c, 0x811c9dc5);\n }\n const hex = (n: number) => (n >>> 0).toString(16).padStart(8, \"0\");\n return `d_${hex(a)}${hex(b)}`;\n}\n","import {\n dictionaryId,\n dictionaryLocales,\n localeStrings,\n type DictionaryTranslations,\n type LocaleStrings,\n} from \"./dictionaryShape\";\nimport {\n loadDictionary,\n loadDictionaryForRender,\n registerDictionary,\n} from \"./dictionaryRegistry\";\n\ndeclare const brand: unique symbol;\n\nexport interface DictionaryHandle<\n T extends DictionaryTranslations = DictionaryTranslations,\n> {\n readonly id: string;\n /** Locales this dictionary declares, source language first. */\n readonly locales: readonly string[];\n /**\n * Strings for `locale`. Synchronous when they are already in memory —\n * always, for an unbundled dictionary; after a preload or the SSR seed, for a\n * bundled one.\n */\n load(locale: string): LocaleStrings | Promise<LocaleStrings>;\n /**\n * `load`, but never rejecting — safe to hand React's `use()`. A failed locale\n * chunk resolves to no strings so the component degrades to rendering keys\n * instead of unmounting into an error boundary.\n */\n loadForRender(locale: string): LocaleStrings | Promise<LocaleStrings>;\n get(locale: string): LocaleStrings | undefined;\n /** Type-only: carries the literal's shape through to `useDictionary`. */\n readonly [brand]?: T;\n}\n\n/**\n * Declare the strings a component needs, next to the component.\n *\n * ```ts\n * export const homeDict = defineDictionary({\n * title: { \"en-US\": \"Welcome {{name}}\", \"tr-TR\": \"Hoş geldin {{name}}\" },\n * });\n * ```\n *\n * As written this holds every locale. Under gemi's Vite plugin the call is\n * rewritten so each locale becomes its own chunk and a page downloads only the\n * one it renders in — but the plugin is strictly an optimization, and the\n * behaviour is identical without it (in `bun test`, and in server code that\n * does not go through the bundler).\n *\n * The first locale in the literal is the source language: a key missing from\n * another locale falls back to it rather than rendering as its own key.\n */\nexport interface DefineDictionaryOptions {\n /**\n * The locale this dictionary is authored in. Keys missing from another locale\n * fall back to it, and it is what renders when the app has no locale\n * configured.\n *\n * Optional, but worth setting on any dictionary that is not uniformly\n * translated: without it the source language is whichever locale appears\n * first in the literal, so adding a key at the top can re-point every\n * fallback in the dictionary.\n */\n sourceLocale?: string;\n}\n\nexport function defineDictionary<const T extends DictionaryTranslations>(\n translations: T,\n options: DefineDictionaryOptions = {},\n): DictionaryHandle<T> {\n const locales = dictionaryLocales(translations, options.sourceLocale);\n return createHandle(dictionaryId(translations), locales, (locale) =>\n localeStrings(translations, locale, locales),\n );\n}\n\n/**\n * The rewritten form of a `defineDictionary` call — emitted by\n * `packages/gemi/vite/dictionaryPlugin.ts`, never written by hand. `loaders`\n * holds one dynamic import per locale so the bundler emits one chunk per\n * locale and the untaken ones never reach the browser.\n */\nexport function __gemi_dict__<\n const T extends DictionaryTranslations = DictionaryTranslations,\n>(\n id: string,\n loaders: Record<string, () => Promise<{ default: LocaleStrings }>>,\n): DictionaryHandle<T> {\n const locales = Object.keys(loaders);\n return createHandle(id, locales, (locale) => {\n // An unknown locale falls back to the source language, matching what\n // `localeStrings` does per key on the unbundled path.\n const load = loaders[locale] ?? loaders[locales[0]];\n if (!load) {\n return {};\n }\n return load().then((mod) => mod.default);\n });\n}\n\nfunction createHandle<T extends DictionaryTranslations>(\n id: string,\n locales: string[],\n load: (locale: string) => LocaleStrings | Promise<LocaleStrings>,\n): DictionaryHandle<T> {\n const entry = { id, locales, load };\n registerDictionary(entry);\n\n // Re-asserted on every read rather than only at construction. A handle is\n // created once, at module scope, but the registry it delegates to can be\n // emptied under it — a test's `afterEach` reset, an HMR boundary — and the\n // handle would then be permanently orphaned, throwing \"Unknown dictionary\"\n // for a dictionary the caller is holding. `registerDictionary` is a no-op\n // when the id is already there, so this costs one Map lookup.\n const ensure = () => registerDictionary(entry);\n\n return {\n id,\n locales,\n // Routed through the registry rather than calling `load` directly so\n // concurrent readers share one in-flight import and results are cached.\n load: (locale: string) => {\n ensure();\n return loadDictionary(id, locale);\n },\n loadForRender: (locale: string) => {\n ensure();\n return loadDictionaryForRender(id, locale);\n },\n get: (locale: string) => {\n ensure();\n const strings = loadDictionary(id, locale);\n if (strings instanceof Promise) {\n // Nothing downstream awaits this one — `get` is the synchronous peek,\n // and the caller is about to discard it. An unattached rejection (a\n // locale chunk that 404s mid-deploy) would surface as an\n // `unhandledRejection`, which under Node's default handler takes the\n // process down over one missing translation file. The load itself is\n // still cached and still retried through `loadDictionary`.\n strings.catch(() => {});\n return undefined;\n }\n return strings;\n },\n };\n}\n\n","import { useLocation } from \"./useLocation\";\nimport { useNavigate } from \"./useNavigate\";\nimport { useParams } from \"./useParams\";\nimport { useRouteData } from \"./useRouteData\";\n\nconst LOCALE_COOKIE = \"i18n-locale\";\nconst LOCALE_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;\n\n/**\n * The active locale lives in two places: the URL segment `setLocale` navigates\n * to, and the `i18n-locale` cookie the server falls back to when the URL has no\n * segment — which is exactly the case for the default locale. Both have to be in\n * place *before* the navigation asks for route data, or `Translator.detectLocale`\n * answers the request with a redirect back to the locale the cookie still names.\n *\n * Hence a synchronous `document.cookie` write rather than an awaited one. The\n * previous implementation awaited `cookieStore.set()` and hung the navigation off\n * its `.then()`; that promise is reported to never settle on iOS Safari, so the\n * `.then()` never ran and changing the language became a silent no-op — no\n * rejection, nothing for an error reporter to pick up. A synchronous write cannot\n * hang and cannot fail asynchronously, so nothing is left to gate navigation on.\n */\nfunction persistLocale(locale: string) {\n if (typeof document === \"undefined\") {\n return;\n }\n try {\n document.cookie = [\n // Encoded, not interpolated: `cookieStore.set()` rejected malformed\n // values, a raw string write does not. A locale carrying `;` would\n // otherwise write cookie *attributes* — `Domain`, `Path` — from whatever\n // the app happens to feed the switcher.\n `${LOCALE_COOKIE}=${encodeURIComponent(locale)}`,\n `Max-Age=${LOCALE_COOKIE_MAX_AGE}`,\n \"SameSite=Strict\",\n \"Path=/\",\n ].join(\"; \");\n } catch {\n // A sandboxed iframe with no storage access throws here. The navigation\n // still carries the locale in its URL, so it is better to switch without\n // remembering the choice than to not switch at all.\n }\n}\n\n/**\n * `onLocaleChange` is a server-side hook, so it takes a request to fire it. The\n * switch must not wait on that round trip, nor be cancelled by one that fails —\n * including one that fails *synchronously*: `fetch` is absent in some old\n * WebViews, and an unguarded call would throw before the navigation ran, which\n * is the same silent no-op this hook exists to prevent through another door.\n */\nfunction notifyLocaleChange(locale: string) {\n try {\n void fetch(\n `/api/__gemi__/services/i18n/set-locale/${encodeURIComponent(locale)}`,\n ).catch(() => {});\n } catch {\n // `fetch` itself is unavailable. The locale is already persisted and the\n // navigation still runs; only the server-side hook misses this switch.\n }\n}\n\nexport function useLocale() {\n const { i18n } = useRouteData();\n const { pathname, search } = useLocation();\n const { replace } = useNavigate();\n const params = useParams();\n\n const setLocale = async (locale: string) => {\n persistLocale(locale);\n notifyLocaleChange(locale);\n\n const urlSearchParams = new URLSearchParams(search);\n await replace(pathname, {\n locale,\n // TODO: fix: this conversion is wrong, because there can be multiple\n // search params with the same name\n search: Object.fromEntries(urlSearchParams.entries()),\n params,\n } as any);\n };\n\n return [i18n.currentLocale, setLocale] as const;\n}\n","import { useCallback, useContext, useEffect, useMemo } from \"react\";\nimport { WebSocketContext } from \"./WebsocketContext\";\nimport { applyParams } from \"../utils/applyParams\";\n\nexport function useSubscription(\n route: string,\n options: { params: {}; cb: (data: any) => void },\n) {\n const { cb, params } = options;\n const { subscribe, unsubscribe } = useContext(WebSocketContext);\n\n const topic = useMemo(\n () => applyParams(route, options.params),\n [route, params],\n );\n\n const handler = (event: MessageEvent<any>) => {\n const message = JSON.parse(event.data);\n if (topic === message.topic) {\n cb(message.data);\n }\n };\n\n useEffect(() => {\n subscribe(topic, handler);\n\n return () => {\n unsubscribe(topic, handler);\n };\n }, [topic]);\n}\n","import { useContext } from \"react\";\nimport { WebSocketContext } from \"./WebsocketContext\";\nimport { applyParams } from \"../utils/applyParams\";\n\nexport function useBroadcast(\n path: string,\n options: { params: Record<string, string | number> },\n) {\n const { params = {} } = options;\n const { broadcast } = useContext(WebSocketContext);\n\n const topic = applyParams(path, params);\n\n return (payload: Record<string, any>) => broadcast(topic, payload);\n}\n","import { createElement, Fragment, type ReactNode } from \"react\";\nimport type { SatoriOptions } from \"satori\";\n\ntype Font = Omit<SatoriOptions[\"fonts\"][number], \"data\">;\ntype Options = Omit<SatoriOptions, \"fonts\"> & {\n fonts: Font[];\n} & { width: number; height: number };\n\nexport const OpenGraphImage = ({\n children,\n ...satoriOptions\n}: Options & { children: ReactNode }) => {\n return (\n <>\n {(() => {\n throw {\n jsx: createElement(Fragment, { children }),\n satoriOptions,\n };\n })()}\n </>\n );\n};\n","import { useContext } from \"react\";\nimport { ServerDataContext } from \"./ServerDataProvider\";\nimport { RouteStateContext } from \"./RouteStateContext\";\n\nexport function useAppIdMissmatch() {\n const { appId: next } = useContext(RouteStateContext);\n const { appId: current } = useContext(ServerDataContext);\n\n return current !== next;\n}\n"],"mappings":";;;;;;;;;;AA+BA,IAAa,qBAAqB,cAAwC,IAAI;;;AC5B9E,SAAgB,eAAe;CAC7B,MAAM,EAAE,MAAM,MAAM,gBAAgB,gBAClC,WAAW,iBAAiB;CAE9B,OAAO;EAAE;EAAM;EAAM;EAAgB;CAAY;AACnD;;;ACRA,SAAgB,cACd,OACkC;CAClC,OACE,UAAU,QACV,OAAO,UAAU,YACjB,CAAC,MAAM,QAAQ,KAAK,KACpB,OAAO,eAAe,KAAK,MAAM,OAAO;AAE5C;;;AC6DA,IAAM,gBAA6B;CACjC,cAAc;CACd,kBAAkB;CAClB,sBAAsB;CACtB,iBAAiB;CACjB,mBAAmB;CACnB,uBAAuB;CACvB,WAAW;CAC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ACd,MACA,SACA;CACA,MAAM,EAAE,SAAS,CAAC,MAAM;CACxB,MAAM,EAAE,cAAc,WAAW,gBAAgB;CAEjD,MAAM,QAAQ,cAAY,MAAM,MAAM;CAEtC,QAAQ,YAAiC,UAAU,OAAO,OAAO;AACnE;;;ACNA,IAAa,kBAAkB,EAC7B,UACA,GAAG,oBACoC;CACvC,OACE,oBAAA,YAAA,EAAA,iBACU;EACN,MAAM;GACJ,KAAK,cAAc,UAAU,EAAE,SAAS,CAAC;GACzC;EACF;CACF,EAAA,CAAG,EACH,CAAA;AAEN;;;AClBA,SAAgB,oBAAoB;CAClC,MAAM,EAAE,OAAO,SAAS,WAAW,iBAAiB;CACpD,MAAM,EAAE,OAAO,YAAY,WAAW,iBAAiB;CAEvD,OAAO,YAAY;AACrB"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../client/ServerQueryContext.tsx","../../client/useRouteData.ts","../../client/isPlainObject.ts","../../client/useQuery.ts","../../client/useMutation.ts","../../client/useMutate.ts","../../client/Mutation.tsx","../../client/useIsNavigationPending.ts","../../client/useNavigationProgress.ts","../../client/usePrefetch.ts","../../client/useBreadcrumbs.ts","../../client/Link.tsx","../../client/Redirect.tsx","../../client/Head.tsx","../../utils/partialRender.ts","../../client/helpers/mergeCarriedSegments.ts","../../client/helpers/loadRoutePayload.ts","../../client/ClientRouter.tsx","../../client/init.tsx","../../client/DictionarySinkContext.ts","../../client/createRoot.tsx","../../client/Image.tsx","../../client/auth/useForgotPassword.ts","../../client/auth/useSignIn.tsx","../../client/auth/useSignUp.ts","../../client/auth/useSignOut.ts","../../client/auth/useResetPassword.ts","../../client/auth/useUser.ts","../../client/useFeature.ts","../../utils/parseTranslation.tsx","../../client/useTranslator.ts","../../client/useDictionary.ts","../../i18n/dictionaryShape.ts","../../i18n/defineDictionary.ts","../../client/useLocale.ts","../../client/useSubscription.ts","../../client/useBroadcast.ts","../../client/OpenGraphImage.tsx","../../client/useAppIdMissmatch.ts"],"sourcesContent":["import { createContext } from \"react\";\n\n/**\n * The structural slice of the server's `ServerQueryStore` that `useQuery`\n * needs during a streaming server render. Declared here — not imported from\n * `services/router` — because this file ships in the browser bundle; only the\n * shape crosses over, never the implementation.\n */\nexport interface ServerQueryEntryLike {\n status: \"pending\" | \"resolved\" | \"rejected\";\n data?: any;\n error?: any;\n promise: Promise<void>;\n}\n\nexport interface ServerQueriesLike {\n ensure(\n path: string,\n options?: {\n params?: Record<string, any>;\n search?: Record<string, string | number | boolean | null>;\n },\n source?: \"prefetch\" | \"render\",\n ): ServerQueryEntryLike;\n}\n\n/**\n * Populated only during a streaming server render (`createRoot` threads the\n * request's store through); always `null` in the browser, where suspension\n * runs on `QueryResource` instead.\n */\nexport const ServerQueryContext = createContext<ServerQueriesLike | null>(null);\n","import { useContext } from \"react\";\nimport { RouteStateContext } from \"./RouteStateContext\";\n\nexport function useRouteData() {\n const { data, i18n, prefetchedData, breadcrumbs } =\n useContext(RouteStateContext);\n\n return { data, i18n, prefetchedData, breadcrumbs };\n}\n","export function isPlainObject(\n value: unknown,\n): value is Record<string, unknown> {\n return (\n value !== null &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n","import {\n useCallback,\n useContext,\n useDeferredValue,\n useEffect,\n useRef,\n useSyncExternalStore,\n} from \"react\";\nimport type { RPC } from \"./rpc\";\nimport type { NestedPrettify } from \"../utils/type\";\n\nimport type { ApiRouterHandler } from \"../http/ApiRouter\";\nimport type { UnwrapPromise } from \"../utils/type\";\nimport { QueryConfigContext, QueryManagerContext } from \"./QueryManagerContext\";\nimport { ServerQueryContext } from \"./ServerQueryContext\";\nimport { DEFAULT_STALE_TIME } from \"./QueryResource\";\nimport { applyParams } from \"../utils/applyParams\";\nimport type { UrlParser } from \"./types\";\nimport { toVariantKey } from \"../utils/variantKey\";\nimport { useParams } from \"./useParams\";\nimport { useRouteData } from \"./useRouteData\";\nimport { isPlainObject } from \"./isPlainObject\";\n\ninterface Config<T> {\n fallbackData?: T;\n /**\n * When true (the default), a variant change keeps rendering the previous\n * variant's data while the new one loads. Under suspense this reads through\n * a deferred variant key, so changing `search`/`params` never flashes the\n * segment fallback and needs no `startTransition` at the call site — the\n * pending window is exposed as `loading: true`. Set to `false` to get the\n * suspend-on-variant-change semantics back (e.g. tab-like switches where\n * stale rows would mislead). First mount always suspends either way.\n */\n keepPreviousData?: boolean;\n retryIntervalOnError?: number;\n refreshInterval?: number;\n /**\n * When true, the query revalidates whenever the tab comes back to the\n * foreground. Off by default. `staleTime` still gates it, so a quick\n * tab-out-and-back costs nothing and only data that has actually aged goes\n * back to the wire — silently, keeping what's on screen rendered.\n */\n revalidateOnFocus?: boolean;\n /**\n * Minimum gap between two `revalidateOnFocus` revalidations of the same\n * query, in ms (default 5000). `focus` fires on far more than tab returns —\n * dismissing a file picker, closing a popup, clicking in and out of an\n * embedded iframe — and `staleTime: 0` would otherwise turn each of those\n * into a request per mounted query.\n */\n focusThrottleInterval?: number;\n /** How long cached data stays fresh before a read revalidates it, in ms. */\n staleTime?: number;\n debug?: boolean;\n lazy?: boolean;\n /**\n * When true (the default), a query with no cached data suspends the nearest\n * `Suspense` boundary instead of returning `loading: true`, and an HTTP\n * failure throws into the nearest error boundary. `lazy: true` implies\n * `suspense: false`.\n */\n suspense?: boolean;\n refetchUntil?: (data: T, duration: number) => number;\n}\n\ntype WithOptionalValues<T> = {\n [K in keyof T]: T[K] | null;\n};\n\nconst defaultConfig: Config<any> = {\n fallbackData: null,\n keepPreviousData: true,\n retryIntervalOnError: 10000,\n refreshInterval: 999999,\n revalidateOnFocus: false,\n focusThrottleInterval: 5000,\n staleTime: DEFAULT_STALE_TIME,\n debug: false,\n lazy: false,\n suspense: true,\n};\n\ntype GetRPC = {\n [K in keyof RPC as K extends `GET:${infer P}` ? P : never]: RPC[K];\n};\n\ntype Data<T extends keyof GetRPC> =\n GetRPC[T] extends ApiRouterHandler<any, infer Data, any>\n ? UnwrapPromise<Data>\n : never;\n\ntype Input<T extends keyof GetRPC> =\n GetRPC[T] extends ApiRouterHandler<infer I, any, any> ? I : never;\n\ntype QueryOptions<T extends keyof GetRPC> = {\n search?: Partial<WithOptionalValues<Input<T>>>;\n};\n\ntype Error = Record<string, unknown>;\n\nconst defaultOptions: QueryOptions<any> & { params?: Record<string, any> } = {\n params: {} as Record<string, string>,\n search: {} as Record<string, string>,\n};\n\nexport type QueryResult<T extends keyof GetRPC> = NestedPrettify<Data<T> & {}>;\n\ntype Options<T extends keyof GetRPC> = {\n search?: Record<string, string | number | boolean | null>;\n params?: Partial<UrlParser<`${T & string}`>>;\n};\n\ninterface QueryReturn<T extends keyof GetRPC, D> {\n data: D;\n loading: boolean;\n error: Error;\n mutate: {\n (fn?: NestedPrettify<Data<T>>): void;\n (fn?: (data: NestedPrettify<Data<T>>) => NestedPrettify<Data<T>>): void;\n };\n trigger: () => void;\n prefetch: () => void;\n refetch: () => void;\n version: number;\n}\n\n/**\n * A suspense-enabled query never renders without data, so `data` is\n * non-nullable. Opting out — `suspense: false` or `lazy: true` — brings back\n * the `loading` flag and with it a `data` that can be `undefined`.\n */\ninterface SuspenseConfig<T> extends Omit<Config<T>, \"suspense\" | \"lazy\"> {\n suspense?: true;\n lazy?: false;\n}\n\n/** A per-call `suspense: true` opt-in — wins over an app-wide `suspense: false`. */\ninterface ExplicitSuspenseConfig<T> extends Omit<\n Config<T>,\n \"suspense\" | \"lazy\"\n> {\n suspense: true;\n lazy?: false;\n}\n\n/**\n * The type-level mirror of a provider-level `queryConfig: { suspense: false }`.\n * The `useQuery` overloads reflect the call site only — they cannot see the\n * value threaded through `createRoot` — so an app that turns suspense off\n * app-wide flips the default `data` nullability with the same\n * module-augmentation switch RPC types use:\n *\n * ```ts\n * declare module \"gemi/client\" {\n * interface GemiQueryDefaults {\n * suspense: false;\n * }\n * }\n * ```\n *\n * A per-call `suspense: true` still narrows `data` back to non-nullable.\n */\nexport interface GemiQueryDefaults {}\n\ntype DefaultData<T extends keyof GetRPC> = GemiQueryDefaults extends {\n suspense: false;\n}\n ? NestedPrettify<Data<T>> | undefined\n : NestedPrettify<Data<T>>;\n\nexport function useQuery<T extends keyof GetRPC>(\n url: T,\n options: Options<T> | undefined,\n config: ExplicitSuspenseConfig<Data<T>>,\n): QueryReturn<T, NestedPrettify<Data<T>>>;\nexport function useQuery<T extends keyof GetRPC>(\n url: T,\n options?: Options<T>,\n config?: SuspenseConfig<Data<T>>,\n): QueryReturn<T, DefaultData<T>>;\nexport function useQuery<T extends keyof GetRPC>(\n url: T,\n options?: Options<T>,\n config?: Config<Data<T>>,\n): QueryReturn<T, NestedPrettify<Data<T>> | undefined>;\nexport function useQuery<T extends keyof GetRPC>(\n url: T,\n ...args: [options?: Options<T>, config?: Config<Data<T>>]\n) {\n const [options, config] = args;\n // Resolution order: per-call config → provider `queryConfig` → framework\n // defaults. The first two merge here; `useFrameworkQuery` applies the last.\n // Only *defined* per-call keys participate: a key explicitly set to\n // `undefined` (`{ suspense: cond ? true : undefined }`, forwarding an\n // optional prop) must fall through to the provider default, not clobber it\n // — a plain spread would copy the `undefined` over it. The provider value\n // is already sanitized at the provider (see `QueryManagerProvider`).\n const queryConfig = useContext(QueryConfigContext);\n const merged: Config<Data<T>> = { ...queryConfig };\n if (config) {\n for (const key of Object.keys(config) as Array<keyof Config<Data<T>>>) {\n if (config[key] !== undefined) {\n (merged as Record<string, unknown>)[key] = config[key];\n }\n }\n }\n return useFrameworkQuery(url, options, merged);\n}\n\n/**\n * `useQuery` minus the app's provider-level `queryConfig`: per-call config\n * resolves straight against the framework defaults. Framework-internal hooks\n * (`useUser`'s `suspense: false`, `useSignIn`'s `lazy`) build on this so an\n * app-wide `queryConfig` can never change their semantics. Deliberately not\n * exported from the package root.\n */\nexport function useFrameworkQuery<T extends keyof GetRPC>(\n url: T,\n ...args: [options?: Options<T>, config?: Config<Data<T>>]\n): QueryReturn<T, NestedPrettify<Data<T>> | undefined> {\n const _params = useParams();\n const [_options = defaultOptions, _config = defaultConfig] = args;\n const options = { ...defaultOptions, ..._options };\n const config = { ...defaultConfig, ..._config };\n const suspense = config.suspense !== false && !config.lazy;\n const params =\n \"params\" in options ? { ..._params, ...options.params } : _params;\n const search = \"search\" in options ? (options.search ?? {}) : {};\n const { getResource } = useContext(QueryManagerContext);\n const serverQueries = useContext(ServerQueryContext);\n const currentPath = applyParams(url, params);\n const currentVariantKey = toVariantKey(search);\n // `keepPreviousData` under suspense: read through deferred keys so a\n // variant change never suspends the committed tree. The urgent render keeps\n // showing the previous variant's data; React re-renders in the background\n // with the new keys, suspends *that* attempt only (no fallback flash), and\n // commits when the data lands — no `startTransition` needed at the call\n // site. First mount is unchanged: deferred and current keys are equal, so\n // an uncached query suspends into the segment fallback as today. Both hooks\n // run unconditionally (hook order); the values are only *used* when\n // deferring applies.\n //\n // Deliberate: during the pending window the imperative callbacks\n // (`mutate`/`refetch`/`trigger`/`prefetch`) and the revalidation effects\n // close over the deferred — i.e. *visible* — variant and resource, so they\n // act on the data the user is looking at, not the variant still loading in\n // the background. The window ends when the deferred render commits, at\n // which point they re-bind to the new keys.\n const deferredPath = useDeferredValue(currentPath);\n const deferredVariantKey = useDeferredValue(currentVariantKey);\n const deferVariant = suspense && config.keepPreviousData;\n const normalPath = deferVariant ? deferredPath : currentPath;\n const variantKey = deferVariant ? deferredVariantKey : currentVariantKey;\n // The pending signal for pager UI: true while the visible data belongs to\n // the previous variant and the new one is still loading in the background.\n const isDeferred =\n normalPath !== currentPath || variantKey !== currentVariantKey;\n const { prefetchedData } = useRouteData();\n // `fallbackData` is a single variant's value, so it seeds under this\n // query's variant key; `prefetchedData[normalPath]` is already the full\n // `{ [variantKey]: data }` map the server produced.\n const seed =\n config.fallbackData != null\n ? { [variantKey]: config.fallbackData }\n : prefetchedData?.[normalPath];\n // A memoized map lookup on the provider's ref: stable and cheap, so the\n // resource is derived every render — a params change swaps it in the same\n // render pass instead of flashing through an effect.\n const resource = getResource(normalPath, seed ?? undefined);\n const lazy = config.lazy;\n\n const configRef = useRef(config);\n configRef.current = config;\n\n const refreshIntervalRef = useRef<ReturnType<typeof setInterval> | null>(\n null,\n );\n const retryIntervalRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const retryingMap = useRef<Map<string, boolean>>(new Map());\n const fetchedRef = useRef(!lazy);\n const refetchUntilTimerRef = useRef<ReturnType<typeof setTimeout> | null>(\n null,\n );\n const refetchUntilDurationRef = useRef(0);\n const prefetchedRef = useRef(false);\n // Focus revalidation eligibility, deliberately *not* `fetchedRef`: that one\n // is flipped by `prefetch()` too, and a hover prefetch is documented as\n // \"fetch once\" for data the user may never look at — enrolling it in focus\n // revalidation would keep re-requesting it for the life of the component.\n // Only the reads that put data on screen (`trigger`, `refetch`, `mutate`,\n // or simply not being lazy) count.\n const focusEligibleRef = useRef(!lazy);\n // The away latch: `focus` fires for things that never left the page —\n // dismissing an `alert`, returning from devtools — so a revalidation is only\n // owed when the window actually lost focus or the tab was hidden first.\n const wasAwayRef = useRef(false);\n const lastFocusRevalidationRef = useRef(0);\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => resource.store.subscribe(onStoreChange),\n [resource],\n );\n // `peek` hands back the object stored in the map — its identity only\n // changes on a real write, so the snapshot is stable across render\n // attempts. Also the server snapshot: SSR renders whatever the prefetch\n // payload seeded, and never fetches.\n //\n // uSES and transitions: store updates are always urgent, so a write landing\n // mid-transition restarts the pending transition — wasted work, never wrong\n // UI. Exposure is kept small by design: render-phase reads never write the\n // store synchronously (fetches are silent), and a suspended component has no\n // subscription — it is woken by its thrown promise, not the store. The\n // navigation-shaped consequences are pinned in `useQuery.transition.test.tsx`.\n const getSnapshot = useCallback(\n () => resource.peek(variantKey),\n [resource, variantKey],\n );\n const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n // `keepPreviousData`: remember the last snapshot that had data, and show it\n // whenever the current one is loading without data (e.g. a variant change\n // with `suspense: false`). Presence is `hasData`, never `data`'s truthiness\n // — `null`/`0`/`false`/`\"\"` are legitimate response bodies.\n const lastDataRef = useRef(snapshot?.hasData ? snapshot : null);\n useEffect(() => {\n if (snapshot?.hasData) {\n lastDataRef.current = snapshot;\n }\n }, [snapshot]);\n\n let state = snapshot;\n if (\n config.keepPreviousData &&\n !snapshot?.hasData &&\n snapshot?.loading &&\n lastDataRef.current\n ) {\n state = { ...lastDataRef.current, loading: true };\n }\n\n // The render-phase read for the suspense path. Only when there is nothing\n // to show — data in hand always renders, and revalidation stays where it\n // was (the mount effect below). Both reads dedupe across the render\n // attempts React discards, so this is safe to hit on every attempt.\n //\n // On a streaming server render the read goes to the request's\n // `ServerQueryStore` instead of the client resource: a prefetched query is\n // already in flight there and is joined, an undiscovered one starts now\n // (the store logs the late-discovery hint when that cost something).\n let readPromise: Promise<void> | undefined;\n let serverError: unknown;\n if (suspense && !state?.hasData && !state?.error) {\n if (typeof window === \"undefined\") {\n if (serverQueries) {\n const entry = serverQueries.ensure(url, { params, search });\n if (entry.status === \"resolved\") {\n state = {\n loading: false,\n data: entry.data,\n hasData: true,\n error: null,\n version: 0,\n };\n } else if (entry.status === \"rejected\") {\n serverError = entry.error;\n } else {\n readPromise = entry.promise;\n }\n }\n } else {\n readPromise = resource.read(variantKey, config.staleTime).promise;\n }\n }\n\n if (\n suspense &&\n typeof window === \"undefined\" &&\n !serverQueries &&\n !state?.hasData &&\n process.env.NODE_ENV !== \"production\"\n ) {\n const searchHint = variantKey\n ? `, { search: ${JSON.stringify(\n Object.fromEntries(new URLSearchParams(variantKey)),\n )} }`\n : \"\";\n console.warn(\n `[gemi] useQuery(\"${url}\") rendered on the server without data. ` +\n `The server never fetches, so this page ships without it and the ` +\n `client suspends after hydration. Add ` +\n `\\`Query.prefetch(\"${url}\"${searchHint})\\` to the route's view handler.`,\n );\n }\n\n const retry = useCallback(\n (vk: string) => {\n if (!retryingMap.current.get(vk)) {\n if (configRef.current.debug) console.log(\"retrying\", vk);\n retryingMap.current.set(vk, true);\n retryIntervalRef.current = setTimeout(() => {\n resource.getVariant(vk, configRef.current.staleTime);\n retryingMap.current.set(vk, false);\n }, configRef.current.retryIntervalOnError);\n }\n },\n [resource],\n );\n\n // Mount / variant-change revalidation — unchanged semantics: `getVariant`\n // fetches when the variant is missing or stale, and now joins an in-flight\n // render-initiated read instead of racing it.\n useEffect(() => {\n if (fetchedRef.current) {\n resource.getVariant(variantKey, configRef.current.staleTime);\n }\n return () => {\n clearTimeout(retryIntervalRef.current);\n };\n }, [variantKey, resource]);\n\n // With `suspense: false` an error is returned and retried in the\n // background; under suspense it throws below instead.\n useEffect(() => {\n if (!suspense && snapshot?.error) {\n retry(variantKey);\n }\n }, [snapshot, suspense, retry, variantKey]);\n\n useEffect(() => {\n const cfg = configRef.current;\n if (!cfg.refetchUntil) return;\n if (snapshot && !snapshot.loading && snapshot.hasData && !snapshot.error) {\n const nextDuration = cfg.refetchUntil(\n snapshot.data,\n refetchUntilDurationRef.current,\n );\n if (nextDuration > 0) {\n refetchUntilDurationRef.current = nextDuration;\n refetchUntilTimerRef.current = setTimeout(() => {\n resource.refetch(variantKey);\n }, nextDuration);\n } else {\n refetchUntilDurationRef.current = 0;\n }\n }\n return () => {\n if (refetchUntilTimerRef.current) {\n clearTimeout(refetchUntilTimerRef.current);\n }\n };\n }, [snapshot, resource, variantKey]);\n\n const handleReload = useCallback(() => {\n if (configRef.current.debug) {\n console.log(\"Reloading query for\", variantKey);\n }\n const data = resource.getVariant(\n variantKey,\n configRef.current.staleTime,\n ).data;\n resource.mutate(variantKey, () => data);\n }, [variantKey, resource]);\n\n useEffect(() => {\n if (!fetchedRef.current) return;\n refreshIntervalRef.current = setInterval(() => {\n handleReload();\n }, config.refreshInterval);\n\n return () => {\n if (refreshIntervalRef.current) {\n clearInterval(refreshIntervalRef.current);\n }\n };\n }, [config.refreshInterval, handleReload]);\n\n // Revalidate when the tab comes back to the foreground — opt-in via\n // `revalidateOnFocus` (per call or app-wide). `resource.revalidate` applies\n // `staleTime` like the mount effect does, but always fetches silently, so\n // data still inside its freshness window is left alone and anything older\n // is refreshed without what's on screen ever flashing a loading state.\n //\n // Three guards decide whether a return to the foreground is owed a request,\n // because `focus` alone is a poor proxy for one:\n // - eligibility — an untriggered lazy query has nothing on screen;\n // - the away latch — `focus` also fires for a dismissed `alert` or a\n // closed devtools pane, neither of which is a return from anywhere;\n // - the throttle — clicking in and out of an embedded iframe (a payment\n // form, a video) blurs and focuses the window every time, and `focus`\n // runs this for *every* mounted query, so a dashboard would otherwise\n // fire a dozen requests per interaction under `staleTime: 0`.\n //\n // Both events are listened for because neither covers the other: switching\n // between windows fires `focus` while the document stays visible, and\n // switching tabs (or unlocking the device) fires `visibilitychange` without\n // necessarily firing `focus`. They land on one guarded call, so the overlap\n // costs nothing — the latch is already spent by the time the second fires.\n useEffect(() => {\n if (!config.revalidateOnFocus) return;\n const markAway = () => {\n wasAwayRef.current = true;\n };\n const revalidate = () => {\n if (!focusEligibleRef.current) return;\n if (document.visibilityState === \"hidden\") return;\n if (!wasAwayRef.current) return;\n const now = Date.now();\n // Throttled: leave the latch armed so the next return, once the\n // interval has passed, still revalidates.\n if (\n now - lastFocusRevalidationRef.current <\n configRef.current.focusThrottleInterval\n ) {\n return;\n }\n wasAwayRef.current = false;\n lastFocusRevalidationRef.current = now;\n resource.revalidate(variantKey, configRef.current.staleTime);\n };\n const onVisibilityChange = () => {\n if (document.visibilityState === \"hidden\") {\n markAway();\n } else {\n revalidate();\n }\n };\n window.addEventListener(\"blur\", markAway);\n window.addEventListener(\"focus\", revalidate);\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n return () => {\n window.removeEventListener(\"blur\", markAway);\n window.removeEventListener(\"focus\", revalidate);\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n };\n }, [config.revalidateOnFocus, resource, variantKey]);\n\n useEffect(() => {\n // Feature-checked per method: vitest's `import.meta.hot` shim has `on`\n // but not `off`.\n // @ts-ignore\n if (typeof import.meta.hot?.on === \"function\") {\n // @ts-ignore\n import.meta.hot.on(\"http-reload\", handleReload);\n }\n return () => {\n // @ts-ignore\n if (typeof import.meta.hot?.off === \"function\") {\n // @ts-ignore\n import.meta.hot.off(\"http-reload\", handleReload);\n }\n };\n }, [handleReload]);\n\n const trigger = useCallback(() => {\n fetchedRef.current = true;\n focusEligibleRef.current = true;\n const store = resource.store.getValue();\n const variant = store.get(variantKey);\n if (!variant || (!variant.loading && !variant.hasData)) {\n resource.refetch(variantKey);\n }\n }, [resource, variantKey]);\n\n const prefetch = useCallback(() => {\n if (prefetchedRef.current) return;\n prefetchedRef.current = true;\n fetchedRef.current = true;\n // `read`, not `refetch`: a suspending read that follows joins this\n // request instead of racing it, and fresh data is a no-op.\n resource.read(variantKey, configRef.current.staleTime);\n }, [resource, variantKey]);\n\n const refetch = useCallback(() => {\n fetchedRef.current = true;\n focusEligibleRef.current = true;\n resource.refetch(variantKey);\n }, [resource, variantKey]);\n\n function mutate(fn?: NestedPrettify<Data<T>>): void;\n function mutate(\n fn?: (data: NestedPrettify<Data<T>>) => NestedPrettify<Data<T>>,\n ): void;\n function mutate(fn?: any) {\n // Either form ends in a fetch whose result the component renders, so a\n // lazy query mutated by hand is as focus-eligible as a triggered one.\n focusEligibleRef.current = true;\n if (!fn) {\n fetchedRef.current = true;\n resource.refetch(variantKey);\n return;\n }\n return resource.mutate(variantKey, (data: any) => {\n // `null` is a legitimate cached body; only `undefined` means the query\n // hasn't produced anything (and `mutate` refetches instead of calling\n // this in that case).\n if (data === undefined) {\n console.warn(\"Mutate function called before the query.\");\n return data;\n }\n\n // The callback's return value *replaces* the cached data. The type checks\n // below only ensure the shape matches so a stray value can't corrupt the\n // cache; they do not merge or append.\n const updatedData = typeof fn === \"function\" ? fn(data) : fn;\n\n if (isPlainObject(data)) {\n if (isPlainObject(updatedData)) {\n return updatedData;\n }\n throw new Error(\n \"Mutate function must return an object when the current data is an object.\",\n );\n }\n\n if (Array.isArray(data)) {\n if (Array.isArray(updatedData)) {\n return updatedData;\n }\n throw new Error(\n \"Mutate function must return an array when the current data is an array.\",\n );\n }\n\n if (typeof data !== typeof updatedData) {\n throw new Error(\n \"Mutate function must return the same type as the current data.\",\n );\n }\n\n return updatedData;\n });\n }\n\n // Suspend last, after every hook has run: the attempt React discards ran\n // them all, and the retry re-runs them identically. The promise is *thrown*\n // rather than passed to `use()` — the thenable-throw protocol is what\n // React's ping-and-retry machinery is built around (React.lazy, SWR, React\n // Query), whereas `use()` on a client-created promise is documented as\n // unsupported outside a Suspense-compatible framework and React never\n // retries it. A streaming server render takes the same paths: a pending\n // entry suspends (React streams the fallback and resumes on settle), and a\n // rejected one throws so the segment falls back to client rendering, where\n // the browser's own fetch surfaces the error into the boundary.\n if (suspense) {\n if (serverError) {\n throw serverError;\n }\n if (state?.error && !state?.hasData) {\n throw state.error;\n }\n if (!state?.hasData && readPromise) {\n throw readPromise;\n }\n }\n\n return {\n data: state?.data as NestedPrettify<Data<T>>,\n loading: isDeferred || (state?.loading ?? !lazy),\n error: state?.error as Error,\n mutate,\n trigger,\n prefetch,\n refetch,\n version: state?.version as number,\n };\n}\n","import { useContext, useRef, useState } from \"react\";\nimport type { RPC } from \"./rpc\";\nimport type { ApiRouterHandler } from \"../http/ApiRouter\";\nimport type { UnwrapPromise } from \"../utils/type\";\nimport type { UrlParser } from \"./types\";\nimport { useParams } from \"./useParams\";\nimport { ClientRouterContext } from \"./ClientRouterContext\";\n\ntype Methods = {\n POST: {\n [K in keyof RPC as K extends `POST:${infer P}` ? P : never]: RPC[K];\n };\n PUT: {\n [K in keyof RPC as K extends `PUT:${infer P}` ? P : never]: RPC[K];\n };\n PATCH: {\n [K in keyof RPC as K extends `PATCH:${infer P}` ? P : never]: RPC[K];\n };\n DELETE: {\n [K in keyof RPC as K extends `DELETE:${infer P}` ? P : never]: RPC[K];\n };\n};\n\nfunction applyParams(url: string, params: Record<string, any> = {}) {\n let out = url;\n\n for (const [key, value] of Object.entries(params)) {\n out = out.replace(`:${key}?`, value).replace(`:${key}`, value);\n }\n return out;\n}\n\ntype Config<T> = {\n autoInvalidate?: boolean;\n onSuccess: (data: T) => void;\n onError: (error: MutationError) => void;\n onCanceled?: () => void;\n};\n\nconst defaultOptions: Config<any> = {\n autoInvalidate: false,\n onSuccess: () => {},\n onError: (_: MutationError) => {},\n onCanceled: () => {},\n};\n\ntype Data<\n M extends keyof Methods,\n K extends keyof Methods[M],\n> = Methods[M][K] extends ApiRouterHandler<any, infer T, any>\n ? UnwrapPromise<T>\n : never;\n\ntype Body<\n M extends keyof Methods,\n K extends keyof Methods[M],\n> = Methods[M][K] extends ApiRouterHandler<infer T, any, any> ? T : never;\n\ntype MutationError =\n | {\n kind: \"validation_error\";\n messages: Record<string, any>;\n }\n | {\n kind: \"form_error\";\n message: string;\n }\n | {\n kind: \"server_error\";\n message: string;\n }\n | {\n kind: \"not_authorized\";\n message: string;\n }\n | {\n kind: \"insufficient_permissions\";\n message: string;\n };\n\ntype ParseParams<T> = UrlParser<`${T & string}`>;\n\ntype State<T> = {\n data: T | null;\n error: MutationError | null;\n loading: boolean;\n};\n\nexport function useMutation<\n M extends keyof Methods,\n K extends keyof Methods[M],\n T = Data<M, K>,\n U = Body<M, K>,\n>(\n method: M,\n url: K,\n ...args: [\n options?: { params?: Partial<ParseParams<K>>, search?: Record<string, string> },\n config?: Partial<Config<T>>,\n ]\n) {\n const _params = useParams();\n // A write may have moved the data behind any page warmed ahead of a click,\n // and a prefetched payload is committed wholesale — into the query cache too.\n const { clearPrefetchCache } = useContext(ClientRouterContext);\n const [state, setState] = useState<State<T>>({\n data: null,\n error: null,\n loading: false,\n });\n\n const [abortController, setAbortController] = useState(\n () => new AbortController(),\n );\n\n const formData = useRef(new FormData());\n\n async function trigger(input?: U): Promise<T> {\n setState({\n data: state.data,\n error: state.error,\n loading: true,\n });\n const [inputs = {}, options = defaultOptions] = args ?? [];\n const params =\n \"params\" in inputs ? { ..._params, ...inputs.params } : _params;\n const search = \"search\" in inputs ? inputs.search : {};\n const searchParams = new URLSearchParams(search);\n const finalUrl = [applyParams(String(url).replace(`${method}:`, \"\"), params), searchParams.toString()].filter(Boolean).join(\"?\");\n\n let body = null;\n\n const contentType =\n typeof input === \"undefined\" || input instanceof FormData\n ? {}\n : { \"Content-Type\": \"application/json\" };\n\n if (input instanceof FormData) {\n body = input;\n } else if (typeof input === \"undefined\") {\n body = formData.current;\n } else if (input) {\n body = JSON.stringify(input);\n }\n\n try {\n const response = await fetch(`/api${finalUrl}`, {\n method,\n headers: {\n ...contentType,\n },\n ...(body ? { body } : {}),\n signal: abortController.signal,\n });\n\n formData.current = new FormData();\n\n const data = await response.json();\n\n if (!response.ok) {\n setState({\n data: null,\n error: data.error,\n loading: false,\n });\n\n options?.onError?.(data);\n return;\n }\n\n clearPrefetchCache?.();\n options.onSuccess(data);\n\n setState({\n data,\n error: null,\n loading: false,\n });\n\n return data as any;\n } catch (error) {\n formData.current = new FormData();\n options?.onError?.(error);\n setState({\n data: null,\n error,\n loading: false,\n });\n }\n }\n\n trigger.formData = (formData: FormData) => {\n return trigger(formData as U);\n };\n\n return {\n data: state.data as T,\n error: state.error as any,\n loading: state.loading,\n formData: formData.current,\n cancel: () => {\n const [, options = defaultOptions] = args ?? [];\n abortController.abort();\n setAbortController(new AbortController());\n setState({\n data: state.data,\n error: state.error,\n loading: false,\n });\n\n formData.current = new FormData();\n options.onCanceled();\n },\n trigger,\n };\n}\n\nexport function usePost<K extends keyof Methods[\"POST\"], T = Data<\"POST\", K>>(\n url: K,\n ...args: [\n options?: { params?: Partial<ParseParams<K>> },\n config?: Partial<Config<T>>,\n ]\n) {\n return useMutation(\"POST\", url, ...(args as any));\n}\n\nexport function usePut<K extends keyof Methods[\"PUT\"], T = Data<\"PUT\", K>>(\n url: K,\n ...args: [\n options?: { params?: Partial<ParseParams<K>> },\n config?: Partial<Config<T>>,\n ]\n) {\n return useMutation(\"PUT\", url, ...(args as any));\n}\n\nexport function usePatch<\n K extends keyof Methods[\"PATCH\"],\n T = Data<\"PATCH\", K>,\n>(\n url: K,\n ...args: [\n options?: { params?: Partial<ParseParams<K>> },\n config?: Partial<Config<T>>,\n ]\n) {\n return useMutation(\"PATCH\", url, ...(args as any));\n}\n\nexport function useDelete<\n K extends keyof Methods[\"DELETE\"],\n T = Data<\"DELETE\", K>,\n>(\n url: K,\n ...args: [\n options?: { params?: Partial<ParseParams<K>> },\n config?: Partial<Config<T>>,\n ]\n) {\n return useMutation(\"DELETE\", url, ...(args as any));\n}\n\nexport function useUpload<K extends keyof Methods[\"POST\"], T = Data<\"POST\", K>>(\n url: K,\n ...args: [\n options?: { params?: Partial<ParseParams<K>> },\n config?: Partial<Config<T>>,\n ]\n) {\n const [state, setState] = useState<\"idle\" | \"uploading\" | \"done\" | \"error\">(\n \"idle\",\n );\n const [progress, setProgress] = useState(0);\n const _params = useParams();\n const { clearPrefetchCache } = useContext(ClientRouterContext);\n const abortRef = useRef<VoidFunction | null>(null);\n\n const [inputs = {}, options = defaultOptions] = args ?? [];\n\n const cancel = () => {\n if (abortRef.current) {\n abortRef.current();\n options.onCanceled?.();\n setState(\"idle\");\n setProgress(0);\n }\n };\n\n const trigger = async (fileList: FileList | null | File): Promise<T> => {\n if (!fileList) {\n return;\n }\n const params =\n \"params\" in inputs ? { ..._params, ...inputs.params } : _params;\n const finalUrl = applyParams(String(url).replace(\"POST:\", \"\"), params);\n\n const method = \"POST\";\n const action = `/api${finalUrl}`;\n const data = new FormData();\n if (fileList instanceof FileList) {\n for (const file of Array.from(fileList)) {\n data.append(\"file\", file);\n }\n } else {\n data.append(\"file\", fileList);\n }\n const xhr = new XMLHttpRequest();\n abortRef.current = () => {\n xhr.abort();\n };\n\n try {\n const result = await new Promise<Response>((resolve, reject) => {\n xhr.responseType = \"blob\";\n xhr.onreadystatechange = async () => {\n if (xhr.readyState !== 4) {\n // done\n return;\n }\n\n const response = new Response(xhr.response, {\n status: xhr.status,\n statusText: xhr.statusText,\n });\n\n resolve(response);\n };\n\n xhr.addEventListener(\"error\", () => {\n reject(new TypeError(\"Failed to fetch\"));\n });\n\n xhr.upload.addEventListener(\"loadstart\", () => {\n setProgress(0);\n });\n xhr.upload.addEventListener(\"loadend\", () => {\n setProgress(1);\n });\n\n xhr.upload.addEventListener(\"progress\", (event) => {\n setProgress(event.loaded / event.total);\n });\n\n xhr.open(method, action, true);\n xhr.send(data);\n });\n setState(\"uploading\");\n if (!result.ok) {\n let error: MutationError = {\n kind: \"server_error\",\n message: result.statusText,\n };\n try {\n const data = await result.json();\n error = data.error;\n } catch (e) {\n // do nothing\n }\n setState(\"error\");\n options?.onError?.(error);\n return;\n }\n const json = await result.json();\n clearPrefetchCache?.();\n options?.onSuccess?.(json);\n return json;\n } catch (error) {\n setState(\"error\");\n options?.onError?.(error);\n return;\n }\n };\n\n return {\n state,\n progress,\n trigger,\n cancel,\n };\n}\n","import { useContext } from \"react\";\nimport type { ApiRouterHandler } from \"../http/ApiRouter\";\nimport type { NestedPrettify, UnwrapPromise } from \"../utils/type\";\nimport { isPlainObject } from \"./isPlainObject\";\n\nimport type { RPC } from \"./rpc\";\nimport { QueryManagerContext } from \"./QueryManagerContext\";\nimport type { UrlParser } from \"./types\";\nimport { applyParams } from \"../utils/applyParams\";\nimport { toVariantKey } from \"../utils/variantKey\";\ntype GetRPC = {\n [K in keyof RPC as K extends `GET:${infer P}` ? P : never]: RPC[K];\n};\n\ntype Data<T extends keyof GetRPC> =\n GetRPC[T] extends ApiRouterHandler<any, infer Data, any>\n ? UnwrapPromise<Data>\n : never;\n\nexport function useMutate() {\n const { getResource } = useContext(QueryManagerContext);\n return function mutate<T extends keyof GetRPC>(\n options: {\n path: T;\n params?: UrlParser<`${T & string}`>;\n search?: Record<string, any>;\n },\n fn?:\n | ((data: NestedPrettify<Data<T>>) => NestedPrettify<Data<T>>)\n | NestedPrettify<Data<T>>,\n ) {\n const { path, params = {}, search = {} } = options ?? {};\n const normalPath = applyParams(path, params);\n const resource = getResource(normalPath);\n const variantKey = toVariantKey(search);\n return resource.mutate.call(resource, variantKey, (data: any) => {\n if (data === undefined || data === null) {\n console.warn(\"Mutate function called before the query.\");\n return data;\n }\n\n if (!fn) {\n return data;\n }\n\n // The callback's return value *replaces* the cached data. The type checks\n // below only ensure the shape matches; they do not merge or append.\n const updatedData = typeof fn === \"function\" ? fn(data) : fn;\n\n if (isPlainObject(data)) {\n if (isPlainObject(updatedData)) {\n return updatedData;\n }\n throw new Error(\n \"Mutate function must return an object when the current data is an object.\",\n );\n }\n\n if (Array.isArray(data)) {\n if (Array.isArray(updatedData)) {\n return updatedData;\n }\n throw new Error(\n \"Mutate function must return an array when the current data is an array.\",\n );\n }\n\n if (typeof data !== typeof updatedData) {\n throw new Error(\n \"Mutate function must return the same type as the current data.\",\n );\n }\n\n return updatedData;\n });\n };\n}\n","import {\n createContext,\n useContext,\n type ComponentProps,\n type FormEvent,\n useRef,\n useEffect,\n useSyncExternalStore,\n useCallback,\n} from \"react\";\nimport type { RPC } from \"./rpc\";\nimport type { ApiRouterHandler } from \"../http/ApiRouter\";\nimport { useMutation } from \"./useMutation\";\nimport type { UnwrapPromise } from \"../utils/type\";\nimport type { UrlParser } from \"./types\";\nimport { useParams } from \"./useParams\";\nimport { ServerDataContext } from \"./ServerDataProvider\";\nimport { Subject } from \"../utils/Subject\";\n\ntype Any = any;\n\ninterface MutationContextValue {\n isPending: boolean;\n result: null | Any;\n validationErrors: Record<string, string[]>;\n formError: null | string;\n formDataSubject: React.RefObject<Subject<FormData>>;\n}\n\nconst MutationContext = createContext({\n isPending: false,\n result: null,\n} as MutationContextValue);\n\ntype GetResult<T> =\n T extends ApiRouterHandler<Any, infer Result, Any>\n ? UnwrapPromise<Result>\n : never;\n\ntype PostRequests = {\n [K in keyof RPC as K extends `POST:${infer P}` ? P : never]: GetResult<\n RPC[K]\n >;\n};\n\ntype PutRequests = {\n [K in keyof RPC as K extends `PUT:${infer P}` ? P : never]: GetResult<RPC[K]>;\n};\n\ntype DeleteRequests = {\n [K in keyof RPC as K extends `DELETE:${infer P}` ? P : never]: GetResult<\n RPC[K]\n >;\n};\n\ntype PatchRequests = {\n [K in keyof RPC as K extends `PATCH:${infer P}` ? P : never]: GetResult<\n RPC[K]\n >;\n};\n\ntype Methods = {\n POST: PostRequests;\n PUT: PutRequests;\n DELETE: DeleteRequests;\n PATCH: PatchRequests;\n};\n\ninterface FormProps<\n M extends keyof Methods,\n K extends keyof Methods[M],\n> extends Omit<ComponentProps<\"form\">, \"action\" | \"onError\"> {\n method?: M;\n action: K;\n onSuccess?: (result: Methods[M][K], form: HTMLFormElement) => void;\n onError?: (error: Any, form: HTMLFormElement) => void;\n params?: Partial<UrlParser<`${K & string}`>>;\n search?: Record<string, string>;\n dynamicInputs?: (formData: FormData) => Record<string, any>;\n}\n\nexport function Form<\n K extends keyof Methods[T],\n T extends keyof Methods = \"POST\",\n>(props: FormProps<T, K>) {\n const _params = useParams();\n const {\n method = \"POST\",\n action,\n onSuccess = () => {},\n onError = () => {},\n params,\n search = {},\n className,\n dynamicInputs = () => ({}),\n ...formProps\n } = \"params\" in props\n ? { ...props, params: { ..._params, ...props.params } }\n : { ...props, params: _params };\n const formRef = useRef<HTMLFormElement>(null);\n const { __csrf } = useContext(ServerDataContext);\n const formDataSubject = useRef(new Subject(new FormData()));\n\n const updateFormData = useCallback(() => {\n formDataSubject.current.next(new FormData(formRef.current));\n }, []);\n\n useEffect(() => {\n if (!formRef.current) return;\n\n formRef.current.addEventListener(\"input\", updateFormData);\n\n const observer = new MutationObserver(() => {\n const formData = new FormData(formRef.current);\n formDataSubject.current.next(formData);\n });\n\n formRef.current.querySelectorAll(\"input\").forEach((input) =>\n observer.observe(input, {\n attributes: true,\n attributeFilter: [\"value\"],\n }),\n );\n\n formRef.current.querySelectorAll(\"select\").forEach((input) =>\n observer.observe(input, {\n attributes: true,\n attributeFilter: [\"value\"],\n }),\n );\n\n formRef.current.querySelectorAll(\"textarea\").forEach((input) =>\n observer.observe(input, {\n attributes: true,\n attributeFilter: [\"value\"],\n }),\n );\n\n return () => {\n observer.disconnect();\n if (formRef.current) {\n formRef.current.removeEventListener(\"input\", updateFormData);\n }\n };\n }, [updateFormData]);\n\n const { trigger, data, error, loading } = useMutation(\n method,\n String(action) as Any,\n {\n params,\n search,\n } as Any,\n {\n onSuccess: (data) => onSuccess(data as Any, formRef.current),\n onError: (error) => onError(error, formRef.current),\n },\n );\n\n const handleSubmit = async (e: FormEvent) => {\n if (loading) {\n return;\n }\n e.preventDefault();\n if (!formRef.current) {\n return;\n }\n const formData = new FormData(formRef.current);\n for (const [key, value] of Object.entries(dynamicInputs(formData))) {\n formData.append(key, value as any);\n }\n trigger(formData as any);\n };\n\n const validationErrors =\n error?.kind === \"validation_error\" ? error.messages : {};\n\n const formError = error?.kind === \"form_error\" ? error.message : null;\n\n return (\n <MutationContext.Provider\n value={{\n isPending: loading,\n result: data,\n validationErrors,\n formError,\n formDataSubject,\n }}\n >\n <form\n className={[\"group\", className].filter(Boolean).join(\" \")}\n data-loading={loading}\n ref={formRef}\n onSubmit={handleSubmit}\n {...formProps}\n >\n <input type=\"hidden\" name=\"__csrf\" value={__csrf} />\n {props.children}\n </form>\n </MutationContext.Provider>\n );\n}\n\nexport function useMutationStatus() {\n const { isPending } = useContext(MutationContext);\n\n return { isPending };\n}\n\nexport function useFormStatus() {\n const { isPending, validationErrors, formError } =\n useContext(MutationContext);\n\n return { isPending, validationErrors, formError };\n}\n\nexport function useFormData() {\n const context = useContext(MutationContext);\n\n const { formDataSubject } = context;\n\n // Unbound on purpose: `Subject` binds in its constructor, so these are\n // stable across renders. The `.bind` calls that used to be here allocated a\n // fresh `subscribe` every render, which made `useSyncExternalStore` drop and\n // re-add this component's subscription on each pass.\n return useSyncExternalStore(\n formDataSubject.current.subscribe,\n formDataSubject.current.getValue,\n formDataSubject.current.getValue,\n );\n}\n\nexport const ValidationErrors = (props: {\n name: string;\n className?: string;\n render?: (props: ComponentProps<\"div\">) => React.JSX.Element;\n}) => {\n const {\n render = (props: ComponentProps<\"div\">) => <div {...props} />,\n name,\n } = props;\n const { validationErrors } = useContext(MutationContext);\n\n const Comp = render;\n\n if (validationErrors[name]?.length > 0) {\n return (\n <>\n {validationErrors[name].map((error) => {\n return (\n <Comp className={props.className} key={error}>\n {error}\n </Comp>\n );\n })}\n </>\n );\n }\n\n return null;\n};\n\nexport const FormFieldContainer = (\n props: ComponentProps<\"div\"> & { name: string },\n) => {\n const { name, children, ...rest } = props;\n const { validationErrors } = useContext(MutationContext);\n const errors = validationErrors[name] || [];\n return (\n <div data-has-error={errors.length > 0} {...rest}>\n {children}\n </div>\n );\n};\n\nexport const FormError = (props: ComponentProps<\"div\">) => {\n const { formError } = useContext(MutationContext);\n\n if (formError) {\n return <div {...props}>{formError}</div>;\n }\n\n return null;\n};\n","import { useContext, useSyncExternalStore } from \"react\";\nimport { ClientRouterContext } from \"./ClientRouterContext\";\n\nexport function useIsNavigationPending() {\n const { isNavigatingSubject } = useContext(ClientRouterContext);\n // These read `this`, and `useSyncExternalStore` calls whatever it is handed\n // as a plain function — which used to throw `undefined is not an object\n // (evaluating 'this.value')` on the first render of any component calling\n // this hook. `Subject` now binds in its constructor, so the references are\n // both correct and stable across renders; binding here instead would hand\n // uSES a new `subscribe` every render and churn the subscription.\n const isNavigating = useSyncExternalStore(\n isNavigatingSubject.subscribe,\n isNavigatingSubject.getValue,\n isNavigatingSubject.getValue,\n );\n\n return isNavigating;\n}\n","import { useContext, useEffect, useState } from \"react\";\nimport { ClientRouterContext } from \"./ClientRouterContext\";\n\nexport function useNavigationProgress() {\n const { progressManager } = useContext(ClientRouterContext);\n const [progress, setProgress] = useState(progressManager.state.getValue());\n\n useEffect(() => {\n const unsub = progressManager.state.subscribe((p) => setProgress(p));\n return () => {\n unsub();\n };\n }, [progressManager.state]);\n\n return progress;\n}\n","import { useCallback, useContext } from \"react\";\n\nimport { applyParams } from \"../utils/applyParams\";\nimport { ClientRouterContext } from \"./ClientRouterContext\";\nimport { I18nContext } from \"./I18nContext\";\nimport { useLocation } from \"./useLocation\";\nimport type { UrlParser, ViewPaths } from \"./types\";\n\ntype Search = Record<string, string | number | boolean | undefined | null>;\n\n/**\n * A prefetch spends the visitor's data on a page they may never open, so it\n * stands down when they have asked for less of that or the connection cannot\n * spare it. `navigator.connection` only exists in Chromium — everywhere else\n * there is nothing to go on and prefetching proceeds.\n */\nfunction connectionRefusesPrefetch() {\n const connection = (navigator as any)?.connection;\n if (!connection) {\n return false;\n }\n if (connection.saveData) {\n return true;\n }\n return [\"slow-2g\", \"2g\"].includes(connection.effectiveType);\n}\n\ntype Options<T extends ViewPaths> =\n UrlParser<T> extends Record<string, never>\n ? {\n search?: Search;\n locale?: string;\n }\n : {\n search?: Search;\n params: UrlParser<T>;\n locale?: string;\n };\n\n/**\n * Warms a route ahead of the navigation to it: its page data, its stylesheets\n * and its component chunks. A navigation that lands on a prefetched route\n * renders from the cached payload instead of waiting on a request.\n *\n * The URL is built exactly the way `useNavigate` builds it — the prefetch is\n * only ever used by a navigation that asks for the same one.\n */\nexport function usePrefetch() {\n const { prefetchRoute } = useContext(ClientRouterContext);\n const { defaultLocale } = useContext(I18nContext);\n const location = useLocation();\n\n const currentPathname = location.pathname;\n const currentSearch = location.search;\n const currentLocale = location.locale;\n\n return useCallback(\n async <T extends ViewPaths>(\n path: T | (string & {}),\n ...args: UrlParser<T> extends Record<string, never>\n ? [options?: Options<T>]\n : [options: Options<T>]\n ) => {\n if (typeof window === \"undefined\" || !prefetchRoute) {\n return;\n }\n\n if (connectionRefusesPrefetch()) {\n return;\n }\n\n const [options = {}] = args;\n const {\n search = {},\n params = {},\n locale = null,\n } = { params: {}, search: {}, locale: null, ...options };\n\n let localeSegment = locale ?? currentLocale;\n if (localeSegment === defaultLocale) {\n localeSegment = \"\";\n }\n\n const pathname = applyParams(path, params) || \"/\";\n // Matches `useNavigate`, which hands the search object straight to\n // `URLSearchParams` — the query string a click produces has to be the one\n // the payload was cached under.\n const queryString = new URLSearchParams(search as any).toString();\n const searchSegment = queryString.length > 0 ? `?${queryString}` : \"\";\n\n // The route already on screen has nothing to warm, and eagerly prefetched\n // links pointing back at it would just replay the current page's queries.\n if (pathname === currentPathname && searchSegment === currentSearch) {\n return;\n }\n\n await prefetchRoute({\n pathname,\n search: searchSegment,\n localeSegment: localeSegment ? `/${localeSegment}` : \"\",\n });\n },\n [\n prefetchRoute,\n defaultLocale,\n currentLocale,\n currentPathname,\n currentSearch,\n ],\n );\n}\n","import { useContext } from \"react\";\nimport { useRoute } from \"./useRoute\";\nimport { ClientRouterContext } from \"./ClientRouterContext\";\n\nexport type Breadcrumb = {\n label: string;\n href: string;\n};\n\nexport function useBreadcrumbs() {\n const { pathname } = useRoute();\n const { getViewPathsFromPathname, breadcrumbsCache } =\n useContext(ClientRouterContext);\n\n let breadcrumbs: Breadcrumb[] = [];\n const viewPaths = getViewPathsFromPathname(pathname);\n for (const viewPath of viewPaths) {\n if (breadcrumbsCache.has(`${viewPath}:${pathname}`)) {\n breadcrumbs.push(breadcrumbsCache.get(`${viewPath}:${pathname}`));\n }\n }\n\n return breadcrumbs.filter((breadcrumb) => breadcrumb?.label.length > 0);\n}\n","import {\n useCallback,\n useContext,\n useEffect,\n useRef,\n memo,\n type ComponentProps,\n type SyntheticEvent,\n} from \"react\";\n\nimport { applyParams } from \"../utils/applyParams\";\nimport { useLocation } from \"./useLocation\";\nimport type { UrlParser, ViewResult } from \"./types\";\nimport { useNavigate } from \"./useNavigate\";\nimport type { ViewRPC } from \"./rpc\";\nimport type { Prettify } from \"../utils/type\";\nimport { useParams } from \"./useParams\";\nimport { I18nContext } from \"./I18nContext\";\nimport { useRouteTransition } from \"./RouteTransitionProvider\";\nimport { usePrefetch } from \"./usePrefetch\";\n\ntype Views = {\n [K in keyof ViewRPC as K extends `view:${infer P}`\n ? P\n : never]: ViewResult<K>;\n};\n\ntype Search = Record<string, string | number | boolean | undefined | null>;\n\n/**\n * When to warm the target route's data, styles and chunks.\n *\n * - `hover` — the moment the pointer arrives, or on touch or keyboard focus.\n * - `intent` — hover held long enough to read as intent, so a cursor sweeping\n * across a nav bar does not fire a request per link it crosses.\n * - `viewport` — as the link comes into view.\n * - `render` — as soon as the link renders.\n *\n * Several can be combined. The useful pairing is a bulk strategy with an\n * interactive one — `[\"viewport\", \"intent\"]` warms the link on the way past and\n * warms it again on approach if the cached payload has since gone stale.\n * `hover` and `intent` together is just `hover`, since it fires first.\n *\n * Every strategy stands down on metered or very slow connections.\n */\nexport type PrefetchStrategy = \"hover\" | \"intent\" | \"viewport\" | \"render\";\n\n/** How long the pointer has to rest on an `intent` link before it counts. */\nconst INTENT_DELAY = 100;\n\n/** How far ahead of the viewport a `viewport` link starts warming. */\nconst VIEWPORT_MARGIN = \"200px\";\n\ntype LinkBaseProps<T extends keyof Views> = Omit<\n ComponentProps<\"a\">,\n \"href\"\n> & {\n active?: boolean;\n href: T;\n hash?: string;\n /** Off unless set. `false` is accepted so it can be driven by a variable. */\n prefetch?: PrefetchStrategy | readonly PrefetchStrategy[] | false;\n params: UrlParser<T>;\n search?: T extends keyof Views\n ? Views[T][\"input\"] extends Record<string, never>\n ? Search\n : Prettify<Partial<Views[T][\"input\"]> & Search>\n : Search;\n};\n\ntype LinkProps<T extends keyof Views, U = UrlParser<T>> = U extends Record<\n string,\n never\n>\n ? Omit<LinkBaseProps<T>, \"params\">\n : LinkBaseProps<T>;\n\nfunction normalizeSearch(search: Search): Record<string, string> {\n return Object.fromEntries(\n Object.entries(search)\n .filter(([_k, v]) => v !== undefined && v !== null)\n .map(([k, v]) => [k, String(v)]),\n ) as Record<string, string>;\n}\n\nexport const Link = memo(<T extends keyof Views>(props: LinkProps<T>) => {\n const _params = useParams();\n const { isTransitioning, targetPath } = useRouteTransition();\n const {\n href,\n onClick,\n onMouseEnter,\n onMouseLeave,\n onTouchStart,\n onFocus,\n onBlur,\n ref,\n hash = \"\",\n active = false,\n prefetch,\n params = {},\n search = {},\n ...rest\n } = { params: _params, search: {}, ...props };\n const { defaultLocale } = useContext(I18nContext);\n const { push } = useNavigate();\n const location = useLocation();\n const prefetchRoute = usePrefetch();\n const searchParams = new URLSearchParams(normalizeSearch(search));\n\n const path = applyParams(href, params);\n // `applyParams` drops the trailing slash, so the root route comes back empty\n // where every pathname the router reports says `/`.\n const resolvedPath = path || \"/\";\n let urlLocaleSegment = location.locale;\n if (urlLocaleSegment === defaultLocale) {\n urlLocaleSegment = \"\";\n }\n\n const localeSegment = urlLocaleSegment ? `/${urlLocaleSegment}` : \"\";\n\n const targetHref = [\n [`${localeSegment}${path}`, searchParams.toString()]\n .filter((s) => s.length > 0)\n .join(\"?\"),\n hash,\n ].join(\"\");\n\n const currentHref = [location.pathname, location.search, location.hash]\n .filter((item) => !!item)\n .join(\"\");\n\n // Held in a ref because the prefetch callback is rebuilt on every router\n // render — an effect that depended on it would re-fire on renders that have\n // nothing to do with this link.\n const prefetchRouteRef = useRef(prefetchRoute);\n useEffect(() => {\n prefetchRouteRef.current = prefetchRoute;\n });\n\n // Clicking through to the path we are already on is a shallow navigation —\n // it moves the URL without fetching, so there is nothing to warm.\n const isShallowTarget = resolvedPath === location.pathname;\n\n const strategies = !prefetch\n ? []\n : Array.isArray(prefetch)\n ? prefetch\n : [prefetch];\n const uses = (strategy: PrefetchStrategy) => strategies.includes(strategy);\n // Effects below key off the strategies, which arrive as an array literal with\n // a fresh identity on every render. The names are what actually matters.\n const strategyKey = strategies.join(\",\");\n\n // Repeats are the cache's problem, not this component's: it collapses a\n // hover storm into one request and lets a hover past the TTL refresh a\n // payload that has gone stale.\n const runPrefetch = () => {\n if (strategies.length === 0 || isShallowTarget) {\n return;\n }\n prefetchRouteRef.current(href, { params, search } as never);\n };\n\n useEffect(() => {\n if (uses(\"render\")) {\n runPrefetch();\n }\n }, [strategyKey, targetHref]);\n\n const anchorRef = useRef<HTMLAnchorElement | null>(null);\n // A caller's own `ref` still has to reach them — under React 19 it arrives as\n // a plain prop, and the spread below would otherwise hand the element to one\n // of us and null to the other.\n //\n // Memoised because `Link` re-renders on every navigation in the app: a fresh\n // callback identity would have React detach and reattach the element each\n // time, handing a caller's ref callback a null it never asked for.\n const setAnchorRef = useCallback(\n (node: HTMLAnchorElement | null) => {\n anchorRef.current = node;\n if (typeof ref === \"function\") {\n ref(node);\n } else if (ref) {\n ref.current = node;\n }\n },\n [ref],\n );\n\n useEffect(() => {\n if (!uses(\"viewport\")) {\n return;\n }\n const element = anchorRef.current;\n if (!element || typeof IntersectionObserver === \"undefined\") {\n return;\n }\n // One shot: a link scrolled past and back is already warm, and if its entry\n // has expired the next hover or click pays for a fresh one.\n const observer = new IntersectionObserver(\n (entries) => {\n if (entries.some((entry) => entry.isIntersecting)) {\n observer.disconnect();\n runPrefetch();\n }\n },\n { rootMargin: VIEWPORT_MARGIN },\n );\n observer.observe(element);\n return () => observer.disconnect();\n }, [strategyKey, targetHref]);\n\n const intentTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const cancelIntent = () => {\n if (intentTimerRef.current !== null) {\n clearTimeout(intentTimerRef.current);\n intentTimerRef.current = null;\n }\n };\n useEffect(() => cancelIntent, []);\n\n /** A pointer arriving — the one signal `intent` waits on before believing. */\n const pointerArrived = () => {\n if (uses(\"hover\")) {\n runPrefetch();\n } else if (uses(\"intent\")) {\n cancelIntent();\n intentTimerRef.current = setTimeout(runPrefetch, INTENT_DELAY);\n }\n };\n\n /** Focus and touch are deliberate, so neither strategy makes them wait. */\n const linkTargeted = () => {\n if (uses(\"hover\") || uses(\"intent\")) {\n runPrefetch();\n }\n };\n\n /** Runs the caller's own handler first, then the prefetch trigger. */\n const prefetchOn =\n <E extends SyntheticEvent>(\n handler: ((event: E) => void) | undefined,\n trigger: () => void,\n ) =>\n (event: E) => {\n handler?.(event);\n trigger();\n };\n\n return (\n <a\n ref={setAnchorRef}\n data-active={active || currentHref === targetHref}\n // The resolved path, not the template: one template can back a whole list\n // of rows, and only the row that was clicked is heading anywhere.\n data-pending={isTransitioning && resolvedPath === targetPath}\n href={targetHref === '' ? '/' : targetHref}\n onClick={(e) => {\n if (typeof window !== \"undefined\") {\n if (currentHref === targetHref) {\n e.preventDefault();\n return;\n }\n }\n let currentPath = window.location.pathname.replace(localeSegment, \"\");\n currentPath = currentPath === \"\" ? \"/\" : currentPath;\n onClick?.(e);\n\n if (hash === \"\") {\n e.preventDefault();\n }\n push(href, {\n hash,\n search,\n params,\n shallow: path === currentPath,\n } as unknown as never);\n }}\n onMouseEnter={prefetchOn(onMouseEnter, pointerArrived)}\n onMouseLeave={prefetchOn(onMouseLeave, cancelIntent)}\n onTouchStart={prefetchOn(onTouchStart, linkTargeted)}\n onFocus={prefetchOn(onFocus, linkTargeted)}\n onBlur={prefetchOn(onBlur, cancelIntent)}\n {...rest}\n />\n );\n});\n","import { type ComponentProps, useEffect } from \"react\";\nimport type { Link } from \"./Link\";\n\nimport { useNavigate } from \"./useNavigate\";\n\nexport const Redirect = (\n props: ComponentProps<typeof Link> & { action: \"push\" | \"replace\" },\n) => {\n const { href, params = {}, search = {}, action = \"replace\" } = props;\n const { push, replace } = useNavigate();\n\n useEffect(() => {\n if (action === \"replace\") {\n replace(href, { params, search } as any);\n } else {\n push(href, { params, search } as any);\n }\n }, [replace, action, push, params, search, href]);\n\n return <></>;\n};\n","import { type ReactNode, useContext } from \"react\";\nimport { ServerDataContext } from \"./ServerDataProvider\";\n\nexport function updateMeta(meta: any) {\n // A partially rendered response whose segments set no metadata sends none —\n // what is on the page belongs to the segments that were skipped.\n if (!meta) {\n return;\n }\n const { title, description } = meta;\n if (title) {\n document.title = title;\n }\n if (description) {\n const desc = document.querySelector(\"meta[name='description']\");\n if (desc) {\n desc.setAttribute(\"content\", description);\n } else {\n const newDesc = document.createElement(\"meta\");\n newDesc.setAttribute(\"name\", \"description\");\n newDesc.setAttribute(\"content\", description);\n document.head.appendChild(newDesc);\n }\n }\n}\n\nconst OpenGraph = (props: {\n title: string;\n type: string;\n url: string;\n image: string;\n description?: string;\n imageAlt?: string;\n imageWidth?: number;\n imageHeight?: number;\n twitterImage?: string;\n twitterImageAlt?: string;\n twitterImageWidth?: number;\n twitterImageHeight?: number;\n}) => {\n const {\n title,\n description,\n type,\n url,\n image,\n imageAlt,\n imageWidth,\n imageHeight,\n twitterImage,\n twitterImageAlt,\n twitterImageWidth,\n twitterImageHeight,\n } = props;\n\n return (\n <>\n <meta property=\"og:title\" content={title} />\n <meta property=\"og:type\" content={type} />\n <meta property=\"og:url\" content={url} />\n <meta property=\"og:image\" content={image} />\n {description && <meta property=\"og:description\" content={description} />}\n {imageAlt && <meta property=\"og:image:alt\" content={imageAlt} />}\n {imageWidth && (\n <meta property=\"og:image:width\" content={String(imageWidth)} />\n )}\n {imageHeight && (\n <meta property=\"og:image:height\" content={String(imageHeight)} />\n )}\n {twitterImage && (\n <>\n <meta name=\"twitter:image\" content={twitterImage} />\n <meta name=\"twitter:card\" content=\"summary_large_image\" />\n </>\n )}\n {twitterImageAlt && (\n <meta name=\"twitter:image:alt\" content={twitterImageAlt} />\n )}\n {twitterImageWidth && (\n <meta name=\"twitter:image:width\" content={String(twitterImageWidth)} />\n )}\n {twitterImageHeight && (\n <meta\n name=\"twitter:image:height\"\n content={String(twitterImageHeight)}\n />\n )}\n </>\n );\n};\n\nexport const Head = ({\n children = null,\n charSet = \"utf-8\",\n}: { children?: ReactNode; charSet?: string }) => {\n const { meta } = useContext(ServerDataContext);\n return (\n <head>\n <meta charSet={charSet} />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n {/*\n Disable browser auto-translation (Chrome/Google Translate). Gemi apps do\n their own i18n, and a translator that rewrites text nodes *before* React\n hydrates mutates the SSR DOM — which React rejects as a hydration\n mismatch (Minified React error #418) and then regenerates the tree,\n dropping the server-injected <style> and leaving the page unstyled.\n Pair this with `translate=\"no\"` on the <html> element in RootLayout.\n */}\n <meta name=\"google\" content=\"notranslate\" />\n <title>{meta?.title}</title>\n {meta?.description && (\n <meta name=\"description\" content={meta.description} />\n )}\n {meta?.openGraph && <OpenGraph {...meta.openGraph} />}\n {children}\n </head>\n );\n};\n","import { applyParams } from \"./applyParams\";\n\n/**\n * Route the client is currently rendering, sent on `.json` navigations so the\n * server can skip the handlers of the segments that route already has mounted.\n * Value is a locale-less pathname plus search, e.g. `/app/A/chat?tab=2`.\n */\nexport const PARTIAL_RENDER_HEADER = \"x-gemi-from\";\n\n/** What the server reports back about the skip it performed, if any. */\nexport interface PartialRenderInfo {\n /** The `x-gemi-from` value the plan was computed against. */\n from: string;\n /** View paths of the skipped segments, in order. Their data is carried forward. */\n carriedViews: string[];\n}\n\n/**\n * The `x-gemi-from` value for the route the client starts on.\n *\n * On the first render the router's `pathname` is still the route *pattern* the\n * server matched — it only becomes a resolved path once the history listener\n * has run — so this has to apply the params. Sending `/app/:orgId/chat` names\n * no route the server can resolve, and the first navigation after every full\n * page load would skip nothing.\n */\nexport function initialRenderedRoute(route: {\n pathname?: string;\n params?: Record<string, string>;\n search?: string;\n}) {\n // `applyParams` strips the trailing slash, so the root route resolves to the\n // empty string — which the server reads as \"no header\" and renders in full.\n const pathname = applyParams(route.pathname ?? \"/\", route.params ?? {}) || \"/\";\n return `${pathname}${route.search ?? \"\"}`;\n}\n","import type { Breadcrumb } from \"../useBreadcrumbs\";\n\ninterface RouteSnapshot {\n /** Concrete pathname, without the locale segment. */\n pathname: string;\n /** Route pattern the data was produced for — part of every breadcrumb key. */\n routePath: string;\n data: Record<string, any>;\n breadcrumbs: Record<string, Breadcrumb>;\n}\n\n/**\n * A partially rendered response only carries the segments the server actually\n * ran. Everything is keyed by the *new* pathname, so a carried layout would\n * render with empty props unless the data it already had is copied across.\n *\n * Data the server sent always wins: a carried view is only filled in where the\n * response has nothing for it.\n */\nexport function mergeCarriedSegments(\n previous: RouteSnapshot,\n next: RouteSnapshot,\n carriedViews: string[],\n) {\n if (carriedViews.length === 0) {\n return { data: next.data, breadcrumbs: next.breadcrumbs };\n }\n\n // Page data is keyed by the pathname it was fetched for, and a shallow\n // navigation moves the pathname on without fetching — so fall back to the key\n // the data is actually under. The server sends exactly one.\n const previousData = previous.data ?? {};\n const previousViewData =\n previousData[previous.pathname] ?? previousData[Object.keys(previousData)[0]] ?? {};\n const previousBreadcrumbs = previous.breadcrumbs ?? {};\n\n const carriedViewData: Record<string, unknown> = {};\n const carriedBreadcrumbs: Record<string, Breadcrumb> = {};\n\n for (const viewPath of carriedViews) {\n if (viewPath in previousViewData) {\n carriedViewData[viewPath] = previousViewData[viewPath];\n }\n // Breadcrumbs are keyed by route pattern, and that changed even though the\n // segment did not, so they have to be re-keyed rather than copied.\n const previousKey = `${viewPath}:${previous.routePath}`;\n if (previousKey in previousBreadcrumbs) {\n carriedBreadcrumbs[`${viewPath}:${next.routePath}`] = previousBreadcrumbs[previousKey];\n }\n }\n\n // The server sends page data under exactly one key. Take it from the payload\n // rather than recomputing it, so the two never disagree on spelling.\n const [nextKey = next.pathname] = Object.keys(next.data ?? {});\n\n return {\n data: {\n ...next.data,\n [nextKey]: { ...carriedViewData, ...next.data?.[nextKey] },\n },\n breadcrumbs: { ...carriedBreadcrumbs, ...next.breadcrumbs },\n };\n}\n","import {\n PARTIAL_RENDER_HEADER,\n type PartialRenderInfo,\n} from \"../../utils/partialRender\";\nimport { readRoutePayload, type RouteQueryPayload } from \"./readRoutePayload\";\n\ninterface LoadRoutePayloadOptions {\n /** The `.json` URL for the route being navigated to. */\n url: string;\n /** `x-gemi-from` value for the route currently on screen. */\n from: string;\n /** Hands over a payload warmed ahead of this navigation, if there is one. */\n takePrefetched?: (url: string) => Promise<unknown> | null;\n /**\n * The route that is on screen *now*, re-read at the moment a response lands.\n * A navigation that committed while this one was in flight invalidates the\n * partial-render plan the server computed.\n */\n renderedRoute: () => string;\n /**\n * Receives each query result the server streams behind the envelope\n * (#290) — the caller hydrates it into the cache, which settles any\n * segment suspended on that variant.\n */\n onQueryPayload?: (payload: RouteQueryPayload) => void;\n}\n\n/**\n * The page data for a navigation, from whichever source can produce it.\n *\n * A prefetched payload is always a full render, so it can be committed as-is\n * and the `x-gemi-from` round trip skipped entirely. Everything else — no\n * prefetch, a prefetch that failed, a partial response computed against a route\n * that has since been navigated away from — falls through to a request.\n *\n * Returns `null` when nothing usable came back; the caller leaves the current\n * route on screen.\n */\nexport async function loadRoutePayload(\n options: LoadRoutePayloadOptions,\n): Promise<any> {\n const { url, from, takePrefetched, renderedRoute, onQueryPayload } = options;\n\n const prefetched = takePrefetched?.(url);\n if (prefetched) {\n const payload = await prefetched;\n if (payload) {\n return payload;\n }\n }\n\n let response = { ok: false, json: async () => ({}) } as Response;\n try {\n response = await fetch(url, { headers: { [PARTIAL_RENDER_HEADER]: from } });\n } catch (e) {\n console.error(e);\n return null;\n }\n\n if (!response.ok) {\n return null;\n }\n\n // Resolves with the envelope as soon as its line arrives; query results\n // streaming behind it keep draining into `onQueryPayload`.\n const payload = await readRoutePayload(response, onQueryPayload);\n\n // The segments the server carried forward were computed against a route that\n // is no longer on screen. Nothing sound to merge onto — ask for the whole\n // tree instead.\n const claimed: PartialRenderInfo | null = payload?.partial ?? null;\n if (claimed && claimed.from !== renderedRoute()) {\n try {\n const full = await fetch(url);\n if (full.ok) {\n return await readRoutePayload(full, onQueryPayload);\n }\n } catch (e) {\n console.error(e);\n }\n }\n\n return payload;\n}\n","import {\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n StrictMode,\n memo,\n useTransition,\n Suspense,\n useSyncExternalStore,\n} from \"react\";\n\nimport type { PropsWithChildren, ReactNode, ComponentType, lazy } from \"react\";\nimport { ErrorBoundary, type FallbackProps } from \"react-error-boundary\";\n\nimport { ServerDataContext } from \"./ServerDataProvider\";\nimport {\n ClientRouterContext,\n ClientRouterProvider,\n} from \"./ClientRouterContext\";\nimport type { ComponentTree } from \"./types\";\nimport {\n ComponentsContext,\n ComponentsProvider,\n loadViewModule,\n subscribeViewModules,\n} from \"./ComponentContext\";\nimport {\n QueryManagerContext,\n QueryManagerProvider,\n type QueryConfig,\n} from \"./QueryManagerContext\";\nimport { I18nProvider } from \"./I18nContext\";\nimport { WebSocketContextProvider } from \"./WebsocketContext\";\nimport { useNavigate } from \"./useNavigate\";\nimport {\n type PageData,\n type RouteState,\n RouteStateProvider,\n} from \"./RouteStateContext\";\nimport { applyParams } from \"../utils/applyParams\";\nimport { Action } from \"history\";\nimport { useRouteData } from \"./useRouteData\";\nimport { updateMeta } from \"./Head\";\nimport { RouteTransitionProvider } from \"./RouteTransitionProvider\";\nimport { ThemeProvider } from \"./ThemeProvider\";\nimport { initialRenderedRoute } from \"../utils/partialRender\";\nimport { mergeCarriedSegments } from \"./helpers/mergeCarriedSegments\";\nimport { routeDataUrl } from \"./helpers/routeDataUrl\";\nimport { loadRoutePayload } from \"./helpers/loadRoutePayload\";\n\ndeclare global {\n interface Window {\n scrollHistory: Map<string, number>;\n loaders: Record<string, () => void>;\n }\n}\n\nfunction restoreScroll(action: Action | null = null, _pathname = \"no path\") {\n if (action === null) {\n return;\n }\n\n const { pathname, search, hash } = window.location;\n\n const key = [pathname, search, hash].join(\"\");\n const sh = window.scrollHistory;\n\n const scrollPosition = sh?.get(key);\n\n if (action !== Action.Pop) {\n window.scrollTo(0, 0);\n } else {\n // In dev mode the effect runs scroll restoration\n // will be called twice, this if statement prevents\n // scroll to top\n if (!scrollPosition) {\n return;\n }\n window.scrollTo(0, scrollPosition ?? 0);\n }\n\n sh?.delete(key);\n}\n\ninterface RouteProps {\n componentPath: string;\n pathname: string;\n action: Action | null;\n}\n\nconst DefaultQueryErrorFallback = (props: FallbackProps) => {\n return (\n <div role=\"alert\">\n <p>Something went wrong.</p>\n <button type=\"button\" onClick={() => props.resetErrorBoundary()}>\n Try again\n </button>\n </div>\n );\n};\n\nconst Route = memo((props: PropsWithChildren<RouteProps>) => {\n const { componentPath, pathname, action, children } = props;\n const { viewImportMap, getViewModule } = useContext(ComponentsContext);\n const { clearErrors } = useContext(QueryManagerContext);\n const { data } = useRouteData();\n\n // `Loading` / `Error` are optional named exports of the view module,\n // subscribed so a Route that rendered before its chunk arrived re-reads\n // the registry once it lands. On the server `getViewModule` reads the\n // eagerly-loaded modules the http server passed in — a streaming render\n // suspends for real, so the `Loading` fallback it puts in the shell must be\n // the same one the client hydrates.\n const getModule = useCallback(\n () => getViewModule?.(componentPath),\n [getViewModule, componentPath],\n );\n const mod = useSyncExternalStore(subscribeViewModules, getModule, getModule);\n\n const componentData = data?.[pathname]?.[componentPath] ?? {};\n const Component = viewImportMap[componentPath];\n\n useEffect(() => {\n if (!children) {\n restoreScroll(action, componentPath);\n }\n }, [action, children, componentPath]);\n\n if (!Component) {\n const NotFound = viewImportMap[\"404\"];\n return <NotFound />;\n }\n const Loading = mod?.Loading;\n const ErrorFallback = mod?.Error ?? DefaultQueryErrorFallback;\n\n return (\n <ErrorBoundary\n FallbackComponent={ErrorFallback}\n resetKeys={[pathname]}\n onReset={clearErrors}\n >\n <Suspense fallback={Loading ? <Loading /> : null}>\n {/* Keyed by view path so swapping views remounts the view (fresh\n state), while the boundary above — keyed by tree slot in `Tree` —\n stays revealed across the swap. */}\n <Component key={componentPath} {...componentData}>\n {props.children}\n </Component>\n </Suspense>\n </ErrorBoundary>\n );\n});\n\nexport const Tree = memo(\n (props: {\n action: Action;\n tree: ComponentTree;\n entries: string[];\n pathname: string;\n }) => {\n const { entries, tree, pathname, action } = props;\n\n return (\n <>\n {tree\n .filter(([path]) => entries.includes(path))\n .map((node, slot) => {\n const [path, subtree] = node;\n // Keyed by tree SLOT, not by view path: the Suspense/error\n // boundary inside `Route` must survive a sibling swap (Home →\n // Pricing under the same layout), so React treats it as already\n // revealed and a suspending navigation keeps the previous page on\n // screen. A path key would remount the boundary every navigation,\n // and a brand-new boundary commits its fallback the moment any\n // sibling content (the layout's re-rendered chrome) commits —\n // blanking the outgoing page. The view itself still remounts when\n // the path changes: `Route` keys its Component render.\n if (subtree.length > 0) {\n return (\n <Route\n action={action}\n key={`slot-${slot}`}\n componentPath={path}\n pathname={pathname}\n >\n <Tree\n action={action}\n tree={subtree}\n entries={entries}\n pathname={pathname}\n />\n </Route>\n );\n }\n return (\n <Route\n action={action}\n key={`slot-${slot}`}\n componentPath={path}\n pathname={pathname}\n />\n );\n })}\n </>\n );\n },\n);\n\nconst Routes = (props: { componentTree: ComponentTree }) => {\n const { componentTree } = props;\n const [isPending, startTransition] = useTransition();\n const [isFetching, setIsFetching] = useState(false);\n const { routerSubject, fetchRouteCSS, preloadRouteModules, takePrefetched } =\n useContext(ClientRouterContext);\n const { hydrate } = useContext(QueryManagerContext);\n\n const [transitionPath, setTransitionPath] = useState<[string, string]>([\n null,\n routerSubject?.getValue().pathname,\n ]);\n\n const {\n breadcrumbs,\n pageData,\n i18n,\n prefetchedData,\n features,\n appId: currentAppId,\n } = useContext(ServerDataContext);\n\n const [routeState, setRouteState] = useState<RouteState & PageData>({\n params: routerSubject?.getValue().params,\n search: routerSubject?.getValue().search,\n pathname: routerSubject?.getValue().pathname,\n views: routerSubject?.getValue().views,\n action: null,\n hash: routerSubject?.getValue().hash,\n state: routerSubject?.getValue().state,\n routePath: routerSubject?.getValue().routePath,\n locale: routerSubject?.getValue().locale,\n breadcrumbs,\n data: pageData,\n i18n,\n prefetchedData,\n features: features ?? {},\n appId: currentAppId,\n });\n\n const { replace } = useNavigate();\n\n // Adopt what the document was rendered with. Without this the initial payload\n // only ever reaches a component that mounts on the first render, and one that\n // mounts on a later navigation — into a route whose layout has since been\n // carried forward rather than re-run — would fetch it over `/api` instead.\n useEffect(() => {\n hydrate(prefetchedData);\n }, [hydrate, prefetchedData]);\n\n // The route currently on screen, in `x-gemi-from` form. Updated when a\n // response is committed, never when one is merely requested — a navigation\n // that fails must leave the base the server carries segments from intact.\n const renderedRouteRef = useRef(initialRenderedRoute(routeState));\n\n useEffect(() => {\n return routerSubject?.subscribe(async (routerState) => {\n const { pathname, search, state, views } = routerState;\n setTransitionPath((current) => {\n const [, prevTarget] = current;\n return [prevTarget, pathname];\n });\n if (routerState.views.length === 0) {\n // Same reason as the `is404` branch below: the tree about to be mounted\n // carries none of the segments the stale `from` would have the server\n // skip.\n renderedRouteRef.current = \"\";\n setRouteState((routerState) => ({\n ...routerState,\n views: [\"404\"],\n }));\n return;\n }\n\n if (state?.shallow) {\n setRouteState((state) => ({\n ...state,\n ...routerState,\n }));\n return;\n }\n\n const localeSegment = routerState.locale ? `/${routerState.locale}` : \"\";\n\n const url = routeDataUrl({ pathname, search, localeSegment });\n const from = renderedRouteRef.current;\n setIsFetching(true);\n\n // `fetchRouteCSS` keys off the route manifest, so it needs the pattern\n // rather than the concrete path — `/posts/:id`, not `/posts/123`.\n fetchRouteCSS(routerState.routePath).catch((e) => console.error(e));\n // Announced before the imports below start, so each view's own static\n // imports are already in flight rather than discovered one parse at a\n // time once its chunk lands (#352).\n preloadRouteModules(routerState.routePath);\n // Through `loadViewModule` so the module registry — and with it each\n // view's `Loading`/`Error` exports — is populated before the\n // transition commits the new surface.\n for (const component of views) {\n loadViewModule(component);\n }\n\n const payload = await loadRoutePayload({\n url,\n from,\n takePrefetched,\n renderedRoute: () => renderedRouteRef.current,\n // Query results streaming behind the envelope (#290): hydrating each\n // settles the segment suspended on it — the same wake path streamed\n // documents use.\n onQueryPayload: ([path, variantKey, data]) => {\n hydrate({ [path]: { [variantKey]: data } });\n },\n });\n\n if (payload) {\n const {\n data,\n i18n,\n prefetchedData,\n breadcrumbs,\n meta,\n directive = {},\n is404 = false,\n appId,\n features,\n } = payload;\n updateMeta(meta);\n if (directive?.kind === \"Redirect\") {\n if (directive?.path) {\n replace(directive.path, { params: {} } as unknown);\n }\n\n return;\n }\n\n // Returns, rather than falling through. The commit below spreads\n // `routerState`, which carries the *matched* route's views — so without\n // the return this updater's `[\"404\"]` is queued and then overwritten in\n // the same batch, and the route renders its real views with no data.\n //\n // Reachable only since `.feature()`: a path the client cannot match is\n // caught by the `views.length === 0` guard above and never fetched, so\n // `is404` from the server used to imply an empty client `views`. A gated\n // route keeps its manifest entry, which is exactly the case where the\n // server says 404 and the client still knows how to render the page.\n if (is404) {\n // Not `${pathname}${search}`. `x-gemi-from` tells the server which\n // segments are already mounted so it can skip their handlers, and\n // after this commit the mounted tree is `[\"404\"]` — none of the target\n // route's layouts, and none of the previous route's either. The empty\n // string is what the server reads as \"carry nothing\".\n renderedRouteRef.current = \"\";\n startTransition(() => {\n setRouteState((state) => ({\n ...state,\n ...routerState,\n appId,\n i18n,\n features: features ?? state.features,\n // After the spread, deliberately.\n views: [\"404\"],\n }));\n });\n setIsFetching(false);\n return;\n }\n\n const carriedViews: string[] = payload.partial?.carriedViews ?? [];\n renderedRouteRef.current = `${pathname}${search}`;\n\n // Adopt what the server just prefetched before the new surface mounts\n // and its queries read the cache, otherwise they refetch it over /api.\n // Safe here: this callback is async, so we are past the render phase.\n hydrate(prefetchedData);\n\n startTransition(() => {\n setRouteState((state) => ({\n ...routerState,\n appId,\n i18n,\n // `?? state.features` rather than a bare assignment: an error-path\n // or older-server envelope carrying no flags must leave the current\n // values on screen, not blank every flag mid-session.\n features: features ?? state.features,\n prefetchedData,\n ...mergeCarriedSegments(\n state,\n { pathname, routePath: routerState.routePath, data, breadcrumbs },\n carriedViews,\n ),\n }));\n });\n }\n setIsFetching(false);\n });\n }, [\n routerSubject,\n fetchRouteCSS,\n preloadRouteModules,\n takePrefetched,\n replace,\n hydrate,\n ]);\n\n return (\n <RouteTransitionProvider\n isPending={isPending}\n isFetching={isFetching}\n transitionPath={transitionPath}\n >\n <RouteStateProvider state={routeState}>\n <Tree\n action={routeState.action}\n pathname={applyParams(routeState.pathname ?? \"/\", routeState.params)}\n tree={componentTree}\n entries={routeState.pathname ? routeState.views : [\"404\"]}\n />\n </RouteStateProvider>\n </RouteTransitionProvider>\n );\n};\n\nexport const ClientRouter = (props: {\n viewImportMap?: Record<string, ReturnType<typeof lazy>>;\n /** Server only: full view modules for `Loading`/`Error` fallbacks. */\n viewModules?: Record<string, Record<string, any>>;\n RootLayout: ComponentType<{ children: ReactNode; locale: string }>;\n /** App-wide `useQuery` defaults; per-call config always wins. */\n queryConfig?: QueryConfig;\n}) => {\n const { RootLayout } = props;\n const {\n routeManifest,\n router,\n componentTree,\n pageData,\n cssManifest,\n modulePreloadManifest,\n breadcrumbs,\n i18n,\n } = useContext(ServerDataContext);\n\n return (\n <ThemeProvider>\n <I18nProvider>\n <WebSocketContextProvider>\n <QueryManagerProvider queryConfig={props.queryConfig}>\n <ComponentsProvider\n viewImportMap={props.viewImportMap}\n modules={props.viewModules}\n >\n <ClientRouterProvider\n cssManifest={cssManifest}\n modulePreloadManifest={modulePreloadManifest}\n searchParams={router.searchParams}\n params={router.params}\n pageData={pageData}\n is404={router.is404}\n is500={false}\n pathname={router.pathname}\n currentPath={router.currentPath}\n routeManifest={routeManifest}\n breadcrumbs={breadcrumbs}\n urlLocaleSegment={router.urlLocaleSegment}\n >\n <StrictMode>\n <RootLayout locale={i18n.currentLocale}>\n <Routes componentTree={componentTree} />\n </RootLayout>\n </StrictMode>\n </ClientRouterProvider>\n </ComponentsProvider>\n </QueryManagerProvider>\n </WebSocketContextProvider>\n </I18nProvider>\n </ThemeProvider>\n );\n};\n","import { useEffect, type ComponentType } from \"react\";\nimport { hydrateRoot, createRoot } from \"react-dom/client\";\nimport { ServerDataProvider } from \"./ServerDataProvider\";\nimport { ClientRouter } from \"./ClientRouter\";\nimport type { QueryConfig } from \"./QueryManagerContext\";\nimport { ErrorBoundary } from \"react-error-boundary\";\nimport { initialViewModulesReady } from \"./ComponentContext\";\n\nexport interface InitOptions {\n /**\n * App-wide `useQuery` defaults (per-call config always wins). Mirror the\n * value passed to `createRoot` in the view router's service provider so the\n * server render and hydration agree.\n */\n queryConfig?: QueryConfig;\n}\n\nconst StackTrace = () => {\n useEffect(() => {\n window.addEventListener(\"load\", () => {\n const container = document.getElementById(\"overlay\");\n const ErrorOverlay = customElements.get(\"vite-error-overlay\");\n if (ErrorOverlay) {\n const overlay = new ErrorOverlay({\n message: (window as any).error,\n stack: (window as any).stack_trace || \"\",\n });\n container.appendChild(overlay);\n }\n });\n }, []);\n\n return <div id=\"overlay\" />;\n};\n\nexport function init(\n RootLayout: ComponentType<any>,\n options: InitOptions = {},\n) {\n if (typeof window !== \"undefined\" && (window as any).render_error) {\n createRoot(document.body).render(<StackTrace />);\n } else {\n // Held until the current route's view chunks are in the registry, so no\n // segment's first registration lands on a boundary that is mid-hydration.\n // See `initialViewModulesReady`.\n //\n // The `.catch` re-throws out of the microtask for the same reason the\n // bootstrap script wraps the entry `import()` that way: hydration used to\n // run inside the entry's evaluation, so a throw from `hydrateRoot` — a\n // `RootLayout` that fails at module scope, a root already attached —\n // reached that handler. Deferring it past a `.then` puts the throw in a\n // rejection no `window.onerror` reporter sees, and the page sits\n // permanently unhydrated with nothing raised.\n void initialViewModulesReady\n .then(() => hydrate(RootLayout, options))\n .catch((e) => {\n setTimeout(() => {\n throw e;\n });\n });\n }\n}\n\nfunction hydrate(RootLayout: ComponentType<any>, options: InitOptions) {\n hydrateRoot(\n document,\n <>\n <></>\n <></>\n <ErrorBoundary fallback={<div />}>\n <ServerDataProvider>\n <ClientRouter\n RootLayout={RootLayout}\n queryConfig={options.queryConfig}\n />\n </ServerDataProvider>\n </ErrorBoundary>\n </>,\n {\n onCaughtError: (error) => {\n console.error(error);\n // @ts-ignore\n if (import.meta.env.DEV) {\n const ErrorOverlay = customElements.get(\"vite-error-overlay\");\n if (ErrorOverlay) {\n const overlay = new ErrorOverlay({\n message: (error as any).message,\n stack: (error as any).stack || \"\",\n });\n document.body.appendChild(overlay);\n }\n }\n },\n },\n );\n}\n\nexport function create(\n RootLayout: ComponentType<any>,\n {\n componentTree,\n loaders,\n routeManifest,\n router,\n i18n,\n auth,\n prefetchedData,\n viewImportMap,\n }: any,\n) {\n (window as any).__GEMI_DATA__ = {\n componentTree,\n loaders,\n routeManifest,\n router,\n i18n,\n auth,\n prefetchedData,\n pageData: {},\n };\n createRoot(document.getElementById(\"root\")).render(\n <ServerDataProvider>\n <ClientRouter viewImportMap={viewImportMap} RootLayout={RootLayout} />\n </ServerDataProvider>,\n );\n}\n","import { createContext } from \"react\";\nimport type { DictionarySink } from \"../i18n/dictionarySink\";\n\n/**\n * The SSR-only collector `useDictionary` reports into. `null` in the browser,\n * where nothing needs collecting — the strings are already there.\n *\n * Mirrors `ServerQueryContext`: a server-supplied per-request object handed to\n * the tree by `createRoot`.\n */\nexport const DictionarySinkContext = createContext<DictionarySink | null>(null);\n","import type { ComponentType } from \"react\";\nimport { ClientRouter } from \"./ClientRouter\";\nimport { DictionarySinkContext } from \"./DictionarySinkContext\";\nimport type { QueryConfig } from \"./QueryManagerContext\";\nimport { ServerDataProvider } from \"./ServerDataProvider\";\nimport { ServerQueryContext } from \"./ServerQueryContext\";\n\nexport interface CreateRootOptions {\n /**\n * App-wide `useQuery` defaults (per-call config always wins). Set the same\n * value in the client entry's `init` call so hydration matches the server\n * render.\n */\n queryConfig?: QueryConfig;\n}\n\nexport function createRoot(\n RootLayout: ComponentType<{ children: React.ReactNode; locale: string }>,\n options: CreateRootOptions = {},\n) {\n // `serverQueries`, `viewModules` and `dictionarySink` exist only when the view\n // router renders this on the server — the browser mounts with all three absent.\n return (props: any) => (\n <ServerDataProvider value={props.data}>\n <ServerQueryContext.Provider value={props.serverQueries ?? null}>\n <DictionarySinkContext.Provider value={props.dictionarySink ?? null}>\n <ClientRouter\n RootLayout={RootLayout}\n viewImportMap={props.viewImportMap}\n viewModules={props.viewModules}\n queryConfig={options.queryConfig}\n />\n </DictionarySinkContext.Provider>\n </ServerQueryContext.Provider>\n </ServerDataProvider>\n );\n}\n","import type { ComponentProps } from \"react\";\n\nconst defaultScreen = [390, 768, 1024];\nconst defaultContainer = [100, 100, 100, 100];\n\nfunction generateImageProps(\n src: string,\n width: number,\n container = defaultContainer,\n screen = defaultScreen,\n quality = 80,\n) {\n const baseUrl = src;\n\n const widths = [...container.map((c, i) => (screen[i] * c) / 100), width * 2];\n\n return {\n srcSet: [\n ...screen.map((size, i) => {\n return `/api/__gemi__/services/image/resize?url=${baseUrl}&q=${quality}&w=${widths[i]} ${size}${isNaN(Number(size)) ? \"\" : \"w\"}`;\n }),\n `/api/__gemi__/services/image/resize?url=${baseUrl}&q=${quality}&w=${width * 2} 2x`,\n ].join(\", \"),\n sources: [\n ...container.map((c, i) => {\n if (!screen[i]) {\n return `${c}vw`;\n }\n return `(max-width: ${screen[i]}px) ${c}vw`;\n }),\n ].join(\", \"),\n };\n}\n\nfunction fillRestWithLast<T>(arr: T[], length: number): T[] {\n return [\n ...arr,\n ...Array.from({ length: length - arr.length }).fill(arr[arr.length - 1]),\n ] as T[];\n}\n\ninterface ImageProps {\n src: string;\n width: number;\n container?: number[];\n screen?: number[];\n quality?: number;\n}\n\nexport const Image = (props: ComponentProps<\"img\"> & ImageProps) => {\n const {\n screen = defaultScreen,\n container = defaultContainer,\n src,\n width,\n quality = 80,\n srcSet: __,\n ...rest\n } = props;\n\n if (!src) {\n return null;\n }\n\n const srcProps = generateImageProps(\n src,\n width,\n fillRestWithLast(container, 4),\n screen,\n quality,\n );\n\n return <img {...srcProps} width={width} {...rest} />;\n};\n","import { usePost } from \"../useMutation\";\n\ninterface UseForgotPasswordArgs {\n onSuccess: () => void;\n}\n\nconst defaultArgs: UseForgotPasswordArgs = {\n onSuccess: () => {},\n};\n\nexport function useForgotPassword(args: UseForgotPasswordArgs = defaultArgs) {\n return usePost(\n \"/auth/forgot-password\",\n {},\n {\n onSuccess: () => {\n args.onSuccess();\n },\n },\n );\n}\n","import { usePost } from \"../useMutation\";\nimport { useFrameworkQuery } from \"../useQuery\";\n\ninterface UseSignInArgs {\n onSuccess?: (data: any) => void;\n}\n\nconst defaultArgs: UseSignInArgs = {\n onSuccess: () => {},\n};\n\nexport function useSignIn(args: UseSignInArgs = defaultArgs) {\n // Only here for `mutate` — `lazy` so the sign-in form neither fetches nor\n // suspends on a user it does not have yet. `useFrameworkQuery` keeps that\n // pinned regardless of the app's `queryConfig`.\n const { mutate } = useFrameworkQuery(\"/auth/me\", {}, { lazy: true });\n return usePost(\n \"/auth/sign-in\",\n {},\n {\n onSuccess: (user) => {\n args.onSuccess(user);\n mutate(user as any);\n },\n },\n );\n}\n","import { usePost } from \"../useMutation\";\n\nexport function useSignUp() {\n return usePost(\"/auth/sign-up\");\n}\n","import { useMutate } from \"../useMutate\";\nimport { usePost } from \"../useMutation\";\n\ninterface UseSignOutArgs {\n onSuccess?: () => void;\n}\n\nconst defaultArgs: UseSignOutArgs = {\n onSuccess: () => {},\n};\n\nexport function useSignOut(args: UseSignOutArgs = defaultArgs) {\n const mutator = useMutate();\n return usePost(\n \"/auth/sign-out\",\n {},\n {\n onSuccess: () => {\n args.onSuccess();\n mutator({ path: \"/auth/me\" });\n },\n },\n );\n}\n","import { usePost } from \"../useMutation\";\n\ninterface UseResetPasswordArgs {\n onSuccess: () => void;\n}\n\nconst defaultArgs: UseResetPasswordArgs = {\n onSuccess: () => {},\n};\n\nexport function useResetPassword(args: UseResetPasswordArgs = defaultArgs) {\n return usePost(\n \"/auth/reset-password\",\n {},\n {\n onSuccess: () => {\n args.onSuccess();\n },\n },\n );\n}\n","import { useContext } from \"react\";\nimport { ServerDataContext } from \"../ServerDataProvider\";\nimport { useFrameworkQuery } from \"../useQuery\";\n\nexport function useUser() {\n const { auth } = useContext(ServerDataContext);\n const {\n data: user,\n loading,\n error,\n // `useFrameworkQuery`: the semantics below are pinned, so an app-wide\n // `queryConfig` must not leak in.\n } = useFrameworkQuery(\n \"/auth/me\",\n {},\n {\n fallbackData: auth?.user ? auth.user : null,\n // An anonymous visitor has no `/auth/me` data and never will — this\n // must resolve to `user: null`, not suspend the page behind a 401.\n suspense: false,\n },\n );\n\n if (loading && !user) {\n return { user: null, loading, error };\n }\n\n return { user: user, loading, error };\n}\n","import { useContext } from \"react\";\nimport { RouteStateContext } from \"./RouteStateContext\";\nimport type { ClientFeatureKey } from \"./rpc\";\n\n/**\n * Reads a feature evaluated by the server for this request.\n *\n * ```tsx\n * if (useFeature(\"new-checkout\")) {\n * return <NewCheckout />;\n * }\n * ```\n *\n * Keys are typed against `app/features`, so a typo is a compile error rather\n * than a feature that silently reads as off. Features declared\n * `serverOnly: true` are excluded from that set: they are withheld from the\n * payload on purpose, so reading one here could only ever answer `false`. Use\n * the `Features` facade for those.\n *\n * ## It never fetches\n *\n * The value comes from the payload the server already sent — embedded in the\n * document on first load, and replaced by each navigation's envelope after\n * that. So this is a context read: no request, no suspense, no loading state,\n * and no flash of the wrong branch, which is the failure mode that makes\n * client-evaluated features unusable for anything above the fold.\n *\n * The corollary is that switching a feature on reaches an open page on its next\n * navigation, not instantly.\n *\n * ## Reads route state, not server data\n *\n * `RouteStateContext` is what each navigation replaces — the same reason\n * `useLocale` reads it. Reading `ServerDataContext` instead would pin every\n * feature to the values from the initial document for the life of the session.\n */\nexport function useFeature(key: ClientFeatureKey): boolean {\n // `= {}` because several existing tests provide a bare object as page data,\n // and an error-path envelope may carry no features at all.\n const { features = {} } = useContext(RouteStateContext);\n\n if (process.env.NODE_ENV !== \"production\" && !(key in features)) {\n // Both reasons, because the type system only rules out the second one for a\n // caller whose `gemi.d.ts` resolved — and \"declare it\" is actively wrong\n // advice for the app that already did, then marked it `serverOnly`.\n console.warn(\n `[gemi] Feature \"${String(key)}\" is not in the payload the server sent. Either it is not declared in app/features, or it is declared \\`serverOnly: true\\` and never reaches the browser.`,\n );\n }\n\n // An unknown key reads as off rather than throwing: a feature deleted from the\n // declarations, or a payload that predates one, must not white-screen a page\n // that renders it.\n return features[key as string] === true;\n}\n\n/**\n * Every feature the server sent, for a component that needs to branch on\n * several at once or forward them somewhere.\n */\nexport function useFeatures(): Record<string, boolean> {\n const { features = {} } = useContext(RouteStateContext);\n return features;\n}\n","import { createElement, Fragment, isValidElement, type JSX } from \"react\";\n\ntype TemplateParams = Record<\n string,\n string | ((p: unknown) => string | JSX.Element)\n>;\n\nexport function parseTranslation(template: string, params: TemplateParams) {\n // Check if we have any JSX in our parameters\n const hasJSX = Object.values(params).some(\n (value) =>\n typeof value === \"function\" &&\n isValidElement((value as (p: unknown) => unknown)(\"\")),\n );\n\n // Regular expression to match template variables:\n // {{name}} - simple variable\n // {{name:type}} - variable with type casting\n // {{name:[content]}} - variable with interpolated content\n const regex = /{{([^{}]+?)(?::([^{}\\[\\]]+?))?(?:\\[(.*?)\\])?}}/g;\n\n if (!hasJSX) {\n // Simple string replacement\n const result = template.replace(regex, (match, name, type, content) => {\n // Clean the name part by removing any colon if present\n const cleanName = name.includes(\":\") ? name.split(\":\")[0] : name;\n\n const value = params[cleanName];\n if (value === undefined) {\n return match; // Return original match if no parameter found\n }\n\n if (typeof value === \"function\") {\n // If value is a function, call it with the content if available\n const functionParam = content !== undefined ? content : \"\";\n const functionResult = value(functionParam);\n // Check if function returned JSX - this shouldn't happen in the string branch\n if (isValidElement(functionResult)) {\n throw new Error(\"JSX returned in string context\");\n }\n return String(functionResult);\n }\n\n // Handle type casting if specified\n if (type) {\n switch (type.toLowerCase()) {\n case \"number\":\n return Number(value).toString();\n case \"string\":\n return String(value);\n case \"boolean\":\n return Boolean(value).toString();\n default:\n return String(value);\n }\n }\n return String(value);\n });\n return result as any;\n } else {\n // JSX replacement - we'll split the template into parts\n const parts: Array<string | JSX.Element> = [];\n let lastIndex = 0;\n let match: RegExpExecArray | null = null;\n\n while ((match = regex.exec(template)) !== null) {\n const [fullMatch, name, type, content] = match;\n const matchIndex = match.index;\n\n // Clean the name part by removing any colon if present\n const cleanName = name.includes(\":\") ? name.split(\":\")[0] : name;\n\n // Add text before the match\n if (matchIndex > lastIndex) {\n parts.push(template.substring(lastIndex, matchIndex));\n }\n\n const value = params[cleanName];\n if (value === undefined) {\n // Keep original template variable if no parameter found\n parts.push(fullMatch);\n } else if (typeof value === \"function\") {\n // If value is a function, call it with the content if available\n const functionParam = content !== undefined ? content : \"\";\n const functionResult = value(functionParam);\n parts.push(functionResult);\n } else if (type) {\n // Handle type casting if specified\n switch (type.toLowerCase()) {\n case \"number\":\n parts.push(Number(value).toString());\n break;\n case \"string\":\n parts.push(String(value));\n break;\n case \"boolean\":\n parts.push(Boolean(value).toString());\n break;\n default:\n parts.push(String(value));\n }\n } else {\n parts.push(String(value));\n }\n\n lastIndex = matchIndex + fullMatch.length;\n }\n\n // Add any remaining text\n if (lastIndex < template.length) {\n parts.push(template.substring(lastIndex));\n }\n\n // Convert the parts array to JSX\n return createElement(Fragment, {}, ...parts) as any;\n }\n}\n","import type { I18nDictionary } from \"./rpc\";\nimport type { ParseTranslationParams, Prettify } from \"../utils/type\";\nimport type { JSX } from \"react\";\nimport { parseTranslation } from \"../utils/parseTranslation\";\nimport { useRouteData } from \"./useRouteData\";\n\ntype Parser<T extends Record<string, string>> = Prettify<\n {\n [K in keyof T]: ParseTranslationParams<T[K]>;\n }[keyof T]\n>;\n\ntype ParamsOrNever<T> = T extends Record<string, never>\n ? [params?: never]\n : [params: T];\n\n/**\n * @deprecated Use `useDictionary(dict)` with a `defineDictionary` dictionary\n * declared next to the component. This resolves a dictionary by name through\n * the global `I18nDictionary` interface, which needs a `gemi.d.ts`\n * declaration, a central `app/i18n/index.ts`, and a hand-maintained `prefetch`\n * map naming every route's dictionaries — and it ships whatever that map says\n * whether the page reads it or not. Still supported; see `docs/i18n.md`.\n */\nexport function useTranslator<T extends keyof I18nDictionary>(component: T) {\n const { i18n } = useRouteData();\n\n function parse<\n K extends keyof I18nDictionary[T][\"dictionary\"],\n U extends Record<string, string> = I18nDictionary[T][\"dictionary\"][K],\n >(key: K, ...args: ParamsOrNever<Parser<U>>) {\n try {\n const translations = i18n.dictionary[i18n.currentLocale][component];\n const [params = {}] = args;\n return parseTranslation(translations[key as any], params);\n } catch (err) {\n console.error(\n `Unresolved translation Component:${component} key:${String(key)}`,\n );\n return String(key);\n }\n }\n\n parse.jsx = <\n K extends keyof I18nDictionary[T][\"dictionary\"],\n U extends Record<string, string> = I18nDictionary[T][\"dictionary\"][K],\n >(\n key: K,\n ...args: ParamsOrNever<Parser<U>>\n ) => {\n return parse(key, ...(args as any)) as unknown as JSX.Element;\n };\n\n return parse;\n}\n","import { use, useContext, type JSX } from \"react\";\nimport type { DictionaryHandle } from \"../i18n/defineDictionary\";\nimport { setActiveLocale } from \"../i18n/dictionaryRegistry\";\nimport type { DictionaryTranslations } from \"../i18n/dictionaryShape\";\nimport { parseTranslation } from \"../utils/parseTranslation\";\nimport type { ParseTranslationParams, Prettify } from \"../utils/type\";\nimport { DictionarySinkContext } from \"./DictionarySinkContext\";\nimport { useRouteData } from \"./useRouteData\";\n\ntype Parser<T extends Record<string, string>> = Prettify<\n {\n [K in keyof T]: ParseTranslationParams<T[K]>;\n }[keyof T]\n>;\n\ntype ParamsOrNever<T> = T extends Record<string, never>\n ? [params?: never]\n : [params: T];\n\n/**\n * Read a dictionary declared with `defineDictionary`, next to the component\n * that uses it.\n *\n * ```tsx\n * const t = useDictionary(homeDict);\n * t(\"title\", { name });\n * ```\n *\n * Keys and interpolation params come straight from the literal — there is no\n * name string to keep in sync and no `gemi.d.ts` augmentation.\n *\n * Normally this resolves without suspending: the server seeds the strings it\n * rendered with into the hydration payload, and the router warms a view's\n * dictionaries while it is already loading that view's chunks. It falls back to\n * suspending on the locale's chunk when neither happened — a dictionary inside\n * a `lazy()` subtree, or the first render after a locale switch.\n *\n * Replaces `useTranslator`, which is deprecated.\n */\nexport function useDictionary<const T extends DictionaryTranslations>(\n dictionary: DictionaryHandle<T>,\n) {\n const { i18n } = useRouteData();\n const sink = useContext(DictionarySinkContext);\n // An app with i18n switched off still renders dictionaries — fall back to the\n // source language rather than blowing up on an empty `i18n` payload.\n const locale = i18n?.currentLocale ?? dictionary.locales[0];\n // Tells the view loader which locale's chunks to warm on the next\n // navigation. `__GEMI_DATA__` only knows the locale the document loaded in.\n setActiveLocale(locale);\n\n // `loadForRender`, not the plain loader: a rejected locale chunk must not\n // rethrow out of `use()` and take the route down. It degrades to no strings,\n // and the per-key lookup below falls back to the key — what `useTranslator`\n // did. Called on the handle rather than the registry so a dictionary declared\n // at module scope survives the registry being reset under it.\n const pending = dictionary.loadForRender(locale);\n const strings = pending instanceof Promise ? use(pending) : pending;\n\n // Reported from the render phase, and deliberately so: on the server the\n // strings have to reach the document before the segment that used them is\n // revealed, or hydration would find them missing and refetch. The sink\n // de-duplicates, and it is null in the browser.\n sink?.use(dictionary.id, locale, strings);\n\n // Annotated `string` rather than inferred: `parseTranslation` returns `any`\n // (it hands back a JSX element on the `t.jsx` path), and letting that leak\n // through would silently defeat the key and param checking below — every\n // call site would typecheck against `any`.\n function parse<K extends keyof T & string, U extends T[K] = T[K]>(\n key: K,\n ...args: ParamsOrNever<Parser<U extends Record<string, string> ? U : never>>\n ): string {\n const template = strings[key];\n if (typeof template !== \"string\") {\n console.error(\n `Unresolved translation key:${key} locale:${locale} dictionary:${dictionary.id}`,\n );\n return key;\n }\n const [params = {}] = args;\n return parseTranslation(template, params as any) as string;\n }\n\n parse.jsx = <K extends keyof T & string, U extends T[K] = T[K]>(\n key: K,\n ...args: ParamsOrNever<Parser<U extends Record<string, string> ? U : never>>\n ) => {\n return parse(key, ...(args as any)) as unknown as JSX.Element;\n };\n\n return parse;\n}\n","/**\n * The one implementation of \"what is a dictionary literal, and what is its id\",\n * shared by the runtime (`defineDictionary`) and the Vite plugin.\n *\n * Both sides must agree exactly. A dictionary's id is a hash of its own\n * contents rather than of its file path, so a module that is bundled on one\n * side and evaluated raw on the other still lands on the same id — which is\n * what lets the SSR payload seed the client registry.\n */\n\nexport type DictionaryTranslations = Record<string, Record<string, string>>;\n\nexport type LocaleStrings = Record<string, string>;\n\n/**\n * Locales the dictionary declares, source language first.\n *\n * The order is meaningful: the first locale is the source language, and a key\n * missing from some other locale falls back along this list.\n *\n * `sourceLocale` pins that choice. Without it the source language is whichever\n * locale is seen first while walking the literal, which makes it an emergent\n * property of key order — adding a key at the top of a dictionary whose other\n * keys happen to lack `en-US` would silently re-point every fallback in it. Any\n * dictionary that is not uniformly translated should say which locale it is\n * authored in.\n */\nexport function dictionaryLocales(\n translations: DictionaryTranslations,\n sourceLocale?: string,\n): string[] {\n const locales: string[] = [];\n const seen = new Set<string>();\n if (sourceLocale) {\n seen.add(sourceLocale);\n locales.push(sourceLocale);\n }\n for (const byLocale of Object.values(translations)) {\n for (const locale of Object.keys(byLocale)) {\n if (!seen.has(locale)) {\n seen.add(locale);\n locales.push(locale);\n }\n }\n }\n return locales;\n}\n\n/**\n * Flatten one locale out of a dictionary.\n *\n * A key with no string for `locale` falls back along the declared locale order\n * rather than vanishing, so a half-translated dictionary degrades one string at\n * a time instead of rendering the whole component as raw keys.\n */\nexport function localeStrings(\n translations: DictionaryTranslations,\n locale: string,\n fallbackOrder: string[] = dictionaryLocales(translations),\n): LocaleStrings {\n const out: LocaleStrings = {};\n for (const [key, byLocale] of Object.entries(translations)) {\n let value = byLocale?.[locale];\n if (typeof value !== \"string\") {\n for (const candidate of fallbackOrder) {\n const fallback = byLocale?.[candidate];\n if (typeof fallback === \"string\") {\n value = fallback;\n break;\n }\n }\n }\n if (typeof value === \"string\") {\n out[key] = value;\n }\n }\n return out;\n}\n\nexport interface SourceDisagreement {\n key: string;\n first: string;\n againstKey: string;\n againstFirst: string;\n}\n\n/**\n * Whether the inferred source language survives reordering the literal.\n *\n * `dictionaryLocales` collects locales entry by entry, so `locales[0]` is the\n * first locale of the first entry. That is invariant under key reordering\n * exactly when every entry lists the same locale first — and order-dependent\n * the moment two entries disagree, because then whichever happens to be written\n * first decides what the *whole* dictionary falls back to. Adding one key at\n * the top can flip every other key's fallback language, from a diff that reads\n * as an addition.\n *\n * Returns the disagreement so the build can name both keys; `null` when the\n * inference is stable. `sourceLocale` settles it and makes the question moot.\n */\nexport function findSourceDisagreement(\n translations: DictionaryTranslations,\n): SourceDisagreement | null {\n let againstKey: string | undefined;\n let againstFirst: string | undefined;\n\n for (const [key, byLocale] of Object.entries(translations)) {\n const first = Object.keys(byLocale ?? {})[0];\n // A key with no locales at all is a different problem, reported elsewhere.\n if (first === undefined) continue;\n\n if (againstFirst === undefined) {\n againstFirst = first;\n againstKey = key;\n continue;\n }\n if (first !== againstFirst) {\n return { key, first, againstKey: againstKey!, againstFirst };\n }\n }\n return null;\n}\n\n/**\n * Canonical serialization — key order in the source file must not change the\n * id, or an innocuous reordering would break the payload/registry match.\n */\nexport function canonicalizeDictionary(\n translations: DictionaryTranslations,\n): string {\n const keys = Object.keys(translations).sort();\n const parts = keys.map((key) => {\n const byLocale = translations[key] ?? {};\n const locales = Object.keys(byLocale).sort();\n const inner = locales.map((l) => JSON.stringify([l, byLocale[l]])).join(\",\");\n return `${JSON.stringify(key)}:[${inner}]`;\n });\n return `{${parts.join(\",\")}}`;\n}\n\n/**\n * FNV-1a, run twice with different offsets for a 64-bit-wide id. No crypto\n * import, and it has to work identically in the browser bundle, under Bun on\n * the server, and inside the Vite plugin.\n */\nexport function dictionaryId(translations: DictionaryTranslations): string {\n const input = canonicalizeDictionary(translations);\n let a = 0x811c9dc5;\n let b = 0x01000193;\n for (let i = 0; i < input.length; i++) {\n const c = input.charCodeAt(i);\n a = Math.imul(a ^ c, 0x01000193);\n b = Math.imul(b ^ c, 0x811c9dc5);\n }\n const hex = (n: number) => (n >>> 0).toString(16).padStart(8, \"0\");\n return `d_${hex(a)}${hex(b)}`;\n}\n","import {\n dictionaryId,\n dictionaryLocales,\n localeStrings,\n type DictionaryTranslations,\n type LocaleStrings,\n} from \"./dictionaryShape\";\nimport {\n loadDictionary,\n loadDictionaryForRender,\n registerDictionary,\n} from \"./dictionaryRegistry\";\n\ndeclare const brand: unique symbol;\n\nexport interface DictionaryHandle<\n T extends DictionaryTranslations = DictionaryTranslations,\n> {\n readonly id: string;\n /** Locales this dictionary declares, source language first. */\n readonly locales: readonly string[];\n /**\n * Strings for `locale`. Synchronous when they are already in memory —\n * always, for an unbundled dictionary; after a preload or the SSR seed, for a\n * bundled one.\n */\n load(locale: string): LocaleStrings | Promise<LocaleStrings>;\n /**\n * `load`, but never rejecting — safe to hand React's `use()`. A failed locale\n * chunk resolves to no strings so the component degrades to rendering keys\n * instead of unmounting into an error boundary.\n */\n loadForRender(locale: string): LocaleStrings | Promise<LocaleStrings>;\n get(locale: string): LocaleStrings | undefined;\n /** Type-only: carries the literal's shape through to `useDictionary`. */\n readonly [brand]?: T;\n}\n\n/**\n * Declare the strings a component needs, next to the component.\n *\n * ```ts\n * export const homeDict = defineDictionary({\n * title: { \"en-US\": \"Welcome {{name}}\", \"tr-TR\": \"Hoş geldin {{name}}\" },\n * });\n * ```\n *\n * As written this holds every locale. Under gemi's Vite plugin the call is\n * rewritten so each locale becomes its own chunk and a page downloads only the\n * one it renders in — but the plugin is strictly an optimization, and the\n * behaviour is identical without it (in `bun test`, and in server code that\n * does not go through the bundler).\n *\n * The first locale in the literal is the source language: a key missing from\n * another locale falls back to it rather than rendering as its own key.\n */\nexport interface DefineDictionaryOptions {\n /**\n * The locale this dictionary is authored in. Keys missing from another locale\n * fall back to it, and it is what renders when the app has no locale\n * configured.\n *\n * Optional, but worth setting on any dictionary that is not uniformly\n * translated: without it the source language is whichever locale appears\n * first in the literal, so adding a key at the top can re-point every\n * fallback in the dictionary.\n */\n sourceLocale?: string;\n}\n\nexport function defineDictionary<const T extends DictionaryTranslations>(\n translations: T,\n options: DefineDictionaryOptions = {},\n): DictionaryHandle<T> {\n const locales = dictionaryLocales(translations, options.sourceLocale);\n return createHandle(dictionaryId(translations), locales, (locale) =>\n localeStrings(translations, locale, locales),\n );\n}\n\n/**\n * The rewritten form of a `defineDictionary` call — emitted by\n * `packages/gemi/vite/dictionaryPlugin.ts`, never written by hand. `loaders`\n * holds one dynamic import per locale so the bundler emits one chunk per\n * locale and the untaken ones never reach the browser.\n */\nexport function __gemi_dict__<\n const T extends DictionaryTranslations = DictionaryTranslations,\n>(\n id: string,\n loaders: Record<string, () => Promise<{ default: LocaleStrings }>>,\n): DictionaryHandle<T> {\n const locales = Object.keys(loaders);\n return createHandle(id, locales, (locale) => {\n // An unknown locale falls back to the source language, matching what\n // `localeStrings` does per key on the unbundled path.\n const load = loaders[locale] ?? loaders[locales[0]];\n if (!load) {\n return {};\n }\n return load().then((mod) => mod.default);\n });\n}\n\nfunction createHandle<T extends DictionaryTranslations>(\n id: string,\n locales: string[],\n load: (locale: string) => LocaleStrings | Promise<LocaleStrings>,\n): DictionaryHandle<T> {\n const entry = { id, locales, load };\n registerDictionary(entry);\n\n // Re-asserted on every read rather than only at construction. A handle is\n // created once, at module scope, but the registry it delegates to can be\n // emptied under it — a test's `afterEach` reset, an HMR boundary — and the\n // handle would then be permanently orphaned, throwing \"Unknown dictionary\"\n // for a dictionary the caller is holding. `registerDictionary` is a no-op\n // when the id is already there, so this costs one Map lookup.\n const ensure = () => registerDictionary(entry);\n\n return {\n id,\n locales,\n // Routed through the registry rather than calling `load` directly so\n // concurrent readers share one in-flight import and results are cached.\n load: (locale: string) => {\n ensure();\n return loadDictionary(id, locale);\n },\n loadForRender: (locale: string) => {\n ensure();\n return loadDictionaryForRender(id, locale);\n },\n get: (locale: string) => {\n ensure();\n const strings = loadDictionary(id, locale);\n if (strings instanceof Promise) {\n // Nothing downstream awaits this one — `get` is the synchronous peek,\n // and the caller is about to discard it. An unattached rejection (a\n // locale chunk that 404s mid-deploy) would surface as an\n // `unhandledRejection`, which under Node's default handler takes the\n // process down over one missing translation file. The load itself is\n // still cached and still retried through `loadDictionary`.\n strings.catch(() => {});\n return undefined;\n }\n return strings;\n },\n };\n}\n\n","import { useLocation } from \"./useLocation\";\nimport { useNavigate } from \"./useNavigate\";\nimport { useParams } from \"./useParams\";\nimport { useRouteData } from \"./useRouteData\";\n\nconst LOCALE_COOKIE = \"i18n-locale\";\nconst LOCALE_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;\n\n/**\n * The active locale lives in two places: the URL segment `setLocale` navigates\n * to, and the `i18n-locale` cookie the server falls back to when the URL has no\n * segment — which is exactly the case for the default locale. Both have to be in\n * place *before* the navigation asks for route data, or `Translator.detectLocale`\n * answers the request with a redirect back to the locale the cookie still names.\n *\n * Hence a synchronous `document.cookie` write rather than an awaited one. The\n * previous implementation awaited `cookieStore.set()` and hung the navigation off\n * its `.then()`; that promise is reported to never settle on iOS Safari, so the\n * `.then()` never ran and changing the language became a silent no-op — no\n * rejection, nothing for an error reporter to pick up. A synchronous write cannot\n * hang and cannot fail asynchronously, so nothing is left to gate navigation on.\n */\nfunction persistLocale(locale: string) {\n if (typeof document === \"undefined\") {\n return;\n }\n try {\n document.cookie = [\n // Encoded, not interpolated: `cookieStore.set()` rejected malformed\n // values, a raw string write does not. A locale carrying `;` would\n // otherwise write cookie *attributes* — `Domain`, `Path` — from whatever\n // the app happens to feed the switcher.\n `${LOCALE_COOKIE}=${encodeURIComponent(locale)}`,\n `Max-Age=${LOCALE_COOKIE_MAX_AGE}`,\n \"SameSite=Strict\",\n \"Path=/\",\n ].join(\"; \");\n } catch {\n // A sandboxed iframe with no storage access throws here. The navigation\n // still carries the locale in its URL, so it is better to switch without\n // remembering the choice than to not switch at all.\n }\n}\n\n/**\n * `onLocaleChange` is a server-side hook, so it takes a request to fire it. The\n * switch must not wait on that round trip, nor be cancelled by one that fails —\n * including one that fails *synchronously*: `fetch` is absent in some old\n * WebViews, and an unguarded call would throw before the navigation ran, which\n * is the same silent no-op this hook exists to prevent through another door.\n */\nfunction notifyLocaleChange(locale: string) {\n try {\n void fetch(\n `/api/__gemi__/services/i18n/set-locale/${encodeURIComponent(locale)}`,\n ).catch(() => {});\n } catch {\n // `fetch` itself is unavailable. The locale is already persisted and the\n // navigation still runs; only the server-side hook misses this switch.\n }\n}\n\nexport function useLocale() {\n const { i18n } = useRouteData();\n const { pathname, search } = useLocation();\n const { replace } = useNavigate();\n const params = useParams();\n\n const setLocale = async (locale: string) => {\n persistLocale(locale);\n notifyLocaleChange(locale);\n\n const urlSearchParams = new URLSearchParams(search);\n await replace(pathname, {\n locale,\n // TODO: fix: this conversion is wrong, because there can be multiple\n // search params with the same name\n search: Object.fromEntries(urlSearchParams.entries()),\n params,\n } as any);\n };\n\n return [i18n.currentLocale, setLocale] as const;\n}\n","import { useCallback, useContext, useEffect, useMemo } from \"react\";\nimport { WebSocketContext } from \"./WebsocketContext\";\nimport { applyParams } from \"../utils/applyParams\";\n\nexport function useSubscription(\n route: string,\n options: { params: {}; cb: (data: any) => void },\n) {\n const { cb, params } = options;\n const { subscribe, unsubscribe } = useContext(WebSocketContext);\n\n const topic = useMemo(\n () => applyParams(route, options.params),\n [route, params],\n );\n\n const handler = (event: MessageEvent<any>) => {\n const message = JSON.parse(event.data);\n if (topic === message.topic) {\n cb(message.data);\n }\n };\n\n useEffect(() => {\n subscribe(topic, handler);\n\n return () => {\n unsubscribe(topic, handler);\n };\n }, [topic]);\n}\n","import { useContext } from \"react\";\nimport { WebSocketContext } from \"./WebsocketContext\";\nimport { applyParams } from \"../utils/applyParams\";\n\nexport function useBroadcast(\n path: string,\n options: { params: Record<string, string | number> },\n) {\n const { params = {} } = options;\n const { broadcast } = useContext(WebSocketContext);\n\n const topic = applyParams(path, params);\n\n return (payload: Record<string, any>) => broadcast(topic, payload);\n}\n","import { createElement, Fragment, type ReactNode } from \"react\";\nimport type { SatoriOptions } from \"satori\";\n\ntype Font = Omit<SatoriOptions[\"fonts\"][number], \"data\">;\ntype Options = Omit<SatoriOptions, \"fonts\"> & {\n fonts: Font[];\n} & { width: number; height: number };\n\nexport const OpenGraphImage = ({\n children,\n ...satoriOptions\n}: Options & { children: ReactNode }) => {\n return (\n <>\n {(() => {\n throw {\n jsx: createElement(Fragment, { children }),\n satoriOptions,\n };\n })()}\n </>\n );\n};\n","import { useContext } from \"react\";\nimport { ServerDataContext } from \"./ServerDataProvider\";\nimport { RouteStateContext } from \"./RouteStateContext\";\n\nexport function useAppIdMissmatch() {\n const { appId: next } = useContext(RouteStateContext);\n const { appId: current } = useContext(ServerDataContext);\n\n return current !== next;\n}\n"],"mappings":";;;;;;;;;;AA+BA,IAAa,qBAAqB,cAAwC,IAAI;;;AC5B9E,SAAgB,eAAe;CAC7B,MAAM,EAAE,MAAM,MAAM,gBAAgB,gBAClC,WAAW,iBAAiB;CAE9B,OAAO;EAAE;EAAM;EAAM;EAAgB;CAAY;AACnD;;;ACRA,SAAgB,cACd,OACkC;CAClC,OACE,UAAU,QACV,OAAO,UAAU,YACjB,CAAC,MAAM,QAAQ,KAAK,KAC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