import { hydrateRoot } from 'react-dom/client' import { createBrowserHistory, RouterProvider } from '@tanstack/react-router' import { QueryClient, hydrate } from '@tanstack/react-query' import type { Visitor } from './auth.ts' import type { Item } from './data/items.ts' import { createAppRouter } from './router.tsx' import type { AppApi, RouterContext } from './router-context.ts' const root = document.documentElement const appBasePath = (root.dataset['appBase'] ?? '').replace(/\/+$/, '') async function request(path: string, init?: RequestInit): Promise { const response = await fetch(`${appBasePath}${path}`, { credentials: 'same-origin', ...init, headers: { 'content-type': 'application/json', ...init?.headers }, }) if (!response.ok) { const body = (await response.json().catch(() => null)) as { error?: string } | null throw new Error(body?.error ?? `Request failed (${response.status})`) } return (response.status === 204 ? undefined : await response.json()) as T } const api: AppApi = { listItems: async () => (await request<{ items: Array }>('/api/items')).items, addItem: async (text) => (await request<{ item: Item }>('/api/items', { method: 'POST', body: JSON.stringify({ text }), })).item, deleteItem: (id) => request(`/api/items/${encodeURIComponent(id)}`, { method: 'DELETE' }), } const queryClient = new QueryClient() const state = document.getElementById('query-state')?.textContent if (state) hydrate(queryClient, JSON.parse(state)) const visitorJson = root.dataset['visitor'] const context: RouterContext = { queryClient, api, visitor: visitorJson ? (JSON.parse(visitorJson) as Visitor) : null, appBasePath, assetBasePath: root.dataset['assetBase'] ?? '', clientModuleUrl: null, hostedUrl: root.dataset['hostedUrl'] || null, } const router = createAppRouter({ history: createBrowserHistory(), context }) void router.load().then(() => { hydrateRoot(document, ) })