modelence 0.23.1 → 0.24.0-dev.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.
Files changed (43) hide show
  1. package/dist/chunk-3KUADF4A.js +41 -0
  2. package/dist/chunk-3KUADF4A.js.map +1 -0
  3. package/dist/chunk-63RBLFRJ.js +4 -0
  4. package/dist/chunk-63RBLFRJ.js.map +1 -0
  5. package/dist/chunk-ACX7KY6E.js +3 -0
  6. package/dist/{chunk-WDY7BYXR.js.map → chunk-ACX7KY6E.js.map} +1 -1
  7. package/dist/chunk-CHBJAOMP.js +2 -0
  8. package/dist/chunk-CHBJAOMP.js.map +1 -0
  9. package/dist/{chunk-UJ2WYHH7.js → chunk-NPBIRXLC.js} +2 -2
  10. package/dist/{chunk-UJ2WYHH7.js.map → chunk-NPBIRXLC.js.map} +1 -1
  11. package/dist/chunk-PPPB2U34.js +2 -0
  12. package/dist/chunk-PPPB2U34.js.map +1 -0
  13. package/dist/chunk-ZCIM5A5S.js +3 -0
  14. package/dist/chunk-ZCIM5A5S.js.map +1 -0
  15. package/dist/client.d.ts +120 -2
  16. package/dist/client.js +1 -1
  17. package/dist/{package-YDKHBRBH.js → package-D62UBES3.js} +2 -2
  18. package/dist/{package-YDKHBRBH.js.map → package-D62UBES3.js.map} +1 -1
  19. package/dist/{render-OM7ZJWZA.js → render-FZAHNIJB.js} +2 -2
  20. package/dist/{render-OM7ZJWZA.js.map → render-FZAHNIJB.js.map} +1 -1
  21. package/dist/renderApp-DZBN6IKT.js +2 -0
  22. package/dist/{renderApp-MD5O44UP.js.map → renderApp-DZBN6IKT.js.map} +1 -1
  23. package/dist/server-TGEMYLAH.js +2 -0
  24. package/dist/{server-GHQ5XNNQ.js.map → server-TGEMYLAH.js.map} +1 -1
  25. package/dist/server.d.ts +81 -2
  26. package/dist/server.js +1 -1
  27. package/dist/transport-N3EV2QPS.js +2 -0
  28. package/dist/{transport-VKGH6BY6.js.map → transport-N3EV2QPS.js.map} +1 -1
  29. package/package.json +1 -1
  30. package/dist/chunk-4I4BI7KD.js +0 -2
  31. package/dist/chunk-4I4BI7KD.js.map +0 -1
  32. package/dist/chunk-KDOTVIEY.js +0 -4
  33. package/dist/chunk-KDOTVIEY.js.map +0 -1
  34. package/dist/chunk-KFTT3M45.js +0 -3
  35. package/dist/chunk-KFTT3M45.js.map +0 -1
  36. package/dist/chunk-LCXJNLNK.js +0 -41
  37. package/dist/chunk-LCXJNLNK.js.map +0 -1
  38. package/dist/chunk-W4RFIS5E.js +0 -2
  39. package/dist/chunk-W4RFIS5E.js.map +0 -1
  40. package/dist/chunk-WDY7BYXR.js +0 -3
  41. package/dist/renderApp-MD5O44UP.js +0 -2
  42. package/dist/server-GHQ5XNNQ.js +0 -2
  43. package/dist/transport-VKGH6BY6.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client/SetupScreen.tsx","../src/client/AppProvider.tsx","../src/websocket/socketio/client.ts","../src/websocket/client.ts","../src/client/query.ts","../src/client/queryProvider.tsx"],"names":["styles","SetupScreen","jsx","jsxs","Step","number","children","SSR_STATE_SCRIPT_ID","SETUP_POLL_INTERVAL","isInitialized","hasServerRenderedMarkup","AppProvider","loadingElement","setupElement","isServer","isLoading","setIsLoading","useState","isSessionInitialized","needsSetup","setNeedsSetup","_isSetupRequired","useEffect","initConfig","_isReconciliationPending","reconcileSession","initSession","cancelled","timer","poll","setupRequired","callMethod","socketClient","activeLiveSubscriptions","getSocket","resubscribeAll","authToken","getAuthToken","clientInfo","getClientInfo","sub","init","props","baseUrl","getClientConfig","io","channel","on","category","listener","once","off","emit","eventName","id","joinChannel","leaveChannel","liveQueryCounter","subscribeLiveQuery","method","args","onData","onError","subscriptionId","handleData","sid","data","typeMap","reviveResponseTypes","handleError","error","socket","websocketProvider","client_default","websocketClientProvider","setWebsocketClientProvider","provider","getWebsocketClientProvider","startWebsockets","queryClientRef","cacheUnsubscribe","websocketsStarted","subscriptions","connectModelenceQueryClient","queryClient","disconnectModelenceQueryClient","event","subscriptionKey","hashKey","cancelError","r","hasConnectedQueryClient","ModelenceQueryClient","modelenceQuery","methodName","modelenceLiveQuery","queryKey","resolve","reject","currentSub","modelenceMutation","defaultArgs","variables","createQueryKey","SSR_QUERY_STATE_SCRIPT_ID","readDehydratedState","node","e","ModelenceQueryProvider","client","dehydratedState","internalClient","qc","QueryClient","state","QueryClientProvider","HydrationBoundary"],"mappings":"2TAeA,IAAMA,EAA8C,CAClD,IAAA,CAAM,CACJ,SAAA,CAAW,OAAA,CACX,gBAAiB,SAAA,CACjB,OAAA,CAAS,MAAA,CACT,UAAA,CAAY,SACZ,cAAA,CAAgB,QAAA,CAChB,QAAS,QAAA,CACT,UAAA,CACE,6FACF,KAAA,CAAO,SACT,CAAA,CACA,SAAA,CAAW,CACT,QAAA,CAAU,OAAA,CACV,MAAO,MACT,CAAA,CACA,SAAU,CACR,OAAA,CAAS,MAAA,CACT,cAAA,CAAgB,SAChB,YAAA,CAAc,MAChB,EACA,KAAA,CAAO,CACL,SAAU,MAAA,CACV,UAAA,CAAY,MAAA,CACZ,UAAA,CAAY,IACZ,SAAA,CAAW,QAAA,CACX,OAAQ,CACV,CAAA,CACA,SAAU,CACR,SAAA,CAAW,MAAA,CACX,KAAA,CAAO,UACP,SAAA,CAAW,QACb,EACA,KAAA,CAAO,CACL,UAAW,MAAA,CACX,SAAA,CAAW,OACX,OAAA,CAAS,CAAA,CACT,QAAS,MAAA,CACT,aAAA,CAAe,SACf,GAAA,CAAK,MACP,EACA,IAAA,CAAM,CACJ,OAAA,CAAS,MAAA,CACT,IAAK,MAAA,CACL,UAAA,CAAY,aACZ,eAAA,CAAiB,SAAA,CACjB,aAAc,KAAA,CACd,MAAA,CAAQ,mBAAA,CACR,OAAA,CAAS,MACX,CAAA,CACA,UAAA,CAAY,CACV,IAAA,CAAM,MAAA,CACN,MAAO,MAAA,CACP,MAAA,CAAQ,MAAA,CACR,YAAA,CAAc,SACd,eAAA,CAAiB,SAAA,CAC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AA5G,CAAAA,CAAS,EAC7C,CAEJ","file":"chunk-WDY7BYXR.js","sourcesContent":["'use client';\n\nimport { ReactNode } from 'react';\n\n/*\n Shown by AppProvider instead of the app when a development server reports it\n has no backend at all — no Modelence Cloud connection and no local database\n (see server-side isSetupRequired). This is the state of every fresh clone:\n .modelence.env holds the environment's credentials and is gitignored, so it\n never travels with the repo.\n\n Styled inline: this renders inside arbitrary user apps, so it can't rely on\n any CSS framework being present.\n*/\n\nconst styles: Record<string, React.CSSProperties> = {\n page: {\n minHeight: '100vh',\n backgroundColor: '#f3f4f6',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n padding: '0 16px',\n fontFamily:\n \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif\",\n color: '#111827',\n },\n container: {\n maxWidth: '576px',\n width: '100%',\n },\n logoWrap: {\n display: 'flex',\n justifyContent: 'center',\n marginBottom: '32px',\n },\n title: {\n fontSize: '30px',\n lineHeight: '36px',\n fontWeight: 700,\n textAlign: 'center',\n margin: 0,\n },\n subtitle: {\n marginTop: '16px',\n color: '#4b5563',\n textAlign: 'center',\n },\n steps: {\n marginTop: '32px',\n listStyle: 'none',\n padding: 0,\n display: 'flex',\n flexDirection: 'column',\n gap: '16px',\n },\n step: {\n display: 'flex',\n gap: '16px',\n alignItems: 'flex-start',\n backgroundColor: '#ffffff',\n borderRadius: '8px',\n border: '1px solid #e5e7eb',\n padding: '16px',\n },\n stepNumber: {\n flex: 'none',\n width: '28px',\n height: '28px',\n borderRadius: '9999px',\n backgroundColor: '#111827',\n color: '#ffffff',\n fontSize: '14px',\n fontWeight: 600,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n },\n stepText: {\n color: '#374151',\n lineHeight: '28px',\n },\n code: {\n fontSize: '14px',\n fontFamily: \"ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace\",\n backgroundColor: '#e5e7eb',\n borderRadius: '4px',\n padding: '2px 4px',\n },\n footer: {\n marginTop: '32px',\n fontSize: '14px',\n color: '#6b7280',\n textAlign: 'center',\n },\n};\n\nexport default function SetupScreen() {\n return (\n <div style={styles.page}>\n <div style={styles.container}>\n <div style={styles.logoWrap}>\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"80\"\n height=\"80\"\n viewBox=\"0 0 48 48\"\n fill=\"none\"\n aria-label=\"Modelence Logo\"\n >\n <path\n fill=\"#5509D9\"\n d=\"M45 22.788V12L24 0l-9.437 5.392L45 22.788ZM25.152 35.24l10.589 6.052 8.107-4.632-10.589-6.052-8.107 4.632Zm9.26-15.872v9.264L45 34.684V25.42l-10.589-6.052ZM3 25.212V36l21 12 9.441-5.392L3 25.212ZM22.848 12.76 12.26 6.708 4.152 11.34l10.589 6.052 8.107-4.632Zm-9.26 15.872v-9.264L3 13.316v9.264l10.589 6.052Z\"\n />\n </svg>\n </div>\n <h1 style={styles.title}>Connect this project to Modelence Cloud</h1>\n <p style={styles.subtitle}>One quick step before you can use this app locally.</p>\n\n <ol style={styles.steps}>\n <Step number={1}>\n Run <code style={styles.code}>npx modelence setup</code> in the project folder.\n </Step>\n <Step number={2}>Your browser opens &mdash; log in and choose your environment.</Step>\n <Step number={3}>\n Restart the dev server (<code style={styles.code}>npm run dev</code>).\n </Step>\n </ol>\n\n <p style={styles.footer}>\n This page refreshes automatically once the project is connected.\n </p>\n </div>\n </div>\n );\n}\n\nfunction Step({ number, children }: { number: number; children: ReactNode }) {\n return (\n <li style={styles.step}>\n <span style={styles.stepNumber}>{number}</span>\n <span style={styles.stepText}>{children}</span>\n </li>\n );\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n\n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport { useState, useEffect, ReactNode } from 'react';\nimport { callMethod } from './method';\nimport SetupScreen from './SetupScreen';\nimport {\n _isReconciliationPending,\n _isSetupRequired,\n initSession,\n isSessionInitialized,\n reconcileSession,\n} from './session';\n\nconst SSR_STATE_SCRIPT_ID = '__MODELENCE_STATE__';\nconst SETUP_POLL_INTERVAL = 3000;\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n /*\n Replaces the built-in setup screen shown when a development server has no\n backend yet (see SetupScreen). Pass `null` to disable the screen entirely\n and render the app regardless.\n */\n setupElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\n// Presence of the state script signals server-rendered markup in the DOM,\n// even if `hydrateSession` failed to parse it. Hiding under a loading shell\n// here would cause a hydration mismatch and a flash-of-spinner.\nfunction hasServerRenderedMarkup(): boolean {\n return typeof document !== 'undefined' && document.getElementById(SSR_STATE_SCRIPT_ID) !== null;\n}\n\nexport function AppProvider({ children, loadingElement, setupElement }: AppProviderProps) {\n const isServer = typeof window === 'undefined';\n const [isLoading, setIsLoading] = useState(\n () => !isServer && !isSessionInitialized() && !hasServerRenderedMarkup()\n );\n const [needsSetup, setNeedsSetup] = useState(\n () => !isServer && isSessionInitialized() && _isSetupRequired()\n );\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n if (isSessionInitialized()) {\n // SSR couldn't authenticate via cookie; reconcile via body token now.\n if (_isReconciliationPending()) {\n await reconcileSession();\n }\n // The initial useState read already saw the hydrated value, but only\n // because hydrateSession() runs before the first render — re-read\n // here so the setup screen doesn't depend on that ordering.\n setNeedsSetup(_isSetupRequired());\n return;\n }\n\n await initSession();\n setNeedsSetup(_isSetupRequired());\n setIsLoading(false);\n }\n\n void initConfig();\n }, []);\n\n // While the setup screen is up, watch for the project getting connected\n // (setup writes .modelence.env and the user restarts the dev server) and\n // reload for a clean boot. Poll errors are expected mid-restart.\n // Rescheduled after each poll settles, so requests never pile up while the\n // dev server hangs mid-restart and background-tab throttling can't burst.\n useEffect(() => {\n if (!needsSetup) {\n return;\n }\n\n let cancelled = false;\n let timer: ReturnType<typeof setTimeout>;\n\n async function poll() {\n try {\n const { setupRequired } = await callMethod<{ setupRequired: boolean }>(\n '_system.setupStatus',\n {},\n { errorHandler: () => {} }\n );\n if (!setupRequired) {\n window.location.reload();\n return;\n }\n } catch {\n // Dev server restarting — keep polling.\n }\n if (!cancelled) {\n timer = setTimeout(poll, SETUP_POLL_INTERVAL);\n }\n }\n\n timer = setTimeout(poll, SETUP_POLL_INTERVAL);\n\n return () => {\n cancelled = true;\n clearTimeout(timer);\n };\n }, [needsSetup]);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n if (needsSetup && setupElement !== null) {\n return setupElement ?? <SetupScreen />;\n }\n\n return children;\n}\n","import io, { Socket } from 'socket.io-client';\nimport { WebsocketClientProvider } from '../types';\nimport { ClientChannel } from '../clientChannel';\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { getClientConfig } from '@/client/clientConfig';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nlet socketClient: Socket | null = null;\n\ninterface ActiveLiveSubscription {\n subscriptionId: string;\n method: string;\n args: Record<string, unknown>;\n}\nconst activeLiveSubscriptions = new Map<string, ActiveLiveSubscription>();\n\nfunction getSocket(): Socket {\n if (!socketClient) {\n throw new Error('WebSocket not initialized. Call startWebsockets() first.');\n }\n return socketClient;\n}\n\nfunction resubscribeAll() {\n const authToken = getAuthToken();\n const clientInfo = getClientInfo();\n for (const sub of activeLiveSubscriptions.values()) {\n socketClient?.emit('subscribeLiveQuery', {\n subscriptionId: sub.subscriptionId,\n method: sub.method,\n args: sub.args,\n authToken,\n clientInfo,\n });\n }\n}\n\nfunction init(props: { channels?: ClientChannel<unknown>[] }) {\n const baseUrl = getClientConfig()?.baseUrl ?? '/';\n socketClient = io(baseUrl, {\n transports: ['websocket'],\n auth: {\n token: getAuthToken(),\n },\n });\n\n // Subscribe to all live queries on connect/reconnect\n socketClient.on('connect', () => {\n if (activeLiveSubscriptions.size > 0) {\n console.log(\n `[Modelence] WebSocket reconnected, re-subscribing to ${activeLiveSubscriptions.size} live queries`\n );\n resubscribeAll();\n }\n });\n\n props.channels?.forEach((channel) => channel.init());\n}\n\nfunction on<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().on(category, listener);\n}\n\nfunction once<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().once(category, listener);\n}\n\nfunction off<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().off(category, listener);\n}\n\nfunction emit({ eventName, category, id }: { eventName: string; category: string; id: string }) {\n getSocket().emit(eventName, `${category}:${id}`);\n}\n\nfunction joinChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'joinChannel',\n category,\n id,\n });\n}\n\nfunction leaveChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'leaveChannel',\n category,\n id,\n });\n}\n\nlet liveQueryCounter = 0;\n\nexport function subscribeLiveQuery<T = unknown>(\n method: string,\n args: Record<string, unknown>,\n onData: (data: T) => void,\n onError?: (error: string) => void\n): () => void {\n const subscriptionId = `sub-${++liveQueryCounter}-${Date.now()}`;\n\n const handleData = ({\n subscriptionId: sid,\n data,\n typeMap,\n }: {\n subscriptionId: string;\n data: T;\n typeMap?: Record<string, unknown>;\n }) => {\n if (sid === subscriptionId) {\n onData(reviveResponseTypes(data, typeMap));\n }\n };\n\n const handleError = ({\n subscriptionId: sid,\n error,\n }: {\n subscriptionId: string;\n error: string;\n }) => {\n if (sid === subscriptionId) {\n console.error(`[Modelence] Live query error for ${method}:`, error);\n onError?.(error);\n }\n };\n\n const socket = getSocket();\n socket.on('liveQueryData', handleData);\n socket.on('liveQueryError', handleError);\n\n activeLiveSubscriptions.set(subscriptionId, { subscriptionId, method, args });\n\n // Only emit if already connected; otherwise the connect handler will handle it\n if (socket.connected) {\n socket.emit('subscribeLiveQuery', {\n subscriptionId,\n method,\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n });\n }\n\n // Return unsubscribe function\n return () => {\n activeLiveSubscriptions.delete(subscriptionId);\n socket.emit('unsubscribeLiveQuery', { subscriptionId });\n socket.off('liveQueryData', handleData);\n socket.off('liveQueryError', handleError);\n };\n}\n\nconst websocketProvider: WebsocketClientProvider = {\n init,\n on,\n once,\n off,\n emit,\n joinChannel,\n leaveChannel,\n};\n\nexport default websocketProvider;\n","import { ClientChannel } from './clientChannel';\nimport websocketProvider, { subscribeLiveQuery } from './socketio/client';\nimport { WebsocketClientProvider } from './types';\n\nexport { subscribeLiveQuery };\n\nlet websocketClientProvider: WebsocketClientProvider | null = null;\n\nexport function setWebsocketClientProvider(provider: WebsocketClientProvider | null) {\n websocketClientProvider = provider;\n}\n\nexport function getWebsocketClientProvider() {\n return websocketClientProvider;\n}\n\nexport function startWebsockets(props?: {\n provider?: WebsocketClientProvider;\n channels?: ClientChannel[];\n}) {\n if (websocketClientProvider) {\n console.warn('WebSocket already initialized. Skipping initialization.');\n return;\n }\n\n const provider = props?.provider || websocketProvider;\n setWebsocketClientProvider(provider);\n try {\n provider.init({\n channels: props?.channels,\n });\n } catch (error) {\n setWebsocketClientProvider(null);\n throw error;\n }\n}\n","'use client';\n\nimport { QueryClient, hashKey } from '@tanstack/react-query';\nimport { callMethod } from './method';\nimport { startWebsockets, subscribeLiveQuery } from '../websocket/client';\n\ntype Args = Record<string, unknown>;\n\ninterface Subscription {\n unsubscribe: () => void;\n resolvers: Set<{\n resolve: (data: unknown) => void;\n reject: (error: Error) => void;\n }>;\n}\n\nlet queryClientRef: QueryClient | null = null;\nlet cacheUnsubscribe: (() => void) | null = null;\nlet websocketsStarted = false;\nconst subscriptions = new Map<string, Subscription>();\n\n/**\n * Connects a `QueryClient` to Modelence's live-query layer. Auto-called by\n * `<ModelenceQueryProvider>`; only call manually if you mount your own\n * `<QueryClientProvider>`.\n *\n * Note: WebSocket setup is deferred until the first `modelenceLiveQuery`\n * call, so apps that only use `modelenceQuery`/`modelenceMutation` never\n * open a socket.\n */\nexport function connectModelenceQueryClient(queryClient: QueryClient) {\n if (queryClientRef === queryClient) {\n return;\n }\n\n if (queryClientRef) {\n disconnectModelenceQueryClient();\n }\n\n queryClientRef = queryClient;\n\n cacheUnsubscribe = queryClient.getQueryCache().subscribe((event) => {\n if (event.type === 'removed') {\n const subscriptionKey = hashKey(event.query.queryKey);\n const sub = subscriptions.get(subscriptionKey);\n if (sub) {\n if (sub.resolvers.size > 0) {\n const cancelError = new Error('Query was removed from cache');\n sub.resolvers.forEach((r) => r.reject(cancelError));\n sub.resolvers.clear();\n }\n sub.unsubscribe();\n subscriptions.delete(subscriptionKey);\n }\n }\n });\n}\n\n/**\n * Whether a `QueryClient` is already connected to the live-query layer.\n * `renderApp` uses this to avoid injecting its own `<ModelenceQueryProvider>`\n * when the app already mounts its own provider and connects it beforehand.\n */\nexport function hasConnectedQueryClient(): boolean {\n return queryClientRef !== null;\n}\n\nexport function disconnectModelenceQueryClient() {\n if (cacheUnsubscribe) {\n cacheUnsubscribe();\n cacheUnsubscribe = null;\n }\n subscriptions.forEach((sub) => sub.unsubscribe());\n subscriptions.clear();\n queryClientRef = null;\n websocketsStarted = false;\n}\n\n/** @deprecated Use `connectModelenceQueryClient(queryClient)` instead. */\nexport class ModelenceQueryClient {\n connect(queryClient: QueryClient) {\n connectModelenceQueryClient(queryClient);\n }\n}\n\n/**\n * @example\n * ```tsx\n * const { data } = useQuery(modelenceQuery('todo.getAll'));\n * ```\n */\nexport function modelenceQuery<T = unknown>(methodName: string, args: Args = {}) {\n return {\n queryKey: [methodName, args],\n queryFn: () => callMethod<T>(methodName, args),\n };\n}\n\n/**\n * Live query — data updates in real time as the underlying collection changes.\n * Requires a `QueryClient` connected via `<ModelenceQueryProvider>` or\n * `connectModelenceQueryClient(...)`.\n */\nexport function modelenceLiveQuery<T = unknown>(methodName: string, args: Args = {}) {\n const queryKey = ['live', methodName, args] as const;\n const subscriptionKey = hashKey(queryKey);\n\n return {\n queryKey,\n queryFn: () =>\n new Promise<T>((resolve, reject) => {\n // Live queries are WebSocket subscriptions — no server snapshot. Stay\n // pending on the server so Suspense renders; client re-runs after hydration.\n if (typeof window === 'undefined') {\n return;\n }\n\n if (!queryClientRef) {\n const error = new Error(\n 'Modelence: connect a QueryClient before using modelenceLiveQuery(). Mount <ModelenceQueryProvider> or call connectModelenceQueryClient().'\n );\n console.error('[Modelence]', error.message);\n reject(error);\n return;\n }\n\n if (!websocketsStarted) {\n startWebsockets();\n websocketsStarted = true;\n }\n\n let sub = subscriptions.get(subscriptionKey);\n\n if (!sub) {\n const unsubscribe = subscribeLiveQuery<T>(\n methodName,\n args,\n (data) => {\n const currentSub = subscriptions.get(subscriptionKey);\n\n if (currentSub?.resolvers.size) {\n currentSub.resolvers.forEach((r) => r.resolve(data));\n currentSub.resolvers.clear();\n }\n\n if (queryClientRef) {\n queryClientRef.setQueryData(queryKey, data);\n }\n },\n (error) => {\n const currentSub = subscriptions.get(subscriptionKey);\n if (currentSub) {\n if (currentSub.resolvers.size) {\n currentSub.resolvers.forEach((r) => r.reject(new Error(error)));\n currentSub.resolvers.clear();\n }\n currentSub.unsubscribe();\n subscriptions.delete(subscriptionKey);\n }\n }\n );\n\n sub = { unsubscribe, resolvers: new Set() };\n subscriptions.set(subscriptionKey, sub);\n }\n\n // Shared map stores resolvers across `T` instantiations; erase the union.\n sub.resolvers.add({\n resolve: resolve as (data: unknown) => void,\n reject,\n });\n }),\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n refetchOnMount: false,\n refetchOnReconnect: false,\n gcTime: 0,\n };\n}\n\nexport function modelenceMutation<T = unknown>(methodName: string, defaultArgs: Args = {}) {\n return {\n mutationFn: (variables: Args = {}) =>\n callMethod<T>(methodName, { ...defaultArgs, ...variables }),\n };\n}\n\nexport type ModelenceQueryKey<T extends string, U extends Args = Args> = readonly [T, U];\n\n/** Builds a query key matching `modelenceQuery(...)` for cache operations. */\nexport function createQueryKey<T extends string, U extends Args = Args>(\n methodName: T,\n args: U = {} as U\n): ModelenceQueryKey<T, U> {\n return [methodName, args] as const;\n}\n","'use client';\n\nimport { useState, type ReactNode } from 'react';\nimport {\n QueryClient,\n QueryClientProvider,\n HydrationBoundary,\n type DehydratedState,\n} from '@tanstack/react-query';\nimport { connectModelenceQueryClient } from './query';\n\nconst SSR_QUERY_STATE_SCRIPT_ID = '__MODELENCE_QUERY_STATE__';\n\nfunction readDehydratedState(): DehydratedState | undefined {\n if (typeof document === 'undefined') {\n return undefined;\n }\n\n const node = document.getElementById(SSR_QUERY_STATE_SCRIPT_ID);\n if (!node || !node.textContent) {\n return undefined;\n }\n\n try {\n return JSON.parse(node.textContent) as DehydratedState;\n } catch (e) {\n console.error('Modelence: failed to parse SSR query state', e);\n return undefined;\n }\n}\n\ninterface ModelenceQueryProviderProps {\n children: ReactNode;\n client?: QueryClient;\n dehydratedState?: DehydratedState;\n}\n\nexport function ModelenceQueryProvider({\n children,\n client,\n dehydratedState,\n}: ModelenceQueryProviderProps) {\n const [internalClient] = useState(() => {\n const qc =\n client ??\n new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: 60 * 1000,\n },\n },\n });\n if (typeof window !== 'undefined') {\n connectModelenceQueryClient(qc);\n }\n return qc;\n });\n\n const state = dehydratedState ?? readDehydratedState();\n\n return (\n <QueryClientProvider client={internalClient}>\n <HydrationBoundary state={state}>{children}</HydrationBoundary>\n </QueryClientProvider>\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/client/SetupScreen.tsx","../src/client/AppProvider.tsx","../src/websocket/socketio/client.ts","../src/websocket/client.ts","../src/client/query.ts","../src/client/queryProvider.tsx"],"names":["styles","SetupScreen","jsx","jsxs","Step","number","children","SSR_STATE_SCRIPT_ID","SETUP_POLL_INTERVAL","isInitialized","hasServerRenderedMarkup","AppProvider","loadingElement","setupElement","isServer","isLoading","setIsLoading","useState","isSessionInitialized","needsSetup","setNeedsSetup","_isSetupRequired","useEffect","initConfig","_isReconciliationPending","reconcileSession","initSession","cancelled","timer","poll","setupRequired","callMethod","socketClient","activeLiveSubscriptions","getSocket","resubscribeAll","authToken","getAuthToken","clientInfo","getClientInfo","sub","init","props","baseUrl","getClientConfig","io","channel","on","category","listener","once","off","emit","eventName","id","joinChannel","leaveChannel","liveQueryCounter","subscribeLiveQuery","method","args","onData","onError","subscriptionId","handleData","sid","data","typeMap","reviveResponseTypes","handleError","error","socket","websocketProvider","client_default","websocketClientProvider","setWebsocketClientProvider","provider","getWebsocketClientProvider","startWebsockets","queryClientRef","cacheUnsubscribe","websocketsStarted","subscriptions","connectModelenceQueryClient","queryClient","disconnectModelenceQueryClient","event","subscriptionKey","hashKey","cancelError","r","hasConnectedQueryClient","ModelenceQueryClient","modelenceQuery","methodName","modelenceLiveQuery","queryKey","resolve","reject","currentSub","modelenceMutation","defaultArgs","variables","createQueryKey","SSR_QUERY_STATE_SCRIPT_ID","readDehydratedState","node","e","ModelenceQueryProvider","client","dehydratedState","internalClient","qc","QueryClient","state","QueryClientProvider","HydrationBoundary"],"mappings":"yUAeA,IAAMA,EAA8C,CAClD,IAAA,CAAM,CACJ,SAAA,CAAW,OAAA,CACX,gBAAiB,SAAA,CACjB,OAAA,CAAS,MAAA,CACT,UAAA,CAAY,SACZ,cAAA,CAAgB,QAAA,CAChB,QAAS,QAAA,CACT,UAAA,CACE,6FACF,KAAA,CAAO,SACT,CAAA,CACA,SAAA,CAAW,CACT,QAAA,CAAU,OAAA,CACV,MAAO,MACT,CAAA,CACA,SAAU,CACR,OAAA,CAAS,MAAA,CACT,cAAA,CAAgB,SAChB,YAAA,CAAc,MAChB,EACA,KAAA,CAAO,CACL,SAAU,MAAA,CACV,UAAA,CAAY,MAAA,CACZ,UAAA,CAAY,IACZ,SAAA,CAAW,QAAA,CACX,OAAQ,CACV,CAAA,CACA,SAAU,CACR,SAAA,CAAW,MAAA,CACX,KAAA,CAAO,UACP,SAAA,CAAW,QACb,EACA,KAAA,CAAO,CACL,UAAW,MAAA,CACX,SAAA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,IAAM+F,CAAAA,CACJH,CAAAA,EACA,IAAII,YAAY,CACd,cAAA,CAAgB,CACd,OAAA,CAAS,CACP,UAAW,GACb,CACF,CACF,CAAC,EACH,OAAI,OAAO,OAAW,GAAA,EACpB9B,CAAAA,CAA4B6B,CAAE,CAAA,CAEzBA,CACT,CAAC,CAAA,CAEKE,EAAQJ,CAAAA,EAAmBL,EAAAA,GAEjC,OACEvG,GAAAA,CAACiH,oBAAA,CAAoB,MAAA,CAAQJ,EAC3B,QAAA,CAAA7G,GAAAA,CAACkH,kBAAA,CAAkB,KAAA,CAAOF,EAAQ,QAAA,CAAA5G,CAAAA,CAAS,EAC7C,CAEJ","file":"chunk-ACX7KY6E.js","sourcesContent":["'use client';\n\nimport { ReactNode } from 'react';\n\n/*\n Shown by AppProvider instead of the app when a development server reports it\n has no backend at all — no Modelence Cloud connection and no local database\n (see server-side isSetupRequired). This is the state of every fresh clone:\n .modelence.env holds the environment's credentials and is gitignored, so it\n never travels with the repo.\n\n Styled inline: this renders inside arbitrary user apps, so it can't rely on\n any CSS framework being present.\n*/\n\nconst styles: Record<string, React.CSSProperties> = {\n page: {\n minHeight: '100vh',\n backgroundColor: '#f3f4f6',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n padding: '0 16px',\n fontFamily:\n \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif\",\n color: '#111827',\n },\n container: {\n maxWidth: '576px',\n width: '100%',\n },\n logoWrap: {\n display: 'flex',\n justifyContent: 'center',\n marginBottom: '32px',\n },\n title: {\n fontSize: '30px',\n lineHeight: '36px',\n fontWeight: 700,\n textAlign: 'center',\n margin: 0,\n },\n subtitle: {\n marginTop: '16px',\n color: '#4b5563',\n textAlign: 'center',\n },\n steps: {\n marginTop: '32px',\n listStyle: 'none',\n padding: 0,\n display: 'flex',\n flexDirection: 'column',\n gap: '16px',\n },\n step: {\n display: 'flex',\n gap: '16px',\n alignItems: 'flex-start',\n backgroundColor: '#ffffff',\n borderRadius: '8px',\n border: '1px solid #e5e7eb',\n padding: '16px',\n },\n stepNumber: {\n flex: 'none',\n width: '28px',\n height: '28px',\n borderRadius: '9999px',\n backgroundColor: '#111827',\n color: '#ffffff',\n fontSize: '14px',\n fontWeight: 600,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n },\n stepText: {\n color: '#374151',\n lineHeight: '28px',\n },\n code: {\n fontSize: '14px',\n fontFamily: \"ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace\",\n backgroundColor: '#e5e7eb',\n borderRadius: '4px',\n padding: '2px 4px',\n },\n footer: {\n marginTop: '32px',\n fontSize: '14px',\n color: '#6b7280',\n textAlign: 'center',\n },\n};\n\nexport default function SetupScreen() {\n return (\n <div style={styles.page}>\n <div style={styles.container}>\n <div style={styles.logoWrap}>\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"80\"\n height=\"80\"\n viewBox=\"0 0 48 48\"\n fill=\"none\"\n aria-label=\"Modelence Logo\"\n >\n <path\n fill=\"#5509D9\"\n d=\"M45 22.788V12L24 0l-9.437 5.392L45 22.788ZM25.152 35.24l10.589 6.052 8.107-4.632-10.589-6.052-8.107 4.632Zm9.26-15.872v9.264L45 34.684V25.42l-10.589-6.052ZM3 25.212V36l21 12 9.441-5.392L3 25.212ZM22.848 12.76 12.26 6.708 4.152 11.34l10.589 6.052 8.107-4.632Zm-9.26 15.872v-9.264L3 13.316v9.264l10.589 6.052Z\"\n />\n </svg>\n </div>\n <h1 style={styles.title}>Connect this project to Modelence Cloud</h1>\n <p style={styles.subtitle}>One quick step before you can use this app locally.</p>\n\n <ol style={styles.steps}>\n <Step number={1}>\n Run <code style={styles.code}>npx modelence setup</code> in the project folder.\n </Step>\n <Step number={2}>Your browser opens &mdash; log in and choose your environment.</Step>\n <Step number={3}>\n Restart the dev server (<code style={styles.code}>npm run dev</code>).\n </Step>\n </ol>\n\n <p style={styles.footer}>\n This page refreshes automatically once the project is connected.\n </p>\n </div>\n </div>\n );\n}\n\nfunction Step({ number, children }: { number: number; children: ReactNode }) {\n return (\n <li style={styles.step}>\n <span style={styles.stepNumber}>{number}</span>\n <span style={styles.stepText}>{children}</span>\n </li>\n );\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n\n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport { useState, useEffect, ReactNode } from 'react';\nimport { callMethod } from './method';\nimport SetupScreen from './SetupScreen';\nimport {\n _isReconciliationPending,\n _isSetupRequired,\n initSession,\n isSessionInitialized,\n reconcileSession,\n} from './session';\n\nconst SSR_STATE_SCRIPT_ID = '__MODELENCE_STATE__';\nconst SETUP_POLL_INTERVAL = 3000;\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n /*\n Replaces the built-in setup screen shown when a development server has no\n backend yet (see SetupScreen). Pass `null` to disable the screen entirely\n and render the app regardless.\n */\n setupElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\n// Presence of the state script signals server-rendered markup in the DOM,\n// even if `hydrateSession` failed to parse it. Hiding under a loading shell\n// here would cause a hydration mismatch and a flash-of-spinner.\nfunction hasServerRenderedMarkup(): boolean {\n return typeof document !== 'undefined' && document.getElementById(SSR_STATE_SCRIPT_ID) !== null;\n}\n\nexport function AppProvider({ children, loadingElement, setupElement }: AppProviderProps) {\n const isServer = typeof window === 'undefined';\n const [isLoading, setIsLoading] = useState(\n () => !isServer && !isSessionInitialized() && !hasServerRenderedMarkup()\n );\n const [needsSetup, setNeedsSetup] = useState(\n () => !isServer && isSessionInitialized() && _isSetupRequired()\n );\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n if (isSessionInitialized()) {\n // SSR couldn't authenticate via cookie; reconcile via body token now.\n if (_isReconciliationPending()) {\n await reconcileSession();\n }\n // The initial useState read already saw the hydrated value, but only\n // because hydrateSession() runs before the first render — re-read\n // here so the setup screen doesn't depend on that ordering.\n setNeedsSetup(_isSetupRequired());\n return;\n }\n\n await initSession();\n setNeedsSetup(_isSetupRequired());\n setIsLoading(false);\n }\n\n void initConfig();\n }, []);\n\n // While the setup screen is up, watch for the project getting connected\n // (setup writes .modelence.env and the user restarts the dev server) and\n // reload for a clean boot. Poll errors are expected mid-restart.\n // Rescheduled after each poll settles, so requests never pile up while the\n // dev server hangs mid-restart and background-tab throttling can't burst.\n useEffect(() => {\n if (!needsSetup) {\n return;\n }\n\n let cancelled = false;\n let timer: ReturnType<typeof setTimeout>;\n\n async function poll() {\n try {\n const { setupRequired } = await callMethod<{ setupRequired: boolean }>(\n '_system.setupStatus',\n {},\n { errorHandler: () => {} }\n );\n if (!setupRequired) {\n window.location.reload();\n return;\n }\n } catch {\n // Dev server restarting — keep polling.\n }\n if (!cancelled) {\n timer = setTimeout(poll, SETUP_POLL_INTERVAL);\n }\n }\n\n timer = setTimeout(poll, SETUP_POLL_INTERVAL);\n\n return () => {\n cancelled = true;\n clearTimeout(timer);\n };\n }, [needsSetup]);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n if (needsSetup && setupElement !== null) {\n return setupElement ?? <SetupScreen />;\n }\n\n return children;\n}\n","import io, { Socket } from 'socket.io-client';\nimport { WebsocketClientProvider } from '../types';\nimport { ClientChannel } from '../clientChannel';\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { getClientConfig } from '@/client/clientConfig';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nlet socketClient: Socket | null = null;\n\ninterface ActiveLiveSubscription {\n subscriptionId: string;\n method: string;\n args: Record<string, unknown>;\n}\nconst activeLiveSubscriptions = new Map<string, ActiveLiveSubscription>();\n\nfunction getSocket(): Socket {\n if (!socketClient) {\n throw new Error('WebSocket not initialized. Call startWebsockets() first.');\n }\n return socketClient;\n}\n\nfunction resubscribeAll() {\n const authToken = getAuthToken();\n const clientInfo = getClientInfo();\n for (const sub of activeLiveSubscriptions.values()) {\n socketClient?.emit('subscribeLiveQuery', {\n subscriptionId: sub.subscriptionId,\n method: sub.method,\n args: sub.args,\n authToken,\n clientInfo,\n });\n }\n}\n\nfunction init(props: { channels?: ClientChannel<unknown>[] }) {\n const baseUrl = getClientConfig()?.baseUrl ?? '/';\n socketClient = io(baseUrl, {\n transports: ['websocket'],\n auth: {\n token: getAuthToken(),\n },\n });\n\n // Subscribe to all live queries on connect/reconnect\n socketClient.on('connect', () => {\n if (activeLiveSubscriptions.size > 0) {\n console.log(\n `[Modelence] WebSocket reconnected, re-subscribing to ${activeLiveSubscriptions.size} live queries`\n );\n resubscribeAll();\n }\n });\n\n props.channels?.forEach((channel) => channel.init());\n}\n\nfunction on<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().on(category, listener);\n}\n\nfunction once<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().once(category, listener);\n}\n\nfunction off<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().off(category, listener);\n}\n\nfunction emit({ eventName, category, id }: { eventName: string; category: string; id: string }) {\n getSocket().emit(eventName, `${category}:${id}`);\n}\n\nfunction joinChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'joinChannel',\n category,\n id,\n });\n}\n\nfunction leaveChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'leaveChannel',\n category,\n id,\n });\n}\n\nlet liveQueryCounter = 0;\n\nexport function subscribeLiveQuery<T = unknown>(\n method: string,\n args: Record<string, unknown>,\n onData: (data: T) => void,\n onError?: (error: string) => void\n): () => void {\n const subscriptionId = `sub-${++liveQueryCounter}-${Date.now()}`;\n\n const handleData = ({\n subscriptionId: sid,\n data,\n typeMap,\n }: {\n subscriptionId: string;\n data: T;\n typeMap?: Record<string, unknown>;\n }) => {\n if (sid === subscriptionId) {\n onData(reviveResponseTypes(data, typeMap));\n }\n };\n\n const handleError = ({\n subscriptionId: sid,\n error,\n }: {\n subscriptionId: string;\n error: string;\n }) => {\n if (sid === subscriptionId) {\n console.error(`[Modelence] Live query error for ${method}:`, error);\n onError?.(error);\n }\n };\n\n const socket = getSocket();\n socket.on('liveQueryData', handleData);\n socket.on('liveQueryError', handleError);\n\n activeLiveSubscriptions.set(subscriptionId, { subscriptionId, method, args });\n\n // Only emit if already connected; otherwise the connect handler will handle it\n if (socket.connected) {\n socket.emit('subscribeLiveQuery', {\n subscriptionId,\n method,\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n });\n }\n\n // Return unsubscribe function\n return () => {\n activeLiveSubscriptions.delete(subscriptionId);\n socket.emit('unsubscribeLiveQuery', { subscriptionId });\n socket.off('liveQueryData', handleData);\n socket.off('liveQueryError', handleError);\n };\n}\n\nconst websocketProvider: WebsocketClientProvider = {\n init,\n on,\n once,\n off,\n emit,\n joinChannel,\n leaveChannel,\n};\n\nexport default websocketProvider;\n","import { ClientChannel } from './clientChannel';\nimport websocketProvider, { subscribeLiveQuery } from './socketio/client';\nimport { WebsocketClientProvider } from './types';\n\nexport { subscribeLiveQuery };\n\nlet websocketClientProvider: WebsocketClientProvider | null = null;\n\nexport function setWebsocketClientProvider(provider: WebsocketClientProvider | null) {\n websocketClientProvider = provider;\n}\n\nexport function getWebsocketClientProvider() {\n return websocketClientProvider;\n}\n\nexport function startWebsockets(props?: {\n provider?: WebsocketClientProvider;\n channels?: ClientChannel[];\n}) {\n if (websocketClientProvider) {\n console.warn('WebSocket already initialized. Skipping initialization.');\n return;\n }\n\n const provider = props?.provider || websocketProvider;\n setWebsocketClientProvider(provider);\n try {\n provider.init({\n channels: props?.channels,\n });\n } catch (error) {\n setWebsocketClientProvider(null);\n throw error;\n }\n}\n","'use client';\n\nimport { QueryClient, hashKey } from '@tanstack/react-query';\nimport { callMethod } from './method';\nimport { startWebsockets, subscribeLiveQuery } from '../websocket/client';\n\ntype Args = Record<string, unknown>;\n\ninterface Subscription {\n unsubscribe: () => void;\n resolvers: Set<{\n resolve: (data: unknown) => void;\n reject: (error: Error) => void;\n }>;\n}\n\nlet queryClientRef: QueryClient | null = null;\nlet cacheUnsubscribe: (() => void) | null = null;\nlet websocketsStarted = false;\nconst subscriptions = new Map<string, Subscription>();\n\n/**\n * Connects a `QueryClient` to Modelence's live-query layer. Auto-called by\n * `<ModelenceQueryProvider>`; only call manually if you mount your own\n * `<QueryClientProvider>`.\n *\n * Note: WebSocket setup is deferred until the first `modelenceLiveQuery`\n * call, so apps that only use `modelenceQuery`/`modelenceMutation` never\n * open a socket.\n */\nexport function connectModelenceQueryClient(queryClient: QueryClient) {\n if (queryClientRef === queryClient) {\n return;\n }\n\n if (queryClientRef) {\n disconnectModelenceQueryClient();\n }\n\n queryClientRef = queryClient;\n\n cacheUnsubscribe = queryClient.getQueryCache().subscribe((event) => {\n if (event.type === 'removed') {\n const subscriptionKey = hashKey(event.query.queryKey);\n const sub = subscriptions.get(subscriptionKey);\n if (sub) {\n if (sub.resolvers.size > 0) {\n const cancelError = new Error('Query was removed from cache');\n sub.resolvers.forEach((r) => r.reject(cancelError));\n sub.resolvers.clear();\n }\n sub.unsubscribe();\n subscriptions.delete(subscriptionKey);\n }\n }\n });\n}\n\n/**\n * Whether a `QueryClient` is already connected to the live-query layer.\n * `renderApp` uses this to avoid injecting its own `<ModelenceQueryProvider>`\n * when the app already mounts its own provider and connects it beforehand.\n */\nexport function hasConnectedQueryClient(): boolean {\n return queryClientRef !== null;\n}\n\nexport function disconnectModelenceQueryClient() {\n if (cacheUnsubscribe) {\n cacheUnsubscribe();\n cacheUnsubscribe = null;\n }\n subscriptions.forEach((sub) => sub.unsubscribe());\n subscriptions.clear();\n queryClientRef = null;\n websocketsStarted = false;\n}\n\n/** @deprecated Use `connectModelenceQueryClient(queryClient)` instead. */\nexport class ModelenceQueryClient {\n connect(queryClient: QueryClient) {\n connectModelenceQueryClient(queryClient);\n }\n}\n\n/**\n * @example\n * ```tsx\n * const { data } = useQuery(modelenceQuery('todo.getAll'));\n * ```\n */\nexport function modelenceQuery<T = unknown>(methodName: string, args: Args = {}) {\n return {\n queryKey: [methodName, args],\n queryFn: () => callMethod<T>(methodName, args),\n };\n}\n\n/**\n * Live query — data updates in real time as the underlying collection changes.\n * Requires a `QueryClient` connected via `<ModelenceQueryProvider>` or\n * `connectModelenceQueryClient(...)`.\n */\nexport function modelenceLiveQuery<T = unknown>(methodName: string, args: Args = {}) {\n const queryKey = ['live', methodName, args] as const;\n const subscriptionKey = hashKey(queryKey);\n\n return {\n queryKey,\n queryFn: () =>\n new Promise<T>((resolve, reject) => {\n // Live queries are WebSocket subscriptions — no server snapshot. Stay\n // pending on the server so Suspense renders; client re-runs after hydration.\n if (typeof window === 'undefined') {\n return;\n }\n\n if (!queryClientRef) {\n const error = new Error(\n 'Modelence: connect a QueryClient before using modelenceLiveQuery(). Mount <ModelenceQueryProvider> or call connectModelenceQueryClient().'\n );\n console.error('[Modelence]', error.message);\n reject(error);\n return;\n }\n\n if (!websocketsStarted) {\n startWebsockets();\n websocketsStarted = true;\n }\n\n let sub = subscriptions.get(subscriptionKey);\n\n if (!sub) {\n const unsubscribe = subscribeLiveQuery<T>(\n methodName,\n args,\n (data) => {\n const currentSub = subscriptions.get(subscriptionKey);\n\n if (currentSub?.resolvers.size) {\n currentSub.resolvers.forEach((r) => r.resolve(data));\n currentSub.resolvers.clear();\n }\n\n if (queryClientRef) {\n queryClientRef.setQueryData(queryKey, data);\n }\n },\n (error) => {\n const currentSub = subscriptions.get(subscriptionKey);\n if (currentSub) {\n if (currentSub.resolvers.size) {\n currentSub.resolvers.forEach((r) => r.reject(new Error(error)));\n currentSub.resolvers.clear();\n }\n currentSub.unsubscribe();\n subscriptions.delete(subscriptionKey);\n }\n }\n );\n\n sub = { unsubscribe, resolvers: new Set() };\n subscriptions.set(subscriptionKey, sub);\n }\n\n // Shared map stores resolvers across `T` instantiations; erase the union.\n sub.resolvers.add({\n resolve: resolve as (data: unknown) => void,\n reject,\n });\n }),\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n refetchOnMount: false,\n refetchOnReconnect: false,\n gcTime: 0,\n };\n}\n\nexport function modelenceMutation<T = unknown>(methodName: string, defaultArgs: Args = {}) {\n return {\n mutationFn: (variables: Args = {}) =>\n callMethod<T>(methodName, { ...defaultArgs, ...variables }),\n };\n}\n\nexport type ModelenceQueryKey<T extends string, U extends Args = Args> = readonly [T, U];\n\n/** Builds a query key matching `modelenceQuery(...)` for cache operations. */\nexport function createQueryKey<T extends string, U extends Args = Args>(\n methodName: T,\n args: U = {} as U\n): ModelenceQueryKey<T, U> {\n return [methodName, args] as const;\n}\n","'use client';\n\nimport { useState, type ReactNode } from 'react';\nimport {\n QueryClient,\n QueryClientProvider,\n HydrationBoundary,\n type DehydratedState,\n} from '@tanstack/react-query';\nimport { connectModelenceQueryClient } from './query';\n\nconst SSR_QUERY_STATE_SCRIPT_ID = '__MODELENCE_QUERY_STATE__';\n\nfunction readDehydratedState(): DehydratedState | undefined {\n if (typeof document === 'undefined') {\n return undefined;\n }\n\n const node = document.getElementById(SSR_QUERY_STATE_SCRIPT_ID);\n if (!node || !node.textContent) {\n return undefined;\n }\n\n try {\n return JSON.parse(node.textContent) as DehydratedState;\n } catch (e) {\n console.error('Modelence: failed to parse SSR query state', e);\n return undefined;\n }\n}\n\ninterface ModelenceQueryProviderProps {\n children: ReactNode;\n client?: QueryClient;\n dehydratedState?: DehydratedState;\n}\n\nexport function ModelenceQueryProvider({\n children,\n client,\n dehydratedState,\n}: ModelenceQueryProviderProps) {\n const [internalClient] = useState(() => {\n const qc =\n client ??\n new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: 60 * 1000,\n },\n },\n });\n if (typeof window !== 'undefined') {\n connectModelenceQueryClient(qc);\n }\n return qc;\n });\n\n const state = dehydratedState ?? readDehydratedState();\n\n return (\n <QueryClientProvider client={internalClient}>\n <HydrationBoundary state={state}>{children}</HydrationBoundary>\n </QueryClientProvider>\n );\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import {c}from'./chunk-5M6FUMUK.js';import {a}from'./chunk-DO5TZLF5.js';import {create}from'zustand';import {z as z$1}from'zod';var H={},C=null;function fe(e){C=e;}function de(e){return typeof window>"u"&&C?C(e):H[e]?.value}function y(e){H=e;}var E="modelence.session";function b(){return typeof globalThis<"u"&&typeof globalThis.localStorage<"u"}function T(){if(!b())return null;let e=globalThis.localStorage.getItem(E);try{return e?JSON.parse(e):null}catch(n){return console.error("Error parsing session from localStorage",n),null}}function d(e){b()&&globalThis.localStorage.setItem(E,JSON.stringify(e));}function q(){b()&&globalThis.localStorage.removeItem(E);}var $=null;function he(e){$=e;}function l(){return $}var j="modelence:oauth-verifier-request",D="modelence:oauth-verifier-reply";function F(){let e=globalThis.window;return Z(e)?e:null}function Z(e){if(typeof e!="object"||e===null)return false;let n=e;return typeof n.addEventListener=="function"&&typeof n.removeEventListener=="function"&&typeof n.location?.origin=="string"}function _(e){return typeof e=="object"&&e!==null&&typeof e.postMessage=="function"}function ee(e){return e?.type===j}function ne(e){if(typeof e!="object"||e===null)return false;let n=e;return n.type===D&&(typeof n.verifier=="string"||n.verifier===null)}var P=null;function K(e,n){Y();let t=F();if(!t)return;let r=t.location.origin,o=i=>{if(i.source!==e||i.origin!==r||!ee(i.data))return;Y();let a={type:D,verifier:n()};e.postMessage(a,r);};t.addEventListener("message",o),P=()=>t.removeEventListener("message",o);}function Y(){P?.(),P=null;}function z(){let e=F(),n=e?.opener;if(!e||!_(n))return Promise.resolve(null);let t=e.location.origin;return new Promise(r=>{let o=false,i=f=>{o||(o=true,clearTimeout(h),e.removeEventListener("message",a),r(f));},a=f=>{f.source===n&&f.origin===t&&ne(f.data)&&i(f.data.verifier);},h=setTimeout(()=>i(null),3e3);e.addEventListener("message",a);let c={type:j};try{n.postMessage(c,t);}catch{i(null);}})}var m=null,v="modelence.oauth.verifier";function O(){try{let e=globalThis.sessionStorage;if(!e)return null;let n=`${v}.probe`;return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}function te(e){let n=new Uint8Array(e),t=globalThis.crypto;if(t?.getRandomValues)t.getRandomValues(n);else for(let o=0;o<n.length;o++)n[o]=Math.floor(Math.random()*256);let r="";for(let o of n)r+=o.toString(16).padStart(2,"0");return r}function J(){m=te(32);try{O()?.setItem(v,m);}catch{}return m}function A(){let e=m??O()?.getItem(v)??null;return re(),e}function re(){m=null;try{O()?.removeItem(v);}catch{}}function oe(e){let n=l();n?n.setAuthToken(e.authToken):d(e);}function R(e){return oe(e.session),U(e.user)}async function xe(e){let{email:n,password:t,handle:r,firstName:o,lastName:i,avatarUrl:a}=e;await s("_system.user.signupWithPassword",{email:n,password:t,...r!==void 0?{handle:r}:{},...o!==void 0?{firstName:o}:{},...i!==void 0?{lastName:i}:{},...a!==void 0?{avatarUrl:a}:{}});}async function Ce(e){let{email:n,password:t}=e,r=await s("_system.user.loginWithPassword",{email:n,password:t});return R(r)}async function Ee(e){let{firstName:n,lastName:t,avatarUrl:r,handle:o}=e,{user:i}=await s("_system.user.updateProfile",{...n!==void 0?{firstName:n}:{},...t!==void 0?{lastName:t}:{},...r!==void 0?{avatarUrl:r}:{},...o!==void 0?{handle:o}:{}});return U(i)}async function be(e){let{token:n}=e;await s("_system.user.verifyEmail",{token:n});}async function Pe(e){let{email:n}=e;await s("_system.user.resendEmailVerification",{email:n});}async function _e(){await s("_system.user.logout"),q();let e=l();e&&e.setAuthToken(null),U(null);}async function Oe(e){let{email:n}=e;await s("_system.user.sendResetPasswordToken",{email:n});}async function Ae(e){let{email:n}=e;await s("_system.user.sendMagicLink",{email:n});}async function Me(){let e=await s("_system.user.loginWithMagicLink");return R(e)}async function Ie(e){let{email:n,code:t}=e,r=await s("_system.user.loginWithOneTimeCode",{email:n,code:t});return R(r)}async function Ne(e){let{token:n,password:t}=e;await s("_system.user.resetPassword",{...n?{token:n}:{},password:t});}async function Le(e){let{provider:n,redirectUri:t}=e,r=l(),o=r?.baseUrl??"";if(t){if(!r?.openUrl)throw new Error("signInWithOAuth was given a redirectUri but the client has no openUrl. Configure openUrl (e.g. (url) => Linking.openURL(url)) to use the native flow.");let a=J(),h=`${o}/api/_internal/auth/${n}?mode=login&platform=mobile&redirectUri=${encodeURIComponent(t)}&codeChallenge=${encodeURIComponent(a)}`,c=r.openUrl(h);_(c)&&K(c,A);return}let i=`${o}/api/_internal/auth/${n}?mode=login`;if(r?.openUrl){r.openUrl(i);return}window.location.href=i;}async function We(e){let{code:n}=e,t=A()??await z();if(!t)throw console.error("[modelence] loginWithOAuth was called with no sign-in in progress. Either signInWithOAuth was never called on this client, or the code came from somewhere other than a flow this client started. On native, the app process must survive the round trip; in a browser the verifier is kept in sessionStorage, so a new tab or a cleared session also produces this. If the app runs in an iframe and opens the provider in a popup, openUrl must return the window from window.open so the popup can ask this page. A plain web app that never calls signInWithOAuth({ redirectUri }) does not need loginWithOAuth at all \u2014 the cookie flow signs the user in on its own."),new Error("This sign-in link is no longer valid. Please sign in again.");let r=await s("_system.user.loginWithOAuth",{code:n,codeVerifier:t});return R(r)}async function Ve(e){let{provider:n,redirectUri:t}=e,r=l(),o=r?.baseUrl??"";if(t){if(!r?.openUrl)throw new Error("linkOAuthProvider was given a redirectUri but the client has no openUrl. Configure openUrl (e.g. (url) => Linking.openURL(url)) to use the native flow.");let i=S();if(!i)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");let a=await fetch(`${o}/api/_internal/auth/issue-link-nonce`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({authToken:i})});if(!a.ok)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");let{nonce:h}=await a.json(),c=`${o}/api/_internal/auth/${n}?mode=link&linkNonce=${encodeURIComponent(h)}&platform=mobile&redirectUri=${encodeURIComponent(t)}`;r.openUrl(c);}else {let i=S();if(i&&!(await fetch(`${o}/api/_internal/auth/set-link-cookie`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({authToken:i}),credentials:"include"})).ok)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");window.location.href=`${o}/api/_internal/auth/${n}?mode=link`;}}async function He(e){let{provider:n}=e;await s("_system.user.unlinkOAuthProvider",{provider:n});}function S(){let e=l();return e?e.getAuthToken():T()?.authToken}function G(){let e=l();return e?e.getClientInfo():typeof window>"u"?{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null}:{screenWidth:window.screen.width,screenHeight:window.screen.height,windowWidth:window.innerWidth,windowHeight:window.innerHeight,pixelRatio:window.devicePixelRatio,orientation:window.screen.orientation?.type??null}}var B=(e,n)=>{console.error(`Error calling method '${n}':`,e);};function $e(e){B=e;}function Q(e,n){return B(e,n)}var M=class extends Error{constructor(n,t,r){super(n),this.name="MethodError",this.status=t,this.code=r;}},ie=async(e,n)=>{let t=l()?.baseUrl??"";return ae(`${t}/api/_internal/method/${e}`,n)},k="__modelence_call_method_transport__";function se(){return globalThis[k]??ie}function ze(e){let n=globalThis[k];return globalThis[k]=e,()=>{globalThis[k]=n;}}async function s(e,n,t){n=n??{},t=t??{};try{return await se()(e,n)}catch(r){throw (t.errorHandler??Q)(r,e),r}}async function ae(e,n){let t=await fetch(e,{method:"POST",credentials:l()?.credentials??"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:n,authToken:S(),clientInfo:G()})});if(!t.ok){let i=await t.text(),a=t.headers?.get("X-Modelence-Error-Code")??void 0;throw new M(i,t.status,a)}let r=await t.text(),o=r?JSON.parse(r):void 0;if(!o)throw new Error("Invalid response from server");return c(o.data,o.typeMap)}var g=create(e=>({user:null,setUser:n=>e({user:n})})),w=false,x=false,ue=a.seconds(30),X=null,ce=z$1.object({id:z$1.string(),handle:z$1.string(),roles:z$1.array(z$1.string()),firstName:z$1.string().optional(),lastName:z$1.string().optional(),avatarUrl:z$1.string().optional()});function p(e){if(!e)return null;let n=ce.safeParse(e);if(!n.success)return console.error("Session Error: Invalid user payload",n.error),null;let t=n.data;return Object.freeze({...t,firstName:t.firstName??void 0,lastName:t.lastName??void 0,avatarUrl:t.avatarUrl??void 0,hasRole:r=>t.roles.includes(r),requireRole:r=>{if(!t.roles.includes(r))throw new Error(`Access denied - role '${r}' required`)}})}var N=false;function tn(){return N}function rn(e){if(w)return;w=true,N=!!e.setupRequired,y(e.configs);let t=T()?.authToken,r=e.session;if(t&&!e.user&&t!==r.authToken){x=true,g.getState().setUser(p(e.user));return}d(e.session),g.getState().setUser(p(e.user));}async function on(){if(x){x=false;try{let{configs:e,session:n,user:t}=await s("_system.session.init");y(e),d(n),g.getState().setUser(p(t));}catch(e){console.error("Modelence: session reconciliation failed",e);}}}function sn(){return x}async function an(){if(w)return;w=true;let e=await s("_system.session.init"),{configs:n,session:t,user:r}=e;N=!!e.setupRequired,y(n);let o=l();o?o.setAuthToken(t.authToken):d(t),g.getState().setUser(p(r)),await L();}async function ln(){typeof window>"u"||X!==null||await L();}async function L(){if(!(typeof window>"u")){try{await s("_system.session.heartbeat",{},{errorHandler:()=>{}});}catch{}X=setTimeout(L,ue);}}function U(e){let n=p(e);return g.getState().setUser(n),n}function un(){return w}var I=null;function cn(e){I=e;}function fn(e){return p(e)}function dn(){return typeof window>"u"&&I?{user:I()}:{user:g(n=>n.user)}}export{Le as A,We as B,Ve as C,He as D,S as E,G as F,$e as G,M as H,ie as I,ze as J,s as K,fe as a,de as b,T as c,he as d,l as e,tn as f,rn as g,on as h,sn as i,an as j,ln as k,un as l,cn as m,fn as n,dn as o,xe as p,Ce as q,Ee as r,be as s,Pe as t,_e as u,Oe as v,Ae as w,Me as x,Ie as y,Ne as z};//# sourceMappingURL=chunk-CHBJAOMP.js.map
2
+ //# sourceMappingURL=chunk-CHBJAOMP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/config/client.ts","../src/client/localStorage.ts","../src/client/clientConfig.ts","../src/auth/client/oauthPopupHandoff.ts","../src/auth/client/oauthVerifier.ts","../src/auth/client/index.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/client/session.ts"],"names":["config","ssrConfigResolver","_setSsrConfigResolver","resolver","getConfig","key","_setConfig","configs","SESSION_KEY","hasLocalStorage","getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","clearLocalStorageSession","configureClient","userConfig","getClientConfig","REQUEST_TYPE","REPLY_TYPE","getWindow","w","isHandoffWindow","value","isMessageTarget","isVerifierRequest","data","isVerifierReply","d","cancelActiveOffer","offerVerifierToPopup","popup","takeVerifier","cancelPopupHandoff","origin","onMessage","event","reply","requestVerifierFromOpener","opener","resolve","settled","finish","verifier","timer","request","pendingVerifier","STORAGE_KEY","getSessionStorage","storage","probe","randomHex","byteLength","bytes","cryptoObj","i","out","byte","startOAuthVerifier","consumeOAuthVerifier","resetOAuthVerifier","persistSession","completeLogin","result","setCurrentUser","signupWithPassword","options","email","password","handle","firstName","lastName","avatarUrl","callMethod","loginWithPassword","updateProfile","user","verifyEmail","token","resendEmailVerification","logout","sendResetPasswordToken","sendMagicLink","loginWithMagicLink","loginWithOneTimeCode","code","resetPassword","signInWithOAuth","provider","redirectUri","baseUrl","codeChallenge","url","opened","webUrl","loginWithOAuth","codeVerifier","linkOAuthProvider","getAuthToken","nonceResponse","nonce","unlinkOAuthProvider","getClientInfo","errorHandler","error","methodName","setErrorHandler","handler","handleError","MethodError","message","status","defaultCallMethodTransport","args","call","TRANSPORT_KEY","getTransport","setCallMethodTransport","next","previous","endpoint","response","text","reviveResponseTypes","useSessionStore","create","set","isInitialized","pendingReconciliation","SESSION_HEARTBEAT_INTERVAL","time","heartbeatTimer","userSchema","z","parseUser","parsedData","role","setupRequired","_isSetupRequired","hydrateSession","payload","existingToken","ssrSession","reconcileSession","_isReconciliationPending","initSession","loopSessionHeartbeat","startSessionHeartbeat","enrichedUser","isSessionInitialized","ssrSessionResolver","_setSsrSessionResolver","_parseSessionUser","useSession","state"],"mappings":"gIAEA,IAAIA,CAAAA,CAAuC,EAAC,CAGxCC,CAAAA,CAA8C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,CAAgB,QAAA,EAAS,CAAE,OAAA,CAAQwB,CAAY,CAAA,CACxCA,CACT,CAEO,SAASC,EAAAA,EAAuB,CACrC,OAAOtB,CACT,CAcA,IAAIuB,CAAAA,CAAgD,IAAA,CAG7C,SAASC,EAAAA,CAAuBrJ,CAAAA,CAAqC,CAC1EoJ,CAAAA,CAAqBpJ,EACvB,CAGO,SAASsJ,EAAAA,CAAkB5E,CAAAA,CAA4B,CAC5D,OAAO0D,CAAAA,CAAU1D,CAAI,CACvB,CAeO,SAAS6E,EAAAA,EAAa,CAC3B,OAAI,OAAO,MAAA,CAAW,GAAA,EAAeH,CAAAA,CAC5B,CAAE,IAAA,CAAMA,CAAAA,EAAqB,CAAA,CAG/B,CAAE,IAAA,CADI1B,CAAAA,CAAiB8B,CAAAA,EAAUA,CAAAA,CAAM,IAAI,CACpC,CAChB","file":"chunk-CHBJAOMP.js","sourcesContent":["import { AppConfig, ConfigKey, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\ntype SsrConfigResolver = (key: ConfigKey) => string | number | boolean | undefined;\nlet ssrConfigResolver: SsrConfigResolver | null = null;\n\n/** @internal SSR resolver reads from AsyncLocalStorage (per-request scoped). */\nexport function _setSsrConfigResolver(resolver: SsrConfigResolver | null) {\n ssrConfigResolver = resolver;\n}\n\n/**\n * @sidebarTitle getConfig (client)\n *\n * @param key\n * @returns\n */\nexport function getConfig(key: ConfigKey): string | number | boolean | undefined {\n if (typeof window === 'undefined' && ssrConfigResolver) {\n return ssrConfigResolver(key);\n }\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","const SESSION_KEY = 'modelence.session';\n\nfunction hasLocalStorage(): boolean {\n return typeof globalThis !== 'undefined' && typeof globalThis.localStorage !== 'undefined';\n}\n\nexport function getLocalStorageSession() {\n if (!hasLocalStorage()) {\n return null;\n }\n\n const sessionJson = globalThis.localStorage.getItem(SESSION_KEY);\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n if (!hasLocalStorage()) {\n return;\n }\n\n globalThis.localStorage.setItem(SESSION_KEY, JSON.stringify(session));\n}\n\nexport function clearLocalStorageSession() {\n if (!hasLocalStorage()) {\n return;\n }\n\n globalThis.localStorage.removeItem(SESSION_KEY);\n}\n","import type { ClientInfo } from '@/methods/types';\n\nexport interface ClientConfig {\n baseUrl: string;\n getAuthToken: () => string | undefined;\n setAuthToken: (token: string | null) => void;\n getClientInfo: () => ClientInfo;\n /**\n * Opens a URL for OAuth redirects. React Native must use\n * `(url) => Linking.openURL(url)` — WebView is not supported.\n * Defaults to `window.location.href` when not provided.\n *\n * A web client that opens the flow in a popup should return the window\n * `window.open` gave it: `(url) => window.open(url)`. With that reference the\n * callback page in the popup can obtain the sign-in verifier from this page\n * directly, which is what makes `loginWithOAuth` work when the app itself\n * runs inside a cross-origin iframe and the popup's storage is partitioned\n * away from it. Any other return value (including the `Promise` from\n * `Linking.openURL`) is ignored.\n */\n openUrl?: (url: string) => unknown;\n /**\n * Credentials mode for method-call requests. Defaults to `'include'`, which\n * browser apps need for the cookie-based flows (password reset, magic link).\n *\n * Clients configured with token-in-body auth (React Native / Expo) never use\n * cookies, so set `'omit'` there — on Expo Web a credentialed cross-origin\n * request is otherwise blocked by any server answering\n * `Access-Control-Allow-Origin: *`, surfacing as \"TypeError: Failed to fetch\".\n */\n credentials?: RequestCredentials;\n}\n\nlet config: ClientConfig | null = null;\n\n/**\n * Configure the Modelence client for non-browser environments like React Native.\n *\n * When configured, the client uses the provided functions for auth-token\n * storage, client-info collection, and URL resolution instead of the\n * default browser APIs (localStorage, window.screen, relative URLs).\n *\n * @example\n * ```ts\n * import { configureClient } from 'modelence/client';\n * import { Linking } from 'react-native';\n *\n * let authToken: string | undefined;\n *\n * configureClient({\n * baseUrl: 'https://myapp.com',\n * getAuthToken: () => authToken,\n * setAuthToken: (token) => { authToken = token ?? undefined; },\n * getClientInfo: () => ({\n * screenWidth: Dimensions.get('screen').width,\n * screenHeight: Dimensions.get('screen').height,\n * windowWidth: Dimensions.get('window').width,\n * windowHeight: Dimensions.get('window').height,\n * pixelRatio: PixelRatio.get(),\n * orientation: null,\n * }),\n * openUrl: (url) => Linking.openURL(url),\n * });\n * ```\n */\nexport function configureClient(userConfig: ClientConfig) {\n config = userConfig;\n}\n\nexport function getClientConfig(): ClientConfig | null {\n return config;\n}\n","/**\n * Verifier handoff from the page that started an OAuth flow to the popup that\n * finishes it.\n *\n * The `sessionStorage` mirror in `oauthVerifier.ts` covers a same-tab redirect.\n * It does not cover an app running inside a cross-origin iframe (an embedded\n * preview or sandbox) whose `openUrl` opens the provider in a real popup —\n * which it must, since providers refuse to render their consent screen in an\n * iframe. Once the popup is a genuine top-level browsing context, its storage\n * is partitioned away from the iframe's (Chrome storage partitioning, Safari\n * ITP), so the callback page cannot read the verifier the iframe wrote.\n *\n * The verifier still lives in memory on the page that minted it, and that page\n * holds the `Window` reference `window.open` returned. So the callback page\n * asks its opener for the verifier over `postMessage`, and the opener answers\n * only that popup, only on its own origin, only once. Identity on both sides is\n * the window reference itself (`event.source`), which no other frame can forge,\n * so the messages carry no nonce. The channel is exactly as trusted as the tab\n * that called `signInWithOAuth`: no more than the in-memory copy it serves, and\n * nothing weaker (no `localStorage`, no URL) is used.\n */\n\nconst REQUEST_TYPE = 'modelence:oauth-verifier-request';\nconst REPLY_TYPE = 'modelence:oauth-verifier-reply';\n\n/**\n * How long the callback page waits for its opener before giving up. A live\n * opener answers in a single event-loop turn; the timeout only matters when\n * the opener is some unrelated page that will never answer.\n */\nconst REPLY_TIMEOUT_MS = 3000;\n\ninterface VerifierRequest {\n type: typeof REQUEST_TYPE;\n}\n\ninterface VerifierReply {\n type: typeof REPLY_TYPE;\n verifier: string | null;\n}\n\n/** The subset of `window` both sides need; keeps tests free of a DOM. */\nexport interface HandoffWindow {\n location: { origin: string };\n opener?: unknown;\n addEventListener: (type: 'message', listener: (event: MessageEvent) => void) => void;\n removeEventListener: (type: 'message', listener: (event: MessageEvent) => void) => void;\n}\n\n/** The subset of a `Window` reference used to talk to the other side. */\nexport interface MessageTarget {\n postMessage: (message: unknown, targetOrigin: string) => void;\n}\n\nfunction getWindow(): HandoffWindow | null {\n const w = (globalThis as { window?: unknown }).window;\n return isHandoffWindow(w) ? w : null;\n}\n\nfunction isHandoffWindow(value: unknown): value is HandoffWindow {\n if (typeof value !== 'object' || value === null) return false;\n const w = value as Partial<HandoffWindow>;\n return (\n typeof w.addEventListener === 'function' &&\n typeof w.removeEventListener === 'function' &&\n typeof w.location?.origin === 'string'\n );\n}\n\n/**\n * Whether `openUrl` handed back a window reference — the return value of\n * `window.open`. A `Promise` (React Native's `Linking.openURL`) or `undefined`\n * is not one, so those clients are unaffected.\n */\nexport function isMessageTarget(value: unknown): value is MessageTarget {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as Partial<MessageTarget>).postMessage === 'function'\n );\n}\n\nfunction isVerifierRequest(data: unknown): data is VerifierRequest {\n return (data as Partial<VerifierRequest> | null)?.type === REQUEST_TYPE;\n}\n\nfunction isVerifierReply(data: unknown): data is VerifierReply {\n if (typeof data !== 'object' || data === null) return false;\n const d = data as Partial<VerifierReply>;\n return d.type === REPLY_TYPE && (typeof d.verifier === 'string' || d.verifier === null);\n}\n\n/** Tears down the listener of the most recent `offerVerifierToPopup`. */\nlet cancelActiveOffer: (() => void) | null = null;\n\n/**\n * Opener side. Serves the pending verifier to `popup` — the exact reference\n * `window.open` returned — and to nothing else.\n *\n * `takeVerifier` is consulted only when a valid request arrives, and the\n * listener is removed as soon as it has answered, so the verifier is handed\n * out at most once. Only the most recent offer is live: starting another flow\n * replaces it, matching how `startOAuthVerifier` discards the previous\n * verifier.\n */\nexport function offerVerifierToPopup(\n popup: MessageTarget,\n takeVerifier: () => string | null\n): void {\n cancelPopupHandoff();\n\n const w = getWindow();\n if (!w) return;\n\n const origin = w.location.origin;\n\n const onMessage = (event: MessageEvent) => {\n // Identity first: the message must come from the window we opened, not\n // merely from something that knows the message shape. Any other frame or\n // tab on this origin could otherwise probe for the verifier.\n if (event.source !== popup) return;\n if (event.origin !== origin) return;\n if (!isVerifierRequest(event.data)) return;\n\n cancelPopupHandoff();\n\n const reply: VerifierReply = { type: REPLY_TYPE, verifier: takeVerifier() };\n // Explicit target origin: if the popup has since navigated elsewhere, the\n // browser drops the message rather than delivering it to a foreign page.\n popup.postMessage(reply, origin);\n };\n\n w.addEventListener('message', onMessage);\n cancelActiveOffer = () => w.removeEventListener('message', onMessage);\n}\n\n/** Stops answering popup requests. Safe to call when nothing is offered. */\nexport function cancelPopupHandoff(): void {\n cancelActiveOffer?.();\n cancelActiveOffer = null;\n}\n\n/**\n * Popup side. Asks `window.opener` for the verifier of the flow it started.\n *\n * Resolves with `null` when there is no opener, the opener never answers\n * (it is not a Modelence page, or is on another origin), or it has nothing\n * left to give.\n */\nexport function requestVerifierFromOpener(): Promise<string | null> {\n const w = getWindow();\n const opener = w?.opener;\n if (!w || !isMessageTarget(opener)) return Promise.resolve(null);\n\n const origin = w.location.origin;\n\n return new Promise((resolve) => {\n let settled = false;\n\n const finish = (verifier: string | null) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n w.removeEventListener('message', onMessage);\n resolve(verifier);\n };\n\n const onMessage = (event: MessageEvent) => {\n if (event.source !== opener) return;\n if (event.origin !== origin) return;\n if (!isVerifierReply(event.data)) return;\n finish(event.data.verifier);\n };\n\n const timer = setTimeout(() => finish(null), REPLY_TIMEOUT_MS);\n w.addEventListener('message', onMessage);\n\n const request: VerifierRequest = { type: REQUEST_TYPE };\n try {\n // Explicit target origin: a cross-origin opener never receives this.\n opener.postMessage(request, origin);\n } catch {\n finish(null);\n }\n });\n}\n","/**\n * Device-side binding for the native OAuth flow (PKCE-style).\n *\n * The deep link that carries the exchange code back into the app is the weakest\n * hop in the chain: a custom scheme can be claimed by any installed app, and a\n * crafted `myapp://auth?code=...` can be handed to the device from outside the\n * flow entirely. Without a device-held secret, redeeming such a code silently\n * rebinds the session to whoever minted it.\n *\n * So `signInWithOAuth` mints a verifier, keeps it in memory, and sends only a\n * derived challenge to the server. `loginWithOAuth` replays the verifier at\n * redemption, and the server checks it against the challenge bound to the code\n * when it was minted. A code minted for an attacker's flow carries the\n * attacker's challenge and cannot be redeemed by this device.\n *\n * Why not the RFC 7636 `S256` transform: bare React Native ships neither\n * `crypto.subtle` nor `crypto.getRandomValues`, so a SHA-256 challenge would\n * force a native crypto dependency on every consumer. The challenge is instead\n * sent as the verifier itself over TLS and stored only as a hash server-side,\n * which is the `plain` method of the same RFC. The property that matters here —\n * a code is redeemable only by the device that started the flow — is identical;\n * what `S256` additionally protects against is a challenge leaking from the\n * *authorization request*, which for us never leaves the TLS channel between\n * the app and its own server.\n */\n\n/** Verifier length in characters. 32 bytes of entropy, hex-encoded. */\nconst VERIFIER_BYTES = 32;\n\n/**\n * The verifier for the in-flight sign-in.\n *\n * Memory suffices on native, where the app survives in the background. A\n * browser — including Expo Web, where `Linking.openURL` navigates the same tab —\n * tears down this module on the way to the provider, so it is mirrored into\n * `sessionStorage`: tab-scoped and discarded on close, which fits a credential\n * that lives for one redirect round trip.\n */\nlet pendingVerifier: string | null = null;\nconst STORAGE_KEY = 'modelence.oauth.verifier';\n\n/**\n * Returns `sessionStorage` when it is usable, else null. Access can throw\n * outright (Safari private mode, webviews with storage disabled), and presence\n * does not imply usability — hence the probe.\n */\nfunction getSessionStorage(): Storage | null {\n try {\n const storage = (globalThis as { sessionStorage?: Storage }).sessionStorage;\n if (!storage) return null;\n const probe = `${STORAGE_KEY}.probe`;\n storage.setItem(probe, '1');\n storage.removeItem(probe);\n return storage;\n } catch {\n return null;\n }\n}\n\n/**\n * Random hex string from the best source the runtime offers.\n *\n * Bare React Native has no `crypto.getRandomValues`, so `Math.random` is the\n * fallback. It is weaker than a CSPRNG, but the verifier only needs to resist an\n * attacker who cannot read process memory — and one who can has already won.\n */\nfunction randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n\n const cryptoObj = (globalThis as { crypto?: Crypto }).crypto;\n if (cryptoObj?.getRandomValues) {\n cryptoObj.getRandomValues(bytes);\n } else {\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n\n let out = '';\n for (const byte of bytes) {\n out += byte.toString(16).padStart(2, '0');\n }\n return out;\n}\n\n/**\n * Mints a fresh verifier for a new sign-in and returns the challenge to send.\n *\n * Any previously pending verifier is discarded: only the most recently started\n * flow is redeemable, so an abandoned flow cannot be completed later.\n */\nexport function startOAuthVerifier(): string {\n pendingVerifier = randomHex(VERIFIER_BYTES);\n\n // Mirrored so a browser flow survives the navigation to the provider. Failure\n // to persist is not fatal: native runtimes rely on the in-memory copy.\n try {\n getSessionStorage()?.setItem(STORAGE_KEY, pendingVerifier);\n } catch {\n // Storage full or blocked mid-flow; the in-memory value still applies.\n }\n\n return pendingVerifier;\n}\n\n/**\n * Returns the pending verifier and clears it, so a given verifier is replayed\n * at most once even if the deep link fires twice.\n */\nexport function consumeOAuthVerifier(): string | null {\n // In-memory first: it is authoritative on native and identical on web when\n // the page was never replaced.\n const verifier = pendingVerifier ?? getSessionStorage()?.getItem(STORAGE_KEY) ?? null;\n resetOAuthVerifier();\n return verifier;\n}\n\n/**\n * Drops only the in-memory copy, leaving any persisted one intact.\n *\n * Exists to let tests reproduce a page navigation, which is precisely the case\n * the persisted copy exists for: the module is rebuilt, storage is not.\n */\nexport function __resetInMemoryVerifierForTests(): void {\n pendingVerifier = null;\n}\n\n/** Clears any pending verifier. Exposed for tests and for abandoning a flow. */\nexport function resetOAuthVerifier(): void {\n pendingVerifier = null;\n try {\n getSessionStorage()?.removeItem(STORAGE_KEY);\n } catch {\n // Nothing to do — a verifier that cannot be cleared still expires with the tab.\n }\n}\n","import { setCurrentUser } from '@/client/session';\nimport { callMethod } from '@/client/method';\nimport {\n clearLocalStorageSession,\n getLocalStorageSession,\n setLocalStorageSession,\n} from '@/client/localStorage';\nimport { getClientConfig } from '@/client/clientConfig';\nimport type { ClientInfo } from '@/methods/types';\nimport { OAuthProvider } from '../types';\nimport {\n isMessageTarget,\n offerVerifierToPopup,\n requestVerifierFromOpener,\n} from './oauthPopupHandoff';\nimport { consumeOAuthVerifier, startOAuthVerifier } from './oauthVerifier';\n\nexport type UserInfo = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\ntype RawUserData = {\n id: string;\n handle: string;\n roles: string[];\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\nfunction persistSession(session: { authToken: string }) {\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(session.authToken);\n } else {\n setLocalStorageSession(session);\n }\n}\n\n/**\n * Stores the session from a completed sign-in and returns the enriched user.\n *\n * Every login method ends the same way — persist the auth token, then publish\n * the user to the reactive session store. Kept in one place so a new sign-in\n * method cannot half-implement it.\n */\nfunction completeLogin(result: { user: RawUserData; session: { authToken: string } }) {\n persistSession(result.session);\n return setCurrentUser(result.user);\n}\n\n/**\n * Sign up a new user with an email and password.\n *\n * @example\n * ```ts\n * await signupWithPassword({ email: 'test@example.com', password: '12345678' });\n * await signupWithPassword({ email: 'test@example.com', password: '12345678', handle: 'myhandle', firstName: 'John' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n * @param options.handle - Optional custom handle. If omitted, one is derived from the email.\n * @param options.firstName - Optional first name.\n * @param options.lastName - Optional last name.\n * @param options.avatarUrl - Optional avatar URL.\n */\nexport async function signupWithPassword(options: {\n email: string;\n password: string;\n handle?: string;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n}) {\n const { email, password, handle, firstName, lastName, avatarUrl } = options;\n await callMethod('_system.user.signupWithPassword', {\n email,\n password,\n ...(handle !== undefined ? { handle } : {}),\n ...(firstName !== undefined ? { firstName } : {}),\n ...(lastName !== undefined ? { lastName } : {}),\n ...(avatarUrl !== undefined ? { avatarUrl } : {}),\n });\n}\n\n/**\n * Login a user with an email and password.\n *\n * @example\n * ```ts\n * await loginWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function loginWithPassword(options: { email: string; password: string }) {\n const { email, password } = options;\n const result = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithPassword',\n {\n email,\n password,\n }\n );\n return completeLogin(result);\n}\n\n/**\n * Update the current user's profile.\n *\n * @example\n * ```ts\n * await updateProfile({ firstName: 'Atul', lastName: 'Yadav', avatarUrl: 'https://example.com/avatar.jpg', handle: 'atulyadav' });\n * ```\n * @param options.firstName - The first name of the user.\n * @param options.lastName - The last name of the user.\n * @param options.avatarUrl - The avatar URL of the user.\n * @param options.handle - The handle of the user.\n */\nexport async function updateProfile(options: {\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n handle?: string;\n}) {\n const { firstName, lastName, avatarUrl, handle } = options;\n const { user } = await callMethod<{ user: RawUserData }>('_system.user.updateProfile', {\n ...(firstName !== undefined ? { firstName } : {}),\n ...(lastName !== undefined ? { lastName } : {}),\n ...(avatarUrl !== undefined ? { avatarUrl } : {}),\n ...(handle !== undefined ? { handle } : {}),\n });\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Verify user's email with a verification token.\n *\n * @example\n * ```ts\n * await verifyEmail({ token: 'verification-token' });\n * ```\n * @param options.token - The email verification token.\n */\nexport async function verifyEmail(options: { token: string }) {\n const { token } = options;\n await callMethod<{ user: RawUserData }>('_system.user.verifyEmail', { token });\n}\n\n/**\n * Resend the verification email for a given email address.\n * The email is only sent if the address is registered and not yet verified.\n * A generic response is always returned to avoid leaking account information.\n *\n * @example\n * ```ts\n * await resendEmailVerification({ email: 'user@example.com' });\n * ```\n * @param options.email - The email address to resend verification to.\n */\nexport async function resendEmailVerification(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.resendEmailVerification', { email });\n}\n\n/**\n * Logout the current user.\n *\n */\nexport async function logout() {\n await callMethod('_system.user.logout');\n clearLocalStorageSession();\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(null);\n }\n setCurrentUser(null);\n}\n\n/**\n * Send reset password token.\n * @param options.email - The email of the user.\n */\nexport async function sendResetPasswordToken(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.sendResetPasswordToken', {\n email,\n });\n}\n\n/**\n * Send a magic sign-in link to the given email address.\n *\n * Clicking the emailed link signs the user in. When the server enables\n * `auth.magicLink.allowSignup`, this also works for new users — the account is\n * created when the link is used; otherwise unknown emails receive no email.\n * A generic response is always returned to avoid leaking account information.\n *\n * @example\n * ```ts\n * await sendMagicLink({ email: 'user@example.com' });\n * ```\n * @param options.email - The email address to send the magic link to.\n */\nexport async function sendMagicLink(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.sendMagicLink', {\n email,\n });\n}\n\n/**\n * Complete a magic link sign-in.\n *\n * Call this from the page the magic link landing route redirects to. The\n * token is exchanged server-side via an httpOnly cookie, so no arguments are\n * needed. Signs the user in — creating the account first when the email is\n * not registered yet and the server enables `auth.magicLink.allowSignup` —\n * and returns the logged-in user.\n *\n * @example\n * ```ts\n * const user = await loginWithMagicLink();\n * ```\n */\nexport async function loginWithMagicLink() {\n const result = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithMagicLink'\n );\n return completeLogin(result);\n}\n\n/**\n * Complete a magic link sign-in by typing the one-time code from the email.\n *\n * Alternative to `loginWithMagicLink()` for contexts where clicking the link\n * can't reach the app — native apps without deep links, or when the email is\n * read on a different device. Signs the user in — creating the account first\n * when the email is not registered yet and the server enables\n * `auth.magicLink.allowSignup` — and returns the logged-in user.\n *\n * @example\n * ```ts\n * const user = await loginWithOneTimeCode({ email: 'user@example.com', code: '482193' });\n * ```\n * @param options.email - The email the magic link was sent to.\n * @param options.code - The one-time code from the email.\n */\nexport async function loginWithOneTimeCode(options: { email: string; code: string }) {\n const { email, code } = options;\n const result = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithOneTimeCode',\n { email, code }\n );\n return completeLogin(result);\n}\n\n/**\n * Reset password.\n *\n * The token is normally exchanged server-side via an httpOnly cookie, so the\n * client only submits the new password. Pass `token` only for legacy flows\n * that still carry it client-side (deprecated).\n *\n * @param options.token - Reset token (optional; read from the httpOnly cookie when omitted).\n * @param options.password - The new password.\n */\nexport async function resetPassword(options: { token?: string; password: string }) {\n const { token, password } = options;\n await callMethod('_system.user.resetPassword', {\n ...(token ? { token } : {}),\n password,\n });\n}\n\n/**\n * Start an OAuth sign-in.\n *\n * On the web this navigates to the provider and the flow finishes on its own —\n * the session cookie is set and the browser lands back on your site.\n *\n * Pass `redirectUri` to run the native flow: the device browser opens the\n * provider, and when the flow completes Modelence redirects back to that deep\n * link with a single-use `code` query parameter. Hand that code to\n * {@link loginWithOAuth} to finish signing in. The redirect target must be\n * listed in the server's `auth.mobile.redirectUrls`, otherwise the request is\n * rejected before the provider is ever reached.\n *\n * The native flow additionally binds the sign-in to this device: a verifier is\n * held in memory here and replayed by `loginWithOAuth`, so a `code` delivered\n * to the app from outside this flow cannot be redeemed.\n *\n * @example Web\n * ```ts\n * await signInWithOAuth({ provider: 'google' });\n * ```\n *\n * @example React Native\n * ```ts\n * import { parseDeepLinkParams } from 'modelence/client';\n *\n * await signInWithOAuth({ provider: 'google', redirectUri: 'myapp://auth' });\n *\n * Linking.addEventListener('url', async ({ url }) => {\n * const { code } = parseDeepLinkParams(url);\n * if (code) await loginWithOAuth({ code });\n * });\n * ```\n * @param options.provider - The OAuth provider to sign in with ('google' or 'github').\n * @param options.redirectUri - Deep link to return to. Required on React Native.\n */\nexport async function signInWithOAuth(options: {\n provider: OAuthProvider;\n redirectUri?: string;\n}): Promise<void> {\n const { provider, redirectUri } = options;\n const config = getClientConfig();\n const baseUrl = config?.baseUrl ?? '';\n\n // `redirectUri` — not the presence of `openUrl` — decides the flow. An\n // Electron or Capacitor client may set `openUrl` purely to control how links\n // open while still completing the ordinary cookie-based web flow.\n if (redirectUri) {\n if (!config?.openUrl) {\n throw new Error(\n 'signInWithOAuth was given a redirectUri but the client has no openUrl. ' +\n 'Configure openUrl (e.g. (url) => Linking.openURL(url)) to use the native flow.'\n );\n }\n\n const codeChallenge = startOAuthVerifier();\n const url =\n `${baseUrl}/api/_internal/auth/${provider}?mode=login&platform=mobile` +\n `&redirectUri=${encodeURIComponent(redirectUri)}` +\n `&codeChallenge=${encodeURIComponent(codeChallenge)}`;\n const opened = config.openUrl(url);\n\n // `openUrl` returned the popup it opened: let the callback page running in\n // it fetch the verifier from here. Needed when this page is an iframe whose\n // storage the popup cannot see; harmless otherwise. `consumeOAuthVerifier`\n // is what answers, so the verifier is handed out once and then gone here.\n if (isMessageTarget(opened)) {\n offerVerifierToPopup(opened, consumeOAuthVerifier);\n }\n return;\n }\n\n const webUrl = `${baseUrl}/api/_internal/auth/${provider}?mode=login`;\n if (config?.openUrl) {\n config.openUrl(webUrl);\n return;\n }\n\n window.location.href = webUrl;\n}\n\n/**\n * Complete a native OAuth sign-in with the code from the deep link.\n *\n * Exchanges the single-use code that {@link signInWithOAuth} delivered to your\n * app's deep link for a session, stores the auth token, and returns the\n * signed-in user. Codes are valid for one minute and can only be redeemed once.\n *\n * Pairs with `signInWithOAuth({ provider, redirectUri })` — the flow that hands\n * a code back to your app. It works on native and under Expo Web, where the\n * verifier is kept in `sessionStorage` so it survives the navigation to the\n * provider. When the flow ran in a popup whose `openUrl` returned the window\n * it opened, the verifier is fetched from the opening page when this page's\n * storage has none, so it also works when the app is embedded in a\n * cross-origin iframe. A plain web app\n * that calls `signInWithOAuth({ provider })` with no `redirectUri` is signed\n * in by a session cookie and never needs this.\n *\n * The verifier minted by `signInWithOAuth` is replayed here, which is what\n * makes a code usable only by the client that started the flow. Calling this\n * without a preceding `signInWithOAuth` — as a crafted deep link would — fails\n * before the code is ever sent.\n *\n * @example\n * ```ts\n * const user = await loginWithOAuth({ code });\n * ```\n * @param options.code - The `code` query parameter from the deep link.\n */\nexport async function loginWithOAuth(options: { code: string }) {\n const { code } = options;\n\n // Own storage first: it is authoritative on native and for a same-tab flow.\n // Only a popup whose storage is partitioned away from the page that opened\n // it comes up empty here; that page still holds the verifier in memory, so\n // the popup asks it.\n const codeVerifier = consumeOAuthVerifier() ?? (await requestVerifierFromOpener());\n if (!codeVerifier) {\n // Thrown mid-flow, so apps surface it in the UI: the thrown message is for\n // the end user, the console line for whoever is debugging.\n console.error(\n '[modelence] loginWithOAuth was called with no sign-in in progress. ' +\n 'Either signInWithOAuth was never called on this client, or the code came ' +\n 'from somewhere other than a flow this client started. On native, the app ' +\n 'process must survive the round trip; in a browser the verifier is kept in ' +\n 'sessionStorage, so a new tab or a cleared session also produces this. ' +\n 'If the app runs in an iframe and opens the provider in a popup, openUrl ' +\n 'must return the window from window.open so the popup can ask this page. ' +\n 'A plain web app that never calls signInWithOAuth({ redirectUri }) does not ' +\n 'need loginWithOAuth at all — the cookie flow signs the user in on its own.'\n );\n\n throw new Error('This sign-in link is no longer valid. Please sign in again.');\n }\n\n const result = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithOAuth',\n { code, codeVerifier }\n );\n return completeLogin(result);\n}\n\n/**\n * Link an OAuth provider to the currently signed-in user's account.\n * Redirects the browser to the OAuth provider's authorization page.\n * The provider will redirect back and the account will be linked.\n *\n * Without `redirectUri` this navigates the current context and authenticates\n * with an httpOnly cookie, so it only works where the navigation stays in the\n * same cookie jar — a browser, or a webview that navigates in place. Clients\n * whose `openUrl` opens an external browser (Electron, Capacitor) must pass a\n * `redirectUri`: that flow carries a single-use nonce in the URL and does not\n * depend on cookies.\n *\n * @example\n * ```ts\n * linkOAuthProvider({ provider: 'google' });\n * ```\n * @param options.provider - The OAuth provider to link ('google' or 'github').\n * @param options.redirectUri - Deep link to return to once linking completes.\n * Required for React Native and any client that opens URLs externally; must be\n * listed in the server's `auth.mobile.redirectUrls`. Without it the flow ends\n * wherever the navigation lands rather than back in the app.\n */\nexport async function linkOAuthProvider(options: {\n provider: OAuthProvider;\n redirectUri?: string;\n}): Promise<void> {\n const { provider, redirectUri } = options;\n const config = getClientConfig();\n const baseUrl = config?.baseUrl ?? '';\n\n if (redirectUri) {\n if (!config?.openUrl) {\n throw new Error(\n 'linkOAuthProvider was given a redirectUri but the client has no openUrl. ' +\n 'Configure openUrl (e.g. (url) => Linking.openURL(url)) to use the native flow.'\n );\n }\n // React Native: exchange authToken for a single-use nonce via an authenticated\n // request, then put the nonce in the URL. A crafted external link can't work\n // because the nonce is bound to this session and consumed on first use.\n const token = getAuthToken();\n if (!token) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n const nonceResponse = await fetch(`${baseUrl}/api/_internal/auth/issue-link-nonce`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ authToken: token }),\n });\n if (!nonceResponse.ok) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n const { nonce } = await nonceResponse.json();\n const url =\n `${baseUrl}/api/_internal/auth/${provider}?mode=link` +\n `&linkNonce=${encodeURIComponent(nonce)}` +\n `&platform=mobile&redirectUri=${encodeURIComponent(redirectUri)}`;\n config.openUrl(url);\n } else {\n // Browser: set httpOnly cookie via same-origin fetch (keeps token out of redirect params).\n const token = getAuthToken();\n if (token) {\n const response = await fetch(`${baseUrl}/api/_internal/auth/set-link-cookie`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ authToken: token }),\n credentials: 'include',\n });\n if (!response.ok) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n }\n // Same-context navigation, not `config.openUrl`: this authenticates with the\n // httpOnly cookie just set on this origin, and `openUrl` may open a system\n // browser that never received it. (`signInWithOAuth` can use `openUrl` on\n // its web path because that path is stateless.) Clients that open externally\n // should pass a `redirectUri` and take the nonce flow above.\n window.location.href = `${baseUrl}/api/_internal/auth/${provider}?mode=link`;\n }\n}\n/**\n * Unlink an OAuth provider from the currently signed-in user's account.\n *\n * @example\n * ```ts\n * await unlinkOAuthProvider({ provider: 'github' });\n * ```\n * @param options.provider - The OAuth provider to unlink ('google' or 'github').\n */\nexport async function unlinkOAuthProvider(options: { provider: OAuthProvider }): Promise<void> {\n const { provider } = options;\n await callMethod('_system.user.unlinkOAuthProvider', { provider });\n}\n\n/**\n * Get the current auth token associated with the current session.\n * @returns The auth token or undefined if not authenticated.\n */\nexport function getAuthToken(): string | undefined {\n const config = getClientConfig();\n if (config) {\n return config.getAuthToken();\n }\n return getLocalStorageSession()?.authToken;\n}\n\nexport function getClientInfo(): ClientInfo {\n const config = getClientConfig();\n if (config) {\n return config.getClientInfo();\n }\n\n if (typeof window === 'undefined') {\n return {\n screenWidth: 0,\n screenHeight: 0,\n windowWidth: 0,\n windowHeight: 0,\n pixelRatio: 1,\n orientation: null,\n };\n }\n\n return {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type ?? null,\n };\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n console.error(`Error calling method '${methodName}':`, error);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { handleError } from '@/client/errorHandler';\nimport { getClientConfig } from '@/client/clientConfig';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nexport class MethodError extends Error {\n status: number;\n /**\n * Machine-readable error code set by the server (when available), so callers\n * can branch on the error kind without matching the human-readable message.\n * For example, a login attempt with an unverified email yields\n * `code === 'EMAIL_NOT_VERIFIED'`.\n */\n code?: string;\n\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = 'MethodError';\n this.status = status;\n this.code = code;\n }\n}\n\nexport type MethodArgs = Record<string, unknown>;\n\nexport type CallMethodOptions = {\n errorHandler?: (error: Error, methodName: string) => void;\n};\n\n// Default: fetch HTTP. SSR swaps in an in-process transport via globalThis\n// so Vite's ssrLoadModule (separate module graph) shares the same instance.\nexport type CallMethodTransport = <T = unknown>(methodName: string, args: MethodArgs) => Promise<T>;\n\n/**\n * The default HTTP transport. Exported so alternative transports (e.g. the SSR\n * in-process transport) can delegate to it when they don't apply.\n * @internal\n */\nexport const defaultCallMethodTransport: CallMethodTransport = async <T>(\n methodName: string,\n args: MethodArgs\n) => {\n const baseUrl = getClientConfig()?.baseUrl ?? '';\n return call<T>(`${baseUrl}/api/_internal/method/${methodName}`, args);\n};\n\nconst TRANSPORT_KEY = '__modelence_call_method_transport__';\n\ntype GlobalWithTransport = typeof globalThis & {\n [TRANSPORT_KEY]?: CallMethodTransport;\n};\n\nfunction getTransport(): CallMethodTransport {\n return (globalThis as GlobalWithTransport)[TRANSPORT_KEY] ?? defaultCallMethodTransport;\n}\n\n/** Returns a disposer that restores the previous transport. */\nexport function setCallMethodTransport(next: CallMethodTransport): () => void {\n const previous = (globalThis as GlobalWithTransport)[TRANSPORT_KEY];\n (globalThis as GlobalWithTransport)[TRANSPORT_KEY] = next;\n return () => {\n (globalThis as GlobalWithTransport)[TRANSPORT_KEY] = previous;\n };\n}\n\n/**\n * Calls a server-side method (query or mutation) defined on a Modelence module.\n *\n * Both `args` and `options` are optional. Use the type parameter `T` to type the return value.\n *\n * @example\n * ```typescript\n * import { callMethod } from 'modelence/client';\n *\n * // No arguments\n * const todos = await callMethod<Todo[]>('todo.getAll');\n *\n * // With arguments\n * const todo = await callMethod<Todo>('todo.getOne', { id: '123' });\n *\n * // With a custom error handler\n * const created = await callMethod<Todo>(\n * 'todo.create',\n * { title: 'Buy groceries' },\n * { errorHandler: (error, methodName) => console.error(methodName, error) }\n * );\n * ```\n *\n * @param methodName - Fully qualified method name, e.g. `'todo.getAll'`.\n * @param args - Arguments passed to the server-side method. Defaults to `{}`.\n * @param options - Call-site options such as a custom {@link CallMethodOptions.errorHandler}. Defaults to `{}`.\n * @returns A promise that resolves to the method's return value.\n */\nexport async function callMethod<T = unknown>(\n methodName: string,\n args?: MethodArgs,\n options?: CallMethodOptions\n): Promise<T> {\n args = args ?? {};\n options = options ?? {};\n try {\n return await getTransport()<T>(methodName, args);\n } catch (error) {\n const handler = options.errorHandler ?? handleError;\n handler(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: MethodArgs): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n // Send cookies even when the SPA and API are on different origins. The\n // password-reset and magic-link flows rely on httpOnly cookies set by the\n // server landing routes; with the default `same-origin` policy the cookie\n // would be dropped on cross-origin POSTs and those flows would fail.\n // (Cross-origin use also requires the server to emit\n // `Access-Control-Allow-Credentials: true` and a non-wildcard origin.)\n // Token-in-body clients (React Native / Expo) don't use cookies and can\n // override this via `configureClient({ credentials: 'omit' })`.\n credentials: getClientConfig()?.credentials ?? 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n const code = response.headers?.get('X-Modelence-Error-Code') ?? undefined;\n throw new MethodError(error, response.status, code);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { getLocalStorageSession, setLocalStorageSession } from './localStorage';\nimport { getClientConfig } from './clientConfig';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\n// Set when SSR rendered anonymously but localStorage holds a token (no\n// cookie yet). `reconcileSession()` then re-auths via the body and refreshes\n// the cookie for subsequent SSR requests.\nlet pendingReconciliation = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\nlet heartbeatTimer: ReturnType<typeof setTimeout> | null = null;\n\nconst userSchema = z.object({\n id: z.string(),\n handle: z.string(),\n roles: z.array(z.string()),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n avatarUrl: z.string().optional(),\n});\n\nfunction parseUser(user: unknown): User | null {\n if (!user) {\n return null;\n }\n\n const result = userSchema.safeParse(user);\n\n if (!result.success) {\n console.error('Session Error: Invalid user payload', result.error);\n return null;\n }\n\n const parsedData = result.data;\n\n return Object.freeze({\n ...parsedData,\n firstName: parsedData.firstName ?? undefined,\n lastName: parsedData.lastName ?? undefined,\n avatarUrl: parsedData.avatarUrl ?? undefined,\n hasRole: (role: string) => parsedData.roles.includes(role),\n requireRole: (role: string) => {\n if (!parsedData.roles.includes(role)) {\n throw new Error(`Access denied - role '${role}' required`);\n }\n },\n });\n}\n\nexport type SessionInitPayload = {\n configs: Configs;\n session: object & { authToken: string };\n user: object;\n /*\n Present (true) only when a development server has no backend at all —\n neither a Modelence Cloud connection nor a local database. AppProvider\n then shows setup instructions instead of the app. The server decides this;\n the client never consults its own build mode.\n */\n setupRequired?: boolean;\n};\n\nlet setupRequired = false;\n\n/** @internal */\nexport function _isSetupRequired(): boolean {\n return setupRequired;\n}\n\n/** Hydrate session state from the SSR payload, skipping the network round-trip. */\nexport function hydrateSession(payload: SessionInitPayload) {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n setupRequired = Boolean(payload.setupRequired);\n _setConfig(payload.configs);\n\n // localStorage token + anonymous SSR payload = server couldn't read the\n // token (no cookie yet). Preserve the localStorage token and defer to\n // `reconcileSession()`; overwriting here would log the user out permanently.\n const existingLocalSession = getLocalStorageSession() as { authToken?: string } | null;\n const existingToken = existingLocalSession?.authToken;\n const ssrSession = payload.session as { authToken?: string };\n\n if (existingToken && !payload.user && existingToken !== ssrSession.authToken) {\n pendingReconciliation = true;\n // First render must match the server (anonymous); reconcile swaps later.\n useSessionStore.getState().setUser(parseUser(payload.user));\n return;\n }\n\n setLocalStorageSession(payload.session);\n useSessionStore.getState().setUser(parseUser(payload.user));\n}\n\n/** Re-auth via the body token when SSR couldn't read it from a cookie. */\nexport async function reconcileSession() {\n if (!pendingReconciliation) {\n return;\n }\n pendingReconciliation = false;\n\n try {\n const { configs, session, user } = await callMethod<SessionInitPayload>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n useSessionStore.getState().setUser(parseUser(user));\n } catch (error) {\n console.error('Modelence: session reconciliation failed', error);\n }\n}\n\n/** @internal */\nexport function _isReconciliationPending(): boolean {\n return pendingReconciliation;\n}\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const payload = await callMethod<SessionInitPayload>('_system.session.init');\n const { configs, session, user } = payload;\n setupRequired = Boolean(payload.setupRequired);\n _setConfig(configs);\n\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(session.authToken);\n } else {\n setLocalStorageSession(session);\n }\n\n useSessionStore.getState().setUser(parseUser(user));\n\n await loopSessionHeartbeat();\n}\n\n/** Idempotent, client-only. Auto-started by `initSession`; call explicitly after `hydrateSession`. */\nexport async function startSessionHeartbeat() {\n if (typeof window === 'undefined' || heartbeatTimer !== null) {\n return;\n }\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n if (typeof window === 'undefined') {\n return;\n }\n\n try {\n await callMethod('_system.session.heartbeat', {}, { errorHandler: () => {} });\n } catch {\n // Silently ignore heartbeat errors - they're expected during HMR/reconnects\n }\n heartbeatTimer = setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: unknown) {\n const enrichedUser = parseUser(user);\n useSessionStore.getState().setUser(enrichedUser);\n return enrichedUser;\n}\n\nexport function isSessionInitialized() {\n return isInitialized;\n}\n\nexport function getHeartbeatTimer() {\n return heartbeatTimer;\n}\n\nexport function stopHeartbeatTimer() {\n if (heartbeatTimer) {\n clearTimeout(heartbeatTimer);\n heartbeatTimer = null;\n }\n}\n\ntype SsrSessionResolver = () => User | null;\nlet ssrSessionResolver: SsrSessionResolver | null = null;\n\n/** @internal SSR resolver reads from AsyncLocalStorage (per-request scoped). */\nexport function _setSsrSessionResolver(resolver: SsrSessionResolver | null) {\n ssrSessionResolver = resolver;\n}\n\n/** @internal */\nexport function _parseSessionUser(user: unknown): User | null {\n return parseUser(user);\n}\n\n/**\n * `useSession` is a hook that returns the current user, and in the future will also return other details about the current session.\n *\n * @example\n * ```ts\n * import { useSession } from 'modelence/client';\n *\n * function MyComponent() {\n * const { user } = useSession();\n * return <div>{user?.handle}</div>;\n * }\n * ```\n */\nexport function useSession() {\n if (typeof window === 'undefined' && ssrSessionResolver) {\n return { user: ssrSessionResolver() };\n }\n const user = useSessionStore((state) => state.user);\n return { user };\n}\n"]}
@@ -1,2 +1,2 @@
1
- import {E}from'./chunk-KDOTVIEY.js';import {a,b,c}from'./chunk-5M6FUMUK.js';import {AsyncLocalStorage}from'async_hooks';async function x(t,e,u){let n=a(await E(t,e,u)),a$1=b(n),y=JSON.parse(JSON.stringify(n));return c(y,a$1??void 0)}var p=new AsyncLocalStorage;function g(t,e){return p.run(t,e)}function d(){return p.getStore()}export{x as a,g as b,d as c};//# sourceMappingURL=chunk-UJ2WYHH7.js.map
2
- //# sourceMappingURL=chunk-UJ2WYHH7.js.map
1
+ import {G}from'./chunk-63RBLFRJ.js';import {a,b,c}from'./chunk-5M6FUMUK.js';import {AsyncLocalStorage}from'async_hooks';async function x(t,e,u){let n=a(await G(t,e,u)),a$1=b(n),y=JSON.parse(JSON.stringify(n));return c(y,a$1??void 0)}var p=new AsyncLocalStorage;function g(t,e){return p.run(t,e)}function d(){return p.getStore()}export{x as a,g as b,d as c};//# sourceMappingURL=chunk-NPBIRXLC.js.map
2
+ //# sourceMappingURL=chunk-NPBIRXLC.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ssr/callInProcess.ts","../src/ssr/context.ts"],"names":["callInProcessMethod","methodName","args","context","sanitized","sanitizeResult","runMethod","typeMap","getResponseTypeMap","jsonRoundTripped","reviveResponseTypes","storage","AsyncLocalStorage","runWithSsrContext","ctx","fn","getSsrContext"],"mappings":"wHAOA,eAAsBA,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACY,CACZ,IAAMC,CAAAA,CAAYC,CAAAA,CAAe,MAAMC,CAAAA,CAAUL,CAAAA,CAAYC,CAAAA,CAAMC,CAAO,CAAC,CAAA,CACrEI,GAAAA,CAAUC,CAAAA,CAAmBJ,CAAS,CAAA,CACtCK,CAAAA,CAAmB,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,SAAA,CAAUL,CAAS,CAAC,CAAA,CAC7D,OAAOM,CAAAA,CAAoBD,CAAAA,CAAkBF,GAAAA,EAAW,MAAS,CACnE,CCAA,IAAMI,CAAAA,CAAU,IAAIC,iBAAAA,CAEb,SAASC,CAAAA,CAAqBC,CAAAA,CAAwBC,CAAAA,CAAgB,CAC3E,OAAOJ,CAAAA,CAAQ,GAAA,CAAIG,CAAAA,CAAKC,CAAE,CAC5B,CAEO,SAASC,CAAAA,EAA+C,CAC7D,OAAOL,CAAAA,CAAQ,QAAA,EACjB","file":"chunk-UJ2WYHH7.js","sourcesContent":["import { runMethod } from '../methods';\nimport { sanitizeResult, getResponseTypeMap, reviveResponseTypes } from '../methods/serialize';\nimport type { Context, Args } from '../methods/types';\n\n// Invoke a method in-process and round-trip through the same JSON pipeline\n// as the HTTP transport so SSR output matches the dehydrated query cache.\n// The JSON.stringify/parse step is load-bearing: strips `undefined` props.\nexport async function callInProcessMethod<T = unknown>(\n methodName: string,\n args: Args,\n context: Context\n): Promise<T> {\n const sanitized = sanitizeResult(await runMethod(methodName, args, context));\n const typeMap = getResponseTypeMap(sanitized);\n const jsonRoundTripped = JSON.parse(JSON.stringify(sanitized));\n return reviveResponseTypes(jsonRoundTripped, typeMap ?? undefined) as T;\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { QueryClient } from '@tanstack/react-query';\nimport type { Context } from '../methods/types';\nimport type { Configs } from '../config/types';\n\nexport type SsrSessionSnapshot = {\n user: unknown;\n configs: Configs;\n};\n\nexport type SsrRequestContext = {\n callContext: Context;\n queryClient: QueryClient;\n session: SsrSessionSnapshot;\n};\n\nconst storage = new AsyncLocalStorage<SsrRequestContext>();\n\nexport function runWithSsrContext<T>(ctx: SsrRequestContext, fn: () => T): T {\n return storage.run(ctx, fn);\n}\n\nexport function getSsrContext(): SsrRequestContext | undefined {\n return storage.getStore();\n}\n"]}
1
+ {"version":3,"sources":["../src/ssr/callInProcess.ts","../src/ssr/context.ts"],"names":["callInProcessMethod","methodName","args","context","sanitized","sanitizeResult","runMethod","typeMap","getResponseTypeMap","jsonRoundTripped","reviveResponseTypes","storage","AsyncLocalStorage","runWithSsrContext","ctx","fn","getSsrContext"],"mappings":"wHAOA,eAAsBA,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACY,CACZ,IAAMC,CAAAA,CAAYC,CAAAA,CAAe,MAAMC,CAAAA,CAAUL,CAAAA,CAAYC,CAAAA,CAAMC,CAAO,CAAC,CAAA,CACrEI,GAAAA,CAAUC,CAAAA,CAAmBJ,CAAS,CAAA,CACtCK,CAAAA,CAAmB,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,SAAA,CAAUL,CAAS,CAAC,CAAA,CAC7D,OAAOM,CAAAA,CAAoBD,CAAAA,CAAkBF,GAAAA,EAAW,MAAS,CACnE,CCAA,IAAMI,CAAAA,CAAU,IAAIC,iBAAAA,CAEb,SAASC,CAAAA,CAAqBC,CAAAA,CAAwBC,CAAAA,CAAgB,CAC3E,OAAOJ,CAAAA,CAAQ,GAAA,CAAIG,CAAAA,CAAKC,CAAE,CAC5B,CAEO,SAASC,CAAAA,EAA+C,CAC7D,OAAOL,CAAAA,CAAQ,QAAA,EACjB","file":"chunk-NPBIRXLC.js","sourcesContent":["import { runMethod } from '../methods';\nimport { sanitizeResult, getResponseTypeMap, reviveResponseTypes } from '../methods/serialize';\nimport type { Context, Args } from '../methods/types';\n\n// Invoke a method in-process and round-trip through the same JSON pipeline\n// as the HTTP transport so SSR output matches the dehydrated query cache.\n// The JSON.stringify/parse step is load-bearing: strips `undefined` props.\nexport async function callInProcessMethod<T = unknown>(\n methodName: string,\n args: Args,\n context: Context\n): Promise<T> {\n const sanitized = sanitizeResult(await runMethod(methodName, args, context));\n const typeMap = getResponseTypeMap(sanitized);\n const jsonRoundTripped = JSON.parse(JSON.stringify(sanitized));\n return reviveResponseTypes(jsonRoundTripped, typeMap ?? undefined) as T;\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { QueryClient } from '@tanstack/react-query';\nimport type { Context } from '../methods/types';\nimport type { Configs } from '../config/types';\n\nexport type SsrSessionSnapshot = {\n user: unknown;\n configs: Configs;\n};\n\nexport type SsrRequestContext = {\n callContext: Context;\n queryClient: QueryClient;\n session: SsrSessionSnapshot;\n};\n\nconst storage = new AsyncLocalStorage<SsrRequestContext>();\n\nexport function runWithSsrContext<T>(ctx: SsrRequestContext, fn: () => T): T {\n return storage.run(ctx, fn);\n}\n\nexport function getSsrContext(): SsrRequestContext | undefined {\n return storage.getStore();\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import {a,d,g as g$1,n}from'./chunk-ACX7KY6E.js';import {K as K$1,b as b$1,G,g,k as k$1}from'./chunk-CHBJAOMP.js';import K from'react';import v from'react-dom/client';import {jsx}from'react/jsx-runtime';function y(t){return {getConfig(e){return b$1(`${t}.${e}`)},query(e,...r){let n=r[0]??{};return {queryKey:[t,e,n],queryFn:()=>K$1(`${t}.${e}`,n)}},mutation(e){return {mutationFn:r=>K$1(`${t}.${e}`,r)}},infiniteQuery(e,r){return {queryKey:[t,e,"infinite",r(void 0)],initialPageParam:void 0,queryFn:({pageParam:n})=>K$1(`${t}.${e}`,r(n))}}}}var w=y("_system");function Q(t){let e={};if(typeof t!="string")return e;let r=t.indexOf("?");if(r===-1)return e;let n=t.indexOf("#",r),c=t.slice(r+1,n===-1?void 0:n);for(let o of c.split("&")){if(!o)continue;let i=o.indexOf("="),u=i===-1?o:o.slice(0,i),l=i===-1?"":o.slice(i+1),s=C(u);s&&(s in e||(e[s]=C(l)));}return e}function C(t){let e=t.replace(/\+/g," ");try{return decodeURIComponent(e)}catch{return e}}var h=class{constructor(e,r){this.category=e,this.onMessage=r;}init(){d()?.on({category:this.category,listener:this.onMessage});}joinChannel(e){d()?.joinChannel({category:this.category,id:e});}leaveChannel(e){d()?.leaveChannel({category:this.category,id:e});}};var k="useClient"in K?K.useClient(a):a;var O="__MODELENCE_STATE__";function L(){return typeof document>"u"?false:document.getElementById(O)!==null}function H(){if(typeof document>"u")return null;let t=document.getElementById(O);if(!t)return null;try{return JSON.parse(t.textContent??"")}catch(e){return console.error("Modelence: failed to parse SSR state",e),null}}var b="__modelence_ssr_snapshot__";function D(t){globalThis[b]=t;}function Ne(){return globalThis[b]??null}function W(t){if(typeof window>"u"){D(t);return}let{loadingElement:e,routesElement:r,favicon:n$1,errorHandler:c,router:o,setupElement:i}=t;c&&G(c),window.addEventListener("unload",()=>{});let u=L(),l=H();l?.session&&(g(l.session),k$1());let s=document.getElementById("root"),q=window.location.pathname+window.location.search,x=o?o({children:r,location:q}):r,_=g$1()?x:jsx(n,{children:x}),S=jsx(K.StrictMode,{children:jsx(k,{loadingElement:e,setupElement:i,children:_})});if(u?v.hydrateRoot(s,S):v.createRoot(s).render(S),n$1){let T=document.querySelector("link[rel~='icon']");if(T)T.href=n$1;else {let p=document.createElement("link");p.rel="icon",p.href=n$1,document.head.appendChild(p);}}}export{y as a,w as b,Ne as c,W as d,Q as e,h as f,k as g};//# sourceMappingURL=chunk-PPPB2U34.js.map
2
+ //# sourceMappingURL=chunk-PPPB2U34.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client/module.ts","../src/system/client.ts","../src/auth/client/deepLink.ts","../src/websocket/clientChannel.ts","../src/client.ts","../src/client/renderApp.tsx"],"names":["createClientModule","moduleName","key","getConfig","name","rest","args","callMethod","getArgs","pageParam","systemConfig","parseDeepLinkParams","url","params","queryStart","fragmentStart","query","pair","eq","rawKey","rawValue","safeDecode","value","plus","ClientChannel","category","onMessage","getWebsocketClientProvider","id","AppProvider","React","SSR_STATE_SCRIPT_ID","hasSsrMarker","readSsrState","node","SNAPSHOT_KEY","setSnapshot","snapshot","_getSsrSnapshot","renderApp","options","loadingElement","routesElement","favicon","errorHandler","router","setupElement","setErrorHandler","isHydrating","ssrState","hydrateSession","startSessionHeartbeat","container","location","routedTree","appTree","hasConnectedQueryClient","jsx","ModelenceQueryProvider","tree","ReactDOM","link","newLink"],"mappings":"2MAuFO,SAASA,CAAAA,CAA8CC,CAAAA,CAAoB,CAChF,OAAO,CACL,SAAA,CACEC,CAAAA,CACqD,CAErD,OAAOC,GAAAA,CAAiB,CAAA,EAAGF,CAAU,CAAA,CAAA,EAAIC,CAAG,CAAA,CAAE,CAChD,CAAA,CAEA,KAAA,CACEE,CAAAA,CAAAA,GACGC,EAGH,CACA,IAAMC,CAAAA,CAAQD,CAAAA,CAAK,CAAC,CAAA,EAAK,EAAC,CAC1B,OAAO,CACL,QAAA,CAAU,CAACJ,CAAAA,CAAYG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MAAM,CAAA,CAC7CA,CAAAA,CAAQ,GAAA,CAAM,MAAA,CACdA,CAAAA,CAAQ,IAAA,CAAOnB,GAAAA,CACf,QAAA,CAAS,IAAA,CAAK,WAAA,CAAYmB,CAAO,EACnC,CAGF,CACF","file":"chunk-PPPB2U34.js","sourcesContent":["'use client';\n\nimport type { ObjectId } from 'mongodb';\nimport type { ConfigParams, ConfigType, ValueType } from '../config/types';\nimport { callMethod, type MethodArgs } from './method';\nimport type { AnyMethodShape } from '../methods/types';\n\n// Pulls the config store value without importing server-side code\nimport { getConfig as _getClientConfig } from '../config/client';\n\n// ── type helpers ─────────────────────────────────────────────────────────────\n\n/**\n * Recursively maps ObjectId → string to match the sanitized runtime values\n * sent over the wire. Dates are preserved (revived via typeMap on the client).\n */\ntype Sanitized<T> = T extends ObjectId\n ? string\n : T extends Date\n ? Date\n : T extends (infer U)[]\n ? Sanitized<U>[]\n : T extends object\n ? { [K in keyof T]: Sanitized<T[K]> }\n : T;\n\ntype ExtractArgs<M> = M extends (args: infer A, ...rest: any[]) => any // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : M extends { handler: (args: infer A, ...rest: any[]) => any } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : MethodArgs;\n\ntype ExtractResult<M> = M extends (...args: any[]) => Promise<infer R> // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : M extends { handler: (...args: any[]) => Promise<infer R> } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : unknown;\n\ntype PublicKeyOf<TSchema extends Record<string, ConfigParams>> = {\n [K in keyof TSchema as TSchema[K] extends ConfigParams<ConfigType, true>\n ? string & K\n : never]: ValueType<TSchema[K]['type']>;\n};\n\ntype AnyModule = {\n name: string;\n configSchema: Record<string, ConfigParams>;\n queries: Record<string, AnyMethodShape>;\n mutations: Record<string, AnyMethodShape>;\n};\n\n// ── createClientModule ────────────────────────────────────────────────────────\n\n/**\n * Creates a typed client accessor for a module's public configs, queries, and mutations.\n *\n * Use `import type` to reference the module so no server code is bundled on the client.\n * Arg and return types for queries and mutations are inferred automatically from the\n * server-side handler signatures.\n *\n * @param moduleName - The module's name as passed to `new Module(name, ...)`.\n *\n * @example\n * ```ts\n * // src/client/payments.ts\n * import type paymentsModule from '../server/payments';\n * import { createClientModule } from 'modelence/client';\n *\n * export const payments = createClientModule<typeof paymentsModule>('payments');\n * ```\n *\n * ```ts\n * // src/components/Checkout.tsx\n * import { useQuery, useMutation } from '@tanstack/react-query';\n * import { payments } from '../client/payments';\n *\n * // Typed config — public keys only, private and secret keys excluded:\n * const currency = payments.getConfig('currency'); // string | undefined\n *\n * // Typed query — pass directly to useQuery:\n * const { data: products } = useQuery(payments.query('getProducts', { page: 1 }));\n *\n * // Typed mutation — pass directly to useMutation:\n * const { mutate: charge } = useMutation(payments.mutation('charge'));\n * charge({ amount: 100 }); // args typed from handler signature\n * ```\n */\nexport function createClientModule<TModule extends AnyModule>(moduleName: string) {\n return {\n getConfig<K extends keyof PublicKeyOf<TModule['configSchema']> & string>(\n key: K\n ): PublicKeyOf<TModule['configSchema']>[K] | undefined {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return _getClientConfig(`${moduleName}.${key}`) as any;\n },\n\n query<K extends keyof TModule['queries'] & string>(\n name: K,\n ...rest: {} extends ExtractArgs<TModule['queries'][K]>\n ? [args?: ExtractArgs<TModule['queries'][K]>]\n : [args: ExtractArgs<TModule['queries'][K]>]\n ) {\n const args = (rest[0] ?? {}) as ExtractArgs<TModule['queries'][K]>;\n return {\n queryKey: [moduleName, name, args] as const,\n queryFn: (): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n mutation<K extends keyof TModule['mutations'] & string>(name: K) {\n return {\n mutationFn: (\n args: ExtractArgs<TModule['mutations'][K]>\n ): Promise<ExtractResult<TModule['mutations'][K]>> =>\n callMethod<ExtractResult<TModule['mutations'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n /**\n * Returns options for `useInfiniteQuery`. The `getArgs` callback receives the\n * current `pageParam` and returns the args to pass to the query handler.\n * Spread the result into `useInfiniteQuery` alongside `getNextPageParam`.\n *\n * Annotate the `pageParam` type in the callback so TypeScript can infer the\n * page param type — no manual generic needed on `useInfiniteQuery`.\n */\n infiniteQuery<K extends keyof TModule['queries'] & string, TPageParam = unknown>(\n name: K,\n getArgs: (pageParam: TPageParam | undefined) => ExtractArgs<TModule['queries'][K]>\n ) {\n return {\n queryKey: [moduleName, name, 'infinite', getArgs(undefined)] as const,\n // Included so TanStack infers TPageParam from the callback type, not from a bare `undefined`.\n initialPageParam: undefined as TPageParam | undefined,\n queryFn: ({\n pageParam,\n }: {\n pageParam: TPageParam | undefined;\n }): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n getArgs(pageParam) as MethodArgs\n ),\n };\n },\n };\n}\n","import type systemModule from './index';\nimport { createClientModule } from '../client/module';\n\nexport const systemConfig = createClientModule<typeof systemModule>('_system');\n","/**\n * Deep-link query parsing that works on bare React Native.\n *\n * `new URL(url).searchParams` is not usable here: React Native's `URL` is a\n * partial implementation that throws on `searchParams` access, and Expo only\n * appears to work because it installs a polyfill. Parsing the query string\n * directly keeps the documented callback snippet working on both.\n */\n\n/**\n * Reads query parameters out of a deep link such as `myapp://auth?code=abc`.\n *\n * Only the query component is considered — everything from the first `?` up to\n * an optional `#` fragment. Values are percent-decoded, with `+` treated as a\n * space to match `application/x-www-form-urlencoded`, which is how the server's\n * `URL.searchParams.set` encodes them.\n */\nexport function parseDeepLinkParams(url: string): Record<string, string> {\n const params: Record<string, string> = {};\n\n if (typeof url !== 'string') return params;\n\n const queryStart = url.indexOf('?');\n if (queryStart === -1) return params;\n\n const fragmentStart = url.indexOf('#', queryStart);\n const query = url.slice(queryStart + 1, fragmentStart === -1 ? undefined : fragmentStart);\n\n for (const pair of query.split('&')) {\n if (!pair) continue;\n\n const eq = pair.indexOf('=');\n const rawKey = eq === -1 ? pair : pair.slice(0, eq);\n const rawValue = eq === -1 ? '' : pair.slice(eq + 1);\n\n const key = safeDecode(rawKey);\n if (!key) continue;\n\n // First occurrence wins, so a crafted link cannot override an earlier\n // parameter by appending a duplicate.\n if (!(key in params)) {\n params[key] = safeDecode(rawValue);\n }\n }\n\n return params;\n}\n\n/**\n * Percent-decodes a component, falling back to the raw text.\n *\n * `decodeURIComponent` throws on malformed escapes like `%zz`; a deep link is\n * attacker-reachable input, so a bad escape must not take down the app's link\n * handler.\n */\nfunction safeDecode(value: string): string {\n const plus = value.replace(/\\+/g, ' ');\n try {\n return decodeURIComponent(plus);\n } catch {\n return plus;\n }\n}\n","import { getWebsocketClientProvider } from './client';\n\nexport class ClientChannel<T = unknown> {\n public readonly category: string;\n private readonly onMessage: (data: T) => void;\n\n constructor(category: string, onMessage: (data: T) => void) {\n this.category = category;\n this.onMessage = onMessage;\n }\n\n init() {\n getWebsocketClientProvider()?.on({\n category: this.category,\n listener: this.onMessage,\n });\n }\n\n joinChannel(id: string) {\n getWebsocketClientProvider()?.joinChannel({\n category: this.category,\n id,\n });\n }\n\n leaveChannel(id: string) {\n getWebsocketClientProvider()?.leaveChannel({\n category: this.category,\n id,\n });\n }\n}\n","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { configureClient, type ClientConfig } from './client/clientConfig';\nexport { getConfig } from './config/client';\nexport { createClientModule } from './client/module';\nexport type { ValueType } from './config/types';\nexport { systemConfig } from './system/client';\n\nexport const AppProvider =\n 'useClient' in React\n ? // @ts-ignore: React.useClient only exists in Next.js\n React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { ModelenceQueryProvider } from './client/queryProvider';\nexport {\n modelenceQuery,\n modelenceLiveQuery,\n modelenceMutation,\n createQueryKey,\n connectModelenceQueryClient,\n disconnectModelenceQueryClient,\n ModelenceQueryClient,\n type ModelenceQueryKey,\n} from './client/query';\nexport { callMethod, MethodError, type MethodArgs, type CallMethodOptions } from './client/method';\nexport { useSession } from './client/session';\nexport {\n signupWithPassword,\n loginWithPassword,\n verifyEmail,\n updateProfile,\n resendEmailVerification,\n logout,\n sendResetPasswordToken,\n resetPassword,\n sendMagicLink,\n loginWithMagicLink,\n loginWithOneTimeCode,\n signInWithOAuth,\n loginWithOAuth,\n linkOAuthProvider,\n unlinkOAuthProvider,\n type UserInfo,\n} from './auth/client';\nexport { parseDeepLinkParams } from './auth/client/deepLink';\nexport {\n getWebsocketClientProvider,\n setWebsocketClientProvider,\n startWebsockets,\n subscribeLiveQuery,\n} from './websocket/client';\nexport { ClientChannel } from './websocket/clientChannel';\nexport { getLocalStorageSession } from './client/localStorage';\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\nimport { hydrateSession, startSessionHeartbeat, type SessionInitPayload } from './session';\nimport { ModelenceQueryProvider } from './queryProvider';\nimport { hasConnectedQueryClient } from './query';\n\nconst SSR_STATE_SCRIPT_ID = '__MODELENCE_STATE__';\n\ntype SsrState = {\n session?: SessionInitPayload;\n};\n\nfunction hasSsrMarker(): boolean {\n if (typeof document === 'undefined') {\n return false;\n }\n return document.getElementById(SSR_STATE_SCRIPT_ID) !== null;\n}\n\nfunction readSsrState(): SsrState | null {\n if (typeof document === 'undefined') {\n return null;\n }\n\n const node = document.getElementById(SSR_STATE_SCRIPT_ID);\n if (!node) {\n return null;\n }\n\n try {\n return JSON.parse(node.textContent ?? '') as SsrState;\n } catch (e) {\n // Caller must still hydrate (marker presence drives that, not parsed payload).\n console.error('Modelence: failed to parse SSR state', e);\n return null;\n }\n}\n\nexport type SsrRouter = (props: {\n children: React.ReactNode;\n location?: string;\n}) => React.ReactElement;\n\nexport interface RenderAppOptions {\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n favicon?: string;\n errorHandler?: ErrorHandler;\n router?: SsrRouter;\n /*\n Replaces the built-in setup screen shown when a development server has no\n backend yet (no Modelence Cloud connection, no local database). Pass\n `null` to disable the screen entirely.\n */\n setupElement?: React.ReactNode;\n}\n\n// Shared via globalThis: ssrLoadModule loads the user's entry in a separate\n// module graph from the framework runtime.\nconst SNAPSHOT_KEY = '__modelence_ssr_snapshot__';\n\ntype GlobalWithSnapshot = typeof globalThis & {\n [SNAPSHOT_KEY]?: RenderAppOptions | null;\n};\n\nfunction setSnapshot(snapshot: RenderAppOptions | null) {\n (globalThis as GlobalWithSnapshot)[SNAPSHOT_KEY] = snapshot;\n}\n\n/** @internal Used by the SSR runtime after evaluating the user's entry. */\nexport function _getSsrSnapshot(): RenderAppOptions | null {\n return (globalThis as GlobalWithSnapshot)[SNAPSHOT_KEY] ?? null;\n}\n\nexport function renderApp(options: RenderAppOptions) {\n if (typeof window === 'undefined') {\n setSnapshot(options);\n return;\n }\n\n const { loadingElement, routesElement, favicon, errorHandler, router, setupElement } = options;\n\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n // Empty 'unload' handler prevents bfcache in most browsers.\n window.addEventListener('unload', () => {});\n\n // Hydrate session BEFORE building the tree so `isSessionInitialized()` is\n // true on the first render and matches the server output. Hydration mode\n // tracks marker presence (not parse success): a parse failure still leaves\n // server-rendered DOM that must be hydrated, not replaced.\n const isHydrating = hasSsrMarker();\n const ssrState = readSsrState();\n if (ssrState?.session) {\n hydrateSession(ssrState.session);\n // Fire-and-forget: the heartbeat loop runs in the background.\n void startSessionHeartbeat();\n }\n\n const container = document.getElementById('root')!;\n // Pass the same location the server used (req.originalUrl == path + search;\n // the hash is never sent to the server) so a location-driven router (e.g. a\n // static router) resolves the same route on hydration as it did during SSR,\n // avoiding hydration mismatches.\n const location = window.location.pathname + window.location.search;\n const routedTree = router ? router({ children: routesElement, location }) : routesElement;\n\n // If the app already connected its own QueryClient (the documented\n // bring-your-own-provider pattern connects before calling renderApp), don't\n // inject ours. A second provider would shadow the user's client: useQuery\n // would read the inner client while live-query updates write to the outer\n // one, so real-time queries would never update.\n const appTree = hasConnectedQueryClient() ? (\n routedTree\n ) : (\n <ModelenceQueryProvider>{routedTree}</ModelenceQueryProvider>\n );\n\n const tree = (\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement} setupElement={setupElement}>\n {appTree}\n </AppProvider>\n </React.StrictMode>\n );\n\n if (isHydrating) {\n ReactDOM.hydrateRoot(container, tree);\n } else {\n ReactDOM.createRoot(container).render(tree);\n }\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n"]}
@@ -0,0 +1,3 @@
1
+ var s="module",i="modelence",r="0.24.0-dev.1",c="The Node.js Framework for Real-Time MongoDB Apps",n="dist/index.js",o="dist/global.d.ts",p={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js","./types":{types:"./dist/types.d.ts",default:"./dist/types.js"}},d=["dist","dist/bin"],a={modelence:"./dist/bin/modelence.js"},l={node:">=22"},m={build:"tsup",dev:"tsup --watch",format:'prettier --write "src/**/*.{ts,tsx,js,jsx,json,css,md}"',"format:check":'prettier --check "src/**/*.{ts,tsx,js,jsx,json,css,md}"',lint:"eslint src --ext .ts,.tsx --fix","lint:check":"eslint src --ext .ts,.tsx",prepublishOnly:"npm run build",bench:"tsx src/bench/index.ts",test:"vitest run","test:watch":"vitest","test:coverage":"vitest run --coverage",postversion:"git push && git push --tags",prepare:"cd ../.. && git config core.hooksPath .husky"},g={type:"git",url:"git+https://github.com/modelence/modelence.git"},u="Modelence",y="SEE LICENSE IN LICENSE",h={url:"https://github.com/modelence/modelence/issues"},v="https://modelence.com",j={"@tanstack/react-query":"^5.100.7","@types/archiver":"^6.0.3","@types/bcrypt":"^6.0.0","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/node":"^22.5.1","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@types/socket.io":"^3.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0","@vitest/coverage-v8":"^2.1.8",eslint:"^9.37.0",husky:"^9.1.7","lint-staged":"^16.2.7",prettier:"^3.6.2",react:"^19.0.0","react-dom":"^19.0.0","ts-node":"^10.9.2","vite-tsconfig-paths":"^5.1.4",vitest:"^2.1.8"},x={"@socket.io/mongo-adapter":"^0.4.0","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^6.0.0",commander:"^12.0.0","cookie-parser":"^1.4.7",dotenv:"^16.4.5","elastic-apm-node":"^4.15.0",express:"^4.21.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0","socket.io":"^4.8.1","socket.io-client":"^4.8.1",tsup:"^8.3.6",tsx:"^4.19.3",typescript:"^5.7.2",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",zod:"^3.23.8",zustand:"^5.0.2"},b={"@tanstack/react-query":">=5.0.0",react:">=18.0.0","react-dom":">=18.0.0"},k={type:s,name:i,version:r,description:c,main:n,types:o,exports:p,files:d,bin:a,engines:l,scripts:m,"lint-staged":{"src/**/*.{ts,tsx,js,jsx,json,css,md}":"prettier --write"},repository:g,author:u,license:y,bugs:h,homepage:v,devDependencies:j,dependencies:x,peerDependencies:b};
2
+ export{s as a,i as b,r as c,c as d,n as e,o as f,p as g,d as h,a as i,l as j,m as k,g as l,u as m,y as n,h as o,v as p,j as q,x as r,b as s,k as t};//# sourceMappingURL=chunk-ZCIM5A5S.js.map
3
+ //# sourceMappingURL=chunk-ZCIM5A5S.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","engines","scripts","repository","author","license","bugs","homepage","devDepend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AGA,OAAA,CAAAC,CAAAA,CAGA,OAAA,CAAAC,CAAAA,CAeA,aAAA,CAAe,CACb,sCAAA,CAAwC,kBAC1C,CAAA,CACA,UAAA,CAAAC,CAAAA,CAIA,MAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CAGA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CAuBA,YAAA,CAAAC,CAAAA,CAuBA,gBAAA,CAAAC,CAKF","file":"chunk-ZCIM5A5S.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.24.0-dev.1\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\",\n \"./types\": {\n \"types\": \"./dist/types.d.ts\",\n \"default\": \"./dist/types.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"engines\": {\n \"node\": \">=22\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"lint\": \"eslint src --ext .ts,.tsx --fix\",\n \"lint:check\": \"eslint src --ext .ts,.tsx\",\n \"prepublishOnly\": \"npm run build\",\n \"bench\": \"tsx src/bench/index.ts\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\",\n \"postversion\": \"git push && git push --tags\",\n \"prepare\": \"cd ../.. && git config core.hooksPath .husky\"\n },\n \"lint-staged\": {\n \"src/**/*.{ts,tsx,js,jsx,json,css,md}\": \"prettier --write\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@tanstack/react-query\": \"^5.100.7\",\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^6.0.0\",\n \"@types/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/node\": \"^22.5.1\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@types/socket.io\": \"^3.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"@vitest/coverage-v8\": \"^2.1.8\",\n \"eslint\": \"^9.37.0\",\n \"husky\": \"^9.1.7\",\n \"lint-staged\": \"^16.2.7\",\n \"prettier\": \"^3.6.2\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"ts-node\": \"^10.9.2\",\n \"vite-tsconfig-paths\": \"^5.1.4\",\n \"vitest\": \"^2.1.8\"\n },\n \"dependencies\": {\n \"@socket.io/mongo-adapter\": \"^0.4.0\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^6.0.0\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.15.0\",\n \"express\": \"^4.21.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"socket.io\": \"^4.8.1\",\n \"socket.io-client\": \"^4.8.1\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"typescript\": \"^5.7.2\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"@tanstack/react-query\": \">=5.0.0\",\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}