@fluid-app/rep-sdk 0.1.3 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/MessagingScreen-5TEWFUX4.js +4 -0
- package/dist/{MessagingScreen-4H7ZBO3V.js.map → MessagingScreen-5TEWFUX4.js.map} +1 -1
- package/dist/MessagingScreen-JC7I55NG.cjs +17 -0
- package/dist/{MessagingScreen-UPFXQZV3.cjs.map → MessagingScreen-JC7I55NG.cjs.map} +1 -1
- package/dist/{chunk-V3IMQZIG.cjs → chunk-OE62VIZU.cjs} +16 -3
- package/dist/chunk-OE62VIZU.cjs.map +1 -0
- package/dist/{chunk-7JMNKWPN.js → chunk-R4SXB6EV.js} +16 -3
- package/dist/chunk-R4SXB6EV.js.map +1 -0
- package/dist/index.cjs +269 -121
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -1
- package/dist/index.d.ts +8 -1
- package/dist/index.js +137 -8
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
- package/dist/MessagingScreen-4H7ZBO3V.js +0 -4
- package/dist/MessagingScreen-UPFXQZV3.cjs +0 -17
- package/dist/chunk-7JMNKWPN.js.map +0 -1
- package/dist/chunk-V3IMQZIG.cjs.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types/page-template.ts","../src/registries/page-template-registry.ts","../src/core/resolve-pages.ts","../src/providers/PageTemplateProvider.tsx","../src/hooks/use-fluid-profile.ts","../../../../node_modules/.pnpm/@tanstack+query-core@5.90.12/node_modules/@tanstack/query-core/src/timeoutManager.ts","../../../../node_modules/.pnpm/@tanstack+query-core@5.90.12/node_modules/@tanstack/query-core/src/utils.ts","../../../../node_modules/.pnpm/@tanstack+query-core@5.90.12/node_modules/@tanstack/query-core/src/notifyManager.ts","../../../../node_modules/.pnpm/@tanstack+query-persist-client-core@5.91.11/node_modules/@tanstack/query-persist-client-core/src/createPersister.ts","../../../platform/query-persister/src/persister.ts","../src/hooks/use-fluid-app.ts","../src/hooks/use-fluid-permissions.ts","../src/hooks/use-fluid-theme.ts","../src/hooks/use-current-rep.ts","../src/hooks/use-fluid-auth.ts","../src/hooks/demo-data/calendar-events.ts","../src/hooks/use-calendar-events.ts","../src/hooks/demo-data/todos.ts","../src/hooks/use-todos.ts","../src/hooks/hook-types.ts","../src/hooks/demo-data/activities.ts","../src/hooks/use-activities.ts","../src/hooks/demo-data/catchups.ts","../src/hooks/use-catchups.ts","../src/hooks/demo-data/mysite.ts","../src/hooks/use-mysite.ts","../src/hooks/demo-data/conversations.ts","../src/hooks/use-conversations.ts","../src/types/screen-types.ts","../src/hooks/demo-data/contacts.ts","../src/hooks/use-contacts.ts","../src/components/AuthError.tsx","../src/components/RequireAuth.tsx","../src/screens/index.ts","../src/shell/AppShellLoading.tsx","../src/shell/slug-utils.ts","../src/shell/SdkNavigation.tsx","../src/shell/QuickLinksDropdown.tsx","../src/shell/SdkHeader.tsx","../src/shell/BuilderScreenView.tsx","../src/shell/PageRouter.tsx","../src/shell/AppNavigationContext.tsx","../src/shell/AppShell.tsx","../src/shell/AppLink.tsx"],"names":["createContext","useRef","useEffect","useMemo","useContext","useFluidApi","useQuery","storage","filters","transformManifestToRepAppData","useThemeContext","useFluidAuthContext","now","daysFromNow","hoursAgo","daysAgo","jsx","jsxs","isLoading","Fragment","SPIN_STYLE_ID","ensureSpinStyle","normalizeSlug","SidebarMenu","SidebarGroupLabel","SidebarMenuItem","SidebarMenuButton","RepIcon","useState","useCallback","getSystemNavigationBySection","FontAwesomeIcon","faTableCellsLarge","sidebar","useSidebar","useThemeMode","faMoon","faSun","faBars","useRegistry","DataAwareWidget","memo","MessagingScreen","ContactsScreen","OrdersScreen","CustomersScreen","ProductsScreen","isSystemNavigationItem","CoreScreenPlaceholder","resolveTheme","applyTheme","removeAllThemes","ThemeModeProvider","AppShellLayout","forwardRef","AppLink"],"mappings":";;;;;;;;;;;;;;;;;;;;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AS,QAAA,EAAU,GAAG,IAAA,EAAK,EAAG,GAAA,EAAK;AACxD,IAAA,MAAM,EAAE,QAAA,EAAU,SAAA,EAAU,GAAI,gBAAA,EAAiB;AAEjD,IAAA,MAAM,WAAA,GAAc,CAAC,CAAA,KAAqC;AAExD,MAAA,OAAA,GAAU,CAAC,CAAA;AACX,MAAA,IAAI,EAAE,gBAAA,EAAkB;AAGxB,MAAA,IAAI,EAAE,OAAA,IAAW,CAAA,CAAE,WAAW,CAAA,CAAE,QAAA,IAAY,EAAE,MAAA,EAAQ;AACtD,MAAA,IAAI,CAAA,CAAE,WAAW,CAAA,EAAG;AACpB,MAAA,IAAI,IAAA,CAAK,MAAA,IAAU,IAAA,CAAK,MAAA,KAAW,OAAA,EAAS;AAE5C,MAAA,CAAA,CAAE,cAAA,EAAe;AACjB,MAAA,QAAA,CAAS,EAAE,CAAA;AAAA,IACb,CAAA;AAEA,IAAA,uBACEvC,cAAAA,CAAC,GAAA,EAAA,EAAE,GAAA,EAAU,IAAA,EAAM,SAAA,CAAU,EAAE,CAAA,EAAG,OAAA,EAAS,WAAA,EAAc,GAAG,IAAA,EACzD,QAAA,EACH,CAAA;AAAA,EAEJ;AACF","file":"index.cjs","sourcesContent":["import type { WidgetSchema } from \"./widget-schema\";\n\n/**\n * Category for organizing page templates in the registry\n */\nexport interface PageCategory {\n /** Unique identifier for the category */\n readonly id: string;\n /** Display label */\n label: string;\n /** Icon identifier (e.g., lucide icon name) */\n icon?: string;\n}\n\n/**\n * A reusable page template that can be shared across multiple navigations\n */\nexport interface PageTemplate {\n /** Unique identifier for the template */\n readonly id: string;\n /** URL-friendly slug */\n slug: string;\n /** Display name */\n name: string;\n /** Description of the template's purpose */\n description?: string;\n /** Category ID for organization */\n category: string;\n /** Tags for filtering and search */\n tags?: readonly string[];\n /** The widget tree that defines the page content */\n component_tree: readonly WidgetSchema[];\n /** Semantic version of the template */\n version: string;\n /** Whether this is a core feature that cannot be removed */\n isCore?: boolean;\n /** Default prop values that can be customized */\n defaultProps?: Readonly<Record<string, unknown>>;\n /** Thumbnail image URL for UI display */\n thumbnail?: string;\n}\n\n/**\n * Reference to a shared page template within a navigation\n */\nexport interface PageReference {\n /** ID of the page template being referenced */\n page_template_id: string;\n /** Screen ID to assign to this page in the navigation */\n screen_id: number;\n /** Optional prop overrides (only prop values, not widget structure) */\n overrides?: readonly PageOverride[];\n}\n\n/**\n * Override for a specific widget's props within a page template\n */\nexport interface PageOverride {\n /** ID of the widget to override (must match WidgetSchema.id in the template) */\n readonly widget_id: string;\n /** Props to override (merged with original props) */\n props: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Built-in page category IDs\n */\nexport const PAGE_CATEGORIES = {\n CORE: \"core\",\n COMMERCE: \"commerce\",\n COMMUNICATION: \"communication\",\n DATA: \"data\",\n CUSTOM: \"custom\",\n} as const;\n\nexport type PageCategoryId =\n (typeof PAGE_CATEGORIES)[keyof typeof PAGE_CATEGORIES];\n","import type {\n PageTemplate,\n PageCategory,\n PageCategoryId,\n} from \"../types/page-template\";\nimport { PAGE_CATEGORIES } from \"../types/page-template\";\n\n/**\n * Registry for managing reusable page templates.\n *\n * The registry provides a central store for page templates that can be\n * shared across multiple navigations. Core pages (like Messaging, Contacts)\n * are pre-registered and cannot be removed.\n *\n * @example\n * ```ts\n * // Register a custom page template\n * PageTemplateRegistry.register({\n * id: 'custom-dashboard',\n * slug: 'dashboard',\n * name: 'Custom Dashboard',\n * category: 'custom',\n * version: '1.0.0',\n * component_tree: [{ type: 'TextWidget', props: { text: 'Hello' } }],\n * });\n *\n * // Get a template by ID\n * const template = PageTemplateRegistry.get('custom-dashboard');\n *\n * // List all templates in a category\n * const corePages = PageTemplateRegistry.getByCategory('core');\n * ```\n */\nclass PageTemplateRegistryImpl {\n private templates = new Map<string, PageTemplate>();\n private categories: PageCategory[] = [];\n\n constructor() {\n // Initialize default categories\n this.categories = [\n { id: PAGE_CATEGORIES.CORE, label: \"Core Features\", icon: \"star\" },\n {\n id: PAGE_CATEGORIES.COMMERCE,\n label: \"Commerce\",\n icon: \"shopping-cart\",\n },\n {\n id: PAGE_CATEGORIES.COMMUNICATION,\n label: \"Communication\",\n icon: \"message-circle\",\n },\n {\n id: PAGE_CATEGORIES.DATA,\n label: \"Data & Analytics\",\n icon: \"bar-chart\",\n },\n { id: PAGE_CATEGORIES.CUSTOM, label: \"Custom\", icon: \"puzzle\" },\n ];\n }\n\n /**\n * Register a new page template.\n * @throws Error if a template with the same ID already exists\n */\n register(template: PageTemplate): void {\n if (this.templates.has(template.id)) {\n throw new Error(\n `Page template with ID \"${template.id}\" is already registered`,\n );\n }\n this.templates.set(template.id, template);\n }\n\n /**\n * Unregister a page template by ID.\n * Core templates cannot be unregistered.\n * @returns true if the template was removed, false if it didn't exist or is a core template\n */\n unregister(id: string): boolean {\n const template = this.templates.get(id);\n if (!template) {\n return false;\n }\n if (template.isCore) {\n console.warn(\n `Cannot unregister core page template \"${id}\". Core templates are required.`,\n );\n return false;\n }\n return this.templates.delete(id);\n }\n\n /**\n * Get a page template by ID.\n */\n get(id: string): PageTemplate | undefined {\n return this.templates.get(id);\n }\n\n /**\n * Get all page templates in a specific category.\n */\n getByCategory(category: PageCategoryId | string): PageTemplate[] {\n return Array.from(this.templates.values()).filter(\n (t) => t.category === category,\n );\n }\n\n /**\n * List all registered page templates.\n */\n listAll(): PageTemplate[] {\n return Array.from(this.templates.values());\n }\n\n /**\n * List all core page templates (isCore: true).\n */\n listCore(): PageTemplate[] {\n return Array.from(this.templates.values()).filter((t) => t.isCore);\n }\n\n /**\n * List all non-core page templates.\n */\n listOptional(): PageTemplate[] {\n return Array.from(this.templates.values()).filter((t) => !t.isCore);\n }\n\n /**\n * List all registered categories.\n */\n listCategories(): PageCategory[] {\n return [...this.categories];\n }\n\n /**\n * Add a custom category.\n */\n addCategory(category: PageCategory): void {\n if (this.categories.some((c) => c.id === category.id)) {\n console.warn(`Category with ID \"${category.id}\" already exists`);\n return;\n }\n this.categories.push(category);\n }\n\n /**\n * Check if a template exists by ID.\n */\n has(id: string): boolean {\n return this.templates.has(id);\n }\n\n /**\n * Get the count of registered templates.\n */\n get size(): number {\n return this.templates.size;\n }\n\n /**\n * Clear all non-core templates.\n * Useful for testing or resetting the registry.\n */\n clearNonCore(): void {\n for (const [id, template] of this.templates) {\n if (!template.isCore) {\n this.templates.delete(id);\n }\n }\n }\n}\n\n/**\n * Global page template registry singleton.\n *\n * This registry is automatically populated with core page templates\n * (Messaging, Contacts) when the SDK is imported.\n */\nexport const PageTemplateRegistry = new PageTemplateRegistryImpl();\n","import type { Navigation, ScreenDefinition, WidgetSchema } from \"../types\";\nimport type { PageReference, PageOverride } from \"../types/page-template\";\nimport { PageTemplateRegistry } from \"../registries/page-template-registry\";\n\n/**\n * Apply prop overrides to widgets in a component tree.\n * Recursively walks widget.props.children so overrides targeting\n * nested widgets (inside LayoutWidget, ContainerWidget, etc.) are applied.\n *\n * @param componentTree - The original component tree from the page template\n * @param overrides - Array of widget-specific prop overrides\n * @returns A new component tree with overrides applied\n */\nfunction applyOverrides(\n componentTree: readonly WidgetSchema[],\n overrides: readonly PageOverride[],\n): WidgetSchema[] {\n if (!overrides.length) {\n // Return a mutable copy to satisfy ScreenDefinition.component_tree type\n return [...componentTree];\n }\n\n // Build a map of widget_id -> override for O(1) lookup (built once, shared across recursion)\n const overrideMap = new Map(overrides.map((o) => [o.widget_id, o.props]));\n\n return componentTree.map((widget) =>\n applyWidgetOverrides(widget, overrideMap),\n );\n}\n\n/**\n * Recursively apply overrides to a widget and its children.\n * Only clones widgets that actually change (have an override or contain children that might).\n */\nfunction applyWidgetOverrides(\n widget: WidgetSchema,\n overrideMap: ReadonlyMap<string, Record<string, unknown>>,\n): WidgetSchema {\n const override = widget.id ? overrideMap.get(widget.id) : undefined;\n const children = widget.props.children;\n\n // Recurse into children if they exist (LayoutWidget, ContainerWidget)\n const hasChildren = Array.isArray(children) && children.length > 0;\n\n if (!override && !hasChildren) {\n return widget;\n }\n\n const newProps = override\n ? { ...widget.props, ...override }\n : { ...widget.props };\n\n if (hasChildren) {\n newProps.children = (children as readonly WidgetSchema[]).map((child) =>\n applyWidgetOverrides(child, overrideMap),\n );\n }\n\n return { ...widget, props: newProps };\n}\n\n/**\n * Resolve a page reference to a screen definition.\n *\n * @param ref - The page reference from navigation\n * @returns A ScreenDefinition or undefined if the template doesn't exist\n */\nfunction resolvePageReference(\n ref: Readonly<PageReference>,\n): ScreenDefinition | undefined {\n const template = PageTemplateRegistry.get(ref.page_template_id);\n if (!template) {\n console.warn(\n `Page template \"${ref.page_template_id}\" not found in registry`,\n );\n return undefined;\n }\n\n // Apply any overrides to the component tree\n // Spread to create mutable array for ScreenDefinition.component_tree\n const componentTree = ref.overrides\n ? applyOverrides(template.component_tree, ref.overrides)\n : [...template.component_tree];\n\n return {\n id: ref.screen_id,\n slug: template.slug,\n name: template.name,\n component_tree: componentTree,\n };\n}\n\n/**\n * Resolve all page references and local screens into a unified screen list.\n *\n * This function merges:\n * 1. Screen definitions from page_refs (shared templates)\n * 2. Local screen definitions (for backwards compatibility and custom screens)\n *\n * When a screen_id appears in both page_refs and screens, the local screen\n * takes precedence (allows local overrides of template pages).\n *\n * @param navigation - The navigation configuration\n * @returns A unified array of ScreenDefinition objects\n *\n * @example\n * ```ts\n * const navigation: Navigation = {\n * definition_id: 1,\n * id: 1,\n * name: \"Main Nav\",\n * navigation_items: [...],\n * screens: [\n * // Local custom screen\n * { id: 1, slug: \"home\", name: \"Home\", component_tree: [...] }\n * ],\n * page_refs: [\n * // Reference to shared messaging template\n * { page_template_id: \"core-messaging\", screen_id: 2 }\n * ],\n * };\n *\n * const allScreens = resolveNavigationPages(navigation);\n * // Returns: [home screen, messaging screen from template]\n * ```\n */\nexport function resolveNavigationPages(\n navigation: Readonly<Navigation>,\n): ScreenDefinition[] {\n // Start with local screens (these take precedence)\n const localScreenIds = new Set(navigation.screens.map((s) => s.id));\n const result: ScreenDefinition[] = [...navigation.screens];\n\n // Resolve page references (skip if local screen already exists with same ID)\n if (navigation.page_refs) {\n for (const ref of navigation.page_refs) {\n if (localScreenIds.has(ref.screen_id)) {\n // Local screen takes precedence\n continue;\n }\n\n const screen = resolvePageReference(ref);\n if (screen) {\n result.push(screen);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Get all available page templates for use in navigation.\n *\n * @returns Array of page templates from the registry\n */\nexport function getAvailablePageTemplates() {\n return PageTemplateRegistry.listAll();\n}\n\n/**\n * Get core page templates that are required for basic functionality.\n *\n * @returns Array of core page templates\n */\nexport function getCorePageTemplates() {\n return PageTemplateRegistry.listCore();\n}\n\n/**\n * Get optional page templates that can be added to navigation.\n *\n * @returns Array of optional (non-core) page templates\n */\nexport function getOptionalPageTemplates() {\n return PageTemplateRegistry.listOptional();\n}\n\n/**\n * Check if a navigation has all required core pages.\n *\n * @param navigation - The navigation to check\n * @returns Object with validation result and missing page IDs\n */\nexport function validateNavigationPages(navigation: Readonly<Navigation>): {\n readonly valid: boolean;\n readonly missingCorePages: readonly string[];\n} {\n const corePages = PageTemplateRegistry.listCore();\n const referencedTemplateIds = new Set(\n navigation.page_refs?.map((ref) => ref.page_template_id) ?? [],\n );\n\n // Check which core pages are referenced\n const missingCorePages = corePages\n .filter((page) => !referencedTemplateIds.has(page.id))\n .map((page) => page.id);\n\n return {\n valid: missingCorePages.length === 0,\n missingCorePages,\n };\n}\n","import React, {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n} from \"react\";\nimport type { PageTemplate } from \"../types/page-template\";\nimport { PageTemplateRegistry } from \"../registries/page-template-registry\";\nimport { resolveNavigationPages } from \"../core/resolve-pages\";\nimport type { Navigation, ScreenDefinition } from \"../types\";\n\n/** Stable empty array for the default `templates` prop (avoids new reference each render) */\nconst EMPTY_TEMPLATES: readonly PageTemplate[] = [];\n\n/**\n * Context value for page template resolution.\n * All properties are readonly since context values should not be mutated by consumers.\n */\ninterface PageTemplateContextValue {\n /**\n * Resolve a navigation's page_refs and screens into a unified screen list\n */\n readonly resolvePages: (navigation: Navigation) => ScreenDefinition[];\n /**\n * Get all available page templates\n */\n readonly listTemplates: () => PageTemplate[];\n /**\n * Get a specific template by ID\n */\n readonly getTemplate: (id: string) => PageTemplate | undefined;\n /**\n * Check if a template exists\n */\n readonly hasTemplate: (id: string) => boolean;\n}\n\nconst PageTemplateContext = createContext<PageTemplateContextValue | null>(\n null,\n);\n\n/**\n * Props for PageTemplateProvider\n */\ninterface PageTemplateProviderProps {\n children: React.ReactNode;\n /**\n * Additional custom page templates to register.\n * These are registered when the provider mounts and unregistered when it unmounts.\n */\n templates?: readonly PageTemplate[];\n}\n\n/**\n * Provider for page template resolution.\n *\n * This provider:\n * 1. Registers any custom templates passed via props\n * 2. Provides methods for resolving navigation pages\n * 3. Cleans up custom templates on unmount\n *\n * @example\n * ```tsx\n * // With custom templates\n * const customTemplates: PageTemplate[] = [\n * {\n * id: 'custom-dashboard',\n * slug: 'dashboard',\n * name: 'Dashboard',\n * category: 'custom',\n * version: '1.0.0',\n * component_tree: [{ type: 'TextWidget', props: { text: 'Custom Dashboard' } }],\n * },\n * ];\n *\n * <PageTemplateProvider templates={customTemplates}>\n * <App />\n * </PageTemplateProvider>\n *\n * // Without custom templates (uses only core templates)\n * <PageTemplateProvider>\n * <App />\n * </PageTemplateProvider>\n * ```\n */\nexport function PageTemplateProvider({\n children,\n templates = EMPTY_TEMPLATES,\n}: PageTemplateProviderProps) {\n // Track which templates we registered so we can clean them up\n const registeredIds = useRef<string[]>([]);\n\n // Derive a stable primitive key from template IDs\n // (rerender-dependencies rule: use primitive dependencies in effects)\n const templateKey = templates.map((t) => t.id).join(\",\");\n\n // Register custom templates when template IDs change\n useEffect(() => {\n const registered: string[] = [];\n\n for (const template of templates) {\n if (!PageTemplateRegistry.has(template.id)) {\n try {\n PageTemplateRegistry.register(template);\n registered.push(template.id);\n } catch (error) {\n console.warn(\n `Failed to register page template \"${template.id}\":`,\n error,\n );\n }\n }\n }\n\n registeredIds.current = registered;\n\n // Cleanup when template IDs change or on unmount\n return () => {\n for (const id of registeredIds.current) {\n PageTemplateRegistry.unregister(id);\n }\n registeredIds.current = [];\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [templateKey]);\n\n // Memoize context value to prevent unnecessary re-renders\n // Use `satisfies` to validate shape at compile time while preserving inference\n const contextValue = useMemo(\n () =>\n ({\n resolvePages: resolveNavigationPages,\n listTemplates: () => PageTemplateRegistry.listAll(),\n getTemplate: (id: string) => PageTemplateRegistry.get(id),\n hasTemplate: (id: string) => PageTemplateRegistry.has(id),\n }) satisfies PageTemplateContextValue,\n [],\n );\n\n return (\n <PageTemplateContext.Provider value={contextValue}>\n {children}\n </PageTemplateContext.Provider>\n );\n}\n\n/**\n * Hook to access page template functionality.\n *\n * @throws Error if used outside of PageTemplateProvider\n *\n * @example\n * ```tsx\n * function NavigationRenderer({ navigation }: { navigation: Navigation }) {\n * const { resolvePages } = usePageTemplates();\n * const screens = resolvePages(navigation);\n *\n * return (\n * <div>\n * {screens.map((screen) => (\n * <Screen key={screen.id} definition={screen} />\n * ))}\n * </div>\n * );\n * }\n * ```\n */\nexport function usePageTemplates(): PageTemplateContextValue {\n const context = useContext(PageTemplateContext);\n if (!context) {\n throw new Error(\n \"usePageTemplates must be used within a PageTemplateProvider\",\n );\n }\n return context;\n}\n\n/**\n * Hook to resolve navigation pages directly.\n * Convenience wrapper around usePageTemplates().resolvePages.\n *\n * @param navigation - The navigation to resolve\n * @returns Array of resolved screen definitions\n */\nexport function useResolvedPages(navigation: Navigation): ScreenDefinition[] {\n const { resolvePages } = usePageTemplates();\n return useMemo(() => resolvePages(navigation), [resolvePages, navigation]);\n}\n","import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { useFluidApi } from \"./use-fluid-api\";\nimport type { Profile } from \"../types/profile\";\n\n/**\n * Query key for profile data\n */\nexport const PROFILE_QUERY_KEY = [\"fluid\", \"profile\"] as const;\n\n/**\n * Hook to fetch the rep portal profile (themes, navigation, screens)\n *\n * @example\n * ```tsx\n * function Navigation() {\n * const { data: profile, isLoading } = useFluidProfile();\n *\n * if (isLoading) return <Spinner />;\n *\n * return (\n * <nav>\n * {profile?.navigation.navigation_items.map(item => (\n * <NavItem key={item.id} item={item} />\n * ))}\n * </nav>\n * );\n * }\n * ```\n */\nexport function useFluidProfile(): UseQueryResult<Profile> {\n const api = useFluidApi();\n\n return useQuery({\n queryKey: PROFILE_QUERY_KEY,\n queryFn: () => api.profile.get(),\n });\n}\n","/**\n * {@link TimeoutManager} does not support passing arguments to the callback.\n *\n * `(_: void)` is the argument type inferred by TypeScript's default typings for\n * `setTimeout(cb, number)`.\n * If we don't accept a single void argument, then\n * `new Promise(resolve => timeoutManager.setTimeout(resolve, N))` is a type error.\n */\nexport type TimeoutCallback = (_: void) => void\n\n/**\n * Wrapping `setTimeout` is awkward from a typing perspective because platform\n * typings may extend the return type of `setTimeout`. For example, NodeJS\n * typings add `NodeJS.Timeout`; but a non-default `timeoutManager` may not be\n * able to return such a type.\n */\nexport type ManagedTimerId = number | { [Symbol.toPrimitive]: () => number }\n\n/**\n * Backend for timer functions.\n */\nexport type TimeoutProvider<TTimerId extends ManagedTimerId = ManagedTimerId> =\n {\n readonly setTimeout: (callback: TimeoutCallback, delay: number) => TTimerId\n readonly clearTimeout: (timeoutId: TTimerId | undefined) => void\n\n readonly setInterval: (callback: TimeoutCallback, delay: number) => TTimerId\n readonly clearInterval: (intervalId: TTimerId | undefined) => void\n }\n\nexport const defaultTimeoutProvider: TimeoutProvider<\n ReturnType<typeof setTimeout>\n> = {\n // We need the wrapper function syntax below instead of direct references to\n // global setTimeout etc.\n //\n // BAD: `setTimeout: setTimeout`\n // GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)`\n //\n // If we use direct references here, then anything that wants to spy on or\n // replace the global setTimeout (like tests) won't work since we'll already\n // have a hard reference to the original implementation at the time when this\n // file was imported.\n setTimeout: (callback, delay) => setTimeout(callback, delay),\n clearTimeout: (timeoutId) => clearTimeout(timeoutId),\n\n setInterval: (callback, delay) => setInterval(callback, delay),\n clearInterval: (intervalId) => clearInterval(intervalId),\n}\n\n/**\n * Allows customization of how timeouts are created.\n *\n * @tanstack/query-core makes liberal use of timeouts to implement `staleTime`\n * and `gcTime`. The default TimeoutManager provider uses the platform's global\n * `setTimeout` implementation, which is known to have scalability issues with\n * thousands of timeouts on the event loop.\n *\n * If you hit this limitation, consider providing a custom TimeoutProvider that\n * coalesces timeouts.\n */\nexport class TimeoutManager implements Omit<TimeoutProvider, 'name'> {\n // We cannot have TimeoutManager<T> as we must instantiate it with a concrete\n // type at app boot; and if we leave that type, then any new timer provider\n // would need to support ReturnType<typeof setTimeout>, which is infeasible.\n //\n // We settle for type safety for the TimeoutProvider type, and accept that\n // this class is unsafe internally to allow for extension.\n #provider: TimeoutProvider<any> = defaultTimeoutProvider\n #providerCalled = false\n\n setTimeoutProvider<TTimerId extends ManagedTimerId>(\n provider: TimeoutProvider<TTimerId>,\n ): void {\n if (process.env.NODE_ENV !== 'production') {\n if (this.#providerCalled && provider !== this.#provider) {\n // After changing providers, `clearTimeout` will not work as expected for\n // timeouts from the previous provider.\n //\n // Since they may allocate the same timeout ID, clearTimeout may cancel an\n // arbitrary different timeout, or unexpected no-op.\n //\n // We could protect against this by mixing the timeout ID bits\n // deterministically with some per-provider bits.\n //\n // We could internally queue `setTimeout` calls to `TimeoutManager` until\n // some API call to set the initial provider.\n console.error(\n `[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`,\n { previous: this.#provider, provider },\n )\n }\n }\n\n this.#provider = provider\n if (process.env.NODE_ENV !== 'production') {\n this.#providerCalled = false\n }\n }\n\n setTimeout(callback: TimeoutCallback, delay: number): ManagedTimerId {\n if (process.env.NODE_ENV !== 'production') {\n this.#providerCalled = true\n }\n return this.#provider.setTimeout(callback, delay)\n }\n\n clearTimeout(timeoutId: ManagedTimerId | undefined): void {\n this.#provider.clearTimeout(timeoutId)\n }\n\n setInterval(callback: TimeoutCallback, delay: number): ManagedTimerId {\n if (process.env.NODE_ENV !== 'production') {\n this.#providerCalled = true\n }\n return this.#provider.setInterval(callback, delay)\n }\n\n clearInterval(intervalId: ManagedTimerId | undefined): void {\n this.#provider.clearInterval(intervalId)\n }\n}\n\nexport const timeoutManager = new TimeoutManager()\n\n/**\n * In many cases code wants to delay to the next event loop tick; this is not\n * mediated by {@link timeoutManager}.\n *\n * This function is provided to make auditing the `tanstack/query-core` for\n * incorrect use of system `setTimeout` easier.\n */\nexport function systemSetTimeoutZero(callback: TimeoutCallback): void {\n setTimeout(callback, 0)\n}\n","import { timeoutManager } from './timeoutManager'\nimport type {\n DefaultError,\n Enabled,\n FetchStatus,\n MutationKey,\n MutationStatus,\n QueryFunction,\n QueryKey,\n QueryOptions,\n StaleTime,\n StaleTimeFunction,\n} from './types'\nimport type { Mutation } from './mutation'\nimport type { FetchOptions, Query } from './query'\n\n// TYPES\n\ntype DropLast<T extends ReadonlyArray<unknown>> = T extends readonly [\n ...infer R,\n unknown,\n]\n ? readonly [...R]\n : never\n\ntype TuplePrefixes<T extends ReadonlyArray<unknown>> = T extends readonly []\n ? readonly []\n : TuplePrefixes<DropLast<T>> | T\n\nexport interface QueryFilters<TQueryKey extends QueryKey = QueryKey> {\n /**\n * Filter to active queries, inactive queries or all queries\n */\n type?: QueryTypeFilter\n /**\n * Match query key exactly\n */\n exact?: boolean\n /**\n * Include queries matching this predicate function\n */\n predicate?: (query: Query) => boolean\n /**\n * Include queries matching this query key\n */\n queryKey?: TQueryKey | TuplePrefixes<TQueryKey>\n /**\n * Include or exclude stale queries\n */\n stale?: boolean\n /**\n * Include queries matching their fetchStatus\n */\n fetchStatus?: FetchStatus\n}\n\nexport interface MutationFilters<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> {\n /**\n * Match mutation key exactly\n */\n exact?: boolean\n /**\n * Include mutations matching this predicate function\n */\n predicate?: (\n mutation: Mutation<TData, TError, TVariables, TOnMutateResult>,\n ) => boolean\n /**\n * Include mutations matching this mutation key\n */\n mutationKey?: TuplePrefixes<MutationKey>\n /**\n * Filter by mutation status\n */\n status?: MutationStatus\n}\n\nexport type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)\n\nexport type QueryTypeFilter = 'all' | 'active' | 'inactive'\n\n// UTILS\n\nexport const isServer = typeof window === 'undefined' || 'Deno' in globalThis\n\nexport function noop(): void\nexport function noop(): undefined\nexport function noop() {}\n\nexport function functionalUpdate<TInput, TOutput>(\n updater: Updater<TInput, TOutput>,\n input: TInput,\n): TOutput {\n return typeof updater === 'function'\n ? (updater as (_: TInput) => TOutput)(input)\n : updater\n}\n\nexport function isValidTimeout(value: unknown): value is number {\n return typeof value === 'number' && value >= 0 && value !== Infinity\n}\n\nexport function timeUntilStale(updatedAt: number, staleTime?: number): number {\n return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)\n}\n\nexport function resolveStaleTime<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n staleTime:\n | undefined\n | StaleTimeFunction<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): StaleTime | undefined {\n return typeof staleTime === 'function' ? staleTime(query) : staleTime\n}\n\nexport function resolveEnabled<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n enabled: undefined | Enabled<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): boolean | undefined {\n return typeof enabled === 'function' ? enabled(query) : enabled\n}\n\nexport function matchQuery(\n filters: QueryFilters,\n query: Query<any, any, any, any>,\n): boolean {\n const {\n type = 'all',\n exact,\n fetchStatus,\n predicate,\n queryKey,\n stale,\n } = filters\n\n if (queryKey) {\n if (exact) {\n if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {\n return false\n }\n } else if (!partialMatchKey(query.queryKey, queryKey)) {\n return false\n }\n }\n\n if (type !== 'all') {\n const isActive = query.isActive()\n if (type === 'active' && !isActive) {\n return false\n }\n if (type === 'inactive' && isActive) {\n return false\n }\n }\n\n if (typeof stale === 'boolean' && query.isStale() !== stale) {\n return false\n }\n\n if (fetchStatus && fetchStatus !== query.state.fetchStatus) {\n return false\n }\n\n if (predicate && !predicate(query)) {\n return false\n }\n\n return true\n}\n\nexport function matchMutation(\n filters: MutationFilters,\n mutation: Mutation<any, any>,\n): boolean {\n const { exact, status, predicate, mutationKey } = filters\n if (mutationKey) {\n if (!mutation.options.mutationKey) {\n return false\n }\n if (exact) {\n if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {\n return false\n }\n } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {\n return false\n }\n }\n\n if (status && mutation.state.status !== status) {\n return false\n }\n\n if (predicate && !predicate(mutation)) {\n return false\n }\n\n return true\n}\n\nexport function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(\n queryKey: TQueryKey,\n options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,\n): string {\n const hashFn = options?.queryKeyHashFn || hashKey\n return hashFn(queryKey)\n}\n\n/**\n * Default query & mutation keys hash function.\n * Hashes the value into a stable hash.\n */\nexport function hashKey(queryKey: QueryKey | MutationKey): string {\n return JSON.stringify(queryKey, (_, val) =>\n isPlainObject(val)\n ? Object.keys(val)\n .sort()\n .reduce((result, key) => {\n result[key] = val[key]\n return result\n }, {} as any)\n : val,\n )\n}\n\n/**\n * Checks if key `b` partially matches with key `a`.\n */\nexport function partialMatchKey(a: QueryKey, b: QueryKey): boolean\nexport function partialMatchKey(a: any, b: any): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n return Object.keys(b).every((key) => partialMatchKey(a[key], b[key]))\n }\n\n return false\n}\n\nconst hasOwn = Object.prototype.hasOwnProperty\n\n/**\n * This function returns `a` if `b` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between JSON values for example.\n */\nexport function replaceEqualDeep<T>(a: unknown, b: T): T\nexport function replaceEqualDeep(a: any, b: any): any {\n if (a === b) {\n return a\n }\n\n const array = isPlainArray(a) && isPlainArray(b)\n\n if (!array && !(isPlainObject(a) && isPlainObject(b))) return b\n\n const aItems = array ? a : Object.keys(a)\n const aSize = aItems.length\n const bItems = array ? b : Object.keys(b)\n const bSize = bItems.length\n const copy: any = array ? new Array(bSize) : {}\n\n let equalItems = 0\n\n for (let i = 0; i < bSize; i++) {\n const key: any = array ? i : bItems[i]\n const aItem = a[key]\n const bItem = b[key]\n\n if (aItem === bItem) {\n copy[key] = aItem\n if (array ? i < aSize : hasOwn.call(a, key)) equalItems++\n continue\n }\n\n if (\n aItem === null ||\n bItem === null ||\n typeof aItem !== 'object' ||\n typeof bItem !== 'object'\n ) {\n copy[key] = bItem\n continue\n }\n\n const v = replaceEqualDeep(aItem, bItem)\n copy[key] = v\n if (v === aItem) equalItems++\n }\n\n return aSize === bSize && equalItems === aSize ? a : copy\n}\n\n/**\n * Shallow compare objects.\n */\nexport function shallowEqualObjects<T extends Record<string, any>>(\n a: T,\n b: T | undefined,\n): boolean {\n if (!b || Object.keys(a).length !== Object.keys(b).length) {\n return false\n }\n\n for (const key in a) {\n if (a[key] !== b[key]) {\n return false\n }\n }\n\n return true\n}\n\nexport function isPlainArray(value: unknown): value is Array<unknown> {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\nexport function isPlainObject(o: any): o is Record<PropertyKey, unknown> {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has no constructor\n const ctor = o.constructor\n if (ctor === undefined) {\n return true\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Handles Objects created by Object.create(<arbitrary prototype>)\n if (Object.getPrototypeOf(o) !== Object.prototype) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\nfunction hasObjectPrototype(o: any): boolean {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\nexport function sleep(timeout: number): Promise<void> {\n return new Promise((resolve) => {\n timeoutManager.setTimeout(resolve, timeout)\n })\n}\n\nexport function replaceData<\n TData,\n TOptions extends QueryOptions<any, any, any, any>,\n>(prevData: TData | undefined, data: TData, options: TOptions): TData {\n if (typeof options.structuralSharing === 'function') {\n return options.structuralSharing(prevData, data) as TData\n } else if (options.structuralSharing !== false) {\n if (process.env.NODE_ENV !== 'production') {\n try {\n return replaceEqualDeep(prevData, data)\n } catch (error) {\n console.error(\n `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`,\n )\n\n // Prevent the replaceEqualDeep from being called again down below.\n throw error\n }\n }\n // Structurally share data between prev and new data if needed\n return replaceEqualDeep(prevData, data)\n }\n return data\n}\n\nexport function keepPreviousData<T>(\n previousData: T | undefined,\n): T | undefined {\n return previousData\n}\n\nexport function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [...items, item]\n return max && newItems.length > max ? newItems.slice(1) : newItems\n}\n\nexport function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [item, ...items]\n return max && newItems.length > max ? newItems.slice(0, -1) : newItems\n}\n\nexport const skipToken = Symbol()\nexport type SkipToken = typeof skipToken\n\nexport function ensureQueryFn<\n TQueryFnData = unknown,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: {\n queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken\n queryHash?: string\n },\n fetchOptions?: FetchOptions<TQueryFnData>,\n): QueryFunction<TQueryFnData, TQueryKey> {\n if (process.env.NODE_ENV !== 'production') {\n if (options.queryFn === skipToken) {\n console.error(\n `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,\n )\n }\n }\n\n // if we attempt to retry a fetch that was triggered from an initialPromise\n // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise\n // if an observer has already mounted, we will be able to retry with that queryFn\n if (!options.queryFn && fetchOptions?.initialPromise) {\n return () => fetchOptions.initialPromise!\n }\n\n if (!options.queryFn || options.queryFn === skipToken) {\n return () =>\n Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))\n }\n\n return options.queryFn\n}\n\nexport function shouldThrowError<T extends (...args: Array<any>) => boolean>(\n throwOnError: boolean | T | undefined,\n params: Parameters<T>,\n): boolean {\n // Allow throwOnError function to override throwing behavior on a per-error basis\n if (typeof throwOnError === 'function') {\n return throwOnError(...params)\n }\n\n return !!throwOnError\n}\n","// TYPES\n\nimport { systemSetTimeoutZero } from './timeoutManager'\n\ntype NotifyCallback = () => void\n\ntype NotifyFunction = (callback: () => void) => void\n\ntype BatchNotifyFunction = (callback: () => void) => void\n\ntype BatchCallsCallback<T extends Array<unknown>> = (...args: T) => void\n\ntype ScheduleFunction = (callback: () => void) => void\n\nexport const defaultScheduler: ScheduleFunction = systemSetTimeoutZero\n\nexport function createNotifyManager() {\n let queue: Array<NotifyCallback> = []\n let transactions = 0\n let notifyFn: NotifyFunction = (callback) => {\n callback()\n }\n let batchNotifyFn: BatchNotifyFunction = (callback: () => void) => {\n callback()\n }\n let scheduleFn = defaultScheduler\n\n const schedule = (callback: NotifyCallback): void => {\n if (transactions) {\n queue.push(callback)\n } else {\n scheduleFn(() => {\n notifyFn(callback)\n })\n }\n }\n const flush = (): void => {\n const originalQueue = queue\n queue = []\n if (originalQueue.length) {\n scheduleFn(() => {\n batchNotifyFn(() => {\n originalQueue.forEach((callback) => {\n notifyFn(callback)\n })\n })\n })\n }\n }\n\n return {\n batch: <T>(callback: () => T): T => {\n let result\n transactions++\n try {\n result = callback()\n } finally {\n transactions--\n if (!transactions) {\n flush()\n }\n }\n return result\n },\n /**\n * All calls to the wrapped function will be batched.\n */\n batchCalls: <T extends Array<unknown>>(\n callback: BatchCallsCallback<T>,\n ): BatchCallsCallback<T> => {\n return (...args) => {\n schedule(() => {\n callback(...args)\n })\n }\n },\n schedule,\n /**\n * Use this method to set a custom notify function.\n * This can be used to for example wrap notifications with `React.act` while running tests.\n */\n setNotifyFunction: (fn: NotifyFunction) => {\n notifyFn = fn\n },\n /**\n * Use this method to set a custom function to batch notifications together into a single tick.\n * By default React Query will use the batch function provided by ReactDOM or React Native.\n */\n setBatchNotifyFunction: (fn: BatchNotifyFunction) => {\n batchNotifyFn = fn\n },\n setScheduler: (fn: ScheduleFunction) => {\n scheduleFn = fn\n },\n } as const\n}\n\n// SINGLETON\nexport const notifyManager = createNotifyManager()\n","import {\n hashKey,\n matchQuery,\n notifyManager,\n partialMatchKey,\n} from '@tanstack/query-core'\nimport type {\n Query,\n QueryClient,\n QueryFilters,\n QueryFunctionContext,\n QueryKey,\n QueryState,\n} from '@tanstack/query-core'\n\nexport interface PersistedQuery {\n buster: string\n queryHash: string\n queryKey: QueryKey\n state: QueryState\n}\n\nexport type MaybePromise<T> = T | Promise<T>\n\nexport interface AsyncStorage<TStorageValue = string> {\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n removeItem: (key: string) => MaybePromise<void>\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /** The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage<TStorageValue> | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>\n /**\n * A unique string that can be used to forcefully invalidate existing caches,\n * if they do not share the same buster string\n */\n buster?: string\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n * @default 24 hours\n */\n maxAge?: number\n /**\n * Prefix to be used for storage key.\n * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.\n * @default 'tanstack-query'\n */\n prefix?: string\n /**\n * If set to `true`, the query will refetch on successful query restoration if the data is stale.\n * If set to `false`, the query will not refetch on successful query restoration.\n * If set to `'always'`, the query will always refetch on successful query restoration.\n * Defaults to `true`.\n */\n refetchOnRestore?: boolean | 'always'\n /**\n * Filters to narrow down which Queries should be persisted.\n */\n filters?: QueryFilters\n}\n\nexport const PERSISTER_KEY_PREFIX = 'tanstack-query'\n\n/**\n * Warning: experimental feature.\n * This utility function enables fine-grained query persistence.\n * Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.\n *\n * ```\n * useQuery({\n queryKey: ['myKey'],\n queryFn: fetcher,\n persister: createPersister({\n storage: localStorage,\n }),\n })\n ```\n */\nexport function experimental_createQueryPersister<TStorageValue = string>({\n storage,\n buster = '',\n maxAge = 1000 * 60 * 60 * 24,\n serialize = JSON.stringify as Required<\n StoragePersisterOptions<TStorageValue>\n >['serialize'],\n deserialize = JSON.parse as Required<\n StoragePersisterOptions<TStorageValue>\n >['deserialize'],\n prefix = PERSISTER_KEY_PREFIX,\n refetchOnRestore = true,\n filters,\n}: StoragePersisterOptions<TStorageValue>) {\n function isExpiredOrBusted(persistedQuery: PersistedQuery) {\n if (persistedQuery.state.dataUpdatedAt) {\n const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt\n const expired = queryAge > maxAge\n const busted = persistedQuery.buster !== buster\n\n if (expired || busted) {\n return true\n }\n\n return false\n }\n\n return true\n }\n\n async function retrieveQuery<T>(\n queryHash: string,\n afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,\n ) {\n if (storage != null) {\n const storageKey = `${prefix}-${queryHash}`\n try {\n const storedData = await storage.getItem(storageKey)\n if (storedData) {\n const persistedQuery = await deserialize(storedData)\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(storageKey)\n } else {\n if (afterRestoreMacroTask) {\n // Just after restoring we want to get fresh data from the server if it's stale\n notifyManager.schedule(() =>\n afterRestoreMacroTask(persistedQuery),\n )\n }\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return persistedQuery.state.data as T\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV === 'development') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore query cache from persisted location.',\n )\n }\n await storage.removeItem(storageKey)\n }\n }\n\n return\n }\n\n async function persistQueryByKey(\n queryKey: QueryKey,\n queryClient: QueryClient,\n ) {\n if (storage != null) {\n const query = queryClient.getQueryCache().find({ queryKey })\n if (query) {\n await persistQuery(query)\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Could not find query to be persisted. QueryKey:',\n JSON.stringify(queryKey),\n )\n }\n }\n }\n }\n\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n storage.setItem(\n storageKey,\n await serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }\n }\n\n async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n ctx: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const matchesFilter = filters ? matchQuery(filters, query) : true\n\n // Try to restore only if we do not have any data in the cache and we have persister defined\n if (matchesFilter && query.state.data === undefined && storage != null) {\n const restoredData = await retrieveQuery(\n query.queryHash,\n (persistedQuery: PersistedQuery) => {\n // Set proper updatedAt, since resolving in the first pass overrides those values\n query.setState({\n dataUpdatedAt: persistedQuery.state.dataUpdatedAt,\n errorUpdatedAt: persistedQuery.state.errorUpdatedAt,\n })\n\n if (\n refetchOnRestore === 'always' ||\n (refetchOnRestore === true && query.isStale())\n ) {\n query.fetch()\n }\n },\n )\n\n if (restoredData !== undefined) {\n return Promise.resolve(restoredData as T)\n }\n }\n\n // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(ctx)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n notifyManager.schedule(() => {\n persistQuery(query)\n })\n }\n\n return Promise.resolve(queryFnResult)\n }\n\n async function persisterGc() {\n if (storage?.entries) {\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(prefix)) {\n const persistedQuery = await deserialize(value)\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n }\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n async function restoreQueries(\n queryClient: QueryClient,\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(prefix)) {\n const persistedQuery = await deserialize(value)\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n continue\n }\n\n if (queryKey) {\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n }\n\n queryClient.setQueryData(\n persistedQuery.queryKey,\n persistedQuery.state.data,\n {\n updatedAt: persistedQuery.state.dataUpdatedAt,\n },\n )\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n return {\n persisterFn,\n persistQuery,\n persistQueryByKey,\n retrieveQuery,\n persisterGc,\n restoreQueries,\n }\n}\n","import {\n type AsyncStorage,\n experimental_createQueryPersister,\n type PersistedQuery,\n} from \"@tanstack/react-query-persist-client\";\n\nconst DB_NAME = \"fluid_tanstack_query_cache\";\nconst STORE_NAME = \"fluid_queries\";\nconst VERSION = 1;\n\nlet dbPromise: Promise<IDBDatabase> | null = null;\n\n// Exported for testing - allows resetting internal state between tests\nexport function _resetForTesting(): void {\n dbPromise = null;\n}\n\nexport async function deleteDatabase(): Promise<void> {\n return new Promise((resolve, reject) => {\n console.warn(\"[IDB] Deleting database due to error\");\n const req = indexedDB.deleteDatabase(DB_NAME);\n req.onsuccess = () => {\n console.log(\"[IDB] Database deleted successfully\");\n resolve();\n };\n req.onerror = () => {\n console.error(\"[IDB] Failed to delete database:\", req.error);\n reject(req.error ?? new Error(\"deleteDatabase failed\"));\n };\n req.onblocked = () => {\n console.warn(\"[IDB] Delete blocked: close all tabs using this database\");\n };\n });\n}\n\nfunction openDatabase(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const req = indexedDB.open(DB_NAME, VERSION);\n\n req.onupgradeneeded = () => {\n const upgradeDb = req.result;\n if (!upgradeDb.objectStoreNames.contains(STORE_NAME)) {\n upgradeDb.createObjectStore(STORE_NAME);\n }\n };\n\n req.onsuccess = () => {\n const conn = req.result;\n conn.onversionchange = () => {\n console.trace(\"[IDB] version change – closing connection\");\n conn.close();\n // clear the cached promise so the next getDb call re-opens a connection\n dbPromise = null;\n };\n resolve(conn);\n };\n\n req.onblocked = () => {\n console.warn(\"[IDB] open blocked: another connection is holding the DB\");\n };\n\n req.onerror = () => {\n reject(\n req.error instanceof Error\n ? req.error\n : new Error(`IndexedDB open failed: ${String(req.error)}`),\n );\n };\n });\n}\n\nasync function getDbWithRecovery(): Promise<IDBDatabase> {\n try {\n return await openDatabase();\n } catch (err) {\n // First open failed - try to delete and recreate\n console.warn(\"[IDB] Initial open failed, attempting recovery:\", err);\n try {\n await deleteDatabase();\n console.log(\"[IDB] Retrying database open after deletion\");\n return await openDatabase();\n } catch (retryErr) {\n console.error(\"[IDB] Recovery failed:\", retryErr);\n throw retryErr;\n }\n }\n}\n\nfunction getDb(): Promise<IDBDatabase> {\n if (dbPromise) return dbPromise;\n\n // Create the promise and cache it immediately to prevent race conditions\n // All concurrent calls will share this same promise\n dbPromise = getDbWithRecovery().catch((err) => {\n // On failure, clear the cache so next call can retry fresh\n dbPromise = null;\n throw err;\n });\n\n return dbPromise;\n}\n\n// Exported for testing - allows direct testing of storage operations\nexport const storage: AsyncStorage<PersistedQuery> = {\n async getItem(key: string) {\n try {\n const db = await getDb();\n return new Promise<PersistedQuery | undefined>((res) => {\n try {\n const r = db\n .transaction(STORE_NAME, \"readonly\")\n .objectStore(STORE_NAME)\n .get(key);\n r.onsuccess = () => res(r.result as PersistedQuery);\n r.onerror = () => {\n console.trace(\"[IDB] getItem error:\", r.error);\n res(undefined);\n };\n } catch (txErr) {\n // Transaction creation failed (e.g., stale connection)\n console.trace(\"[IDB] getItem transaction error:\", txErr);\n res(undefined);\n }\n });\n } catch (err) {\n // getDb() failed - try to recover with a fresh connection\n console.trace(\"[IDB] getItem getDb error:\", err);\n try {\n const db = await getDb();\n // Use fresh connection directly - getDb() already handles recovery\n return new Promise<PersistedQuery | undefined>((res) => {\n try {\n const r = db\n .transaction(STORE_NAME, \"readonly\")\n .objectStore(STORE_NAME)\n .get(key);\n r.onsuccess = () => res(r.result as PersistedQuery);\n r.onerror = () => {\n console.trace(\"[IDB] getItem retry error:\", r.error);\n res(undefined);\n };\n } catch (txErr) {\n console.trace(\"[IDB] getItem retry transaction error:\", txErr);\n res(undefined);\n }\n });\n } catch (recoveryErr) {\n console.trace(\"[IDB] getItem recovery failed:\", recoveryErr);\n }\n return undefined;\n }\n },\n\n async setItem(key: string, value: PersistedQuery) {\n // JSON round-trip strips non-cloneable properties (functions, class instances)\n // before IndexedDB's structured clone algorithm runs. Without this, IDB\n // throws DataCloneError. Theme Color objects are now kept out of the cache\n // via the select pattern, but other queries may still have non-cloneable data.\n const cloneableValue = JSON.parse(JSON.stringify(value));\n try {\n const db = await getDb();\n if (!db) return;\n await new Promise<void>((resolve) => {\n try {\n const req = db\n .transaction(STORE_NAME, \"readwrite\")\n .objectStore(STORE_NAME)\n .put(cloneableValue, key);\n req.onsuccess = () => resolve();\n req.onerror = () => {\n console.trace(\"[IDB] setItem error:\", req.error);\n resolve();\n };\n } catch (txErr) {\n console.trace(\"[IDB] setItem transaction error:\", txErr);\n resolve();\n }\n });\n } catch (err) {\n // getDb() failed - try to recover with a fresh connection\n console.trace(\"[IDB] setItem getDb error:\", err);\n try {\n const db = await getDb();\n // Use fresh connection directly - getDb() already handles recovery\n await new Promise<void>((resolve) => {\n try {\n const req = db\n .transaction(STORE_NAME, \"readwrite\")\n .objectStore(STORE_NAME)\n .put(cloneableValue, key);\n req.onsuccess = () => resolve();\n req.onerror = () => {\n console.trace(\"[IDB] setItem retry error:\", req.error);\n resolve();\n };\n } catch (txErr) {\n console.trace(\"[IDB] setItem retry transaction error:\", txErr);\n resolve();\n }\n });\n } catch (recoveryErr) {\n console.trace(\"[IDB] setItem recovery failed:\", recoveryErr);\n }\n }\n },\n\n async removeItem(key: string) {\n try {\n const db = await getDb();\n if (!db) return;\n await new Promise<void>((resolve) => {\n try {\n const req = db\n .transaction(STORE_NAME, \"readwrite\")\n .objectStore(STORE_NAME)\n .delete(key);\n req.onsuccess = () => resolve();\n req.onerror = () => {\n console.trace(\"[IDB] removeItem error:\", req.error);\n resolve();\n };\n } catch (txErr) {\n console.trace(\"[IDB] removeItem transaction error:\", txErr);\n resolve();\n }\n });\n } catch (err) {\n // getDb() failed - try to recover with a fresh connection\n console.trace(\"[IDB] removeItem getDb error:\", err);\n try {\n const db = await getDb();\n // Use fresh connection directly - getDb() already handles recovery\n await new Promise<void>((resolve) => {\n try {\n const req = db\n .transaction(STORE_NAME, \"readwrite\")\n .objectStore(STORE_NAME)\n .delete(key);\n req.onsuccess = () => resolve();\n req.onerror = () => {\n console.trace(\"[IDB] removeItem retry error:\", req.error);\n resolve();\n };\n } catch (txErr) {\n console.trace(\"[IDB] removeItem retry transaction error:\", txErr);\n resolve();\n }\n });\n } catch (recoveryErr) {\n console.trace(\"[IDB] removeItem recovery failed:\", recoveryErr);\n }\n }\n },\n};\n\n// Factory function to create persister - only call this client-side\nexport function createPersister(): ReturnType<\n typeof experimental_createQueryPersister\n> {\n return experimental_createQueryPersister<PersistedQuery>({\n storage,\n serialize: (persistedQuery) => persistedQuery,\n deserialize: (cached) => cached,\n });\n}\n","import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { createPersister } from \"@fluid-app/query-persister\";\nimport { useFluidApi } from \"./use-fluid-api\";\nimport { transformManifestToRepAppData } from \"../transforms\";\nimport type { RawManifestResponse } from \"../transforms\";\nimport type { RepAppData } from \"@fluid-app/rep-core/types\";\n\n/**\n * Query key for full app data (fluidos endpoint)\n */\nexport const APP_DATA_QUERY_KEY = [\"fluid\", \"app\"] as const;\n\n/**\n * Module-level persister instance (browser only).\n * Created once when the module loads so all calls to useFluidApp share\n * the same IndexedDB connection. Applied at the query level so it works\n * regardless of which QueryClient the app provides.\n */\nconst appDataPersister =\n typeof window !== \"undefined\" ? createPersister() : undefined;\n\n/**\n * Hook to fetch the full rep app data from the fluidos API.\n *\n * Returns a `RepAppData` object containing:\n * - `screens` — all screen definitions with normalized component trees\n * - `profile.themes` — fully-transformed ThemeDefinition[] (handles legacy + new formats)\n * - `profile.activeThemeId` — the currently active theme ID\n * - `profile.navigation.navigation_items` — sorted, recursive navigation tree\n *\n * Uses IndexedDB persistence so subsequent page loads hydrate instantly\n * from cache while revalidating in the background. The raw API response\n * (plain JSON) is cached; Color objects are recreated from cache via\n * `select` on every restore — this is fast (CPU only, no network).\n *\n * @example\n * ```tsx\n * function App() {\n * const { data: appData, isLoading } = useFluidApp();\n *\n * if (isLoading) return <Spinner />;\n *\n * return (\n * <AppShell\n * appData={appData}\n * navigation={appData.profile.navigation.navigation_items}\n * />\n * );\n * }\n * ```\n */\nexport function useFluidApp(options?: {\n enabled?: boolean;\n}): UseQueryResult<RepAppData> {\n const api = useFluidApi();\n\n return useQuery<\n RawManifestResponse,\n Error,\n RepAppData,\n typeof APP_DATA_QUERY_KEY\n >({\n queryKey: APP_DATA_QUERY_KEY,\n queryFn: () => api.app.getRaw(),\n select: transformManifestToRepAppData,\n ...(appDataPersister && { persister: appDataPersister.persisterFn }),\n ...(options?.enabled !== undefined && { enabled: options.enabled }),\n });\n}\n","import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { useMemo } from \"react\";\nimport { useFluidApi } from \"./use-fluid-api\";\nimport type { UserPermissions, PermissionAction } from \"../types/permissions\";\n\n/**\n * Query key for permissions data\n */\nexport const PERMISSIONS_QUERY_KEY = [\"fluid\", \"permissions\"] as const;\n\n/**\n * Result of useFluidPermissions hook\n */\nexport interface UseFluidPermissionsResult {\n /** Raw permissions query result */\n query: UseQueryResult<UserPermissions>;\n /** Permissions data (alias for query.data) */\n permissions: UserPermissions | undefined;\n /** Check if user has a specific permission */\n can: (resource: string, action?: PermissionAction) => boolean;\n /** Check if user is a super admin */\n isSuperAdmin: boolean;\n}\n\n/**\n * Hook to fetch and check user permissions\n *\n * @example\n * ```tsx\n * function TeamSettings() {\n * const { can, isSuperAdmin } = useFluidPermissions();\n *\n * if (!can(\"team\", \"manage\")) {\n * return <AccessDenied />;\n * }\n *\n * return <TeamSettingsForm canDelete={can(\"team\", \"delete\")} />;\n * }\n * ```\n */\nexport function useFluidPermissions(): UseFluidPermissionsResult {\n const api = useFluidApi();\n\n const query = useQuery({\n queryKey: PERMISSIONS_QUERY_KEY,\n queryFn: () => api.permissions.get(),\n });\n\n const permissions = query.data;\n\n // Memoize the can function to maintain referential stability\n const can = useMemo(() => {\n return (resource: string, action: PermissionAction = \"view\"): boolean => {\n if (!permissions) {\n return false;\n }\n\n // Super admins have all permissions\n if (permissions.is_super_admin) {\n return true;\n }\n\n const resourcePermissions = permissions.permissions[resource];\n if (!resourcePermissions) {\n return false;\n }\n\n return resourcePermissions[action] ?? false;\n };\n }, [permissions]);\n\n const isSuperAdmin = permissions?.is_super_admin ?? false;\n\n return {\n query,\n permissions,\n can,\n isSuperAdmin,\n };\n}\n","import { useThemeContext } from \"../providers/FluidThemeProvider\";\nimport type { ThemeDefinition } from \"../types/theme\";\n\n/**\n * Result of useFluidTheme hook\n */\nexport interface UseFluidThemeResult {\n /** Currently active theme */\n currentTheme: ThemeDefinition | null;\n /** Switch to a different theme */\n setTheme: (theme: ThemeDefinition) => void;\n /** Switch between light and dark mode */\n setThemeMode: (mode: \"light\" | \"dark\") => void;\n /** Current theme mode (convenience accessor) */\n mode: \"light\" | \"dark\" | undefined;\n}\n\n/**\n * Hook to access and control theme settings\n *\n * @example\n * ```tsx\n * function ThemeSwitcher({ themes }: { themes: ThemeDefinition[] }) {\n * const { currentTheme, setTheme, setThemeMode, mode } = useFluidTheme();\n *\n * return (\n * <div>\n * <select\n * value={currentTheme?.name}\n * onChange={(e) => {\n * const theme = themes.find(t => t.name === e.target.value);\n * if (theme) setTheme(theme);\n * }}\n * >\n * {themes.map(theme => (\n * <option key={theme.name} value={theme.name}>\n * {theme.name}\n * </option>\n * ))}\n * </select>\n *\n * <button onClick={() => setThemeMode(mode === \"dark\" ? \"light\" : \"dark\")}>\n * Toggle {mode === \"dark\" ? \"Light\" : \"Dark\"} Mode\n * </button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useFluidTheme(): UseFluidThemeResult {\n const { currentTheme, setTheme, setThemeMode, mode } = useThemeContext();\n\n return {\n currentTheme,\n setTheme,\n setThemeMode,\n mode,\n };\n}\n","import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { useFluidApi } from \"./use-fluid-api\";\nimport type { Rep } from \"../types/rep\";\n\n/**\n * Query key for current rep data\n */\nexport const CURRENT_REP_QUERY_KEY = [\"fluid\", \"currentRep\"] as const;\n\n/**\n * Hook to fetch the currently authenticated rep's profile\n *\n * @example\n * ```tsx\n * function RepHeader() {\n * const { data: rep, isLoading } = useCurrentRep();\n *\n * if (isLoading) return <Skeleton />;\n *\n * return (\n * <div>\n * <Avatar src={rep?.avatar_url} />\n * <span>{rep?.first_name} {rep?.last_name}</span>\n * </div>\n * );\n * }\n * ```\n */\nexport function useCurrentRep(): UseQueryResult<Rep> {\n const api = useFluidApi();\n\n return useQuery({\n queryKey: CURRENT_REP_QUERY_KEY,\n queryFn: () => api.reps.current(),\n });\n}\n","/**\n * useFluidAuth Hook\n *\n * Provides access to authentication state and utilities.\n * This is the primary hook for interacting with auth in components.\n */\n\nimport { useFluidAuthContext } from \"../providers/FluidAuthProvider\";\nimport type { FluidAuthContextValue } from \"../auth/types\";\n\n/**\n * Hook to access authentication state and utilities.\n *\n * Must be used within a `FluidAuthProvider`.\n *\n * @returns Authentication context with user info, loading state, and utilities\n * @throws Error if used outside FluidAuthProvider\n *\n * @example\n * ```tsx\n * function UserProfile() {\n * const { isAuthenticated, isLoading, user, clearAuth } = useFluidAuth();\n *\n * if (isLoading) {\n * return <Spinner />;\n * }\n *\n * if (!isAuthenticated) {\n * return <p>Please log in</p>;\n * }\n *\n * return (\n * <div>\n * <p>Welcome, {user.full_name}!</p>\n * <button onClick={clearAuth}>Log out</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useFluidAuth(): FluidAuthContextValue {\n return useFluidAuthContext();\n}\n","import type { CalendarEvent } from \"../hook-types\";\n\nconst now = new Date();\n\nfunction daysFromNow(days: number, hour: number, minute: number = 0): Date {\n const d = new Date(now);\n d.setDate(d.getDate() + days);\n d.setHours(hour, minute, 0, 0);\n return d;\n}\n\nexport const DEMO_CALENDAR_EVENTS: readonly CalendarEvent[] = [\n {\n id: 1,\n title: \"Team Standup\",\n description: { body: \"Daily sync with the sales team\" },\n color: \"#4f46e5\",\n start: daysFromNow(0, 9, 0).toISOString(),\n end: daysFromNow(0, 9, 30).toISOString(),\n active: true,\n status: \"confirmed\",\n },\n {\n id: 2,\n title: \"Client Review - Acme Corp\",\n description: { body: \"Quarterly business review with key accounts\" },\n color: \"#059669\",\n start: daysFromNow(2, 14, 0).toISOString(),\n end: daysFromNow(2, 15, 0).toISOString(),\n active: true,\n status: \"confirmed\",\n venue: \"Conference Room B\",\n },\n {\n id: 3,\n title: \"Product Training Webinar\",\n description: { body: \"New product line training for the field\" },\n color: \"#d97706\",\n start: daysFromNow(4, 11, 0).toISOString(),\n end: daysFromNow(4, 12, 30).toISOString(),\n active: true,\n status: \"confirmed\",\n url: \"https://example.com/webinar\",\n },\n {\n id: 4,\n title: \"Regional Conference\",\n description: { body: \"Annual West Coast regional conference\" },\n color: \"#dc2626\",\n start: daysFromNow(10, 8, 0).toISOString(),\n end: daysFromNow(12, 17, 0).toISOString(),\n active: true,\n status: \"confirmed\",\n venue: \"San Diego Convention Center\",\n isAllDay: true,\n },\n];\n","/**\n * Calendar events hook - stub implementation for SDK\n * In production, implement this hook to fetch from your API\n */\n\nimport type { QueryResult } from \"./hook-types\";\nimport type { CalendarEvent, CalendarEventDescription } from \"./hook-types\";\nimport { DEMO_CALENDAR_EVENTS } from \"./demo-data/calendar-events\";\n\n// Re-export types so external consumers are unaffected\nexport type { CalendarEvent, CalendarEventDescription };\n\n/**\n * Result type for useCalendarEvents hook.\n * Uses QueryResult<CalendarEvent[]> with default Error type.\n */\nexport type UseCalendarEventsResult = QueryResult<CalendarEvent[]>;\n\n/**\n * Hook to fetch calendar events.\n * This is a stub implementation - override with your own data fetching logic.\n */\nexport function useCalendarEvents(): UseCalendarEventsResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching\n return {\n data: [...DEMO_CALENDAR_EVENTS],\n isLoading: false,\n isError: false,\n };\n}\n","import type { Todo } from \"../hook-types\";\n\nconst now = new Date();\n\nfunction daysFromNow(days: number): string {\n const d = new Date(now);\n d.setDate(d.getDate() + days);\n return d.toISOString();\n}\n\nexport const DEMO_TODOS: readonly Todo[] = [\n {\n id: 1,\n body: \"Follow up with Sarah about Q2 order\",\n dueAt: daysFromNow(1),\n completedAt: null,\n createdAt: daysFromNow(-2),\n contactName: \"Sarah Johnson\",\n },\n {\n id: 2,\n body: \"Send pricing proposal to Acme Corp\",\n dueAt: daysFromNow(7),\n completedAt: null,\n createdAt: daysFromNow(-1),\n contactName: \"Mike Chen\",\n },\n {\n id: 3,\n body: \"Schedule onboarding call with new team member\",\n dueAt: daysFromNow(3),\n completedAt: null,\n createdAt: daysFromNow(0),\n contactName: \"Emily Rodriguez\",\n },\n {\n id: 4,\n body: \"Review and approve Q1 expense report\",\n dueAt: daysFromNow(-1),\n completedAt: daysFromNow(-1),\n createdAt: daysFromNow(-5),\n contactName: null,\n },\n {\n id: 5,\n body: \"Prepare presentation for Friday team meeting\",\n dueAt: daysFromNow(4),\n completedAt: daysFromNow(0),\n createdAt: daysFromNow(-3),\n contactName: null,\n },\n];\n","/**\n * Todos hook - stub implementation for SDK\n * In production, implement this hook to fetch from your API\n */\n\nimport type { QueryResult } from \"./hook-types\";\nimport type { Todo } from \"./hook-types\";\nimport { DEMO_TODOS } from \"./demo-data/todos\";\n\n// Re-export type so external consumers are unaffected\nexport type { Todo };\n\n/**\n * Result type for useTodos hook.\n * Uses QueryResult<Todo[]> with default Error type.\n */\nexport type UseTodosResult = QueryResult<Todo[]>;\n\n/**\n * Hook to fetch todo items.\n * This is a stub implementation - override with your own data fetching logic.\n */\nexport function useTodos(): UseTodosResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching\n return {\n data: [...DEMO_TODOS],\n isLoading: false,\n isError: false,\n };\n}\n","/**\n * Hook type utilities and type predicates.\n *\n * This module provides:\n * - Generic hook result types with default type parameters\n * - Type predicates for query state narrowing\n * - Reusable patterns for type-safe property access in hooks\n *\n * Following generics best practices:\n * - generics-default-type-parameters: Default E to Error for common case\n * - generics-type-predicates: Type predicates for result state narrowing\n * - generics-constrain-type-parameters: K extends keyof T for property access\n */\n\n// =============================================================================\n// Base Result Types with Default Type Parameters\n// =============================================================================\n\n/**\n * Base result type for query hooks with default error type.\n * Uses default type parameter for E (generics-default-type-parameters rule).\n *\n * @typeParam T - The data type\n * @typeParam E - The error type (defaults to Error)\n *\n * @example\n * // Error type defaults to Error\n * type UsersResult = QueryResult<User[]>;\n *\n * // Can override when needed\n * type CustomResult = QueryResult<User[], ApiError>;\n */\nexport interface QueryResult<T, E = Error> {\n readonly data: T;\n readonly isLoading: boolean;\n readonly isError: boolean;\n readonly error?: E | undefined;\n}\n\n/**\n * Result type for hooks that may not have data yet.\n * Extends QueryResult with nullable data.\n *\n * @typeParam T - The data type\n * @typeParam E - The error type (defaults to Error)\n */\nexport interface QueryResultNullable<T, E = Error> {\n readonly data: T | null | undefined;\n readonly isLoading: boolean;\n readonly isError: boolean;\n readonly error?: E | undefined;\n}\n\n/**\n * Result type for list/collection hooks with aggregates.\n *\n * @typeParam T - The item type in the array\n * @typeParam E - The error type (defaults to Error)\n */\nexport interface ListQueryResult<T, E = Error> extends QueryResult<T[], E> {\n readonly totalCount: number;\n}\n\n/**\n * Result type for list hooks with value aggregation (e.g., deals with total value).\n *\n * @typeParam T - The item type in the array\n * @typeParam E - The error type (defaults to Error)\n */\nexport interface ValueListQueryResult<T, E = Error>\n extends ListQueryResult<T, E> {\n readonly totalValue: number;\n}\n\n// =============================================================================\n// Type Predicates for Query State Narrowing\n// =============================================================================\n\n/**\n * Type predicate to check if a query result has successfully loaded data.\n * Narrows the data type from T | null | undefined to T.\n *\n * @example\n * const result = useContact(id);\n * if (hasData(result)) {\n * // TypeScript knows result.data is Contact, not Contact | null\n * console.log(result.data.name);\n * }\n */\nexport function hasData<T, E = Error>(\n result: QueryResultNullable<T, E>,\n): result is QueryResultNullable<T, E> & { readonly data: T } {\n return result.data != null && !result.isLoading && !result.isError;\n}\n\n/**\n * Type predicate to check if a query result is in loading state.\n * Useful for conditional rendering.\n *\n * @example\n * if (isLoading(result)) {\n * return <Spinner />;\n * }\n */\nexport function isLoading<T, E = Error>(\n result: QueryResult<T, E> | QueryResultNullable<T, E>,\n): boolean {\n return result.isLoading;\n}\n\n/**\n * Type predicate to check if a query result has an error.\n * Narrows to include the error property.\n *\n * @example\n * if (isErrorResult(result)) {\n * console.error(result.error); // error is E, not undefined\n * }\n */\nexport function isErrorResult<T, E = Error>(\n result: QueryResult<T, E> | QueryResultNullable<T, E>,\n): result is (QueryResult<T, E> | QueryResultNullable<T, E>) & {\n readonly isError: true;\n readonly error: E;\n} {\n return result.isError && result.error !== undefined;\n}\n\n/**\n * Type predicate to check if a query result is in idle state (not loading, no error, has data).\n *\n * @example\n * if (isIdle(result)) {\n * // Safe to access and render data\n * }\n */\nexport function isIdle<T, E = Error>(\n result: QueryResult<T, E> | QueryResultNullable<T, E>,\n): boolean {\n return !result.isLoading && !result.isError;\n}\n\n// =============================================================================\n// Generic Property Selector Pattern\n// =============================================================================\n\n/**\n * Type-safe property selector for hook results.\n * Uses K extends keyof T constraint (generics-function-constraints rule).\n *\n * @typeParam T - The data object type\n * @typeParam K - Key of T (constrained to actual keys)\n *\n * @example\n * const users = [{ name: \"Alice\", age: 30 }];\n * const names = selectProperty(users, \"name\"); // string[]\n * const ages = selectProperty(users, \"age\"); // number[]\n * selectProperty(users, \"invalid\"); // Error: \"invalid\" not in \"name\" | \"age\"\n */\nexport function selectProperty<T, K extends keyof T>(\n items: readonly T[],\n key: K,\n): T[K][] {\n return items.map((item) => item[key]);\n}\n\n/**\n * Type-safe property getter for a single item.\n * Returns undefined if item is null/undefined.\n *\n * @typeParam T - The data object type\n * @typeParam K - Key of T (constrained to actual keys)\n */\nexport function getProperty<T, K extends keyof T>(\n item: T | null | undefined,\n key: K,\n): T[K] | undefined {\n return item?.[key];\n}\n\n// =============================================================================\n// Hook Factory Types\n// =============================================================================\n\n/**\n * Generic type for hooks that fetch a single resource by ID.\n * Useful for creating consistent API across different resource types.\n *\n * @typeParam T - The resource type\n * @typeParam E - The error type (defaults to Error)\n */\nexport type UseSingleResourceHook<T, E = Error> = (\n id: string,\n) => QueryResultNullable<T, E>;\n\n/**\n * Generic type for hooks that fetch a list of resources with optional params.\n * Uses generics-default-type-parameters for the params type.\n *\n * @typeParam T - The item type\n * @typeParam P - The params type (defaults to empty object)\n * @typeParam E - The error type (defaults to Error)\n */\nexport type UseListResourceHook<\n T,\n P extends Record<string, unknown> = Record<string, never>,\n E = Error,\n> = (params?: P) => ListQueryResult<T, E>;\n\n/**\n * Transforms a nullable result to a non-nullable one if data exists.\n * Useful when you've already checked hasData().\n */\nexport type WithData<R extends QueryResultNullable<unknown>> =\n R extends QueryResultNullable<infer T, infer E>\n ? QueryResultNullable<T, E> & { readonly data: T }\n : never;\n\n// =============================================================================\n// Domain Types\n// Shared between hook files and demo-data files to avoid circular imports.\n// =============================================================================\n\n/**\n * Activity slug constants as a const object.\n * Derive the ActivitySlug type from this single source of truth.\n */\nexport const ACTIVITY_SLUGS = {\n abandonedCart: \"abandoned_cart\",\n announcements: \"announcements\",\n cartItemsAdded: \"cart_items_added\",\n commentReply: \"comment_reply\",\n directMessage: \"direct_message\",\n fantasyPoint: \"fantasy_point\",\n newLead: \"new_lead\",\n orderPlaced: \"order_placed\",\n pageViews: \"page_views\",\n pageViewsContact: \"page_views_contact\",\n tasks: \"tasks\",\n upcomingEvent: \"upcoming_event\",\n video: \"video\",\n videoComplete: \"video_complete\",\n videoCompleteContact: \"video_complete_contact\",\n videoContact: \"video_contact\",\n messageReceived: \"message_received\",\n messageSent: \"message_sent\",\n newCartItemsAdded: \"new_cart_items_added\",\n smartLinkClicked: \"smart_link_clicked\",\n reviewLeft: \"review_left\",\n} as const;\n\n/** Activity slug union type derived from ACTIVITY_SLUGS constant. */\nexport type ActivitySlug = (typeof ACTIVITY_SLUGS)[keyof typeof ACTIVITY_SLUGS];\n\n/** Type predicate to check if a string is a valid ActivitySlug. */\nexport function isActivitySlug(value: string): value is ActivitySlug {\n return Object.values(ACTIVITY_SLUGS).includes(value as ActivitySlug);\n}\n\n/** Transformed activity for display. */\nexport interface Activity {\n readonly id: number;\n readonly userName: string;\n readonly avatarUrl: string | null;\n readonly activityType: string;\n readonly targetName: string;\n readonly timestamp: string;\n readonly slug: ActivitySlug;\n}\n\n/** Description/rich text metadata for a calendar event. */\nexport interface CalendarEventDescription {\n readonly id?: number | null;\n readonly name?: string | null;\n readonly body?: string | null;\n readonly record_type?: string | null;\n readonly record_id?: number | null;\n readonly created_at?: string | null;\n readonly updated_at?: string | null;\n readonly locale?: string | null;\n}\n\n/** Calendar event data from the API. */\nexport interface CalendarEvent {\n readonly id: number;\n readonly title: string;\n readonly description?: CalendarEventDescription | null;\n readonly color?: string | null;\n readonly url?: string | null;\n readonly start: string;\n readonly end: string;\n readonly active?: boolean | null;\n readonly time_zone?: string | null;\n readonly status?: string | null;\n readonly image_url?: string | null;\n readonly images?: readonly unknown[] | null;\n readonly venue?: string | null;\n readonly countries?: readonly string[] | null;\n readonly hasTomorrow?: boolean | null;\n readonly hasYesterday?: boolean | null;\n readonly isAllDay?: boolean;\n}\n\n/** Catch up suggestion data from the API. */\nexport interface CatchUp {\n readonly id: number;\n readonly suggestion_title: string;\n}\n\n/** MySite data returned by the hook. */\nexport interface MySiteData {\n readonly url: string | null;\n readonly views: number;\n readonly leads: number;\n readonly userName: string;\n}\n\n/** Transformed todo for display. */\nexport interface Todo {\n readonly id: number;\n readonly body: string;\n readonly dueAt: string | null;\n readonly completedAt: string | null;\n readonly createdAt: string;\n readonly contactName: string | null;\n}\n","import type { Activity } from \"../hook-types\";\n\nconst now = new Date();\n\nfunction hoursAgo(hours: number): string {\n const d = new Date(now);\n d.setHours(d.getHours() - hours);\n return d.toISOString();\n}\nexport const DEMO_ACTIVITIES: readonly Activity[] = [\n {\n id: 1,\n userName: \"Sarah Johnson\",\n avatarUrl: null,\n activityType: \"New Order\",\n targetName: \"Wellness Starter Kit\",\n timestamp: hoursAgo(1),\n slug: \"order_placed\",\n },\n {\n id: 2,\n userName: \"Mike Chen\",\n avatarUrl: null,\n activityType: \"New Lead\",\n targetName: \"Referral from LinkedIn campaign\",\n timestamp: hoursAgo(3),\n slug: \"new_lead\",\n },\n {\n id: 3,\n userName: \"Emily Rodriguez\",\n avatarUrl: null,\n activityType: \"Page View\",\n targetName: \"Product Catalog\",\n timestamp: hoursAgo(5),\n slug: \"page_views\",\n },\n {\n id: 4,\n userName: \"David Park\",\n avatarUrl: null,\n activityType: \"Cart Items Added\",\n targetName: \"Premium Bundle (3 items)\",\n timestamp: hoursAgo(8),\n slug: \"cart_items_added\",\n },\n {\n id: 5,\n userName: \"Lisa Thompson\",\n avatarUrl: null,\n activityType: \"Video Watched\",\n targetName: \"Getting Started Tutorial\",\n timestamp: hoursAgo(12),\n slug: \"video_complete\",\n },\n {\n id: 6,\n userName: \"James Wilson\",\n avatarUrl: null,\n activityType: \"Message Received\",\n targetName: \"Question about shipping\",\n timestamp: hoursAgo(18),\n slug: \"message_received\",\n },\n {\n id: 7,\n userName: \"Rachel Kim\",\n avatarUrl: null,\n activityType: \"Smart Link Clicked\",\n targetName: \"Holiday Promo Link\",\n timestamp: hoursAgo(24),\n slug: \"smart_link_clicked\",\n },\n {\n id: 8,\n userName: \"Tom Martinez\",\n avatarUrl: null,\n activityType: \"Review Left\",\n targetName: \"Essential Oil Set - 5 stars\",\n timestamp: hoursAgo(36),\n slug: \"review_left\",\n },\n];\n","/**\n * Activities hook - stub implementation for SDK\n * In production, implement this hook to fetch from your API\n */\n\nimport type { QueryResult } from \"./hook-types\";\nimport {\n ACTIVITY_SLUGS,\n isActivitySlug,\n type Activity,\n type ActivitySlug,\n} from \"./hook-types\";\nimport { DEMO_ACTIVITIES } from \"./demo-data/activities\";\n\n// Re-export types and constants so external consumers are unaffected\nexport { ACTIVITY_SLUGS, isActivitySlug };\nexport type { Activity, ActivitySlug };\n\n/**\n * Result type for useActivities hook.\n * Uses QueryResult generic with Activity[] and default Error type.\n */\nexport type UseActivitiesResult = QueryResult<Activity[]>;\n\n/**\n * Hook to fetch recent activities.\n * This is a stub implementation - override with your own data fetching logic.\n */\nexport function useActivities(): UseActivitiesResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching\n return {\n data: [...DEMO_ACTIVITIES],\n isLoading: false,\n isError: false,\n };\n}\n","import type { CatchUp } from \"../hook-types\";\n\nexport const DEMO_CATCHUPS: readonly CatchUp[] = [\n {\n id: 1,\n suggestion_title: \"Sarah Johnson hasn't ordered in 30 days\",\n },\n {\n id: 2,\n suggestion_title: \"Mike Chen's subscription is expiring soon\",\n },\n {\n id: 3,\n suggestion_title: \"Emily Rodriguez left a cart with 3 items\",\n },\n];\n","/**\n * Catch ups hook - stub implementation for SDK\n * In production, implement this hook to fetch from your API\n */\n\nimport type { QueryResult } from \"./hook-types\";\nimport type { CatchUp } from \"./hook-types\";\nimport { DEMO_CATCHUPS } from \"./demo-data/catchups\";\n\n// Re-export type so external consumers are unaffected\nexport type { CatchUp };\n\n/**\n * Result type for useCatchUps hook.\n * Uses QueryResult<CatchUp[]> with default Error type.\n */\nexport type UseCatchUpsResult = QueryResult<CatchUp[]>;\n\n/**\n * Hook to fetch catch up items.\n * This is a stub implementation - override with your own data fetching logic.\n */\nexport function useCatchUps(): UseCatchUpsResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching\n return {\n data: [...DEMO_CATCHUPS],\n isLoading: false,\n isError: false,\n };\n}\n","import type { MySiteData } from \"../hook-types\";\n\nexport const DEMO_MYSITE: MySiteData = {\n url: \"https://my-portal.example.com\",\n views: 1243,\n leads: 37,\n userName: \"Demo User\",\n};\n","/**\n * MySite hook - stub implementation for SDK\n * In production, implement this hook to fetch from your API\n */\n\nimport type { QueryResultNullable } from \"./hook-types\";\nimport type { MySiteData } from \"./hook-types\";\nimport { DEMO_MYSITE } from \"./demo-data/mysite\";\n\n// Re-export type so external consumers are unaffected\nexport type { MySiteData };\n\n/**\n * Result type for useMySite hook.\n * Uses QueryResultNullable since MySite data may not be available.\n */\nexport type UseMySiteResult = QueryResultNullable<MySiteData>;\n\n/**\n * Hook to fetch MySite data.\n * This is a stub implementation - override with your own data fetching logic.\n */\nexport function useMySite(): UseMySiteResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching\n return {\n data: DEMO_MYSITE,\n isLoading: false,\n isError: false,\n };\n}\n","import type { Conversation, Message } from \"../../types/screen-types\";\n\nconst now = new Date();\n\nfunction hoursAgo(hours: number): string {\n const d = new Date(now);\n d.setHours(d.getHours() - hours);\n return d.toISOString();\n}\n\nfunction daysAgo(days: number): string {\n const d = new Date(now);\n d.setDate(d.getDate() - days);\n return d.toISOString();\n}\n\nexport const DEMO_CONVERSATIONS: readonly Conversation[] = [\n {\n id: \"conv-1\",\n title: \"Sarah Johnson\",\n participants: [\n { id: \"user-1\", name: \"You\", email: \"me@example.com\", isOnline: true },\n {\n id: \"user-2\",\n name: \"Sarah Johnson\",\n email: \"sarah.johnson@example.com\",\n isOnline: true,\n },\n ],\n lastMessage: {\n id: \"msg-1-3\",\n conversationId: \"conv-1\",\n senderId: \"user-2\",\n senderName: \"Sarah Johnson\",\n type: \"text\",\n content: \"Sounds great! I'll place the order by end of day.\",\n timestamp: hoursAgo(1),\n isRead: false,\n },\n unreadCount: 1,\n status: \"active\",\n createdAt: daysAgo(30),\n updatedAt: hoursAgo(1),\n },\n {\n id: \"conv-2\",\n title: \"Mike Chen\",\n participants: [\n { id: \"user-1\", name: \"You\", email: \"me@example.com\", isOnline: true },\n {\n id: \"user-3\",\n name: \"Mike Chen\",\n email: \"mike.chen@acmecorp.com\",\n isOnline: false,\n },\n ],\n lastMessage: {\n id: \"msg-2-2\",\n conversationId: \"conv-2\",\n senderId: \"user-1\",\n senderName: \"You\",\n type: \"text\",\n content:\n \"I've attached the updated pricing sheet. Let me know if you have any questions!\",\n timestamp: hoursAgo(5),\n isRead: true,\n },\n unreadCount: 0,\n status: \"active\",\n createdAt: daysAgo(14),\n updatedAt: hoursAgo(5),\n },\n {\n id: \"conv-3\",\n title: \"Team Updates\",\n participants: [\n { id: \"user-1\", name: \"You\", email: \"me@example.com\", isOnline: true },\n {\n id: \"user-4\",\n name: \"Emily Rodriguez\",\n email: \"emily.r@healthfirst.io\",\n },\n { id: \"user-5\", name: \"David Park\", email: \"david.park@email.com\" },\n ],\n lastMessage: {\n id: \"msg-3-4\",\n conversationId: \"conv-3\",\n senderId: \"user-4\",\n senderName: \"Emily Rodriguez\",\n type: \"text\",\n content:\n \"The new product samples arrived today. Will distribute to the team tomorrow.\",\n timestamp: daysAgo(1),\n isRead: true,\n },\n unreadCount: 0,\n status: \"active\",\n createdAt: daysAgo(60),\n updatedAt: daysAgo(1),\n },\n];\n\nexport const DEMO_MESSAGES: readonly Message[] = [\n {\n id: \"msg-1-1\",\n conversationId: \"conv-1\",\n senderId: \"user-1\",\n senderName: \"You\",\n type: \"text\",\n content:\n \"Hi Sarah! I wanted to follow up on the Wellness Starter Kit. We have a special promotion running this month.\",\n timestamp: hoursAgo(3),\n isRead: true,\n },\n {\n id: \"msg-1-2\",\n conversationId: \"conv-1\",\n senderId: \"user-2\",\n senderName: \"Sarah Johnson\",\n type: \"text\",\n content:\n \"That's perfect timing! I was just thinking about reordering. What's the promo?\",\n timestamp: hoursAgo(2),\n isRead: true,\n },\n {\n id: \"msg-1-3\",\n conversationId: \"conv-1\",\n senderId: \"user-2\",\n senderName: \"Sarah Johnson\",\n type: \"text\",\n content: \"Sounds great! I'll place the order by end of day.\",\n timestamp: hoursAgo(1),\n isRead: false,\n },\n];\n","/**\n * Conversations hooks - stub implementations for SDK\n * In production, implement these hooks to fetch from your API\n */\n\nimport type { Conversation, Message } from \"../types/screen-types\";\nimport type { QueryResult } from \"./hook-types\";\nimport { DEMO_CONVERSATIONS, DEMO_MESSAGES } from \"./demo-data/conversations\";\n\n// =============================================================================\n// useConversations Hook\n// =============================================================================\n\n/**\n * Result type for useConversations hook.\n * Uses QueryResult<Conversation[]> with default Error type.\n */\nexport type UseConversationsResult = QueryResult<Conversation[]>;\n\n/**\n * Hook to fetch all conversations.\n * This is a stub implementation - override with your own data fetching logic.\n *\n * @returns UseConversationsResult with empty data array\n *\n * @example\n * ```tsx\n * const { data: conversations, isLoading, isError } = useConversations();\n *\n * if (isLoading) return <Loading />;\n * if (isError) return <Error />;\n *\n * return conversations.map(conv => <ConversationItem key={conv.id} {...conv} />);\n * ```\n */\nexport function useConversations(): UseConversationsResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching\n return {\n data: [...DEMO_CONVERSATIONS],\n isLoading: false,\n isError: false,\n };\n}\n\n// =============================================================================\n// useConversationMessages Hook\n// =============================================================================\n\n/**\n * Result type for useConversationMessages hook.\n * Uses QueryResult<Message[]> with default Error type.\n */\nexport type UseConversationMessagesResult = QueryResult<Message[]>;\n\n/**\n * Hook to fetch messages for a specific conversation.\n * This is a stub implementation - override with your own data fetching logic.\n *\n * @param conversationId - The ID of the conversation to fetch messages for\n * @returns UseConversationMessagesResult with empty data array\n *\n * @example\n * ```tsx\n * const { data: messages, isLoading, isError } = useConversationMessages(conversationId);\n *\n * if (isLoading) return <Loading />;\n * if (isError) return <Error />;\n *\n * return messages.map(msg => <MessageBubble key={msg.id} {...msg} />);\n * ```\n */\nexport function useConversationMessages(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _conversationId: string,\n): UseConversationMessagesResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching using _conversationId\n return {\n data: [...DEMO_MESSAGES],\n isLoading: false,\n isError: false,\n };\n}\n","/**\n * Screen Types - Type definitions for core feature screens\n *\n * All status and type unions are derived from constants for single source of truth.\n * Use the constants (e.g., CONVERSATION_STATUSES.active) for type-safe comparisons.\n */\n\n// =============================================================================\n// Messaging Types\n// =============================================================================\n\n/**\n * Conversation status constant - single source of truth.\n */\nexport const CONVERSATION_STATUSES = {\n active: \"active\",\n archived: \"archived\",\n muted: \"muted\",\n} as const;\n\n/**\n * Union type derived from CONVERSATION_STATUSES constant.\n */\nexport type ConversationStatus =\n (typeof CONVERSATION_STATUSES)[keyof typeof CONVERSATION_STATUSES];\n\n/**\n * Message type constant - single source of truth.\n */\nexport const MESSAGE_TYPES = {\n text: \"text\",\n image: \"image\",\n file: \"file\",\n system: \"system\",\n} as const;\n\n/**\n * Union type derived from MESSAGE_TYPES constant.\n */\nexport type MessageType = (typeof MESSAGE_TYPES)[keyof typeof MESSAGE_TYPES];\n\nexport interface Participant {\n readonly id: string;\n readonly name: string;\n readonly email: string;\n readonly avatarUrl?: string;\n readonly isOnline?: boolean;\n}\n\n/**\n * Message attachment type - extracted for reusability and clarity.\n */\nexport interface MessageAttachment {\n readonly id: string;\n readonly name: string;\n readonly url: string;\n readonly type: string;\n readonly size?: number;\n}\n\nexport interface Message {\n readonly id: string;\n readonly conversationId: string;\n readonly senderId: string;\n readonly senderName: string;\n readonly senderAvatarUrl?: string;\n readonly type: MessageType;\n readonly content: string;\n readonly timestamp: string;\n readonly isRead: boolean;\n readonly attachments?: readonly MessageAttachment[];\n}\n\nexport interface Conversation {\n readonly id: string;\n readonly title: string;\n readonly participants: readonly Participant[];\n readonly lastMessage?: Message;\n readonly unreadCount: number;\n readonly status: ConversationStatus;\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\n// =============================================================================\n// Contacts Types\n// =============================================================================\n\n/**\n * Contact status constant - single source of truth.\n */\nexport const CONTACT_STATUSES = {\n active: \"active\",\n inactive: \"inactive\",\n lead: \"lead\",\n prospect: \"prospect\",\n} as const;\n\n/**\n * Union type derived from CONTACT_STATUSES constant.\n */\nexport type ContactStatus =\n (typeof CONTACT_STATUSES)[keyof typeof CONTACT_STATUSES];\n\n/**\n * Contact type constant - single source of truth.\n */\nexport const CONTACT_TYPES = {\n individual: \"individual\",\n company: \"company\",\n} as const;\n\n/**\n * Union type derived from CONTACT_TYPES constant.\n */\nexport type ContactType = (typeof CONTACT_TYPES)[keyof typeof CONTACT_TYPES];\n\nexport interface ContactAddress {\n readonly street?: string;\n readonly city?: string;\n readonly state?: string;\n readonly postalCode?: string;\n readonly country?: string;\n}\n\nexport interface Contact {\n readonly id: string;\n readonly firstName: string;\n readonly lastName: string;\n readonly email: string;\n readonly phone?: string;\n readonly company?: string;\n readonly jobTitle?: string;\n readonly avatarUrl?: string;\n readonly status: ContactStatus;\n readonly type: ContactType;\n readonly address?: ContactAddress;\n readonly tags?: readonly string[];\n readonly notes?: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n","import type { Contact } from \"../../types/screen-types\";\n\nconst now = new Date();\n\nfunction daysAgo(days: number): string {\n const d = new Date(now);\n d.setDate(d.getDate() - days);\n return d.toISOString();\n}\n\nexport const DEMO_CONTACTS: readonly Contact[] = [\n {\n id: \"contact-1\",\n firstName: \"Sarah\",\n lastName: \"Johnson\",\n email: \"sarah.johnson@example.com\",\n phone: \"+1 (555) 123-4567\",\n company: \"Wellness Works Inc.\",\n jobTitle: \"Purchasing Manager\",\n status: \"active\",\n type: \"individual\",\n tags: [\"VIP\", \"Repeat Buyer\"],\n createdAt: daysAgo(90),\n updatedAt: daysAgo(2),\n },\n {\n id: \"contact-2\",\n firstName: \"Mike\",\n lastName: \"Chen\",\n email: \"mike.chen@acmecorp.com\",\n phone: \"+1 (555) 234-5678\",\n company: \"Acme Corp\",\n jobTitle: \"Director of Operations\",\n status: \"active\",\n type: \"individual\",\n tags: [\"Enterprise\"],\n createdAt: daysAgo(60),\n updatedAt: daysAgo(5),\n },\n {\n id: \"contact-3\",\n firstName: \"Emily\",\n lastName: \"Rodriguez\",\n email: \"emily.r@healthfirst.io\",\n company: \"HealthFirst\",\n status: \"lead\",\n type: \"individual\",\n notes: \"Interested in bulk pricing for team orders\",\n createdAt: daysAgo(7),\n updatedAt: daysAgo(1),\n },\n {\n id: \"contact-4\",\n firstName: \"David\",\n lastName: \"Park\",\n email: \"david.park@email.com\",\n phone: \"+1 (555) 345-6789\",\n status: \"prospect\",\n type: \"individual\",\n tags: [\"Referral\"],\n createdAt: daysAgo(14),\n updatedAt: daysAgo(10),\n },\n {\n id: \"contact-5\",\n firstName: \"Lisa\",\n lastName: \"Thompson\",\n email: \"lisa.t@globalfit.com\",\n company: \"Global Fitness\",\n jobTitle: \"CEO\",\n status: \"active\",\n type: \"individual\",\n address: {\n city: \"Los Angeles\",\n state: \"CA\",\n country: \"US\",\n },\n createdAt: daysAgo(120),\n updatedAt: daysAgo(15),\n },\n {\n id: \"contact-6\",\n firstName: \"James\",\n lastName: \"Wilson\",\n email: \"jwilson@retired.net\",\n status: \"inactive\",\n type: \"individual\",\n notes: \"Moved out of area, no longer purchasing\",\n createdAt: daysAgo(200),\n updatedAt: daysAgo(45),\n },\n];\n\nexport const DEMO_CONTACT: Contact = DEMO_CONTACTS[0]!;\n","/**\n * Contacts hooks - stub implementation for SDK\n * In production, implement these hooks to fetch from your API\n */\n\nimport type { Contact, ContactStatus } from \"../types/screen-types\";\nimport { CONTACT_STATUSES } from \"../types/screen-types\";\nimport type { ListQueryResult, QueryResultNullable } from \"./hook-types\";\nimport { DEMO_CONTACTS, DEMO_CONTACT } from \"./demo-data/contacts\";\n\n/**\n * Type predicate to check if a status string is a valid ContactStatus.\n * Enables runtime validation with type narrowing.\n */\nexport function isContactStatus(value: string): value is ContactStatus {\n return Object.values(CONTACT_STATUSES).includes(value as ContactStatus);\n}\n\n/**\n * Parameters for filtering and paginating contacts.\n * Uses readonly properties and proper ContactStatus type for status.\n */\nexport interface UseContactsParams {\n /** Search query to filter contacts by name, email, or company */\n readonly search?: string;\n /** Filter contacts by status - uses ContactStatus union type for type safety */\n readonly status?: ContactStatus;\n /** Maximum number of contacts to return */\n readonly limit?: number;\n}\n\n/**\n * Result type for the useContacts hook.\n * Uses ListQueryResult<Contact> with totalCount and default Error type.\n */\nexport type UseContactsResult = ListQueryResult<Contact>;\n\n/**\n * Result type for the useContact hook.\n * Uses QueryResultNullable since a specific contact may not exist.\n */\nexport type UseContactResult = QueryResultNullable<Contact>;\n\n/**\n * Hook to fetch a list of contacts with optional filtering and pagination.\n * This is a stub implementation - override with your own data fetching logic.\n *\n * @param params - Optional parameters for filtering and pagination\n * @returns Object containing contacts data, loading state, error state, and total count\n *\n * @example\n * ```tsx\n * const { data: contacts, isLoading, totalCount } = useContacts({\n * search: 'john',\n * status: 'active',\n * limit: 20\n * });\n * ```\n */\nexport function useContacts(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _params?: UseContactsParams,\n): UseContactsResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching\n return {\n data: [...DEMO_CONTACTS],\n isLoading: false,\n isError: false,\n totalCount: DEMO_CONTACTS.length,\n };\n}\n\n/**\n * Hook to fetch a single contact by ID.\n * This is a stub implementation - override with your own data fetching logic.\n *\n * @param contactId - The unique identifier of the contact to fetch\n * @returns Object containing contact data, loading state, and error state\n *\n * @example\n * ```tsx\n * const { data: contact, isLoading, isError } = useContact('contact-123');\n * ```\n */\nexport function useContact(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _contactId: string,\n): UseContactResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching using _contactId\n return {\n data: DEMO_CONTACT,\n isLoading: false,\n isError: false,\n };\n}\n","/**\n * AuthError - Default Authentication Error Component\n *\n * Displayed when authentication fails. Can be customized or replaced\n * via the RequireAuth component's errorComponent prop.\n */\n\nimport { useEffect } from \"react\";\nimport type { ReactNode } from \"react\";\n\nexport interface AuthErrorProps {\n /** Error message to display */\n message?: string;\n /** Optional title */\n title?: string;\n /** Optional children for custom content */\n children?: ReactNode;\n}\n\n/**\n * Default authentication error component.\n *\n * Displays a simple error message when authentication fails.\n * Can be customized via props or replaced entirely in RequireAuth.\n *\n * @example\n * ```tsx\n * // Use with default message\n * <AuthError />\n *\n * // Use with custom message\n * <AuthError message=\"Session expired. Please log in again.\" />\n *\n * // Use with custom content\n * <AuthError>\n * <CustomLoginButton />\n * </AuthError>\n * ```\n */\nexport function AuthError({\n message = \"You need to be authenticated to view this content.\",\n title = \"Authentication Required\",\n children,\n}: AuthErrorProps) {\n return (\n <div\n style={{\n display: \"flex\",\n flexDirection: \"column\",\n alignItems: \"center\",\n justifyContent: \"center\",\n minHeight: \"100vh\",\n padding: \"2rem\",\n fontFamily:\n '-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif',\n backgroundColor: \"#f9fafb\",\n color: \"#111827\",\n }}\n >\n <div\n style={{\n maxWidth: \"400px\",\n textAlign: \"center\",\n padding: \"2rem\",\n backgroundColor: \"#ffffff\",\n borderRadius: \"0.75rem\",\n boxShadow:\n \"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)\",\n }}\n >\n {/* Lock Icon */}\n <div\n style={{\n width: \"64px\",\n height: \"64px\",\n margin: \"0 auto 1.5rem\",\n backgroundColor: \"#fee2e2\",\n borderRadius: \"50%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n }}\n >\n <svg\n width=\"32\"\n height=\"32\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"#dc2626\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <rect x=\"3\" y=\"11\" width=\"18\" height=\"11\" rx=\"2\" ry=\"2\" />\n <path d=\"M7 11V7a5 5 0 0 1 10 0v4\" />\n </svg>\n </div>\n\n <h1\n style={{\n fontSize: \"1.5rem\",\n fontWeight: \"600\",\n marginBottom: \"0.75rem\",\n color: \"#111827\",\n }}\n >\n {title}\n </h1>\n\n <p\n style={{\n fontSize: \"1rem\",\n color: \"#6b7280\",\n marginBottom: children ? \"1.5rem\" : \"0\",\n lineHeight: \"1.5\",\n }}\n >\n {message}\n </p>\n\n {children}\n </div>\n </div>\n );\n}\n\nconst SPIN_STYLE_ID = \"fluid-auth-loading-spin\";\n\n/**\n * Inject the spin keyframes style once into the document head.\n */\nfunction ensureSpinStyle(): void {\n if (typeof document === \"undefined\") return;\n if (document.getElementById(SPIN_STYLE_ID)) return;\n\n const style = document.createElement(\"style\");\n style.id = SPIN_STYLE_ID;\n style.textContent = `@keyframes spin { to { transform: rotate(360deg); } }`;\n document.head.appendChild(style);\n}\n\n/**\n * Simple loading spinner component for auth loading state.\n */\nexport function AuthLoading() {\n useEffect(() => {\n ensureSpinStyle();\n }, []);\n\n return (\n <div\n style={{\n display: \"flex\",\n flexDirection: \"column\",\n alignItems: \"center\",\n justifyContent: \"center\",\n minHeight: \"100vh\",\n fontFamily:\n '-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif',\n backgroundColor: \"#f9fafb\",\n }}\n >\n <div\n style={{\n width: \"40px\",\n height: \"40px\",\n border: \"3px solid #e5e7eb\",\n borderTopColor: \"#3b82f6\",\n borderRadius: \"50%\",\n animation: \"spin 1s linear infinite\",\n }}\n />\n <p\n style={{\n marginTop: \"1rem\",\n color: \"#6b7280\",\n fontSize: \"0.875rem\",\n }}\n >\n Authenticating...\n </p>\n </div>\n );\n}\n","/**\n * RequireAuth - Route Protection Component\n *\n * Wraps content that requires authentication. Shows loading state\n * while checking auth, error component if not authenticated, or\n * children if authenticated.\n */\n\nimport type { ReactNode } from \"react\";\nimport { useFluidAuth } from \"../hooks/use-fluid-auth\";\nimport { AuthError, AuthLoading } from \"./AuthError\";\n\nexport interface RequireAuthProps {\n /** Content to render when authenticated */\n children: ReactNode;\n /** Component to show while checking authentication (default: AuthLoading) */\n fallback?: ReactNode;\n /** Component to show when not authenticated (default: AuthError) */\n errorComponent?: ReactNode;\n}\n\n/**\n * Component that protects content requiring authentication.\n *\n * **Important:** This provides UX-level protection only. It prevents\n * unauthenticated users from seeing the UI, but the real security\n * boundary is the server-side API. Client-side auth can always be\n * bypassed by modifying browser state.\n *\n * For defense-in-depth, configure `jwksUrl` in `FluidAuthConfig`\n * to enable client-side JWT signature verification.\n *\n * Shows different states based on auth status:\n * - Loading: Shows fallback (spinner by default)\n * - Not authenticated: Shows errorComponent (AuthError by default)\n * - Authenticated: Shows children\n *\n * @example\n * ```tsx\n * // Basic usage - shows default loading/error states\n * <RequireAuth>\n * <ProtectedContent />\n * </RequireAuth>\n *\n * // Custom loading state\n * <RequireAuth fallback={<CustomSpinner />}>\n * <ProtectedContent />\n * </RequireAuth>\n *\n * // Custom error component\n * <RequireAuth errorComponent={<LoginPrompt />}>\n * <ProtectedContent />\n * </RequireAuth>\n *\n * // Both custom\n * <RequireAuth\n * fallback={<SkeletonLoader />}\n * errorComponent={<RedirectToLogin />}\n * >\n * <Dashboard />\n * </RequireAuth>\n * ```\n */\nexport function RequireAuth({\n children,\n fallback = <AuthLoading />,\n errorComponent = <AuthError />,\n}: RequireAuthProps) {\n const { isAuthenticated, isLoading, error } = useFluidAuth();\n\n // Show loading state while checking authentication\n if (isLoading) {\n return <>{fallback}</>;\n }\n\n // Show error state if not authenticated\n if (!isAuthenticated || error) {\n return <>{errorComponent}</>;\n }\n\n // User is authenticated, render children\n return <>{children}</>;\n}\n","// Screen Components\nexport {\n MessagingScreen,\n messagingScreenPropertySchema,\n} from \"./MessagingScreen\";\nexport { ContactsScreen, contactsScreenPropertySchema } from \"./ContactsScreen\";\nexport { OrdersScreen, ordersScreenPropertySchema } from \"./OrdersScreen\";\nexport {\n CustomersScreen,\n customersScreenPropertySchema,\n} from \"./CustomersScreen\";\nexport { ProductsScreen, productsScreenPropertySchema } from \"./ProductsScreen\";\n\n// Re-export all property schemas as a lazy-loadable collection\nexport const screenPropertySchemas = {\n MessagingScreen: () =>\n import(\"./MessagingScreen\").then((m) => m.messagingScreenPropertySchema),\n ContactsScreen: () =>\n import(\"./ContactsScreen\").then((m) => m.contactsScreenPropertySchema),\n OrdersScreen: () =>\n import(\"./OrdersScreen\").then((m) => m.ordersScreenPropertySchema),\n CustomersScreen: () =>\n import(\"./CustomersScreen\").then((m) => m.customersScreenPropertySchema),\n ProductsScreen: () =>\n import(\"./ProductsScreen\").then((m) => m.productsScreenPropertySchema),\n};\n\n// Page Template Registration\nimport { PageTemplateRegistry } from \"../registries/page-template-registry\";\nimport { PAGE_CATEGORIES } from \"../types/page-template\";\n\n/**\n * Core page template IDs\n */\nexport const CORE_PAGE_IDS = {\n MESSAGING: \"core-messaging\",\n CONTACTS: \"core-contacts\",\n ORDERS: \"core-orders\",\n CUSTOMERS: \"core-customers\",\n PRODUCTS: \"core-products\",\n} as const;\n\n/**\n * Register core page templates.\n * These are automatically registered when the SDK is imported.\n */\nfunction registerCorePageTemplates(): void {\n // Messaging Screen\n PageTemplateRegistry.register({\n id: CORE_PAGE_IDS.MESSAGING,\n slug: \"messaging\",\n name: \"Messaging\",\n description: \"Messaging interface provided by Fluid Commerce\",\n category: PAGE_CATEGORIES.COMMUNICATION,\n tags: [\"messaging\", \"chat\", \"conversations\", \"communication\"],\n version: \"1.0.0\",\n isCore: true,\n component_tree: [\n {\n type: \"MessagingScreen\",\n id: \"messaging-screen-root\",\n props: {},\n },\n ],\n defaultProps: {},\n });\n\n // Contacts Screen\n PageTemplateRegistry.register({\n id: CORE_PAGE_IDS.CONTACTS,\n slug: \"contacts\",\n name: \"Contacts\",\n description: \"Contact management provided by Fluid Commerce\",\n category: PAGE_CATEGORIES.CORE,\n tags: [\"contacts\", \"people\", \"address-book\"],\n version: \"1.0.0\",\n isCore: true,\n component_tree: [\n {\n type: \"ContactsScreen\",\n id: \"contacts-screen-root\",\n props: {},\n },\n ],\n defaultProps: {},\n });\n\n // Orders Screen\n PageTemplateRegistry.register({\n id: CORE_PAGE_IDS.ORDERS,\n slug: \"orders\",\n name: \"Orders\",\n description: \"Order management provided by Fluid Commerce\",\n category: PAGE_CATEGORIES.CORE,\n tags: [\"orders\", \"commerce\", \"sales\"],\n version: \"1.0.0\",\n isCore: true,\n component_tree: [\n {\n type: \"OrdersScreen\",\n id: \"orders-screen-root\",\n props: {},\n },\n ],\n defaultProps: {},\n });\n\n // Customers Screen\n PageTemplateRegistry.register({\n id: CORE_PAGE_IDS.CUSTOMERS,\n slug: \"customers\",\n name: \"Customers\",\n description: \"Customer management provided by Fluid Commerce\",\n category: PAGE_CATEGORIES.CORE,\n tags: [\"customers\", \"people\", \"commerce\"],\n version: \"1.0.0\",\n isCore: true,\n component_tree: [\n {\n type: \"CustomersScreen\",\n id: \"customers-screen-root\",\n props: {},\n },\n ],\n defaultProps: {},\n });\n\n // Products Screen\n PageTemplateRegistry.register({\n id: CORE_PAGE_IDS.PRODUCTS,\n slug: \"products\",\n name: \"Products\",\n description: \"Product catalog provided by Fluid Commerce\",\n category: PAGE_CATEGORIES.CORE,\n tags: [\"products\", \"catalog\", \"commerce\"],\n version: \"1.0.0\",\n isCore: true,\n component_tree: [\n {\n type: \"ProductsScreen\",\n id: \"products-screen-root\",\n props: {},\n },\n ],\n defaultProps: {},\n });\n}\n\n// Auto-register core templates on module load\nregisterCorePageTemplates();\n","import { useEffect } from \"react\";\n\nconst SPIN_STYLE_ID = \"fluid-app-shell-loading-spin\";\n\n/**\n * Inject the spin keyframes style once into the document head.\n */\nfunction ensureSpinStyle(): void {\n if (typeof document === \"undefined\") return;\n if (document.getElementById(SPIN_STYLE_ID)) return;\n\n const style = document.createElement(\"style\");\n style.id = SPIN_STYLE_ID;\n style.textContent = `@keyframes spin { to { transform: rotate(360deg); } }`;\n document.head.appendChild(style);\n}\n\n/**\n * Full-page loading spinner shown while AppShell is fetching app data\n * for the first time. Uses inline styles (not Tailwind) since the theme\n * hasn't loaded yet.\n */\nexport function AppShellLoading() {\n useEffect(() => {\n ensureSpinStyle();\n }, []);\n\n return (\n <div\n style={{\n display: \"flex\",\n flexDirection: \"column\",\n alignItems: \"center\",\n justifyContent: \"center\",\n minHeight: \"100vh\",\n fontFamily:\n '-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif',\n backgroundColor: \"#f9fafb\",\n }}\n >\n <div\n style={{\n width: \"40px\",\n height: \"40px\",\n border: \"3px solid #e5e7eb\",\n borderTopColor: \"#3b82f6\",\n borderRadius: \"50%\",\n animation: \"spin 1s linear infinite\",\n }}\n />\n <p\n style={{\n marginTop: \"1rem\",\n color: \"#6b7280\",\n fontSize: \"0.875rem\",\n }}\n >\n Loading...\n </p>\n </div>\n );\n}\n","import { normalizeSlug } from \"@fluid-app/rep-core/navigation/system-navigation-items\";\nimport type { NavigationItem } from \"../types/navigation\";\n\nexport interface SlugMatch {\n matchedSlug: string;\n rest: string;\n}\n\n/**\n * Extract all slugs from a navigation tree, sorted by segment count descending.\n * Longest slugs first enables greedy prefix matching (e.g. \"share/playlists\"\n * is checked before \"share\").\n */\nexport function collectNavSlugs(items: NavigationItem[]): string[] {\n const slugs: string[] = [];\n\n for (const item of items) {\n if (item.slug) slugs.push(normalizeSlug(item.slug));\n for (const child of item.children ?? []) {\n if (child.slug) slugs.push(normalizeSlug(child.slug));\n }\n }\n\n return [...slugs].sort((a, b) => b.split(\"/\").length - a.split(\"/\").length);\n}\n\n/**\n * Find the longest registered nav slug that is a prefix of `fullSlug`.\n * Uses segment-boundary checking to prevent \"shop\" from matching \"shopping\".\n */\nexport function matchSlugPrefix(\n fullSlug: string,\n navSlugs: string[],\n): SlugMatch | undefined {\n const normalized = normalizeSlug(fullSlug);\n if (!normalized) return undefined;\n\n for (const navSlug of navSlugs) {\n if (normalized === navSlug) {\n return { matchedSlug: navSlug, rest: \"\" };\n }\n if (normalized.startsWith(navSlug + \"/\")) {\n return {\n matchedSlug: navSlug,\n rest: normalized.slice(navSlug.length + 1),\n };\n }\n }\n\n return undefined;\n}\n\n/**\n * Extract the slug portion from a full pathname by stripping the basePath prefix.\n * Returns an empty string when the pathname equals the basePath exactly.\n *\n * Examples:\n * extractSlugFromPathname(\"/contacts/123\", \"/\") → \"contacts/123\"\n * extractSlugFromPathname(\"/portal/contacts\", \"/portal\") → \"contacts\"\n * extractSlugFromPathname(\"/portal\", \"/portal\") → \"\"\n * extractSlugFromPathname(\"/\", \"/\") → \"\"\n */\nexport function extractSlugFromPathname(\n pathname: string,\n basePath: string,\n): string {\n // For root basePath, just strip the leading slash\n if (basePath === \"/\") {\n return pathname.replace(/^\\//, \"\");\n }\n\n // Strip basePath prefix, then strip leading slash from remainder\n if (pathname.startsWith(basePath)) {\n return pathname.slice(basePath.length).replace(/^\\//, \"\");\n }\n\n // Fallback: return pathname without leading slash\n return pathname.replace(/^\\//, \"\");\n}\n\nexport function isSlugInSection(\n item: NavigationItem,\n currentSlug: string,\n navSlugs: string[],\n): boolean {\n const match = matchSlugPrefix(currentSlug, navSlugs);\n const baseSlug = match?.matchedSlug ?? normalizeSlug(currentSlug);\n\n if (normalizeSlug(item.slug) === baseSlug) return true;\n return (\n item.children?.some((child) => normalizeSlug(child.slug) === baseSlug) ??\n false\n );\n}\n","import {\n SidebarGroupLabel,\n SidebarMenu,\n SidebarMenuItem,\n SidebarMenuButton,\n} from \"@fluid-app/rep-core/shell/sidebar\";\nimport { RepIcon } from \"@fluid-app/rep-core/components/RepIcon\";\nimport { normalizeSlug } from \"@fluid-app/rep-core/navigation/system-navigation-items\";\nimport type { NavigationItem } from \"../types/navigation\";\nimport { isSlugInSection } from \"./slug-utils\";\n\nexport interface SdkNavigationProps {\n navItems: NavigationItem[];\n currentSlug: string;\n onNavigate: (slug: string) => void;\n navSlugs: string[];\n}\n\nexport function SdkNavigation({\n navItems,\n currentSlug,\n onNavigate,\n navSlugs,\n}: SdkNavigationProps) {\n return (\n <SidebarMenu>\n {navItems.map((item, index) => {\n // Skip items without slug AND without label\n if (!item.slug && !item.label) return null;\n\n // Items without a slug are section headers\n if (!item.slug) {\n return (\n <SidebarGroupLabel key={item.id ?? `section-${index}`}>\n {item.label}\n </SidebarGroupLabel>\n );\n }\n\n const itemSlug = normalizeSlug(item.slug);\n const isActive = isSlugInSection(item, currentSlug, navSlugs);\n\n return (\n <SidebarMenuItem key={item.id ?? itemSlug}>\n <SidebarMenuButton\n isActive={isActive}\n onClick={() => onNavigate(itemSlug)}\n >\n {item.icon && <RepIcon name={item.icon} />}\n <span className=\"truncate\">{item.label}</span>\n </SidebarMenuButton>\n </SidebarMenuItem>\n );\n })}\n </SidebarMenu>\n );\n}\n","import { useState, useRef, useEffect, useCallback } from \"react\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { faTableCellsLarge } from \"@fortawesome/pro-regular-svg-icons/faTableCellsLarge\";\nimport { RepIcon } from \"@fluid-app/rep-core/components/RepIcon\";\nimport { getSystemNavigationBySection } from \"@fluid-app/rep-core/navigation/system-navigation-items\";\n\nexport interface QuickLinksDropdownProps {\n onNavigate: (slug: string) => void;\n}\n\nexport function QuickLinksDropdown({ onNavigate }: QuickLinksDropdownProps) {\n const [open, setOpen] = useState(false);\n const panelRef = useRef<HTMLDivElement>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n\n const close = useCallback(() => setOpen(false), []);\n\n // Click-outside + Escape to dismiss\n useEffect(() => {\n if (!open) return;\n\n const handleMouseDown = (e: MouseEvent) => {\n if (\n panelRef.current &&\n !panelRef.current.contains(e.target as Node) &&\n buttonRef.current &&\n !buttonRef.current.contains(e.target as Node)\n ) {\n close();\n }\n };\n\n const handleKeyDown = (e: KeyboardEvent) => {\n if (e.key === \"Escape\") close();\n };\n\n document.addEventListener(\"mousedown\", handleMouseDown);\n document.addEventListener(\"keydown\", handleKeyDown);\n return () => {\n document.removeEventListener(\"mousedown\", handleMouseDown);\n document.removeEventListener(\"keydown\", handleKeyDown);\n };\n }, [open, close]);\n\n const sections = getSystemNavigationBySection();\n\n const handleItemClick = (slug: string) => {\n onNavigate(slug);\n close();\n };\n\n return (\n <div className=\"relative\">\n <button\n ref={buttonRef}\n type=\"button\"\n onClick={() => setOpen((prev) => !prev)}\n className=\"flex shrink-0 items-center justify-center rounded-md p-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground\"\n aria-label=\"Quick links\"\n aria-expanded={open}\n >\n <FontAwesomeIcon icon={faTableCellsLarge} className=\"h-4 w-4\" />\n </button>\n\n {open && (\n <div\n ref={panelRef}\n className=\"absolute top-full right-0 z-50 mt-1 w-[700px] max-w-[90vw] overflow-hidden rounded-lg border border-border bg-background shadow-lg\"\n >\n <div className=\"flex flex-col\">\n {/* Header */}\n <div className=\"flex items-center gap-2 border-b bg-background p-4\">\n <FontAwesomeIcon\n icon={faTableCellsLarge}\n className=\"h-5 w-5 text-muted-foreground\"\n />\n <h3 className=\"text-sm font-semibold text-foreground\">\n Shortcuts\n </h3>\n </div>\n\n {/* Sections */}\n <div className=\"space-y-6 bg-muted p-6\">\n {Object.entries(sections).map(([sectionName, items]) => (\n <div key={sectionName} className=\"space-y-3\">\n <h3 className=\"text-sm font-semibold text-foreground\">\n {sectionName}\n </h3>\n <div className=\"grid grid-cols-4 gap-2\">\n {items.map((item) => (\n <button\n key={item.slug}\n type=\"button\"\n onClick={() => handleItemClick(item.slug!)}\n className=\"flex items-center gap-2 rounded-lg px-3 py-2 text-sm text-sidebar-foreground transition-colors hover:bg-sidebar-primary hover:text-sidebar-primary-foreground\"\n >\n {item.icon && (\n <RepIcon\n name={item.icon}\n className=\"h-4 w-4 shrink-0 text-muted-foreground\"\n />\n )}\n <span className=\"truncate\">{item.label}</span>\n </button>\n ))}\n </div>\n </div>\n ))}\n </div>\n </div>\n </div>\n )}\n </div>\n );\n}\n","import { useSidebar } from \"@fluid-app/rep-core/shell/sidebar\";\nimport { useThemeMode } from \"@fluid-app/rep-core/shell/ThemeModeContext\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { faBars } from \"@fortawesome/pro-regular-svg-icons/faBars\";\nimport { faSun } from \"@fortawesome/pro-regular-svg-icons/faSun\";\nimport { faMoon } from \"@fortawesome/pro-regular-svg-icons/faMoon\";\nimport { normalizeSlug } from \"@fluid-app/rep-core/navigation/system-navigation-items\";\nimport type { NavigationItem } from \"../types/navigation\";\nimport { matchSlugPrefix } from \"./slug-utils\";\nimport { QuickLinksDropdown } from \"./QuickLinksDropdown\";\n\nexport interface SdkHeaderProps {\n tabs: NavigationItem[];\n currentSlug: string;\n onNavigate: (slug: string) => void;\n navSlugs: string[];\n}\n\nexport function SdkHeader({\n tabs,\n currentSlug,\n onNavigate,\n navSlugs,\n}: SdkHeaderProps) {\n const sidebar = useSidebar();\n const themeMode = useThemeMode();\n\n const match = matchSlugPrefix(currentSlug, navSlugs);\n const baseSlug = match?.matchedSlug ?? normalizeSlug(currentSlug);\n\n const themeIcon = themeMode.mode === \"dark\" ? faMoon : faSun;\n\n return (\n <header className=\"flex h-[52px] shrink-0 items-center gap-2 bg-sidebar px-6\">\n {/* Mobile hamburger */}\n {sidebar.isMobile && (\n <button\n type=\"button\"\n onClick={sidebar.toggleSidebar}\n className=\"mr-2 flex shrink-0 items-center justify-center rounded-md p-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground\"\n aria-label=\"Toggle sidebar\"\n >\n <FontAwesomeIcon icon={faBars} className=\"size-5\" />\n </button>\n )}\n\n {/* Scrollable sub-tabs */}\n <nav className=\"scrollbar-none flex flex-1 items-center gap-1 overflow-x-auto\">\n {tabs.map((tab) => {\n const tabSlug = normalizeSlug(tab.slug);\n if (!tabSlug) return null;\n\n const isActive = tabSlug === baseSlug;\n\n return (\n <button\n key={tab.id ?? tabSlug}\n type=\"button\"\n onClick={() => onNavigate(tabSlug)}\n className={`border-b-2 px-4 py-3 text-sm font-medium whitespace-nowrap transition-colors ${\n isActive\n ? \"border-primary text-foreground\"\n : \"border-transparent text-muted-foreground hover:border-border hover:text-foreground\"\n }`}\n >\n {tab.label}\n </button>\n );\n })}\n </nav>\n\n {/* Quick Links */}\n <QuickLinksDropdown onNavigate={onNavigate} />\n\n {/* Theme toggle */}\n <button\n type=\"button\"\n onClick={themeMode.cycleMode}\n className=\"ml-2 flex shrink-0 items-center justify-center rounded-md p-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground\"\n aria-label={`Switch theme (current: ${themeMode.mode})`}\n >\n <FontAwesomeIcon icon={themeIcon} className=\"size-3\" />\n </button>\n </header>\n );\n}\n","/**\n * BuilderScreenView — renders a builder screen's component_tree with\n * DataAwareWidget support for data-bound widgets.\n *\n * Uses the shared ScreenRenderer from rep-widgets under the hood,\n * but wraps data-bound widgets with DataAwareWidget from rep-core.\n */\n\nimport { memo } from \"react\";\nimport type { WidgetSchema } from \"@fluid-app/rep-core/types\";\nimport type { ScreenDefinition } from \"@fluid-app/rep-core/types\";\nimport { DataAwareWidget } from \"@fluid-app/rep-core/data-sources/DataAwareWidget\";\nimport { useRegistry } from \"@fluid-app/rep-widgets/contexts\";\n\ninterface WidgetRendererProps {\n widget: WidgetSchema;\n index: number;\n}\n\n/**\n * Renders a single widget, wrapping with DataAwareWidget if it has a dataSource.\n */\nfunction WidgetRenderer({ widget, index }: WidgetRendererProps) {\n const registry = useRegistry();\n const Component = registry[widget.type];\n\n if (!Component) {\n console.warn(\n `[BuilderScreenView] Widget type \"${String(widget.type)}\" not found in registry`,\n );\n return null;\n }\n\n if (widget.dataSource) {\n return (\n <div key={widget.id ?? index} className=\"h-full w-full overflow-x-hidden\">\n <DataAwareWidget widget={widget} Component={Component} />\n </div>\n );\n }\n\n return (\n <div key={widget.id ?? index} className=\"h-full w-full overflow-x-hidden\">\n <Component {...widget.props} />\n </div>\n );\n}\n\nexport interface BuilderScreenViewProps {\n /** The screen definition to render */\n screen: ScreenDefinition;\n /** Additional CSS classes for the wrapper div */\n className?: string;\n}\n\n/**\n * Renders a builder screen's component_tree with full data source support.\n * Widgets with `dataSource` config are automatically wrapped with `DataAwareWidget`\n * which fetches data and merges it with static props before rendering.\n */\nfunction BuilderScreenViewImpl({ screen, className }: BuilderScreenViewProps) {\n const widgets = screen.component_tree;\n\n if (!widgets || widgets.length === 0) {\n return (\n <div className={className ?? \"h-full w-full\"}>\n <div className=\"flex h-full items-center justify-center text-muted-foreground\">\n <p>This screen has no content yet.</p>\n </div>\n </div>\n );\n }\n\n return (\n <div className={className ?? \"h-full w-full\"}>\n {widgets.map((widget, index) => {\n if (!widget) return null;\n return (\n <WidgetRenderer\n key={widget.id ?? index}\n widget={widget}\n index={index}\n />\n );\n })}\n </div>\n );\n}\n\nexport const BuilderScreenView = memo(BuilderScreenViewImpl);\n","import { useMemo, type ComponentType } from \"react\";\nimport { isSystemNavigationItem } from \"@fluid-app/rep-core/navigation/system-navigation-items\";\nimport type { NavigationItem, ScreenDefinition } from \"../types/navigation\";\nimport { CoreScreenPlaceholder } from \"../screens/CoreScreenPlaceholder\";\nimport { MessagingScreen } from \"../screens/MessagingScreen\";\nimport { ContactsScreen } from \"../screens/ContactsScreen\";\nimport { OrdersScreen } from \"../screens/OrdersScreen\";\nimport { CustomersScreen } from \"../screens/CustomersScreen\";\nimport { ProductsScreen } from \"../screens/ProductsScreen\";\nimport { BuilderScreenView } from \"./BuilderScreenView\";\n\nconst SYSTEM_SLUG_SCREEN_MAP: Record<string, ComponentType> = {\n messages: MessagingScreen,\n contacts: ContactsScreen,\n shop: OrdersScreen,\n customers: CustomersScreen,\n products: ProductsScreen,\n};\n\nexport interface PageRouterProps {\n currentSlug: string;\n currentNavItem?: NavigationItem | undefined;\n customPages?:\n | Record<string, ComponentType<{ slug?: string; params?: string }>>\n | undefined;\n /** Builder screen definitions (from fluidos API) */\n screens?: ScreenDefinition[] | undefined;\n baseSlug: string;\n restParams: string;\n}\n\nexport function PageRouter({\n currentSlug,\n currentNavItem,\n customPages,\n screens,\n baseSlug,\n restParams,\n}: PageRouterProps) {\n // Build a screen lookup map by ID for O(1) access\n const screenById = useMemo(() => {\n if (!screens || screens.length === 0) return undefined;\n return new Map(screens.map((s) => [s.id, s]));\n }, [screens]);\n\n // Build a screen lookup map by slug for fallback resolution\n const screenBySlug = useMemo(() => {\n if (!screens || screens.length === 0) return undefined;\n return new Map(screens.filter((s) => s.slug).map((s) => [s.slug, s]));\n }, [screens]);\n\n // Resolve builder screen: screen_id first, then slug fallback\n const builderScreen = useMemo(() => {\n if (currentNavItem?.screen_id && screenById) {\n const byId = screenById.get(currentNavItem.screen_id);\n if (byId) return byId;\n }\n if (screenBySlug) {\n return (\n screenBySlug.get(currentSlug) ?? screenBySlug.get(baseSlug) ?? undefined\n );\n }\n return undefined;\n }, [\n currentNavItem?.screen_id,\n screenById,\n screenBySlug,\n currentSlug,\n baseSlug,\n ]);\n\n // 1. System navigation item with a dedicated screen component\n const SystemScreen = SYSTEM_SLUG_SCREEN_MAP[baseSlug];\n if (SystemScreen) {\n return <SystemScreen />;\n }\n\n // 2. System slug without a dedicated screen (account, my-site, share/*)\n if (isSystemNavigationItem(baseSlug)) {\n return <CoreScreenPlaceholder name={currentNavItem?.label ?? baseSlug} />;\n }\n\n // 3. Exact custom page match (full slug)\n const ExactCustomPage = customPages?.[currentSlug];\n if (ExactCustomPage) {\n return <ExactCustomPage slug={currentSlug} params={restParams} />;\n }\n\n // 4. Prefix custom page match (base slug with rest params)\n if (baseSlug !== currentSlug) {\n const PrefixCustomPage = customPages?.[baseSlug];\n if (PrefixCustomPage) {\n return <PrefixCustomPage slug={currentSlug} params={restParams} />;\n }\n }\n\n // 5. Builder screen (by screen_id or slug match)\n if (builderScreen) {\n return <BuilderScreenView screen={builderScreen} />;\n }\n\n // 6. Fallback\n return <CoreScreenPlaceholder name={currentNavItem?.label ?? currentSlug} />;\n}\n","import { createContext, useContext, useMemo, type ReactNode } from \"react\";\n\nexport interface AppNavigationContextValue {\n /** Current active slug (e.g. \"contacts/123\") */\n currentSlug: string;\n /** Base path for subpath deployments (e.g. \"/portal\"). Default: \"/\" */\n basePath: string;\n /** Navigate to a slug programmatically */\n navigate: (slug: string) => void;\n /** Build a full href for a slug (for use in <a> tags) */\n buildHref: (slug: string) => string;\n}\n\nconst AppNavigationContext = createContext<AppNavigationContextValue | null>(\n null,\n);\n\nexport interface AppNavigationProviderProps {\n currentSlug: string;\n basePath: string;\n navigate: (slug: string) => void;\n children: ReactNode;\n}\n\nexport function AppNavigationProvider({\n currentSlug,\n basePath,\n navigate,\n children,\n}: AppNavigationProviderProps) {\n const buildHref = useMemo(() => {\n return (slug: string) => {\n if (basePath === \"/\") return `/${slug}`;\n return `${basePath}/${slug}`;\n };\n }, [basePath]);\n\n const value = useMemo(\n () => ({ currentSlug, basePath, navigate, buildHref }),\n [currentSlug, basePath, navigate, buildHref],\n );\n\n return (\n <AppNavigationContext.Provider value={value}>\n {children}\n </AppNavigationContext.Provider>\n );\n}\n\nexport function useAppNavigation(): AppNavigationContextValue {\n const ctx = useContext(AppNavigationContext);\n if (!ctx) {\n throw new Error(\n \"useAppNavigation must be used within an <AppShell> or <AppNavigationProvider>\",\n );\n }\n return ctx;\n}\n","import {\n useState,\n useEffect,\n useCallback,\n useMemo,\n type ReactNode,\n type ComponentType,\n} from \"react\";\nimport { AppShellLayout } from \"@fluid-app/rep-core/shell/AppShellLayout\";\nimport {\n ThemeModeProvider,\n type ThemeMode,\n} from \"@fluid-app/rep-core/shell/ThemeModeContext\";\nimport { normalizeSlug } from \"@fluid-app/rep-core/navigation/system-navigation-items\";\nimport type { RepAppData, ScreenDefinition } from \"@fluid-app/rep-core/types\";\nimport {\n applyTheme,\n removeAllThemes,\n resolveTheme,\n} from \"@fluid-app/rep-core/theme\";\nimport { useFluidApp } from \"../hooks/use-fluid-app\";\nimport type { NavigationItem } from \"../types/navigation\";\nimport { AppShellLoading } from \"./AppShellLoading\";\nimport { SdkNavigation } from \"./SdkNavigation\";\nimport { SdkHeader } from \"./SdkHeader\";\nimport { PageRouter } from \"./PageRouter\";\nimport {\n collectNavSlugs,\n matchSlugPrefix,\n extractSlugFromPathname,\n} from \"./slug-utils\";\nimport { AppNavigationProvider } from \"./AppNavigationContext\";\n\nconst THEME_STORAGE_KEY = \"rep-theme-mode\";\n\nconst DEFAULT_NAVIGATION: NavigationItem[] = [\n { label: \"We Commerce\", children: [] },\n { slug: \"shop\", label: \"Shop\", icon: \"store\", children: [] },\n { slug: \"account\", label: \"Account\", icon: \"user-gear\", children: [] },\n { slug: \"messages\", label: \"Messaging\", icon: \"comment\", children: [] },\n { label: \"Marketing Assets\", children: [] },\n {\n slug: \"share/products\",\n label: \"Products\",\n icon: \"boxes-stacked\",\n children: [],\n },\n];\n\nfunction getInitialThemeMode(): ThemeMode {\n if (typeof window === \"undefined\") return \"light\";\n const stored = localStorage.getItem(THEME_STORAGE_KEY);\n if (stored === \"light\" || stored === \"dark\") return stored;\n return \"light\";\n}\n\nfunction findFirstNavigableSlug(items: NavigationItem[]): string {\n for (const item of items) {\n if (item.slug) return normalizeSlug(item.slug);\n for (const child of item.children ?? []) {\n if (child.slug) return normalizeSlug(child.slug);\n }\n }\n return \"\";\n}\n\nfunction findCurrentSection(\n items: NavigationItem[],\n slug: string,\n): NavigationItem | undefined {\n const normalized = normalizeSlug(slug);\n for (const item of items) {\n if (normalizeSlug(item.slug) === normalized) return item;\n if (\n item.children?.some((child) => normalizeSlug(child.slug) === normalized)\n ) {\n return item;\n }\n }\n return undefined;\n}\n\nfunction findNavItem(\n items: NavigationItem[],\n slug: string,\n): NavigationItem | undefined {\n const normalized = normalizeSlug(slug);\n for (const item of items) {\n if (normalizeSlug(item.slug) === normalized) return item;\n for (const child of item.children ?? []) {\n if (normalizeSlug(child.slug) === normalized) return child;\n }\n }\n return undefined;\n}\n\nexport interface AppShellProps {\n /** Pre-fetched app data (skips internal useFluidApp call if provided) */\n appData?: RepAppData;\n /** Override navigation items (otherwise derived from appData/API) */\n navigation?: NavigationItem[];\n /** Custom page components keyed by slug */\n customPages?: Record<\n string,\n ComponentType<{ slug?: string; params?: string }>\n >;\n /** Base path for subpath deployments (e.g. \"/portal\"). Default: \"/\" */\n basePath?: string;\n /** Controlled current slug */\n currentSlug?: string;\n /** Navigation callback */\n onNavigate?: (slug: string) => void;\n /** Custom sidebar header slot */\n sidebarHeader?: ReactNode;\n /** Custom sidebar footer slot */\n sidebarFooter?: ReactNode;\n /** Render prop or static children for the content area */\n children?:\n | ReactNode\n | ((props: {\n currentSlug: string;\n currentNavItem: NavigationItem | undefined;\n }) => ReactNode);\n}\n\nexport function AppShell({\n appData: appDataProp,\n navigation: navigationProp,\n customPages,\n basePath = \"/\",\n currentSlug: controlledSlug,\n onNavigate: onNavigateProp,\n sidebarHeader,\n sidebarFooter,\n children,\n}: AppShellProps) {\n // Normalize basePath: ensure leading slash, no trailing slash\n const normalizedBasePath = useMemo(() => {\n const stripped = basePath.replace(/^\\/|\\/$/g, \"\");\n return stripped ? `/${stripped}` : \"/\";\n }, [basePath]);\n\n // Fetch full app data from fluidos API (disabled when appData is provided)\n const { data: fetchedAppData, isLoading } = useFluidApp({\n enabled: !appDataProp,\n });\n const appData = appDataProp ?? fetchedAppData;\n\n // Resolve the active theme from app data\n const activeTheme = useMemo(() => {\n if (!appData?.profile?.themes?.length) return undefined;\n const themes = appData.profile.themes;\n const activeId = appData.profile.activeThemeId;\n return activeId\n ? (themes.find((t) => t.id === activeId) ?? themes[0])\n : themes[0];\n }, [appData?.profile?.themes, appData?.profile?.activeThemeId]);\n\n // Apply theme CSS via the shared theme pipeline\n useEffect(() => {\n if (!activeTheme) return;\n\n const resolved = resolveTheme(activeTheme);\n applyTheme(resolved);\n\n return () => {\n removeAllThemes();\n };\n }, [activeTheme]);\n\n // Resolve navigation items\n const navItems = useMemo(() => {\n if (navigationProp) return navigationProp;\n const profileNav = appData?.profile?.navigation?.navigation_items;\n if (profileNav && profileNav.length > 0) return profileNav;\n return DEFAULT_NAVIGATION;\n }, [navigationProp, appData?.profile?.navigation?.navigation_items]);\n\n // Resolve builder screen definitions\n const screens: ScreenDefinition[] | undefined = appData?.screens;\n\n // Collect all nav slugs for prefix matching (sorted longest-first)\n const navSlugs = useMemo(() => collectNavSlugs(navItems), [navItems]);\n\n // Theme mode state with localStorage persistence\n const [themeMode, setThemeMode] = useState<ThemeMode>(getInitialThemeMode);\n\n const handleThemeModeChange = useCallback((mode: ThemeMode) => {\n setThemeMode(mode);\n if (typeof window !== \"undefined\") {\n localStorage.setItem(THEME_STORAGE_KEY, mode);\n }\n }, []);\n\n // Path-based routing for uncontrolled mode\n const [pathSlug, setPathSlug] = useState<string>(() => {\n if (typeof window === \"undefined\") return \"\";\n return extractSlugFromPathname(\n window.location.pathname,\n normalizedBasePath,\n );\n });\n\n // Sync initial path when navItems load — redirect to first nav slug if at root\n useEffect(() => {\n if (controlledSlug !== undefined) return;\n if (typeof window === \"undefined\") return;\n\n const currentPath = extractSlugFromPathname(\n window.location.pathname,\n normalizedBasePath,\n );\n\n if (!currentPath) {\n const firstSlug = findFirstNavigableSlug(navItems);\n if (firstSlug) {\n const targetPath =\n normalizedBasePath === \"/\"\n ? `/${firstSlug}`\n : `${normalizedBasePath}/${firstSlug}`;\n // replaceState to avoid polluting back-button history\n history.replaceState(null, \"\", targetPath);\n setPathSlug(firstSlug);\n }\n }\n }, [navItems, controlledSlug, normalizedBasePath]);\n\n // Listen for popstate (browser back/forward)\n useEffect(() => {\n if (controlledSlug !== undefined) return;\n\n const handlePopState = () => {\n const slug = extractSlugFromPathname(\n window.location.pathname,\n normalizedBasePath,\n );\n setPathSlug(slug);\n };\n\n window.addEventListener(\"popstate\", handlePopState);\n return () => window.removeEventListener(\"popstate\", handlePopState);\n }, [controlledSlug, normalizedBasePath]);\n\n const activeSlug = controlledSlug ?? pathSlug;\n\n const handleNavigate = useCallback(\n (slug: string) => {\n if (onNavigateProp) {\n onNavigateProp(slug);\n return;\n }\n const targetPath =\n normalizedBasePath === \"/\"\n ? `/${slug}`\n : `${normalizedBasePath}/${slug}`;\n history.pushState(null, \"\", targetPath);\n setPathSlug(slug);\n },\n [onNavigateProp, normalizedBasePath],\n );\n\n // Derive base slug and rest params via prefix matching\n const slugMatch = useMemo(\n () => matchSlugPrefix(activeSlug, navSlugs),\n [activeSlug, navSlugs],\n );\n const baseSlug = slugMatch?.matchedSlug ?? normalizeSlug(activeSlug);\n const restParams = slugMatch?.rest ?? \"\";\n\n // Derive current section and sub-tabs using base slug\n const currentSection = findCurrentSection(navItems, baseSlug);\n const secondLevelTabs = currentSection?.children ?? [];\n const currentNavItem = findNavItem(navItems, baseSlug);\n\n // Determine content to render\n const content =\n typeof children === \"function\"\n ? children({ currentSlug: activeSlug, currentNavItem })\n : (children ?? (\n <PageRouter\n currentSlug={activeSlug}\n currentNavItem={currentNavItem}\n customPages={customPages}\n screens={screens}\n baseSlug={baseSlug}\n restParams={restParams}\n />\n ));\n\n // Show loading state while app data is being fetched for the first time.\n // This check is placed after all hooks to satisfy React's rules of hooks.\n if (isLoading && !appData) {\n return <AppShellLoading />;\n }\n\n return (\n <ThemeModeProvider\n mode={themeMode}\n onModeChange={handleThemeModeChange}\n autoModeEnabled={false}\n >\n <AppNavigationProvider\n currentSlug={activeSlug}\n basePath={normalizedBasePath}\n navigate={handleNavigate}\n >\n <div\n data-theme={activeTheme?.id}\n data-theme-mode={themeMode === \"auto\" ? undefined : themeMode}\n >\n <AppShellLayout\n sidebarContent={\n <SdkNavigation\n navItems={navItems}\n currentSlug={activeSlug}\n onNavigate={handleNavigate}\n navSlugs={navSlugs}\n />\n }\n headerContent={\n <SdkHeader\n tabs={secondLevelTabs}\n currentSlug={activeSlug}\n onNavigate={handleNavigate}\n navSlugs={navSlugs}\n />\n }\n sidebarHeader={sidebarHeader}\n sidebarFooter={sidebarFooter}\n >\n {content}\n </AppShellLayout>\n </div>\n </AppNavigationProvider>\n </ThemeModeProvider>\n );\n}\n","import { forwardRef, type AnchorHTMLAttributes, type MouseEvent } from \"react\";\nimport { useAppNavigation } from \"./AppNavigationContext\";\n\nexport interface AppLinkProps\n extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> {\n /** Slug to navigate to (e.g. \"contacts/123\") */\n to: string;\n}\n\n/**\n * SPA-aware link that renders a real `<a href>` for accessibility\n * (right-click, ctrl+click, screen readers) but intercepts normal\n * clicks for client-side navigation.\n */\nexport const AppLink = forwardRef<HTMLAnchorElement, AppLinkProps>(\n function AppLink({ to, onClick, children, ...rest }, ref) {\n const { navigate, buildHref } = useAppNavigation();\n\n const handleClick = (e: MouseEvent<HTMLAnchorElement>) => {\n // Allow custom onClick handlers to run first\n onClick?.(e);\n if (e.defaultPrevented) return;\n\n // Skip SPA navigation for modifier keys, non-primary button, or external target\n if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;\n if (e.button !== 0) return;\n if (rest.target && rest.target !== \"_self\") return;\n\n e.preventDefault();\n navigate(to);\n };\n\n return (\n <a ref={ref} href={buildHref(to)} onClick={handleClick} {...rest}>\n {children}\n </a>\n );\n },\n);\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/types/page-template.ts","../src/registries/page-template-registry.ts","../src/core/resolve-pages.ts","../src/providers/PageTemplateProvider.tsx","../src/hooks/use-fluid-profile.ts","../../../../node_modules/.pnpm/@tanstack+query-core@5.90.12/node_modules/@tanstack/query-core/src/timeoutManager.ts","../../../../node_modules/.pnpm/@tanstack+query-core@5.90.12/node_modules/@tanstack/query-core/src/utils.ts","../../../../node_modules/.pnpm/@tanstack+query-core@5.90.12/node_modules/@tanstack/query-core/src/notifyManager.ts","../../../../node_modules/.pnpm/@tanstack+query-persist-client-core@5.91.11/node_modules/@tanstack/query-persist-client-core/src/createPersister.ts","../../../platform/query-persister/src/persister.ts","../src/hooks/use-fluid-app.ts","../src/hooks/use-fluid-permissions.ts","../src/hooks/use-fluid-theme.ts","../src/hooks/use-current-rep.ts","../src/hooks/use-fluid-auth.ts","../src/hooks/demo-data/calendar-events.ts","../src/hooks/use-calendar-events.ts","../src/hooks/demo-data/todos.ts","../src/hooks/use-todos.ts","../src/hooks/hook-types.ts","../src/hooks/demo-data/activities.ts","../src/hooks/use-activities.ts","../src/hooks/demo-data/catchups.ts","../src/hooks/use-catchups.ts","../src/hooks/demo-data/mysite.ts","../src/hooks/use-mysite.ts","../src/hooks/demo-data/conversations.ts","../src/hooks/use-conversations.ts","../src/types/screen-types.ts","../src/hooks/demo-data/contacts.ts","../src/hooks/use-contacts.ts","../src/components/AuthError.tsx","../src/components/RequireAuth.tsx","../src/screens/index.ts","../src/shell/SdkBottomNav.tsx","../src/shell/AppShellLoading.tsx","../src/shell/slug-utils.ts","../src/shell/SdkNavigation.tsx","../src/shell/QuickLinksDropdown.tsx","../src/shell/SdkHeader.tsx","../src/shell/BuilderScreenView.tsx","../src/shell/PageRouter.tsx","../src/shell/AppNavigationContext.tsx","../src/shell/AppShell.tsx","../src/shell/AppLink.tsx"],"names":["createContext","useRef","useEffect","useMemo","useContext","useFluidApi","useQuery","storage","filters","transformManifestToRepAppData","useThemeContext","useFluidAuthContext","now","daysFromNow","hoursAgo","daysAgo","jsx","jsxs","isLoading","Fragment","normalizeSlug","useSidebar","React2","RepIcon","FontAwesomeIcon","faEllipsis","faXmark","SPIN_STYLE_ID","ensureSpinStyle","SidebarMenu","SidebarGroupLabel","SidebarMenuItem","SidebarMenuButton","useState","useCallback","getSystemNavigationBySection","faTableCellsLarge","sidebar","useThemeMode","faMoon","faSun","faBars","useRegistry","DataAwareWidget","memo","MessagingScreen","ContactsScreen","OrdersScreen","CustomersScreen","ProductsScreen","isSystemNavigationItem","CoreScreenPlaceholder","resolveTheme","applyTheme","removeAllThemes","ThemeModeProvider","AppShellLayout","forwardRef","AppLink"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEO,IAAM,eAAA,GAAkB;AAAA,EAC7B,IAAA,EAAM,MAAA;AAAA,EACN,QAAA,EAAU,UAAA;AAAA,EACV,aAAA,EAAe,eAAA;AAAA,EACf,IAAA,EAAM,MAAA;AAAA,EACN,MAAA,EAAQ;AACV;;;ACxCA,IAAM,2BAAN,MAA+B;AAAA,EACrB,SAAA,uBAAgB,GAAA,EAA0B;AAAA,EAC1C,aAA6B,EAAC;AAAA,EAEtC,WAAA,GAAc;AAEZ,IAAA,IAAA,CAAK,UAAA,GAAa;AAAA,MAChB,EAAE,EAAA,EAAI,eAAA,CAAgB,MAAM,KAAA,EAAO,eAAA,EAAiB,MAAM,MAAA,EAAO;AAAA,MACjE;AAAA,QACE,IAAI,eAAA,CAAgB,QAAA;AAAA,QACpB,KAAA,EAAO,UAAA;AAAA,QACP,IAAA,EAAM;AAAA,OACR;AAAA,MACA;AAAA,QACE,IAAI,eAAA,CAAgB,aAAA;AAAA,QACpB,KAAA,EAAO,eAAA;AAAA,QACP,IAAA,EAAM;AAAA,OACR;AAAA,MACA;AAAA,QACE,IAAI,eAAA,CAAgB,IAAA;AAAA,QACpB,KAAA,EAAO,kBAAA;AAAA,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AA;AACH;AAAA;AACF;AAAA;AACF;AAAA,GACF;AAEJ;ACrVO,IAAM,OAAA,GAAUyC,iBAAA;AAAA,EACrB,SAASC,SAAQ,EAAE,EAAA,EAAI,SAAS,QAAA,EAAU,GAAG,IAAA,EAAK,EAAG,GAAA,EAAK;AACxD,IAAA,MAAM,EAAE,QAAA,EAAU,SAAA,EAAU,GAAI,gBAAA,EAAiB;AAEjD,IAAA,MAAM,WAAA,GAAc,CAAC,CAAA,KAAqC;AAExD,MAAA,OAAA,GAAU,CAAC,CAAA;AACX,MAAA,IAAI,EAAE,gBAAA,EAAkB;AAGxB,MAAA,IAAI,EAAE,OAAA,IAAW,CAAA,CAAE,WAAW,CAAA,CAAE,QAAA,IAAY,EAAE,MAAA,EAAQ;AACtD,MAAA,IAAI,CAAA,CAAE,WAAW,CAAA,EAAG;AACpB,MAAA,IAAI,IAAA,CAAK,MAAA,IAAU,IAAA,CAAK,MAAA,KAAW,OAAA,EAAS;AAE5C,MAAA,CAAA,CAAE,cAAA,EAAe;AACjB,MAAA,QAAA,CAAS,EAAE,CAAA;AAAA,IACb,CAAA;AAEA,IAAA,uBACE1C,cAAAA,CAAC,GAAA,EAAA,EAAE,GAAA,EAAU,IAAA,EAAM,SAAA,CAAU,EAAE,CAAA,EAAG,OAAA,EAAS,WAAA,EAAc,GAAG,IAAA,EACzD,QAAA,EACH,CAAA;AAAA,EAEJ;AACF","file":"index.cjs","sourcesContent":["import type { WidgetSchema } from \"./widget-schema\";\n\n/**\n * Category for organizing page templates in the registry\n */\nexport interface PageCategory {\n /** Unique identifier for the category */\n readonly id: string;\n /** Display label */\n label: string;\n /** Icon identifier (e.g., lucide icon name) */\n icon?: string;\n}\n\n/**\n * A reusable page template that can be shared across multiple navigations\n */\nexport interface PageTemplate {\n /** Unique identifier for the template */\n readonly id: string;\n /** URL-friendly slug */\n slug: string;\n /** Display name */\n name: string;\n /** Description of the template's purpose */\n description?: string;\n /** Category ID for organization */\n category: string;\n /** Tags for filtering and search */\n tags?: readonly string[];\n /** The widget tree that defines the page content */\n component_tree: readonly WidgetSchema[];\n /** Semantic version of the template */\n version: string;\n /** Whether this is a core feature that cannot be removed */\n isCore?: boolean;\n /** Default prop values that can be customized */\n defaultProps?: Readonly<Record<string, unknown>>;\n /** Thumbnail image URL for UI display */\n thumbnail?: string;\n}\n\n/**\n * Reference to a shared page template within a navigation\n */\nexport interface PageReference {\n /** ID of the page template being referenced */\n page_template_id: string;\n /** Screen ID to assign to this page in the navigation */\n screen_id: number;\n /** Optional prop overrides (only prop values, not widget structure) */\n overrides?: readonly PageOverride[];\n}\n\n/**\n * Override for a specific widget's props within a page template\n */\nexport interface PageOverride {\n /** ID of the widget to override (must match WidgetSchema.id in the template) */\n readonly widget_id: string;\n /** Props to override (merged with original props) */\n props: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Built-in page category IDs\n */\nexport const PAGE_CATEGORIES = {\n CORE: \"core\",\n COMMERCE: \"commerce\",\n COMMUNICATION: \"communication\",\n DATA: \"data\",\n CUSTOM: \"custom\",\n} as const;\n\nexport type PageCategoryId =\n (typeof PAGE_CATEGORIES)[keyof typeof PAGE_CATEGORIES];\n","import type {\n PageTemplate,\n PageCategory,\n PageCategoryId,\n} from \"../types/page-template\";\nimport { PAGE_CATEGORIES } from \"../types/page-template\";\n\n/**\n * Registry for managing reusable page templates.\n *\n * The registry provides a central store for page templates that can be\n * shared across multiple navigations. Core pages (like Messaging, Contacts)\n * are pre-registered and cannot be removed.\n *\n * @example\n * ```ts\n * // Register a custom page template\n * PageTemplateRegistry.register({\n * id: 'custom-dashboard',\n * slug: 'dashboard',\n * name: 'Custom Dashboard',\n * category: 'custom',\n * version: '1.0.0',\n * component_tree: [{ type: 'TextWidget', props: { text: 'Hello' } }],\n * });\n *\n * // Get a template by ID\n * const template = PageTemplateRegistry.get('custom-dashboard');\n *\n * // List all templates in a category\n * const corePages = PageTemplateRegistry.getByCategory('core');\n * ```\n */\nclass PageTemplateRegistryImpl {\n private templates = new Map<string, PageTemplate>();\n private categories: PageCategory[] = [];\n\n constructor() {\n // Initialize default categories\n this.categories = [\n { id: PAGE_CATEGORIES.CORE, label: \"Core Features\", icon: \"star\" },\n {\n id: PAGE_CATEGORIES.COMMERCE,\n label: \"Commerce\",\n icon: \"shopping-cart\",\n },\n {\n id: PAGE_CATEGORIES.COMMUNICATION,\n label: \"Communication\",\n icon: \"message-circle\",\n },\n {\n id: PAGE_CATEGORIES.DATA,\n label: \"Data & Analytics\",\n icon: \"bar-chart\",\n },\n { id: PAGE_CATEGORIES.CUSTOM, label: \"Custom\", icon: \"puzzle\" },\n ];\n }\n\n /**\n * Register a new page template.\n * @throws Error if a template with the same ID already exists\n */\n register(template: PageTemplate): void {\n if (this.templates.has(template.id)) {\n throw new Error(\n `Page template with ID \"${template.id}\" is already registered`,\n );\n }\n this.templates.set(template.id, template);\n }\n\n /**\n * Unregister a page template by ID.\n * Core templates cannot be unregistered.\n * @returns true if the template was removed, false if it didn't exist or is a core template\n */\n unregister(id: string): boolean {\n const template = this.templates.get(id);\n if (!template) {\n return false;\n }\n if (template.isCore) {\n console.warn(\n `Cannot unregister core page template \"${id}\". Core templates are required.`,\n );\n return false;\n }\n return this.templates.delete(id);\n }\n\n /**\n * Get a page template by ID.\n */\n get(id: string): PageTemplate | undefined {\n return this.templates.get(id);\n }\n\n /**\n * Get all page templates in a specific category.\n */\n getByCategory(category: PageCategoryId | string): PageTemplate[] {\n return Array.from(this.templates.values()).filter(\n (t) => t.category === category,\n );\n }\n\n /**\n * List all registered page templates.\n */\n listAll(): PageTemplate[] {\n return Array.from(this.templates.values());\n }\n\n /**\n * List all core page templates (isCore: true).\n */\n listCore(): PageTemplate[] {\n return Array.from(this.templates.values()).filter((t) => t.isCore);\n }\n\n /**\n * List all non-core page templates.\n */\n listOptional(): PageTemplate[] {\n return Array.from(this.templates.values()).filter((t) => !t.isCore);\n }\n\n /**\n * List all registered categories.\n */\n listCategories(): PageCategory[] {\n return [...this.categories];\n }\n\n /**\n * Add a custom category.\n */\n addCategory(category: PageCategory): void {\n if (this.categories.some((c) => c.id === category.id)) {\n console.warn(`Category with ID \"${category.id}\" already exists`);\n return;\n }\n this.categories.push(category);\n }\n\n /**\n * Check if a template exists by ID.\n */\n has(id: string): boolean {\n return this.templates.has(id);\n }\n\n /**\n * Get the count of registered templates.\n */\n get size(): number {\n return this.templates.size;\n }\n\n /**\n * Clear all non-core templates.\n * Useful for testing or resetting the registry.\n */\n clearNonCore(): void {\n for (const [id, template] of this.templates) {\n if (!template.isCore) {\n this.templates.delete(id);\n }\n }\n }\n}\n\n/**\n * Global page template registry singleton.\n *\n * This registry is automatically populated with core page templates\n * (Messaging, Contacts) when the SDK is imported.\n */\nexport const PageTemplateRegistry = new PageTemplateRegistryImpl();\n","import type { Navigation, ScreenDefinition, WidgetSchema } from \"../types\";\nimport type { PageReference, PageOverride } from \"../types/page-template\";\nimport { PageTemplateRegistry } from \"../registries/page-template-registry\";\n\n/**\n * Apply prop overrides to widgets in a component tree.\n * Recursively walks widget.props.children so overrides targeting\n * nested widgets (inside LayoutWidget, ContainerWidget, etc.) are applied.\n *\n * @param componentTree - The original component tree from the page template\n * @param overrides - Array of widget-specific prop overrides\n * @returns A new component tree with overrides applied\n */\nfunction applyOverrides(\n componentTree: readonly WidgetSchema[],\n overrides: readonly PageOverride[],\n): WidgetSchema[] {\n if (!overrides.length) {\n // Return a mutable copy to satisfy ScreenDefinition.component_tree type\n return [...componentTree];\n }\n\n // Build a map of widget_id -> override for O(1) lookup (built once, shared across recursion)\n const overrideMap = new Map(overrides.map((o) => [o.widget_id, o.props]));\n\n return componentTree.map((widget) =>\n applyWidgetOverrides(widget, overrideMap),\n );\n}\n\n/**\n * Recursively apply overrides to a widget and its children.\n * Only clones widgets that actually change (have an override or contain children that might).\n */\nfunction applyWidgetOverrides(\n widget: WidgetSchema,\n overrideMap: ReadonlyMap<string, Record<string, unknown>>,\n): WidgetSchema {\n const override = widget.id ? overrideMap.get(widget.id) : undefined;\n const children = widget.props.children;\n\n // Recurse into children if they exist (LayoutWidget, ContainerWidget)\n const hasChildren = Array.isArray(children) && children.length > 0;\n\n if (!override && !hasChildren) {\n return widget;\n }\n\n const newProps = override\n ? { ...widget.props, ...override }\n : { ...widget.props };\n\n if (hasChildren) {\n newProps.children = (children as readonly WidgetSchema[]).map((child) =>\n applyWidgetOverrides(child, overrideMap),\n );\n }\n\n return { ...widget, props: newProps };\n}\n\n/**\n * Resolve a page reference to a screen definition.\n *\n * @param ref - The page reference from navigation\n * @returns A ScreenDefinition or undefined if the template doesn't exist\n */\nfunction resolvePageReference(\n ref: Readonly<PageReference>,\n): ScreenDefinition | undefined {\n const template = PageTemplateRegistry.get(ref.page_template_id);\n if (!template) {\n console.warn(\n `Page template \"${ref.page_template_id}\" not found in registry`,\n );\n return undefined;\n }\n\n // Apply any overrides to the component tree\n // Spread to create mutable array for ScreenDefinition.component_tree\n const componentTree = ref.overrides\n ? applyOverrides(template.component_tree, ref.overrides)\n : [...template.component_tree];\n\n return {\n id: ref.screen_id,\n slug: template.slug,\n name: template.name,\n component_tree: componentTree,\n };\n}\n\n/**\n * Resolve all page references and local screens into a unified screen list.\n *\n * This function merges:\n * 1. Screen definitions from page_refs (shared templates)\n * 2. Local screen definitions (for backwards compatibility and custom screens)\n *\n * When a screen_id appears in both page_refs and screens, the local screen\n * takes precedence (allows local overrides of template pages).\n *\n * @param navigation - The navigation configuration\n * @returns A unified array of ScreenDefinition objects\n *\n * @example\n * ```ts\n * const navigation: Navigation = {\n * definition_id: 1,\n * id: 1,\n * name: \"Main Nav\",\n * navigation_items: [...],\n * screens: [\n * // Local custom screen\n * { id: 1, slug: \"home\", name: \"Home\", component_tree: [...] }\n * ],\n * page_refs: [\n * // Reference to shared messaging template\n * { page_template_id: \"core-messaging\", screen_id: 2 }\n * ],\n * };\n *\n * const allScreens = resolveNavigationPages(navigation);\n * // Returns: [home screen, messaging screen from template]\n * ```\n */\nexport function resolveNavigationPages(\n navigation: Readonly<Navigation>,\n): ScreenDefinition[] {\n // Start with local screens (these take precedence)\n const localScreenIds = new Set(navigation.screens.map((s) => s.id));\n const result: ScreenDefinition[] = [...navigation.screens];\n\n // Resolve page references (skip if local screen already exists with same ID)\n if (navigation.page_refs) {\n for (const ref of navigation.page_refs) {\n if (localScreenIds.has(ref.screen_id)) {\n // Local screen takes precedence\n continue;\n }\n\n const screen = resolvePageReference(ref);\n if (screen) {\n result.push(screen);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Get all available page templates for use in navigation.\n *\n * @returns Array of page templates from the registry\n */\nexport function getAvailablePageTemplates() {\n return PageTemplateRegistry.listAll();\n}\n\n/**\n * Get core page templates that are required for basic functionality.\n *\n * @returns Array of core page templates\n */\nexport function getCorePageTemplates() {\n return PageTemplateRegistry.listCore();\n}\n\n/**\n * Get optional page templates that can be added to navigation.\n *\n * @returns Array of optional (non-core) page templates\n */\nexport function getOptionalPageTemplates() {\n return PageTemplateRegistry.listOptional();\n}\n\n/**\n * Check if a navigation has all required core pages.\n *\n * @param navigation - The navigation to check\n * @returns Object with validation result and missing page IDs\n */\nexport function validateNavigationPages(navigation: Readonly<Navigation>): {\n readonly valid: boolean;\n readonly missingCorePages: readonly string[];\n} {\n const corePages = PageTemplateRegistry.listCore();\n const referencedTemplateIds = new Set(\n navigation.page_refs?.map((ref) => ref.page_template_id) ?? [],\n );\n\n // Check which core pages are referenced\n const missingCorePages = corePages\n .filter((page) => !referencedTemplateIds.has(page.id))\n .map((page) => page.id);\n\n return {\n valid: missingCorePages.length === 0,\n missingCorePages,\n };\n}\n","import React, {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n} from \"react\";\nimport type { PageTemplate } from \"../types/page-template\";\nimport { PageTemplateRegistry } from \"../registries/page-template-registry\";\nimport { resolveNavigationPages } from \"../core/resolve-pages\";\nimport type { Navigation, ScreenDefinition } from \"../types\";\n\n/** Stable empty array for the default `templates` prop (avoids new reference each render) */\nconst EMPTY_TEMPLATES: readonly PageTemplate[] = [];\n\n/**\n * Context value for page template resolution.\n * All properties are readonly since context values should not be mutated by consumers.\n */\ninterface PageTemplateContextValue {\n /**\n * Resolve a navigation's page_refs and screens into a unified screen list\n */\n readonly resolvePages: (navigation: Navigation) => ScreenDefinition[];\n /**\n * Get all available page templates\n */\n readonly listTemplates: () => PageTemplate[];\n /**\n * Get a specific template by ID\n */\n readonly getTemplate: (id: string) => PageTemplate | undefined;\n /**\n * Check if a template exists\n */\n readonly hasTemplate: (id: string) => boolean;\n}\n\nconst PageTemplateContext = createContext<PageTemplateContextValue | null>(\n null,\n);\n\n/**\n * Props for PageTemplateProvider\n */\ninterface PageTemplateProviderProps {\n children: React.ReactNode;\n /**\n * Additional custom page templates to register.\n * These are registered when the provider mounts and unregistered when it unmounts.\n */\n templates?: readonly PageTemplate[];\n}\n\n/**\n * Provider for page template resolution.\n *\n * This provider:\n * 1. Registers any custom templates passed via props\n * 2. Provides methods for resolving navigation pages\n * 3. Cleans up custom templates on unmount\n *\n * @example\n * ```tsx\n * // With custom templates\n * const customTemplates: PageTemplate[] = [\n * {\n * id: 'custom-dashboard',\n * slug: 'dashboard',\n * name: 'Dashboard',\n * category: 'custom',\n * version: '1.0.0',\n * component_tree: [{ type: 'TextWidget', props: { text: 'Custom Dashboard' } }],\n * },\n * ];\n *\n * <PageTemplateProvider templates={customTemplates}>\n * <App />\n * </PageTemplateProvider>\n *\n * // Without custom templates (uses only core templates)\n * <PageTemplateProvider>\n * <App />\n * </PageTemplateProvider>\n * ```\n */\nexport function PageTemplateProvider({\n children,\n templates = EMPTY_TEMPLATES,\n}: PageTemplateProviderProps) {\n // Track which templates we registered so we can clean them up\n const registeredIds = useRef<string[]>([]);\n\n // Derive a stable primitive key from template IDs\n // (rerender-dependencies rule: use primitive dependencies in effects)\n const templateKey = templates.map((t) => t.id).join(\",\");\n\n // Register custom templates when template IDs change\n useEffect(() => {\n const registered: string[] = [];\n\n for (const template of templates) {\n if (!PageTemplateRegistry.has(template.id)) {\n try {\n PageTemplateRegistry.register(template);\n registered.push(template.id);\n } catch (error) {\n console.warn(\n `Failed to register page template \"${template.id}\":`,\n error,\n );\n }\n }\n }\n\n registeredIds.current = registered;\n\n // Cleanup when template IDs change or on unmount\n return () => {\n for (const id of registeredIds.current) {\n PageTemplateRegistry.unregister(id);\n }\n registeredIds.current = [];\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [templateKey]);\n\n // Memoize context value to prevent unnecessary re-renders\n // Use `satisfies` to validate shape at compile time while preserving inference\n const contextValue = useMemo(\n () =>\n ({\n resolvePages: resolveNavigationPages,\n listTemplates: () => PageTemplateRegistry.listAll(),\n getTemplate: (id: string) => PageTemplateRegistry.get(id),\n hasTemplate: (id: string) => PageTemplateRegistry.has(id),\n }) satisfies PageTemplateContextValue,\n [],\n );\n\n return (\n <PageTemplateContext.Provider value={contextValue}>\n {children}\n </PageTemplateContext.Provider>\n );\n}\n\n/**\n * Hook to access page template functionality.\n *\n * @throws Error if used outside of PageTemplateProvider\n *\n * @example\n * ```tsx\n * function NavigationRenderer({ navigation }: { navigation: Navigation }) {\n * const { resolvePages } = usePageTemplates();\n * const screens = resolvePages(navigation);\n *\n * return (\n * <div>\n * {screens.map((screen) => (\n * <Screen key={screen.id} definition={screen} />\n * ))}\n * </div>\n * );\n * }\n * ```\n */\nexport function usePageTemplates(): PageTemplateContextValue {\n const context = useContext(PageTemplateContext);\n if (!context) {\n throw new Error(\n \"usePageTemplates must be used within a PageTemplateProvider\",\n );\n }\n return context;\n}\n\n/**\n * Hook to resolve navigation pages directly.\n * Convenience wrapper around usePageTemplates().resolvePages.\n *\n * @param navigation - The navigation to resolve\n * @returns Array of resolved screen definitions\n */\nexport function useResolvedPages(navigation: Navigation): ScreenDefinition[] {\n const { resolvePages } = usePageTemplates();\n return useMemo(() => resolvePages(navigation), [resolvePages, navigation]);\n}\n","import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { useFluidApi } from \"./use-fluid-api\";\nimport type { Profile } from \"../types/profile\";\n\n/**\n * Query key for profile data\n */\nexport const PROFILE_QUERY_KEY = [\"fluid\", \"profile\"] as const;\n\n/**\n * Hook to fetch the rep portal profile (themes, navigation, screens)\n *\n * @example\n * ```tsx\n * function Navigation() {\n * const { data: profile, isLoading } = useFluidProfile();\n *\n * if (isLoading) return <Spinner />;\n *\n * return (\n * <nav>\n * {profile?.navigation.navigation_items.map(item => (\n * <NavItem key={item.id} item={item} />\n * ))}\n * </nav>\n * );\n * }\n * ```\n */\nexport function useFluidProfile(): UseQueryResult<Profile> {\n const api = useFluidApi();\n\n return useQuery({\n queryKey: PROFILE_QUERY_KEY,\n queryFn: () => api.profile.get(),\n });\n}\n","/**\n * {@link TimeoutManager} does not support passing arguments to the callback.\n *\n * `(_: void)` is the argument type inferred by TypeScript's default typings for\n * `setTimeout(cb, number)`.\n * If we don't accept a single void argument, then\n * `new Promise(resolve => timeoutManager.setTimeout(resolve, N))` is a type error.\n */\nexport type TimeoutCallback = (_: void) => void\n\n/**\n * Wrapping `setTimeout` is awkward from a typing perspective because platform\n * typings may extend the return type of `setTimeout`. For example, NodeJS\n * typings add `NodeJS.Timeout`; but a non-default `timeoutManager` may not be\n * able to return such a type.\n */\nexport type ManagedTimerId = number | { [Symbol.toPrimitive]: () => number }\n\n/**\n * Backend for timer functions.\n */\nexport type TimeoutProvider<TTimerId extends ManagedTimerId = ManagedTimerId> =\n {\n readonly setTimeout: (callback: TimeoutCallback, delay: number) => TTimerId\n readonly clearTimeout: (timeoutId: TTimerId | undefined) => void\n\n readonly setInterval: (callback: TimeoutCallback, delay: number) => TTimerId\n readonly clearInterval: (intervalId: TTimerId | undefined) => void\n }\n\nexport const defaultTimeoutProvider: TimeoutProvider<\n ReturnType<typeof setTimeout>\n> = {\n // We need the wrapper function syntax below instead of direct references to\n // global setTimeout etc.\n //\n // BAD: `setTimeout: setTimeout`\n // GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)`\n //\n // If we use direct references here, then anything that wants to spy on or\n // replace the global setTimeout (like tests) won't work since we'll already\n // have a hard reference to the original implementation at the time when this\n // file was imported.\n setTimeout: (callback, delay) => setTimeout(callback, delay),\n clearTimeout: (timeoutId) => clearTimeout(timeoutId),\n\n setInterval: (callback, delay) => setInterval(callback, delay),\n clearInterval: (intervalId) => clearInterval(intervalId),\n}\n\n/**\n * Allows customization of how timeouts are created.\n *\n * @tanstack/query-core makes liberal use of timeouts to implement `staleTime`\n * and `gcTime`. The default TimeoutManager provider uses the platform's global\n * `setTimeout` implementation, which is known to have scalability issues with\n * thousands of timeouts on the event loop.\n *\n * If you hit this limitation, consider providing a custom TimeoutProvider that\n * coalesces timeouts.\n */\nexport class TimeoutManager implements Omit<TimeoutProvider, 'name'> {\n // We cannot have TimeoutManager<T> as we must instantiate it with a concrete\n // type at app boot; and if we leave that type, then any new timer provider\n // would need to support ReturnType<typeof setTimeout>, which is infeasible.\n //\n // We settle for type safety for the TimeoutProvider type, and accept that\n // this class is unsafe internally to allow for extension.\n #provider: TimeoutProvider<any> = defaultTimeoutProvider\n #providerCalled = false\n\n setTimeoutProvider<TTimerId extends ManagedTimerId>(\n provider: TimeoutProvider<TTimerId>,\n ): void {\n if (process.env.NODE_ENV !== 'production') {\n if (this.#providerCalled && provider !== this.#provider) {\n // After changing providers, `clearTimeout` will not work as expected for\n // timeouts from the previous provider.\n //\n // Since they may allocate the same timeout ID, clearTimeout may cancel an\n // arbitrary different timeout, or unexpected no-op.\n //\n // We could protect against this by mixing the timeout ID bits\n // deterministically with some per-provider bits.\n //\n // We could internally queue `setTimeout` calls to `TimeoutManager` until\n // some API call to set the initial provider.\n console.error(\n `[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`,\n { previous: this.#provider, provider },\n )\n }\n }\n\n this.#provider = provider\n if (process.env.NODE_ENV !== 'production') {\n this.#providerCalled = false\n }\n }\n\n setTimeout(callback: TimeoutCallback, delay: number): ManagedTimerId {\n if (process.env.NODE_ENV !== 'production') {\n this.#providerCalled = true\n }\n return this.#provider.setTimeout(callback, delay)\n }\n\n clearTimeout(timeoutId: ManagedTimerId | undefined): void {\n this.#provider.clearTimeout(timeoutId)\n }\n\n setInterval(callback: TimeoutCallback, delay: number): ManagedTimerId {\n if (process.env.NODE_ENV !== 'production') {\n this.#providerCalled = true\n }\n return this.#provider.setInterval(callback, delay)\n }\n\n clearInterval(intervalId: ManagedTimerId | undefined): void {\n this.#provider.clearInterval(intervalId)\n }\n}\n\nexport const timeoutManager = new TimeoutManager()\n\n/**\n * In many cases code wants to delay to the next event loop tick; this is not\n * mediated by {@link timeoutManager}.\n *\n * This function is provided to make auditing the `tanstack/query-core` for\n * incorrect use of system `setTimeout` easier.\n */\nexport function systemSetTimeoutZero(callback: TimeoutCallback): void {\n setTimeout(callback, 0)\n}\n","import { timeoutManager } from './timeoutManager'\nimport type {\n DefaultError,\n Enabled,\n FetchStatus,\n MutationKey,\n MutationStatus,\n QueryFunction,\n QueryKey,\n QueryOptions,\n StaleTime,\n StaleTimeFunction,\n} from './types'\nimport type { Mutation } from './mutation'\nimport type { FetchOptions, Query } from './query'\n\n// TYPES\n\ntype DropLast<T extends ReadonlyArray<unknown>> = T extends readonly [\n ...infer R,\n unknown,\n]\n ? readonly [...R]\n : never\n\ntype TuplePrefixes<T extends ReadonlyArray<unknown>> = T extends readonly []\n ? readonly []\n : TuplePrefixes<DropLast<T>> | T\n\nexport interface QueryFilters<TQueryKey extends QueryKey = QueryKey> {\n /**\n * Filter to active queries, inactive queries or all queries\n */\n type?: QueryTypeFilter\n /**\n * Match query key exactly\n */\n exact?: boolean\n /**\n * Include queries matching this predicate function\n */\n predicate?: (query: Query) => boolean\n /**\n * Include queries matching this query key\n */\n queryKey?: TQueryKey | TuplePrefixes<TQueryKey>\n /**\n * Include or exclude stale queries\n */\n stale?: boolean\n /**\n * Include queries matching their fetchStatus\n */\n fetchStatus?: FetchStatus\n}\n\nexport interface MutationFilters<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> {\n /**\n * Match mutation key exactly\n */\n exact?: boolean\n /**\n * Include mutations matching this predicate function\n */\n predicate?: (\n mutation: Mutation<TData, TError, TVariables, TOnMutateResult>,\n ) => boolean\n /**\n * Include mutations matching this mutation key\n */\n mutationKey?: TuplePrefixes<MutationKey>\n /**\n * Filter by mutation status\n */\n status?: MutationStatus\n}\n\nexport type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)\n\nexport type QueryTypeFilter = 'all' | 'active' | 'inactive'\n\n// UTILS\n\nexport const isServer = typeof window === 'undefined' || 'Deno' in globalThis\n\nexport function noop(): void\nexport function noop(): undefined\nexport function noop() {}\n\nexport function functionalUpdate<TInput, TOutput>(\n updater: Updater<TInput, TOutput>,\n input: TInput,\n): TOutput {\n return typeof updater === 'function'\n ? (updater as (_: TInput) => TOutput)(input)\n : updater\n}\n\nexport function isValidTimeout(value: unknown): value is number {\n return typeof value === 'number' && value >= 0 && value !== Infinity\n}\n\nexport function timeUntilStale(updatedAt: number, staleTime?: number): number {\n return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)\n}\n\nexport function resolveStaleTime<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n staleTime:\n | undefined\n | StaleTimeFunction<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): StaleTime | undefined {\n return typeof staleTime === 'function' ? staleTime(query) : staleTime\n}\n\nexport function resolveEnabled<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n enabled: undefined | Enabled<TQueryFnData, TError, TData, TQueryKey>,\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): boolean | undefined {\n return typeof enabled === 'function' ? enabled(query) : enabled\n}\n\nexport function matchQuery(\n filters: QueryFilters,\n query: Query<any, any, any, any>,\n): boolean {\n const {\n type = 'all',\n exact,\n fetchStatus,\n predicate,\n queryKey,\n stale,\n } = filters\n\n if (queryKey) {\n if (exact) {\n if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {\n return false\n }\n } else if (!partialMatchKey(query.queryKey, queryKey)) {\n return false\n }\n }\n\n if (type !== 'all') {\n const isActive = query.isActive()\n if (type === 'active' && !isActive) {\n return false\n }\n if (type === 'inactive' && isActive) {\n return false\n }\n }\n\n if (typeof stale === 'boolean' && query.isStale() !== stale) {\n return false\n }\n\n if (fetchStatus && fetchStatus !== query.state.fetchStatus) {\n return false\n }\n\n if (predicate && !predicate(query)) {\n return false\n }\n\n return true\n}\n\nexport function matchMutation(\n filters: MutationFilters,\n mutation: Mutation<any, any>,\n): boolean {\n const { exact, status, predicate, mutationKey } = filters\n if (mutationKey) {\n if (!mutation.options.mutationKey) {\n return false\n }\n if (exact) {\n if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {\n return false\n }\n } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {\n return false\n }\n }\n\n if (status && mutation.state.status !== status) {\n return false\n }\n\n if (predicate && !predicate(mutation)) {\n return false\n }\n\n return true\n}\n\nexport function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(\n queryKey: TQueryKey,\n options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,\n): string {\n const hashFn = options?.queryKeyHashFn || hashKey\n return hashFn(queryKey)\n}\n\n/**\n * Default query & mutation keys hash function.\n * Hashes the value into a stable hash.\n */\nexport function hashKey(queryKey: QueryKey | MutationKey): string {\n return JSON.stringify(queryKey, (_, val) =>\n isPlainObject(val)\n ? Object.keys(val)\n .sort()\n .reduce((result, key) => {\n result[key] = val[key]\n return result\n }, {} as any)\n : val,\n )\n}\n\n/**\n * Checks if key `b` partially matches with key `a`.\n */\nexport function partialMatchKey(a: QueryKey, b: QueryKey): boolean\nexport function partialMatchKey(a: any, b: any): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n return Object.keys(b).every((key) => partialMatchKey(a[key], b[key]))\n }\n\n return false\n}\n\nconst hasOwn = Object.prototype.hasOwnProperty\n\n/**\n * This function returns `a` if `b` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between JSON values for example.\n */\nexport function replaceEqualDeep<T>(a: unknown, b: T): T\nexport function replaceEqualDeep(a: any, b: any): any {\n if (a === b) {\n return a\n }\n\n const array = isPlainArray(a) && isPlainArray(b)\n\n if (!array && !(isPlainObject(a) && isPlainObject(b))) return b\n\n const aItems = array ? a : Object.keys(a)\n const aSize = aItems.length\n const bItems = array ? b : Object.keys(b)\n const bSize = bItems.length\n const copy: any = array ? new Array(bSize) : {}\n\n let equalItems = 0\n\n for (let i = 0; i < bSize; i++) {\n const key: any = array ? i : bItems[i]\n const aItem = a[key]\n const bItem = b[key]\n\n if (aItem === bItem) {\n copy[key] = aItem\n if (array ? i < aSize : hasOwn.call(a, key)) equalItems++\n continue\n }\n\n if (\n aItem === null ||\n bItem === null ||\n typeof aItem !== 'object' ||\n typeof bItem !== 'object'\n ) {\n copy[key] = bItem\n continue\n }\n\n const v = replaceEqualDeep(aItem, bItem)\n copy[key] = v\n if (v === aItem) equalItems++\n }\n\n return aSize === bSize && equalItems === aSize ? a : copy\n}\n\n/**\n * Shallow compare objects.\n */\nexport function shallowEqualObjects<T extends Record<string, any>>(\n a: T,\n b: T | undefined,\n): boolean {\n if (!b || Object.keys(a).length !== Object.keys(b).length) {\n return false\n }\n\n for (const key in a) {\n if (a[key] !== b[key]) {\n return false\n }\n }\n\n return true\n}\n\nexport function isPlainArray(value: unknown): value is Array<unknown> {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\nexport function isPlainObject(o: any): o is Record<PropertyKey, unknown> {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has no constructor\n const ctor = o.constructor\n if (ctor === undefined) {\n return true\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Handles Objects created by Object.create(<arbitrary prototype>)\n if (Object.getPrototypeOf(o) !== Object.prototype) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\nfunction hasObjectPrototype(o: any): boolean {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\nexport function sleep(timeout: number): Promise<void> {\n return new Promise((resolve) => {\n timeoutManager.setTimeout(resolve, timeout)\n })\n}\n\nexport function replaceData<\n TData,\n TOptions extends QueryOptions<any, any, any, any>,\n>(prevData: TData | undefined, data: TData, options: TOptions): TData {\n if (typeof options.structuralSharing === 'function') {\n return options.structuralSharing(prevData, data) as TData\n } else if (options.structuralSharing !== false) {\n if (process.env.NODE_ENV !== 'production') {\n try {\n return replaceEqualDeep(prevData, data)\n } catch (error) {\n console.error(\n `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`,\n )\n\n // Prevent the replaceEqualDeep from being called again down below.\n throw error\n }\n }\n // Structurally share data between prev and new data if needed\n return replaceEqualDeep(prevData, data)\n }\n return data\n}\n\nexport function keepPreviousData<T>(\n previousData: T | undefined,\n): T | undefined {\n return previousData\n}\n\nexport function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [...items, item]\n return max && newItems.length > max ? newItems.slice(1) : newItems\n}\n\nexport function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [item, ...items]\n return max && newItems.length > max ? newItems.slice(0, -1) : newItems\n}\n\nexport const skipToken = Symbol()\nexport type SkipToken = typeof skipToken\n\nexport function ensureQueryFn<\n TQueryFnData = unknown,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: {\n queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken\n queryHash?: string\n },\n fetchOptions?: FetchOptions<TQueryFnData>,\n): QueryFunction<TQueryFnData, TQueryKey> {\n if (process.env.NODE_ENV !== 'production') {\n if (options.queryFn === skipToken) {\n console.error(\n `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,\n )\n }\n }\n\n // if we attempt to retry a fetch that was triggered from an initialPromise\n // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise\n // if an observer has already mounted, we will be able to retry with that queryFn\n if (!options.queryFn && fetchOptions?.initialPromise) {\n return () => fetchOptions.initialPromise!\n }\n\n if (!options.queryFn || options.queryFn === skipToken) {\n return () =>\n Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))\n }\n\n return options.queryFn\n}\n\nexport function shouldThrowError<T extends (...args: Array<any>) => boolean>(\n throwOnError: boolean | T | undefined,\n params: Parameters<T>,\n): boolean {\n // Allow throwOnError function to override throwing behavior on a per-error basis\n if (typeof throwOnError === 'function') {\n return throwOnError(...params)\n }\n\n return !!throwOnError\n}\n","// TYPES\n\nimport { systemSetTimeoutZero } from './timeoutManager'\n\ntype NotifyCallback = () => void\n\ntype NotifyFunction = (callback: () => void) => void\n\ntype BatchNotifyFunction = (callback: () => void) => void\n\ntype BatchCallsCallback<T extends Array<unknown>> = (...args: T) => void\n\ntype ScheduleFunction = (callback: () => void) => void\n\nexport const defaultScheduler: ScheduleFunction = systemSetTimeoutZero\n\nexport function createNotifyManager() {\n let queue: Array<NotifyCallback> = []\n let transactions = 0\n let notifyFn: NotifyFunction = (callback) => {\n callback()\n }\n let batchNotifyFn: BatchNotifyFunction = (callback: () => void) => {\n callback()\n }\n let scheduleFn = defaultScheduler\n\n const schedule = (callback: NotifyCallback): void => {\n if (transactions) {\n queue.push(callback)\n } else {\n scheduleFn(() => {\n notifyFn(callback)\n })\n }\n }\n const flush = (): void => {\n const originalQueue = queue\n queue = []\n if (originalQueue.length) {\n scheduleFn(() => {\n batchNotifyFn(() => {\n originalQueue.forEach((callback) => {\n notifyFn(callback)\n })\n })\n })\n }\n }\n\n return {\n batch: <T>(callback: () => T): T => {\n let result\n transactions++\n try {\n result = callback()\n } finally {\n transactions--\n if (!transactions) {\n flush()\n }\n }\n return result\n },\n /**\n * All calls to the wrapped function will be batched.\n */\n batchCalls: <T extends Array<unknown>>(\n callback: BatchCallsCallback<T>,\n ): BatchCallsCallback<T> => {\n return (...args) => {\n schedule(() => {\n callback(...args)\n })\n }\n },\n schedule,\n /**\n * Use this method to set a custom notify function.\n * This can be used to for example wrap notifications with `React.act` while running tests.\n */\n setNotifyFunction: (fn: NotifyFunction) => {\n notifyFn = fn\n },\n /**\n * Use this method to set a custom function to batch notifications together into a single tick.\n * By default React Query will use the batch function provided by ReactDOM or React Native.\n */\n setBatchNotifyFunction: (fn: BatchNotifyFunction) => {\n batchNotifyFn = fn\n },\n setScheduler: (fn: ScheduleFunction) => {\n scheduleFn = fn\n },\n } as const\n}\n\n// SINGLETON\nexport const notifyManager = createNotifyManager()\n","import {\n hashKey,\n matchQuery,\n notifyManager,\n partialMatchKey,\n} from '@tanstack/query-core'\nimport type {\n Query,\n QueryClient,\n QueryFilters,\n QueryFunctionContext,\n QueryKey,\n QueryState,\n} from '@tanstack/query-core'\n\nexport interface PersistedQuery {\n buster: string\n queryHash: string\n queryKey: QueryKey\n state: QueryState\n}\n\nexport type MaybePromise<T> = T | Promise<T>\n\nexport interface AsyncStorage<TStorageValue = string> {\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n removeItem: (key: string) => MaybePromise<void>\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /** The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage<TStorageValue> | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>\n /**\n * A unique string that can be used to forcefully invalidate existing caches,\n * if they do not share the same buster string\n */\n buster?: string\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n * @default 24 hours\n */\n maxAge?: number\n /**\n * Prefix to be used for storage key.\n * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.\n * @default 'tanstack-query'\n */\n prefix?: string\n /**\n * If set to `true`, the query will refetch on successful query restoration if the data is stale.\n * If set to `false`, the query will not refetch on successful query restoration.\n * If set to `'always'`, the query will always refetch on successful query restoration.\n * Defaults to `true`.\n */\n refetchOnRestore?: boolean | 'always'\n /**\n * Filters to narrow down which Queries should be persisted.\n */\n filters?: QueryFilters\n}\n\nexport const PERSISTER_KEY_PREFIX = 'tanstack-query'\n\n/**\n * Warning: experimental feature.\n * This utility function enables fine-grained query persistence.\n * Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.\n *\n * ```\n * useQuery({\n queryKey: ['myKey'],\n queryFn: fetcher,\n persister: createPersister({\n storage: localStorage,\n }),\n })\n ```\n */\nexport function experimental_createQueryPersister<TStorageValue = string>({\n storage,\n buster = '',\n maxAge = 1000 * 60 * 60 * 24,\n serialize = JSON.stringify as Required<\n StoragePersisterOptions<TStorageValue>\n >['serialize'],\n deserialize = JSON.parse as Required<\n StoragePersisterOptions<TStorageValue>\n >['deserialize'],\n prefix = PERSISTER_KEY_PREFIX,\n refetchOnRestore = true,\n filters,\n}: StoragePersisterOptions<TStorageValue>) {\n function isExpiredOrBusted(persistedQuery: PersistedQuery) {\n if (persistedQuery.state.dataUpdatedAt) {\n const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt\n const expired = queryAge > maxAge\n const busted = persistedQuery.buster !== buster\n\n if (expired || busted) {\n return true\n }\n\n return false\n }\n\n return true\n }\n\n async function retrieveQuery<T>(\n queryHash: string,\n afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,\n ) {\n if (storage != null) {\n const storageKey = `${prefix}-${queryHash}`\n try {\n const storedData = await storage.getItem(storageKey)\n if (storedData) {\n const persistedQuery = await deserialize(storedData)\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(storageKey)\n } else {\n if (afterRestoreMacroTask) {\n // Just after restoring we want to get fresh data from the server if it's stale\n notifyManager.schedule(() =>\n afterRestoreMacroTask(persistedQuery),\n )\n }\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return persistedQuery.state.data as T\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV === 'development') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore query cache from persisted location.',\n )\n }\n await storage.removeItem(storageKey)\n }\n }\n\n return\n }\n\n async function persistQueryByKey(\n queryKey: QueryKey,\n queryClient: QueryClient,\n ) {\n if (storage != null) {\n const query = queryClient.getQueryCache().find({ queryKey })\n if (query) {\n await persistQuery(query)\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Could not find query to be persisted. QueryKey:',\n JSON.stringify(queryKey),\n )\n }\n }\n }\n }\n\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n storage.setItem(\n storageKey,\n await serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }\n }\n\n async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n ctx: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const matchesFilter = filters ? matchQuery(filters, query) : true\n\n // Try to restore only if we do not have any data in the cache and we have persister defined\n if (matchesFilter && query.state.data === undefined && storage != null) {\n const restoredData = await retrieveQuery(\n query.queryHash,\n (persistedQuery: PersistedQuery) => {\n // Set proper updatedAt, since resolving in the first pass overrides those values\n query.setState({\n dataUpdatedAt: persistedQuery.state.dataUpdatedAt,\n errorUpdatedAt: persistedQuery.state.errorUpdatedAt,\n })\n\n if (\n refetchOnRestore === 'always' ||\n (refetchOnRestore === true && query.isStale())\n ) {\n query.fetch()\n }\n },\n )\n\n if (restoredData !== undefined) {\n return Promise.resolve(restoredData as T)\n }\n }\n\n // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(ctx)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n notifyManager.schedule(() => {\n persistQuery(query)\n })\n }\n\n return Promise.resolve(queryFnResult)\n }\n\n async function persisterGc() {\n if (storage?.entries) {\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(prefix)) {\n const persistedQuery = await deserialize(value)\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n }\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n async function restoreQueries(\n queryClient: QueryClient,\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(prefix)) {\n const persistedQuery = await deserialize(value)\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n continue\n }\n\n if (queryKey) {\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n }\n\n queryClient.setQueryData(\n persistedQuery.queryKey,\n persistedQuery.state.data,\n {\n updatedAt: persistedQuery.state.dataUpdatedAt,\n },\n )\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n return {\n persisterFn,\n persistQuery,\n persistQueryByKey,\n retrieveQuery,\n persisterGc,\n restoreQueries,\n }\n}\n","import {\n type AsyncStorage,\n experimental_createQueryPersister,\n type PersistedQuery,\n} from \"@tanstack/react-query-persist-client\";\n\nconst DB_NAME = \"fluid_tanstack_query_cache\";\nconst STORE_NAME = \"fluid_queries\";\nconst VERSION = 1;\n\nlet dbPromise: Promise<IDBDatabase> | null = null;\n\n// Exported for testing - allows resetting internal state between tests\nexport function _resetForTesting(): void {\n dbPromise = null;\n}\n\nexport async function deleteDatabase(): Promise<void> {\n return new Promise((resolve, reject) => {\n console.warn(\"[IDB] Deleting database due to error\");\n const req = indexedDB.deleteDatabase(DB_NAME);\n req.onsuccess = () => {\n console.log(\"[IDB] Database deleted successfully\");\n resolve();\n };\n req.onerror = () => {\n console.error(\"[IDB] Failed to delete database:\", req.error);\n reject(req.error ?? new Error(\"deleteDatabase failed\"));\n };\n req.onblocked = () => {\n console.warn(\"[IDB] Delete blocked: close all tabs using this database\");\n };\n });\n}\n\nfunction openDatabase(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const req = indexedDB.open(DB_NAME, VERSION);\n\n req.onupgradeneeded = () => {\n const upgradeDb = req.result;\n if (!upgradeDb.objectStoreNames.contains(STORE_NAME)) {\n upgradeDb.createObjectStore(STORE_NAME);\n }\n };\n\n req.onsuccess = () => {\n const conn = req.result;\n conn.onversionchange = () => {\n console.trace(\"[IDB] version change – closing connection\");\n conn.close();\n // clear the cached promise so the next getDb call re-opens a connection\n dbPromise = null;\n };\n resolve(conn);\n };\n\n req.onblocked = () => {\n console.warn(\"[IDB] open blocked: another connection is holding the DB\");\n };\n\n req.onerror = () => {\n reject(\n req.error instanceof Error\n ? req.error\n : new Error(`IndexedDB open failed: ${String(req.error)}`),\n );\n };\n });\n}\n\nasync function getDbWithRecovery(): Promise<IDBDatabase> {\n try {\n return await openDatabase();\n } catch (err) {\n // First open failed - try to delete and recreate\n console.warn(\"[IDB] Initial open failed, attempting recovery:\", err);\n try {\n await deleteDatabase();\n console.log(\"[IDB] Retrying database open after deletion\");\n return await openDatabase();\n } catch (retryErr) {\n console.error(\"[IDB] Recovery failed:\", retryErr);\n throw retryErr;\n }\n }\n}\n\nfunction getDb(): Promise<IDBDatabase> {\n if (dbPromise) return dbPromise;\n\n // Create the promise and cache it immediately to prevent race conditions\n // All concurrent calls will share this same promise\n dbPromise = getDbWithRecovery().catch((err) => {\n // On failure, clear the cache so next call can retry fresh\n dbPromise = null;\n throw err;\n });\n\n return dbPromise;\n}\n\n// Exported for testing - allows direct testing of storage operations\nexport const storage: AsyncStorage<PersistedQuery> = {\n async getItem(key: string) {\n try {\n const db = await getDb();\n return new Promise<PersistedQuery | undefined>((res) => {\n try {\n const r = db\n .transaction(STORE_NAME, \"readonly\")\n .objectStore(STORE_NAME)\n .get(key);\n r.onsuccess = () => res(r.result as PersistedQuery);\n r.onerror = () => {\n console.trace(\"[IDB] getItem error:\", r.error);\n res(undefined);\n };\n } catch (txErr) {\n // Transaction creation failed (e.g., stale connection)\n console.trace(\"[IDB] getItem transaction error:\", txErr);\n res(undefined);\n }\n });\n } catch (err) {\n // getDb() failed - try to recover with a fresh connection\n console.trace(\"[IDB] getItem getDb error:\", err);\n try {\n const db = await getDb();\n // Use fresh connection directly - getDb() already handles recovery\n return new Promise<PersistedQuery | undefined>((res) => {\n try {\n const r = db\n .transaction(STORE_NAME, \"readonly\")\n .objectStore(STORE_NAME)\n .get(key);\n r.onsuccess = () => res(r.result as PersistedQuery);\n r.onerror = () => {\n console.trace(\"[IDB] getItem retry error:\", r.error);\n res(undefined);\n };\n } catch (txErr) {\n console.trace(\"[IDB] getItem retry transaction error:\", txErr);\n res(undefined);\n }\n });\n } catch (recoveryErr) {\n console.trace(\"[IDB] getItem recovery failed:\", recoveryErr);\n }\n return undefined;\n }\n },\n\n async setItem(key: string, value: PersistedQuery) {\n // JSON round-trip strips non-cloneable properties (functions, class instances)\n // before IndexedDB's structured clone algorithm runs. Without this, IDB\n // throws DataCloneError. Theme Color objects are now kept out of the cache\n // via the select pattern, but other queries may still have non-cloneable data.\n const cloneableValue = JSON.parse(JSON.stringify(value));\n try {\n const db = await getDb();\n if (!db) return;\n await new Promise<void>((resolve) => {\n try {\n const req = db\n .transaction(STORE_NAME, \"readwrite\")\n .objectStore(STORE_NAME)\n .put(cloneableValue, key);\n req.onsuccess = () => resolve();\n req.onerror = () => {\n console.trace(\"[IDB] setItem error:\", req.error);\n resolve();\n };\n } catch (txErr) {\n console.trace(\"[IDB] setItem transaction error:\", txErr);\n resolve();\n }\n });\n } catch (err) {\n // getDb() failed - try to recover with a fresh connection\n console.trace(\"[IDB] setItem getDb error:\", err);\n try {\n const db = await getDb();\n // Use fresh connection directly - getDb() already handles recovery\n await new Promise<void>((resolve) => {\n try {\n const req = db\n .transaction(STORE_NAME, \"readwrite\")\n .objectStore(STORE_NAME)\n .put(cloneableValue, key);\n req.onsuccess = () => resolve();\n req.onerror = () => {\n console.trace(\"[IDB] setItem retry error:\", req.error);\n resolve();\n };\n } catch (txErr) {\n console.trace(\"[IDB] setItem retry transaction error:\", txErr);\n resolve();\n }\n });\n } catch (recoveryErr) {\n console.trace(\"[IDB] setItem recovery failed:\", recoveryErr);\n }\n }\n },\n\n async removeItem(key: string) {\n try {\n const db = await getDb();\n if (!db) return;\n await new Promise<void>((resolve) => {\n try {\n const req = db\n .transaction(STORE_NAME, \"readwrite\")\n .objectStore(STORE_NAME)\n .delete(key);\n req.onsuccess = () => resolve();\n req.onerror = () => {\n console.trace(\"[IDB] removeItem error:\", req.error);\n resolve();\n };\n } catch (txErr) {\n console.trace(\"[IDB] removeItem transaction error:\", txErr);\n resolve();\n }\n });\n } catch (err) {\n // getDb() failed - try to recover with a fresh connection\n console.trace(\"[IDB] removeItem getDb error:\", err);\n try {\n const db = await getDb();\n // Use fresh connection directly - getDb() already handles recovery\n await new Promise<void>((resolve) => {\n try {\n const req = db\n .transaction(STORE_NAME, \"readwrite\")\n .objectStore(STORE_NAME)\n .delete(key);\n req.onsuccess = () => resolve();\n req.onerror = () => {\n console.trace(\"[IDB] removeItem retry error:\", req.error);\n resolve();\n };\n } catch (txErr) {\n console.trace(\"[IDB] removeItem retry transaction error:\", txErr);\n resolve();\n }\n });\n } catch (recoveryErr) {\n console.trace(\"[IDB] removeItem recovery failed:\", recoveryErr);\n }\n }\n },\n};\n\n// Factory function to create persister - only call this client-side\nexport function createPersister(): ReturnType<\n typeof experimental_createQueryPersister\n> {\n return experimental_createQueryPersister<PersistedQuery>({\n storage,\n serialize: (persistedQuery) => persistedQuery,\n deserialize: (cached) => cached,\n });\n}\n","import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { createPersister } from \"@fluid-app/query-persister\";\nimport { useFluidApi } from \"./use-fluid-api\";\nimport { transformManifestToRepAppData } from \"../transforms\";\nimport type { RawManifestResponse } from \"../transforms\";\nimport type { RepAppData } from \"@fluid-app/rep-core/types\";\n\n/**\n * Query key for full app data (fluidos endpoint)\n */\nexport const APP_DATA_QUERY_KEY = [\"fluid\", \"app\"] as const;\n\n/**\n * Module-level persister instance (browser only).\n * Created once when the module loads so all calls to useFluidApp share\n * the same IndexedDB connection. Applied at the query level so it works\n * regardless of which QueryClient the app provides.\n */\nconst appDataPersister =\n typeof window !== \"undefined\" ? createPersister() : undefined;\n\n/**\n * Hook to fetch the full rep app data from the fluidos API.\n *\n * Returns a `RepAppData` object containing:\n * - `screens` — all screen definitions with normalized component trees\n * - `profile.themes` — fully-transformed ThemeDefinition[] (handles legacy + new formats)\n * - `profile.activeThemeId` — the currently active theme ID\n * - `profile.navigation.navigation_items` — sorted, recursive navigation tree\n *\n * Uses IndexedDB persistence so subsequent page loads hydrate instantly\n * from cache while revalidating in the background. The raw API response\n * (plain JSON) is cached; Color objects are recreated from cache via\n * `select` on every restore — this is fast (CPU only, no network).\n *\n * @example\n * ```tsx\n * function App() {\n * const { data: appData, isLoading } = useFluidApp();\n *\n * if (isLoading) return <Spinner />;\n *\n * return (\n * <AppShell\n * appData={appData}\n * navigation={appData.profile.navigation.navigation_items}\n * />\n * );\n * }\n * ```\n */\nexport function useFluidApp(options?: {\n enabled?: boolean;\n}): UseQueryResult<RepAppData> {\n const api = useFluidApi();\n\n return useQuery<\n RawManifestResponse,\n Error,\n RepAppData,\n typeof APP_DATA_QUERY_KEY\n >({\n queryKey: APP_DATA_QUERY_KEY,\n queryFn: () => api.app.getRaw(),\n select: transformManifestToRepAppData,\n ...(appDataPersister && { persister: appDataPersister.persisterFn }),\n ...(options?.enabled !== undefined && { enabled: options.enabled }),\n });\n}\n","import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { useMemo } from \"react\";\nimport { useFluidApi } from \"./use-fluid-api\";\nimport type { UserPermissions, PermissionAction } from \"../types/permissions\";\n\n/**\n * Query key for permissions data\n */\nexport const PERMISSIONS_QUERY_KEY = [\"fluid\", \"permissions\"] as const;\n\n/**\n * Result of useFluidPermissions hook\n */\nexport interface UseFluidPermissionsResult {\n /** Raw permissions query result */\n query: UseQueryResult<UserPermissions>;\n /** Permissions data (alias for query.data) */\n permissions: UserPermissions | undefined;\n /** Check if user has a specific permission */\n can: (resource: string, action?: PermissionAction) => boolean;\n /** Check if user is a super admin */\n isSuperAdmin: boolean;\n}\n\n/**\n * Hook to fetch and check user permissions\n *\n * @example\n * ```tsx\n * function TeamSettings() {\n * const { can, isSuperAdmin } = useFluidPermissions();\n *\n * if (!can(\"team\", \"manage\")) {\n * return <AccessDenied />;\n * }\n *\n * return <TeamSettingsForm canDelete={can(\"team\", \"delete\")} />;\n * }\n * ```\n */\nexport function useFluidPermissions(): UseFluidPermissionsResult {\n const api = useFluidApi();\n\n const query = useQuery({\n queryKey: PERMISSIONS_QUERY_KEY,\n queryFn: () => api.permissions.get(),\n });\n\n const permissions = query.data;\n\n // Memoize the can function to maintain referential stability\n const can = useMemo(() => {\n return (resource: string, action: PermissionAction = \"view\"): boolean => {\n if (!permissions) {\n return false;\n }\n\n // Super admins have all permissions\n if (permissions.is_super_admin) {\n return true;\n }\n\n const resourcePermissions = permissions.permissions[resource];\n if (!resourcePermissions) {\n return false;\n }\n\n return resourcePermissions[action] ?? false;\n };\n }, [permissions]);\n\n const isSuperAdmin = permissions?.is_super_admin ?? false;\n\n return {\n query,\n permissions,\n can,\n isSuperAdmin,\n };\n}\n","import { useThemeContext } from \"../providers/FluidThemeProvider\";\nimport type { ThemeDefinition } from \"../types/theme\";\n\n/**\n * Result of useFluidTheme hook\n */\nexport interface UseFluidThemeResult {\n /** Currently active theme */\n currentTheme: ThemeDefinition | null;\n /** Switch to a different theme */\n setTheme: (theme: ThemeDefinition) => void;\n /** Switch between light and dark mode */\n setThemeMode: (mode: \"light\" | \"dark\") => void;\n /** Current theme mode (convenience accessor) */\n mode: \"light\" | \"dark\" | undefined;\n}\n\n/**\n * Hook to access and control theme settings\n *\n * @example\n * ```tsx\n * function ThemeSwitcher({ themes }: { themes: ThemeDefinition[] }) {\n * const { currentTheme, setTheme, setThemeMode, mode } = useFluidTheme();\n *\n * return (\n * <div>\n * <select\n * value={currentTheme?.name}\n * onChange={(e) => {\n * const theme = themes.find(t => t.name === e.target.value);\n * if (theme) setTheme(theme);\n * }}\n * >\n * {themes.map(theme => (\n * <option key={theme.name} value={theme.name}>\n * {theme.name}\n * </option>\n * ))}\n * </select>\n *\n * <button onClick={() => setThemeMode(mode === \"dark\" ? \"light\" : \"dark\")}>\n * Toggle {mode === \"dark\" ? \"Light\" : \"Dark\"} Mode\n * </button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useFluidTheme(): UseFluidThemeResult {\n const { currentTheme, setTheme, setThemeMode, mode } = useThemeContext();\n\n return {\n currentTheme,\n setTheme,\n setThemeMode,\n mode,\n };\n}\n","import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { useFluidApi } from \"./use-fluid-api\";\nimport type { Rep } from \"../types/rep\";\n\n/**\n * Query key for current rep data\n */\nexport const CURRENT_REP_QUERY_KEY = [\"fluid\", \"currentRep\"] as const;\n\n/**\n * Hook to fetch the currently authenticated rep's profile\n *\n * @example\n * ```tsx\n * function RepHeader() {\n * const { data: rep, isLoading } = useCurrentRep();\n *\n * if (isLoading) return <Skeleton />;\n *\n * return (\n * <div>\n * <Avatar src={rep?.avatar_url} />\n * <span>{rep?.first_name} {rep?.last_name}</span>\n * </div>\n * );\n * }\n * ```\n */\nexport function useCurrentRep(): UseQueryResult<Rep> {\n const api = useFluidApi();\n\n return useQuery({\n queryKey: CURRENT_REP_QUERY_KEY,\n queryFn: () => api.reps.current(),\n });\n}\n","/**\n * useFluidAuth Hook\n *\n * Provides access to authentication state and utilities.\n * This is the primary hook for interacting with auth in components.\n */\n\nimport { useFluidAuthContext } from \"../providers/FluidAuthProvider\";\nimport type { FluidAuthContextValue } from \"../auth/types\";\n\n/**\n * Hook to access authentication state and utilities.\n *\n * Must be used within a `FluidAuthProvider`.\n *\n * @returns Authentication context with user info, loading state, and utilities\n * @throws Error if used outside FluidAuthProvider\n *\n * @example\n * ```tsx\n * function UserProfile() {\n * const { isAuthenticated, isLoading, user, clearAuth } = useFluidAuth();\n *\n * if (isLoading) {\n * return <Spinner />;\n * }\n *\n * if (!isAuthenticated) {\n * return <p>Please log in</p>;\n * }\n *\n * return (\n * <div>\n * <p>Welcome, {user.full_name}!</p>\n * <button onClick={clearAuth}>Log out</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useFluidAuth(): FluidAuthContextValue {\n return useFluidAuthContext();\n}\n","import type { CalendarEvent } from \"../hook-types\";\n\nconst now = new Date();\n\nfunction daysFromNow(days: number, hour: number, minute: number = 0): Date {\n const d = new Date(now);\n d.setDate(d.getDate() + days);\n d.setHours(hour, minute, 0, 0);\n return d;\n}\n\nexport const DEMO_CALENDAR_EVENTS: readonly CalendarEvent[] = [\n {\n id: 1,\n title: \"Team Standup\",\n description: { body: \"Daily sync with the sales team\" },\n color: \"#4f46e5\",\n start: daysFromNow(0, 9, 0).toISOString(),\n end: daysFromNow(0, 9, 30).toISOString(),\n active: true,\n status: \"confirmed\",\n },\n {\n id: 2,\n title: \"Client Review - Acme Corp\",\n description: { body: \"Quarterly business review with key accounts\" },\n color: \"#059669\",\n start: daysFromNow(2, 14, 0).toISOString(),\n end: daysFromNow(2, 15, 0).toISOString(),\n active: true,\n status: \"confirmed\",\n venue: \"Conference Room B\",\n },\n {\n id: 3,\n title: \"Product Training Webinar\",\n description: { body: \"New product line training for the field\" },\n color: \"#d97706\",\n start: daysFromNow(4, 11, 0).toISOString(),\n end: daysFromNow(4, 12, 30).toISOString(),\n active: true,\n status: \"confirmed\",\n url: \"https://example.com/webinar\",\n },\n {\n id: 4,\n title: \"Regional Conference\",\n description: { body: \"Annual West Coast regional conference\" },\n color: \"#dc2626\",\n start: daysFromNow(10, 8, 0).toISOString(),\n end: daysFromNow(12, 17, 0).toISOString(),\n active: true,\n status: \"confirmed\",\n venue: \"San Diego Convention Center\",\n isAllDay: true,\n },\n];\n","/**\n * Calendar events hook - stub implementation for SDK\n * In production, implement this hook to fetch from your API\n */\n\nimport type { QueryResult } from \"./hook-types\";\nimport type { CalendarEvent, CalendarEventDescription } from \"./hook-types\";\nimport { DEMO_CALENDAR_EVENTS } from \"./demo-data/calendar-events\";\n\n// Re-export types so external consumers are unaffected\nexport type { CalendarEvent, CalendarEventDescription };\n\n/**\n * Result type for useCalendarEvents hook.\n * Uses QueryResult<CalendarEvent[]> with default Error type.\n */\nexport type UseCalendarEventsResult = QueryResult<CalendarEvent[]>;\n\n/**\n * Hook to fetch calendar events.\n * This is a stub implementation - override with your own data fetching logic.\n */\nexport function useCalendarEvents(): UseCalendarEventsResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching\n return {\n data: [...DEMO_CALENDAR_EVENTS],\n isLoading: false,\n isError: false,\n };\n}\n","import type { Todo } from \"../hook-types\";\n\nconst now = new Date();\n\nfunction daysFromNow(days: number): string {\n const d = new Date(now);\n d.setDate(d.getDate() + days);\n return d.toISOString();\n}\n\nexport const DEMO_TODOS: readonly Todo[] = [\n {\n id: 1,\n body: \"Follow up with Sarah about Q2 order\",\n dueAt: daysFromNow(1),\n completedAt: null,\n createdAt: daysFromNow(-2),\n contactName: \"Sarah Johnson\",\n },\n {\n id: 2,\n body: \"Send pricing proposal to Acme Corp\",\n dueAt: daysFromNow(7),\n completedAt: null,\n createdAt: daysFromNow(-1),\n contactName: \"Mike Chen\",\n },\n {\n id: 3,\n body: \"Schedule onboarding call with new team member\",\n dueAt: daysFromNow(3),\n completedAt: null,\n createdAt: daysFromNow(0),\n contactName: \"Emily Rodriguez\",\n },\n {\n id: 4,\n body: \"Review and approve Q1 expense report\",\n dueAt: daysFromNow(-1),\n completedAt: daysFromNow(-1),\n createdAt: daysFromNow(-5),\n contactName: null,\n },\n {\n id: 5,\n body: \"Prepare presentation for Friday team meeting\",\n dueAt: daysFromNow(4),\n completedAt: daysFromNow(0),\n createdAt: daysFromNow(-3),\n contactName: null,\n },\n];\n","/**\n * Todos hook - stub implementation for SDK\n * In production, implement this hook to fetch from your API\n */\n\nimport type { QueryResult } from \"./hook-types\";\nimport type { Todo } from \"./hook-types\";\nimport { DEMO_TODOS } from \"./demo-data/todos\";\n\n// Re-export type so external consumers are unaffected\nexport type { Todo };\n\n/**\n * Result type for useTodos hook.\n * Uses QueryResult<Todo[]> with default Error type.\n */\nexport type UseTodosResult = QueryResult<Todo[]>;\n\n/**\n * Hook to fetch todo items.\n * This is a stub implementation - override with your own data fetching logic.\n */\nexport function useTodos(): UseTodosResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching\n return {\n data: [...DEMO_TODOS],\n isLoading: false,\n isError: false,\n };\n}\n","/**\n * Hook type utilities and type predicates.\n *\n * This module provides:\n * - Generic hook result types with default type parameters\n * - Type predicates for query state narrowing\n * - Reusable patterns for type-safe property access in hooks\n *\n * Following generics best practices:\n * - generics-default-type-parameters: Default E to Error for common case\n * - generics-type-predicates: Type predicates for result state narrowing\n * - generics-constrain-type-parameters: K extends keyof T for property access\n */\n\n// =============================================================================\n// Base Result Types with Default Type Parameters\n// =============================================================================\n\n/**\n * Base result type for query hooks with default error type.\n * Uses default type parameter for E (generics-default-type-parameters rule).\n *\n * @typeParam T - The data type\n * @typeParam E - The error type (defaults to Error)\n *\n * @example\n * // Error type defaults to Error\n * type UsersResult = QueryResult<User[]>;\n *\n * // Can override when needed\n * type CustomResult = QueryResult<User[], ApiError>;\n */\nexport interface QueryResult<T, E = Error> {\n readonly data: T;\n readonly isLoading: boolean;\n readonly isError: boolean;\n readonly error?: E | undefined;\n}\n\n/**\n * Result type for hooks that may not have data yet.\n * Extends QueryResult with nullable data.\n *\n * @typeParam T - The data type\n * @typeParam E - The error type (defaults to Error)\n */\nexport interface QueryResultNullable<T, E = Error> {\n readonly data: T | null | undefined;\n readonly isLoading: boolean;\n readonly isError: boolean;\n readonly error?: E | undefined;\n}\n\n/**\n * Result type for list/collection hooks with aggregates.\n *\n * @typeParam T - The item type in the array\n * @typeParam E - The error type (defaults to Error)\n */\nexport interface ListQueryResult<T, E = Error> extends QueryResult<T[], E> {\n readonly totalCount: number;\n}\n\n/**\n * Result type for list hooks with value aggregation (e.g., deals with total value).\n *\n * @typeParam T - The item type in the array\n * @typeParam E - The error type (defaults to Error)\n */\nexport interface ValueListQueryResult<T, E = Error>\n extends ListQueryResult<T, E> {\n readonly totalValue: number;\n}\n\n// =============================================================================\n// Type Predicates for Query State Narrowing\n// =============================================================================\n\n/**\n * Type predicate to check if a query result has successfully loaded data.\n * Narrows the data type from T | null | undefined to T.\n *\n * @example\n * const result = useContact(id);\n * if (hasData(result)) {\n * // TypeScript knows result.data is Contact, not Contact | null\n * console.log(result.data.name);\n * }\n */\nexport function hasData<T, E = Error>(\n result: QueryResultNullable<T, E>,\n): result is QueryResultNullable<T, E> & { readonly data: T } {\n return result.data != null && !result.isLoading && !result.isError;\n}\n\n/**\n * Type predicate to check if a query result is in loading state.\n * Useful for conditional rendering.\n *\n * @example\n * if (isLoading(result)) {\n * return <Spinner />;\n * }\n */\nexport function isLoading<T, E = Error>(\n result: QueryResult<T, E> | QueryResultNullable<T, E>,\n): boolean {\n return result.isLoading;\n}\n\n/**\n * Type predicate to check if a query result has an error.\n * Narrows to include the error property.\n *\n * @example\n * if (isErrorResult(result)) {\n * console.error(result.error); // error is E, not undefined\n * }\n */\nexport function isErrorResult<T, E = Error>(\n result: QueryResult<T, E> | QueryResultNullable<T, E>,\n): result is (QueryResult<T, E> | QueryResultNullable<T, E>) & {\n readonly isError: true;\n readonly error: E;\n} {\n return result.isError && result.error !== undefined;\n}\n\n/**\n * Type predicate to check if a query result is in idle state (not loading, no error, has data).\n *\n * @example\n * if (isIdle(result)) {\n * // Safe to access and render data\n * }\n */\nexport function isIdle<T, E = Error>(\n result: QueryResult<T, E> | QueryResultNullable<T, E>,\n): boolean {\n return !result.isLoading && !result.isError;\n}\n\n// =============================================================================\n// Generic Property Selector Pattern\n// =============================================================================\n\n/**\n * Type-safe property selector for hook results.\n * Uses K extends keyof T constraint (generics-function-constraints rule).\n *\n * @typeParam T - The data object type\n * @typeParam K - Key of T (constrained to actual keys)\n *\n * @example\n * const users = [{ name: \"Alice\", age: 30 }];\n * const names = selectProperty(users, \"name\"); // string[]\n * const ages = selectProperty(users, \"age\"); // number[]\n * selectProperty(users, \"invalid\"); // Error: \"invalid\" not in \"name\" | \"age\"\n */\nexport function selectProperty<T, K extends keyof T>(\n items: readonly T[],\n key: K,\n): T[K][] {\n return items.map((item) => item[key]);\n}\n\n/**\n * Type-safe property getter for a single item.\n * Returns undefined if item is null/undefined.\n *\n * @typeParam T - The data object type\n * @typeParam K - Key of T (constrained to actual keys)\n */\nexport function getProperty<T, K extends keyof T>(\n item: T | null | undefined,\n key: K,\n): T[K] | undefined {\n return item?.[key];\n}\n\n// =============================================================================\n// Hook Factory Types\n// =============================================================================\n\n/**\n * Generic type for hooks that fetch a single resource by ID.\n * Useful for creating consistent API across different resource types.\n *\n * @typeParam T - The resource type\n * @typeParam E - The error type (defaults to Error)\n */\nexport type UseSingleResourceHook<T, E = Error> = (\n id: string,\n) => QueryResultNullable<T, E>;\n\n/**\n * Generic type for hooks that fetch a list of resources with optional params.\n * Uses generics-default-type-parameters for the params type.\n *\n * @typeParam T - The item type\n * @typeParam P - The params type (defaults to empty object)\n * @typeParam E - The error type (defaults to Error)\n */\nexport type UseListResourceHook<\n T,\n P extends Record<string, unknown> = Record<string, never>,\n E = Error,\n> = (params?: P) => ListQueryResult<T, E>;\n\n/**\n * Transforms a nullable result to a non-nullable one if data exists.\n * Useful when you've already checked hasData().\n */\nexport type WithData<R extends QueryResultNullable<unknown>> =\n R extends QueryResultNullable<infer T, infer E>\n ? QueryResultNullable<T, E> & { readonly data: T }\n : never;\n\n// =============================================================================\n// Domain Types\n// Shared between hook files and demo-data files to avoid circular imports.\n// =============================================================================\n\n/**\n * Activity slug constants as a const object.\n * Derive the ActivitySlug type from this single source of truth.\n */\nexport const ACTIVITY_SLUGS = {\n abandonedCart: \"abandoned_cart\",\n announcements: \"announcements\",\n cartItemsAdded: \"cart_items_added\",\n commentReply: \"comment_reply\",\n directMessage: \"direct_message\",\n fantasyPoint: \"fantasy_point\",\n newLead: \"new_lead\",\n orderPlaced: \"order_placed\",\n pageViews: \"page_views\",\n pageViewsContact: \"page_views_contact\",\n tasks: \"tasks\",\n upcomingEvent: \"upcoming_event\",\n video: \"video\",\n videoComplete: \"video_complete\",\n videoCompleteContact: \"video_complete_contact\",\n videoContact: \"video_contact\",\n messageReceived: \"message_received\",\n messageSent: \"message_sent\",\n newCartItemsAdded: \"new_cart_items_added\",\n smartLinkClicked: \"smart_link_clicked\",\n reviewLeft: \"review_left\",\n} as const;\n\n/** Activity slug union type derived from ACTIVITY_SLUGS constant. */\nexport type ActivitySlug = (typeof ACTIVITY_SLUGS)[keyof typeof ACTIVITY_SLUGS];\n\n/** Type predicate to check if a string is a valid ActivitySlug. */\nexport function isActivitySlug(value: string): value is ActivitySlug {\n return Object.values(ACTIVITY_SLUGS).includes(value as ActivitySlug);\n}\n\n/** Transformed activity for display. */\nexport interface Activity {\n readonly id: number;\n readonly userName: string;\n readonly avatarUrl: string | null;\n readonly activityType: string;\n readonly targetName: string;\n readonly timestamp: string;\n readonly slug: ActivitySlug;\n}\n\n/** Description/rich text metadata for a calendar event. */\nexport interface CalendarEventDescription {\n readonly id?: number | null;\n readonly name?: string | null;\n readonly body?: string | null;\n readonly record_type?: string | null;\n readonly record_id?: number | null;\n readonly created_at?: string | null;\n readonly updated_at?: string | null;\n readonly locale?: string | null;\n}\n\n/** Calendar event data from the API. */\nexport interface CalendarEvent {\n readonly id: number;\n readonly title: string;\n readonly description?: CalendarEventDescription | null;\n readonly color?: string | null;\n readonly url?: string | null;\n readonly start: string;\n readonly end: string;\n readonly active?: boolean | null;\n readonly time_zone?: string | null;\n readonly status?: string | null;\n readonly image_url?: string | null;\n readonly images?: readonly unknown[] | null;\n readonly venue?: string | null;\n readonly countries?: readonly string[] | null;\n readonly hasTomorrow?: boolean | null;\n readonly hasYesterday?: boolean | null;\n readonly isAllDay?: boolean;\n}\n\n/** Catch up suggestion data from the API. */\nexport interface CatchUp {\n readonly id: number;\n readonly suggestion_title: string;\n}\n\n/** MySite data returned by the hook. */\nexport interface MySiteData {\n readonly url: string | null;\n readonly views: number;\n readonly leads: number;\n readonly userName: string;\n}\n\n/** Transformed todo for display. */\nexport interface Todo {\n readonly id: number;\n readonly body: string;\n readonly dueAt: string | null;\n readonly completedAt: string | null;\n readonly createdAt: string;\n readonly contactName: string | null;\n}\n","import type { Activity } from \"../hook-types\";\n\nconst now = new Date();\n\nfunction hoursAgo(hours: number): string {\n const d = new Date(now);\n d.setHours(d.getHours() - hours);\n return d.toISOString();\n}\nexport const DEMO_ACTIVITIES: readonly Activity[] = [\n {\n id: 1,\n userName: \"Sarah Johnson\",\n avatarUrl: null,\n activityType: \"New Order\",\n targetName: \"Wellness Starter Kit\",\n timestamp: hoursAgo(1),\n slug: \"order_placed\",\n },\n {\n id: 2,\n userName: \"Mike Chen\",\n avatarUrl: null,\n activityType: \"New Lead\",\n targetName: \"Referral from LinkedIn campaign\",\n timestamp: hoursAgo(3),\n slug: \"new_lead\",\n },\n {\n id: 3,\n userName: \"Emily Rodriguez\",\n avatarUrl: null,\n activityType: \"Page View\",\n targetName: \"Product Catalog\",\n timestamp: hoursAgo(5),\n slug: \"page_views\",\n },\n {\n id: 4,\n userName: \"David Park\",\n avatarUrl: null,\n activityType: \"Cart Items Added\",\n targetName: \"Premium Bundle (3 items)\",\n timestamp: hoursAgo(8),\n slug: \"cart_items_added\",\n },\n {\n id: 5,\n userName: \"Lisa Thompson\",\n avatarUrl: null,\n activityType: \"Video Watched\",\n targetName: \"Getting Started Tutorial\",\n timestamp: hoursAgo(12),\n slug: \"video_complete\",\n },\n {\n id: 6,\n userName: \"James Wilson\",\n avatarUrl: null,\n activityType: \"Message Received\",\n targetName: \"Question about shipping\",\n timestamp: hoursAgo(18),\n slug: \"message_received\",\n },\n {\n id: 7,\n userName: \"Rachel Kim\",\n avatarUrl: null,\n activityType: \"Smart Link Clicked\",\n targetName: \"Holiday Promo Link\",\n timestamp: hoursAgo(24),\n slug: \"smart_link_clicked\",\n },\n {\n id: 8,\n userName: \"Tom Martinez\",\n avatarUrl: null,\n activityType: \"Review Left\",\n targetName: \"Essential Oil Set - 5 stars\",\n timestamp: hoursAgo(36),\n slug: \"review_left\",\n },\n];\n","/**\n * Activities hook - stub implementation for SDK\n * In production, implement this hook to fetch from your API\n */\n\nimport type { QueryResult } from \"./hook-types\";\nimport {\n ACTIVITY_SLUGS,\n isActivitySlug,\n type Activity,\n type ActivitySlug,\n} from \"./hook-types\";\nimport { DEMO_ACTIVITIES } from \"./demo-data/activities\";\n\n// Re-export types and constants so external consumers are unaffected\nexport { ACTIVITY_SLUGS, isActivitySlug };\nexport type { Activity, ActivitySlug };\n\n/**\n * Result type for useActivities hook.\n * Uses QueryResult generic with Activity[] and default Error type.\n */\nexport type UseActivitiesResult = QueryResult<Activity[]>;\n\n/**\n * Hook to fetch recent activities.\n * This is a stub implementation - override with your own data fetching logic.\n */\nexport function useActivities(): UseActivitiesResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching\n return {\n data: [...DEMO_ACTIVITIES],\n isLoading: false,\n isError: false,\n };\n}\n","import type { CatchUp } from \"../hook-types\";\n\nexport const DEMO_CATCHUPS: readonly CatchUp[] = [\n {\n id: 1,\n suggestion_title: \"Sarah Johnson hasn't ordered in 30 days\",\n },\n {\n id: 2,\n suggestion_title: \"Mike Chen's subscription is expiring soon\",\n },\n {\n id: 3,\n suggestion_title: \"Emily Rodriguez left a cart with 3 items\",\n },\n];\n","/**\n * Catch ups hook - stub implementation for SDK\n * In production, implement this hook to fetch from your API\n */\n\nimport type { QueryResult } from \"./hook-types\";\nimport type { CatchUp } from \"./hook-types\";\nimport { DEMO_CATCHUPS } from \"./demo-data/catchups\";\n\n// Re-export type so external consumers are unaffected\nexport type { CatchUp };\n\n/**\n * Result type for useCatchUps hook.\n * Uses QueryResult<CatchUp[]> with default Error type.\n */\nexport type UseCatchUpsResult = QueryResult<CatchUp[]>;\n\n/**\n * Hook to fetch catch up items.\n * This is a stub implementation - override with your own data fetching logic.\n */\nexport function useCatchUps(): UseCatchUpsResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching\n return {\n data: [...DEMO_CATCHUPS],\n isLoading: false,\n isError: false,\n };\n}\n","import type { MySiteData } from \"../hook-types\";\n\nexport const DEMO_MYSITE: MySiteData = {\n url: \"https://my-portal.example.com\",\n views: 1243,\n leads: 37,\n userName: \"Demo User\",\n};\n","/**\n * MySite hook - stub implementation for SDK\n * In production, implement this hook to fetch from your API\n */\n\nimport type { QueryResultNullable } from \"./hook-types\";\nimport type { MySiteData } from \"./hook-types\";\nimport { DEMO_MYSITE } from \"./demo-data/mysite\";\n\n// Re-export type so external consumers are unaffected\nexport type { MySiteData };\n\n/**\n * Result type for useMySite hook.\n * Uses QueryResultNullable since MySite data may not be available.\n */\nexport type UseMySiteResult = QueryResultNullable<MySiteData>;\n\n/**\n * Hook to fetch MySite data.\n * This is a stub implementation - override with your own data fetching logic.\n */\nexport function useMySite(): UseMySiteResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching\n return {\n data: DEMO_MYSITE,\n isLoading: false,\n isError: false,\n };\n}\n","import type { Conversation, Message } from \"../../types/screen-types\";\n\nconst now = new Date();\n\nfunction hoursAgo(hours: number): string {\n const d = new Date(now);\n d.setHours(d.getHours() - hours);\n return d.toISOString();\n}\n\nfunction daysAgo(days: number): string {\n const d = new Date(now);\n d.setDate(d.getDate() - days);\n return d.toISOString();\n}\n\nexport const DEMO_CONVERSATIONS: readonly Conversation[] = [\n {\n id: \"conv-1\",\n title: \"Sarah Johnson\",\n participants: [\n { id: \"user-1\", name: \"You\", email: \"me@example.com\", isOnline: true },\n {\n id: \"user-2\",\n name: \"Sarah Johnson\",\n email: \"sarah.johnson@example.com\",\n isOnline: true,\n },\n ],\n lastMessage: {\n id: \"msg-1-3\",\n conversationId: \"conv-1\",\n senderId: \"user-2\",\n senderName: \"Sarah Johnson\",\n type: \"text\",\n content: \"Sounds great! I'll place the order by end of day.\",\n timestamp: hoursAgo(1),\n isRead: false,\n },\n unreadCount: 1,\n status: \"active\",\n createdAt: daysAgo(30),\n updatedAt: hoursAgo(1),\n },\n {\n id: \"conv-2\",\n title: \"Mike Chen\",\n participants: [\n { id: \"user-1\", name: \"You\", email: \"me@example.com\", isOnline: true },\n {\n id: \"user-3\",\n name: \"Mike Chen\",\n email: \"mike.chen@acmecorp.com\",\n isOnline: false,\n },\n ],\n lastMessage: {\n id: \"msg-2-2\",\n conversationId: \"conv-2\",\n senderId: \"user-1\",\n senderName: \"You\",\n type: \"text\",\n content:\n \"I've attached the updated pricing sheet. Let me know if you have any questions!\",\n timestamp: hoursAgo(5),\n isRead: true,\n },\n unreadCount: 0,\n status: \"active\",\n createdAt: daysAgo(14),\n updatedAt: hoursAgo(5),\n },\n {\n id: \"conv-3\",\n title: \"Team Updates\",\n participants: [\n { id: \"user-1\", name: \"You\", email: \"me@example.com\", isOnline: true },\n {\n id: \"user-4\",\n name: \"Emily Rodriguez\",\n email: \"emily.r@healthfirst.io\",\n },\n { id: \"user-5\", name: \"David Park\", email: \"david.park@email.com\" },\n ],\n lastMessage: {\n id: \"msg-3-4\",\n conversationId: \"conv-3\",\n senderId: \"user-4\",\n senderName: \"Emily Rodriguez\",\n type: \"text\",\n content:\n \"The new product samples arrived today. Will distribute to the team tomorrow.\",\n timestamp: daysAgo(1),\n isRead: true,\n },\n unreadCount: 0,\n status: \"active\",\n createdAt: daysAgo(60),\n updatedAt: daysAgo(1),\n },\n];\n\nexport const DEMO_MESSAGES: readonly Message[] = [\n {\n id: \"msg-1-1\",\n conversationId: \"conv-1\",\n senderId: \"user-1\",\n senderName: \"You\",\n type: \"text\",\n content:\n \"Hi Sarah! I wanted to follow up on the Wellness Starter Kit. We have a special promotion running this month.\",\n timestamp: hoursAgo(3),\n isRead: true,\n },\n {\n id: \"msg-1-2\",\n conversationId: \"conv-1\",\n senderId: \"user-2\",\n senderName: \"Sarah Johnson\",\n type: \"text\",\n content:\n \"That's perfect timing! I was just thinking about reordering. What's the promo?\",\n timestamp: hoursAgo(2),\n isRead: true,\n },\n {\n id: \"msg-1-3\",\n conversationId: \"conv-1\",\n senderId: \"user-2\",\n senderName: \"Sarah Johnson\",\n type: \"text\",\n content: \"Sounds great! I'll place the order by end of day.\",\n timestamp: hoursAgo(1),\n isRead: false,\n },\n];\n","/**\n * Conversations hooks - stub implementations for SDK\n * In production, implement these hooks to fetch from your API\n */\n\nimport type { Conversation, Message } from \"../types/screen-types\";\nimport type { QueryResult } from \"./hook-types\";\nimport { DEMO_CONVERSATIONS, DEMO_MESSAGES } from \"./demo-data/conversations\";\n\n// =============================================================================\n// useConversations Hook\n// =============================================================================\n\n/**\n * Result type for useConversations hook.\n * Uses QueryResult<Conversation[]> with default Error type.\n */\nexport type UseConversationsResult = QueryResult<Conversation[]>;\n\n/**\n * Hook to fetch all conversations.\n * This is a stub implementation - override with your own data fetching logic.\n *\n * @returns UseConversationsResult with empty data array\n *\n * @example\n * ```tsx\n * const { data: conversations, isLoading, isError } = useConversations();\n *\n * if (isLoading) return <Loading />;\n * if (isError) return <Error />;\n *\n * return conversations.map(conv => <ConversationItem key={conv.id} {...conv} />);\n * ```\n */\nexport function useConversations(): UseConversationsResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching\n return {\n data: [...DEMO_CONVERSATIONS],\n isLoading: false,\n isError: false,\n };\n}\n\n// =============================================================================\n// useConversationMessages Hook\n// =============================================================================\n\n/**\n * Result type for useConversationMessages hook.\n * Uses QueryResult<Message[]> with default Error type.\n */\nexport type UseConversationMessagesResult = QueryResult<Message[]>;\n\n/**\n * Hook to fetch messages for a specific conversation.\n * This is a stub implementation - override with your own data fetching logic.\n *\n * @param conversationId - The ID of the conversation to fetch messages for\n * @returns UseConversationMessagesResult with empty data array\n *\n * @example\n * ```tsx\n * const { data: messages, isLoading, isError } = useConversationMessages(conversationId);\n *\n * if (isLoading) return <Loading />;\n * if (isError) return <Error />;\n *\n * return messages.map(msg => <MessageBubble key={msg.id} {...msg} />);\n * ```\n */\nexport function useConversationMessages(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _conversationId: string,\n): UseConversationMessagesResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching using _conversationId\n return {\n data: [...DEMO_MESSAGES],\n isLoading: false,\n isError: false,\n };\n}\n","/**\n * Screen Types - Type definitions for core feature screens\n *\n * All status and type unions are derived from constants for single source of truth.\n * Use the constants (e.g., CONVERSATION_STATUSES.active) for type-safe comparisons.\n */\n\n// =============================================================================\n// Messaging Types\n// =============================================================================\n\n/**\n * Conversation status constant - single source of truth.\n */\nexport const CONVERSATION_STATUSES = {\n active: \"active\",\n archived: \"archived\",\n muted: \"muted\",\n} as const;\n\n/**\n * Union type derived from CONVERSATION_STATUSES constant.\n */\nexport type ConversationStatus =\n (typeof CONVERSATION_STATUSES)[keyof typeof CONVERSATION_STATUSES];\n\n/**\n * Message type constant - single source of truth.\n */\nexport const MESSAGE_TYPES = {\n text: \"text\",\n image: \"image\",\n file: \"file\",\n system: \"system\",\n} as const;\n\n/**\n * Union type derived from MESSAGE_TYPES constant.\n */\nexport type MessageType = (typeof MESSAGE_TYPES)[keyof typeof MESSAGE_TYPES];\n\nexport interface Participant {\n readonly id: string;\n readonly name: string;\n readonly email: string;\n readonly avatarUrl?: string;\n readonly isOnline?: boolean;\n}\n\n/**\n * Message attachment type - extracted for reusability and clarity.\n */\nexport interface MessageAttachment {\n readonly id: string;\n readonly name: string;\n readonly url: string;\n readonly type: string;\n readonly size?: number;\n}\n\nexport interface Message {\n readonly id: string;\n readonly conversationId: string;\n readonly senderId: string;\n readonly senderName: string;\n readonly senderAvatarUrl?: string;\n readonly type: MessageType;\n readonly content: string;\n readonly timestamp: string;\n readonly isRead: boolean;\n readonly attachments?: readonly MessageAttachment[];\n}\n\nexport interface Conversation {\n readonly id: string;\n readonly title: string;\n readonly participants: readonly Participant[];\n readonly lastMessage?: Message;\n readonly unreadCount: number;\n readonly status: ConversationStatus;\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\n// =============================================================================\n// Contacts Types\n// =============================================================================\n\n/**\n * Contact status constant - single source of truth.\n */\nexport const CONTACT_STATUSES = {\n active: \"active\",\n inactive: \"inactive\",\n lead: \"lead\",\n prospect: \"prospect\",\n} as const;\n\n/**\n * Union type derived from CONTACT_STATUSES constant.\n */\nexport type ContactStatus =\n (typeof CONTACT_STATUSES)[keyof typeof CONTACT_STATUSES];\n\n/**\n * Contact type constant - single source of truth.\n */\nexport const CONTACT_TYPES = {\n individual: \"individual\",\n company: \"company\",\n} as const;\n\n/**\n * Union type derived from CONTACT_TYPES constant.\n */\nexport type ContactType = (typeof CONTACT_TYPES)[keyof typeof CONTACT_TYPES];\n\nexport interface ContactAddress {\n readonly street?: string;\n readonly city?: string;\n readonly state?: string;\n readonly postalCode?: string;\n readonly country?: string;\n}\n\nexport interface Contact {\n readonly id: string;\n readonly firstName: string;\n readonly lastName: string;\n readonly email: string;\n readonly phone?: string;\n readonly company?: string;\n readonly jobTitle?: string;\n readonly avatarUrl?: string;\n readonly status: ContactStatus;\n readonly type: ContactType;\n readonly address?: ContactAddress;\n readonly tags?: readonly string[];\n readonly notes?: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n","import type { Contact } from \"../../types/screen-types\";\n\nconst now = new Date();\n\nfunction daysAgo(days: number): string {\n const d = new Date(now);\n d.setDate(d.getDate() - days);\n return d.toISOString();\n}\n\nexport const DEMO_CONTACTS: readonly Contact[] = [\n {\n id: \"contact-1\",\n firstName: \"Sarah\",\n lastName: \"Johnson\",\n email: \"sarah.johnson@example.com\",\n phone: \"+1 (555) 123-4567\",\n company: \"Wellness Works Inc.\",\n jobTitle: \"Purchasing Manager\",\n status: \"active\",\n type: \"individual\",\n tags: [\"VIP\", \"Repeat Buyer\"],\n createdAt: daysAgo(90),\n updatedAt: daysAgo(2),\n },\n {\n id: \"contact-2\",\n firstName: \"Mike\",\n lastName: \"Chen\",\n email: \"mike.chen@acmecorp.com\",\n phone: \"+1 (555) 234-5678\",\n company: \"Acme Corp\",\n jobTitle: \"Director of Operations\",\n status: \"active\",\n type: \"individual\",\n tags: [\"Enterprise\"],\n createdAt: daysAgo(60),\n updatedAt: daysAgo(5),\n },\n {\n id: \"contact-3\",\n firstName: \"Emily\",\n lastName: \"Rodriguez\",\n email: \"emily.r@healthfirst.io\",\n company: \"HealthFirst\",\n status: \"lead\",\n type: \"individual\",\n notes: \"Interested in bulk pricing for team orders\",\n createdAt: daysAgo(7),\n updatedAt: daysAgo(1),\n },\n {\n id: \"contact-4\",\n firstName: \"David\",\n lastName: \"Park\",\n email: \"david.park@email.com\",\n phone: \"+1 (555) 345-6789\",\n status: \"prospect\",\n type: \"individual\",\n tags: [\"Referral\"],\n createdAt: daysAgo(14),\n updatedAt: daysAgo(10),\n },\n {\n id: \"contact-5\",\n firstName: \"Lisa\",\n lastName: \"Thompson\",\n email: \"lisa.t@globalfit.com\",\n company: \"Global Fitness\",\n jobTitle: \"CEO\",\n status: \"active\",\n type: \"individual\",\n address: {\n city: \"Los Angeles\",\n state: \"CA\",\n country: \"US\",\n },\n createdAt: daysAgo(120),\n updatedAt: daysAgo(15),\n },\n {\n id: \"contact-6\",\n firstName: \"James\",\n lastName: \"Wilson\",\n email: \"jwilson@retired.net\",\n status: \"inactive\",\n type: \"individual\",\n notes: \"Moved out of area, no longer purchasing\",\n createdAt: daysAgo(200),\n updatedAt: daysAgo(45),\n },\n];\n\nexport const DEMO_CONTACT: Contact = DEMO_CONTACTS[0]!;\n","/**\n * Contacts hooks - stub implementation for SDK\n * In production, implement these hooks to fetch from your API\n */\n\nimport type { Contact, ContactStatus } from \"../types/screen-types\";\nimport { CONTACT_STATUSES } from \"../types/screen-types\";\nimport type { ListQueryResult, QueryResultNullable } from \"./hook-types\";\nimport { DEMO_CONTACTS, DEMO_CONTACT } from \"./demo-data/contacts\";\n\n/**\n * Type predicate to check if a status string is a valid ContactStatus.\n * Enables runtime validation with type narrowing.\n */\nexport function isContactStatus(value: string): value is ContactStatus {\n return Object.values(CONTACT_STATUSES).includes(value as ContactStatus);\n}\n\n/**\n * Parameters for filtering and paginating contacts.\n * Uses readonly properties and proper ContactStatus type for status.\n */\nexport interface UseContactsParams {\n /** Search query to filter contacts by name, email, or company */\n readonly search?: string;\n /** Filter contacts by status - uses ContactStatus union type for type safety */\n readonly status?: ContactStatus;\n /** Maximum number of contacts to return */\n readonly limit?: number;\n}\n\n/**\n * Result type for the useContacts hook.\n * Uses ListQueryResult<Contact> with totalCount and default Error type.\n */\nexport type UseContactsResult = ListQueryResult<Contact>;\n\n/**\n * Result type for the useContact hook.\n * Uses QueryResultNullable since a specific contact may not exist.\n */\nexport type UseContactResult = QueryResultNullable<Contact>;\n\n/**\n * Hook to fetch a list of contacts with optional filtering and pagination.\n * This is a stub implementation - override with your own data fetching logic.\n *\n * @param params - Optional parameters for filtering and pagination\n * @returns Object containing contacts data, loading state, error state, and total count\n *\n * @example\n * ```tsx\n * const { data: contacts, isLoading, totalCount } = useContacts({\n * search: 'john',\n * status: 'active',\n * limit: 20\n * });\n * ```\n */\nexport function useContacts(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _params?: UseContactsParams,\n): UseContactsResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching\n return {\n data: [...DEMO_CONTACTS],\n isLoading: false,\n isError: false,\n totalCount: DEMO_CONTACTS.length,\n };\n}\n\n/**\n * Hook to fetch a single contact by ID.\n * This is a stub implementation - override with your own data fetching logic.\n *\n * @param contactId - The unique identifier of the contact to fetch\n * @returns Object containing contact data, loading state, and error state\n *\n * @example\n * ```tsx\n * const { data: contact, isLoading, isError } = useContact('contact-123');\n * ```\n */\nexport function useContact(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _contactId: string,\n): UseContactResult {\n // Demo data for first-run experience\n // In production, replace with actual data fetching using _contactId\n return {\n data: DEMO_CONTACT,\n isLoading: false,\n isError: false,\n };\n}\n","/**\n * AuthError - Default Authentication Error Component\n *\n * Displayed when authentication fails. Can be customized or replaced\n * via the RequireAuth component's errorComponent prop.\n */\n\nimport { useEffect } from \"react\";\nimport type { ReactNode } from \"react\";\n\nexport interface AuthErrorProps {\n /** Error message to display */\n message?: string;\n /** Optional title */\n title?: string;\n /** Optional children for custom content */\n children?: ReactNode;\n}\n\n/**\n * Default authentication error component.\n *\n * Displays a simple error message when authentication fails.\n * Can be customized via props or replaced entirely in RequireAuth.\n *\n * @example\n * ```tsx\n * // Use with default message\n * <AuthError />\n *\n * // Use with custom message\n * <AuthError message=\"Session expired. Please log in again.\" />\n *\n * // Use with custom content\n * <AuthError>\n * <CustomLoginButton />\n * </AuthError>\n * ```\n */\nexport function AuthError({\n message = \"You need to be authenticated to view this content.\",\n title = \"Authentication Required\",\n children,\n}: AuthErrorProps) {\n return (\n <div\n style={{\n display: \"flex\",\n flexDirection: \"column\",\n alignItems: \"center\",\n justifyContent: \"center\",\n minHeight: \"100vh\",\n padding: \"2rem\",\n fontFamily:\n '-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif',\n backgroundColor: \"#f9fafb\",\n color: \"#111827\",\n }}\n >\n <div\n style={{\n maxWidth: \"400px\",\n textAlign: \"center\",\n padding: \"2rem\",\n backgroundColor: \"#ffffff\",\n borderRadius: \"0.75rem\",\n boxShadow:\n \"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)\",\n }}\n >\n {/* Lock Icon */}\n <div\n style={{\n width: \"64px\",\n height: \"64px\",\n margin: \"0 auto 1.5rem\",\n backgroundColor: \"#fee2e2\",\n borderRadius: \"50%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n }}\n >\n <svg\n width=\"32\"\n height=\"32\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"#dc2626\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <rect x=\"3\" y=\"11\" width=\"18\" height=\"11\" rx=\"2\" ry=\"2\" />\n <path d=\"M7 11V7a5 5 0 0 1 10 0v4\" />\n </svg>\n </div>\n\n <h1\n style={{\n fontSize: \"1.5rem\",\n fontWeight: \"600\",\n marginBottom: \"0.75rem\",\n color: \"#111827\",\n }}\n >\n {title}\n </h1>\n\n <p\n style={{\n fontSize: \"1rem\",\n color: \"#6b7280\",\n marginBottom: children ? \"1.5rem\" : \"0\",\n lineHeight: \"1.5\",\n }}\n >\n {message}\n </p>\n\n {children}\n </div>\n </div>\n );\n}\n\nconst SPIN_STYLE_ID = \"fluid-auth-loading-spin\";\n\n/**\n * Inject the spin keyframes style once into the document head.\n */\nfunction ensureSpinStyle(): void {\n if (typeof document === \"undefined\") return;\n if (document.getElementById(SPIN_STYLE_ID)) return;\n\n const style = document.createElement(\"style\");\n style.id = SPIN_STYLE_ID;\n style.textContent = `@keyframes spin { to { transform: rotate(360deg); } }`;\n document.head.appendChild(style);\n}\n\n/**\n * Simple loading spinner component for auth loading state.\n */\nexport function AuthLoading() {\n useEffect(() => {\n ensureSpinStyle();\n }, []);\n\n return (\n <div\n style={{\n display: \"flex\",\n flexDirection: \"column\",\n alignItems: \"center\",\n justifyContent: \"center\",\n minHeight: \"100vh\",\n fontFamily:\n '-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif',\n backgroundColor: \"#f9fafb\",\n }}\n >\n <div\n style={{\n width: \"40px\",\n height: \"40px\",\n border: \"3px solid #e5e7eb\",\n borderTopColor: \"#3b82f6\",\n borderRadius: \"50%\",\n animation: \"spin 1s linear infinite\",\n }}\n />\n <p\n style={{\n marginTop: \"1rem\",\n color: \"#6b7280\",\n fontSize: \"0.875rem\",\n }}\n >\n Authenticating...\n </p>\n </div>\n );\n}\n","/**\n * RequireAuth - Route Protection Component\n *\n * Wraps content that requires authentication. Shows loading state\n * while checking auth, error component if not authenticated, or\n * children if authenticated.\n */\n\nimport type { ReactNode } from \"react\";\nimport { useFluidAuth } from \"../hooks/use-fluid-auth\";\nimport { AuthError, AuthLoading } from \"./AuthError\";\n\nexport interface RequireAuthProps {\n /** Content to render when authenticated */\n children: ReactNode;\n /** Component to show while checking authentication (default: AuthLoading) */\n fallback?: ReactNode;\n /** Component to show when not authenticated (default: AuthError) */\n errorComponent?: ReactNode;\n}\n\n/**\n * Component that protects content requiring authentication.\n *\n * **Important:** This provides UX-level protection only. It prevents\n * unauthenticated users from seeing the UI, but the real security\n * boundary is the server-side API. Client-side auth can always be\n * bypassed by modifying browser state.\n *\n * For defense-in-depth, configure `jwksUrl` in `FluidAuthConfig`\n * to enable client-side JWT signature verification.\n *\n * Shows different states based on auth status:\n * - Loading: Shows fallback (spinner by default)\n * - Not authenticated: Shows errorComponent (AuthError by default)\n * - Authenticated: Shows children\n *\n * @example\n * ```tsx\n * // Basic usage - shows default loading/error states\n * <RequireAuth>\n * <ProtectedContent />\n * </RequireAuth>\n *\n * // Custom loading state\n * <RequireAuth fallback={<CustomSpinner />}>\n * <ProtectedContent />\n * </RequireAuth>\n *\n * // Custom error component\n * <RequireAuth errorComponent={<LoginPrompt />}>\n * <ProtectedContent />\n * </RequireAuth>\n *\n * // Both custom\n * <RequireAuth\n * fallback={<SkeletonLoader />}\n * errorComponent={<RedirectToLogin />}\n * >\n * <Dashboard />\n * </RequireAuth>\n * ```\n */\nexport function RequireAuth({\n children,\n fallback = <AuthLoading />,\n errorComponent = <AuthError />,\n}: RequireAuthProps) {\n const { isAuthenticated, isLoading, error } = useFluidAuth();\n\n // Show loading state while checking authentication\n if (isLoading) {\n return <>{fallback}</>;\n }\n\n // Show error state if not authenticated\n if (!isAuthenticated || error) {\n return <>{errorComponent}</>;\n }\n\n // User is authenticated, render children\n return <>{children}</>;\n}\n","// Screen Components\nexport {\n MessagingScreen,\n messagingScreenPropertySchema,\n} from \"./MessagingScreen\";\nexport { ContactsScreen, contactsScreenPropertySchema } from \"./ContactsScreen\";\nexport { OrdersScreen, ordersScreenPropertySchema } from \"./OrdersScreen\";\nexport {\n CustomersScreen,\n customersScreenPropertySchema,\n} from \"./CustomersScreen\";\nexport { ProductsScreen, productsScreenPropertySchema } from \"./ProductsScreen\";\n\n// Re-export all property schemas as a lazy-loadable collection\nexport const screenPropertySchemas = {\n MessagingScreen: () =>\n import(\"./MessagingScreen\").then((m) => m.messagingScreenPropertySchema),\n ContactsScreen: () =>\n import(\"./ContactsScreen\").then((m) => m.contactsScreenPropertySchema),\n OrdersScreen: () =>\n import(\"./OrdersScreen\").then((m) => m.ordersScreenPropertySchema),\n CustomersScreen: () =>\n import(\"./CustomersScreen\").then((m) => m.customersScreenPropertySchema),\n ProductsScreen: () =>\n import(\"./ProductsScreen\").then((m) => m.productsScreenPropertySchema),\n};\n\n// Page Template Registration\nimport { PageTemplateRegistry } from \"../registries/page-template-registry\";\nimport { PAGE_CATEGORIES } from \"../types/page-template\";\n\n/**\n * Core page template IDs\n */\nexport const CORE_PAGE_IDS = {\n MESSAGING: \"core-messaging\",\n CONTACTS: \"core-contacts\",\n ORDERS: \"core-orders\",\n CUSTOMERS: \"core-customers\",\n PRODUCTS: \"core-products\",\n} as const;\n\n/**\n * Register core page templates.\n * These are automatically registered when the SDK is imported.\n */\nfunction registerCorePageTemplates(): void {\n // Messaging Screen\n PageTemplateRegistry.register({\n id: CORE_PAGE_IDS.MESSAGING,\n slug: \"messaging\",\n name: \"Messaging\",\n description: \"Messaging interface provided by Fluid Commerce\",\n category: PAGE_CATEGORIES.COMMUNICATION,\n tags: [\"messaging\", \"chat\", \"conversations\", \"communication\"],\n version: \"1.0.0\",\n isCore: true,\n component_tree: [\n {\n type: \"MessagingScreen\",\n id: \"messaging-screen-root\",\n props: {},\n },\n ],\n defaultProps: {},\n });\n\n // Contacts Screen\n PageTemplateRegistry.register({\n id: CORE_PAGE_IDS.CONTACTS,\n slug: \"contacts\",\n name: \"Contacts\",\n description: \"Contact management provided by Fluid Commerce\",\n category: PAGE_CATEGORIES.CORE,\n tags: [\"contacts\", \"people\", \"address-book\"],\n version: \"1.0.0\",\n isCore: true,\n component_tree: [\n {\n type: \"ContactsScreen\",\n id: \"contacts-screen-root\",\n props: {},\n },\n ],\n defaultProps: {},\n });\n\n // Orders Screen\n PageTemplateRegistry.register({\n id: CORE_PAGE_IDS.ORDERS,\n slug: \"orders\",\n name: \"Orders\",\n description: \"Order management provided by Fluid Commerce\",\n category: PAGE_CATEGORIES.CORE,\n tags: [\"orders\", \"commerce\", \"sales\"],\n version: \"1.0.0\",\n isCore: true,\n component_tree: [\n {\n type: \"OrdersScreen\",\n id: \"orders-screen-root\",\n props: {},\n },\n ],\n defaultProps: {},\n });\n\n // Customers Screen\n PageTemplateRegistry.register({\n id: CORE_PAGE_IDS.CUSTOMERS,\n slug: \"customers\",\n name: \"Customers\",\n description: \"Customer management provided by Fluid Commerce\",\n category: PAGE_CATEGORIES.CORE,\n tags: [\"customers\", \"people\", \"commerce\"],\n version: \"1.0.0\",\n isCore: true,\n component_tree: [\n {\n type: \"CustomersScreen\",\n id: \"customers-screen-root\",\n props: {},\n },\n ],\n defaultProps: {},\n });\n\n // Products Screen\n PageTemplateRegistry.register({\n id: CORE_PAGE_IDS.PRODUCTS,\n slug: \"products\",\n name: \"Products\",\n description: \"Product catalog provided by Fluid Commerce\",\n category: PAGE_CATEGORIES.CORE,\n tags: [\"products\", \"catalog\", \"commerce\"],\n version: \"1.0.0\",\n isCore: true,\n component_tree: [\n {\n type: \"ProductsScreen\",\n id: \"products-screen-root\",\n props: {},\n },\n ],\n defaultProps: {},\n });\n}\n\n// Auto-register core templates on module load\nregisterCorePageTemplates();\n","import * as React from \"react\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { faEllipsis } from \"@fortawesome/pro-regular-svg-icons/faEllipsis\";\nimport { faXmark } from \"@fortawesome/pro-regular-svg-icons/faXmark\";\nimport { normalizeSlug } from \"@fluid-app/rep-core/navigation/system-navigation-items\";\nimport { RepIcon } from \"@fluid-app/rep-core/components/RepIcon\";\nimport { useSidebar } from \"@fluid-app/rep-core/shell/sidebar\";\nimport type { NavigationItem } from \"../types/navigation\";\n\ninterface SdkBottomNavProps {\n navItems: NavigationItem[];\n currentSlug: string;\n onNavigate: (slug: string) => void;\n maxVisibleItems?: number;\n}\n\nfunction isInSection(item: NavigationItem, currentSlug: string): boolean {\n const normalized = normalizeSlug(currentSlug);\n if (normalizeSlug(item.slug) === normalized) return true;\n return (\n item.children?.some((child) => normalizeSlug(child.slug) === normalized) ??\n false\n );\n}\n\nfunction getNavTarget(item: NavigationItem): string | null {\n if (item.slug && (!item.children || item.children.length === 0)) {\n return normalizeSlug(item.slug);\n }\n if (item.children && item.children.length > 0) {\n const firstChild = item.children[0];\n if (firstChild?.slug) return normalizeSlug(firstChild.slug);\n }\n return null;\n}\n\nexport function SdkBottomNav({\n navItems,\n currentSlug,\n onNavigate,\n maxVisibleItems = 5,\n}: SdkBottomNavProps) {\n const { isMobile, useBottomNav } = useSidebar();\n const [moreOpen, setMoreOpen] = React.useState(false);\n\n if (!isMobile || !useBottomNav) return null;\n\n const navigableItems = navItems\n .filter((item) => !item.parent_id)\n .filter((item) => item.slug || (item.children && item.children.length > 0));\n\n const hasOverflow = navigableItems.length > maxVisibleItems;\n const visibleItems = hasOverflow\n ? navigableItems.slice(0, maxVisibleItems - 1)\n : navigableItems;\n const overflowItems = hasOverflow\n ? navigableItems.slice(maxVisibleItems - 1)\n : [];\n\n const handleItemClick = (item: NavigationItem) => {\n const target = getNavTarget(item);\n if (target) onNavigate(target);\n setMoreOpen(false);\n };\n\n return (\n <>\n <nav className=\"fixed right-0 bottom-0 left-0 z-40 flex h-16 items-end justify-around border-t border-border bg-sidebar pb-[env(safe-area-inset-bottom)]\">\n {visibleItems.map((item) => {\n const isActive = isInSection(item, currentSlug);\n return (\n <button\n key={item.id ?? item.slug ?? item.label}\n type=\"button\"\n onClick={() => handleItemClick(item)}\n className={`flex flex-1 flex-col items-center justify-center gap-0.5 py-2 text-[10px] font-medium transition-colors ${\n isActive ? \"text-primary\" : \"text-muted-foreground\"\n }`}\n >\n {item.icon ? (\n <RepIcon name={item.icon} className=\"size-5\" />\n ) : (\n <span className=\"size-5\" />\n )}\n <span className=\"max-w-[72px] truncate\">{item.label}</span>\n </button>\n );\n })}\n\n {hasOverflow && (\n <button\n type=\"button\"\n onClick={() => setMoreOpen(true)}\n className={`flex flex-1 flex-col items-center justify-center gap-0.5 py-2 text-[10px] font-medium transition-colors ${\n overflowItems.some((item) => isInSection(item, currentSlug))\n ? \"text-primary\"\n : \"text-muted-foreground\"\n }`}\n >\n <FontAwesomeIcon icon={faEllipsis} className=\"size-5\" />\n <span>More</span>\n </button>\n )}\n </nav>\n\n {moreOpen && (\n <div className=\"fixed inset-0 z-50 flex flex-col\">\n <div\n className=\"flex-1 bg-black/50\"\n onClick={() => setMoreOpen(false)}\n aria-hidden=\"true\"\n />\n <div className=\"rounded-t-2xl bg-sidebar pb-[env(safe-area-inset-bottom)]\">\n <div className=\"flex items-center justify-between px-4 pt-4 pb-2\">\n <span className=\"text-sm font-semibold text-foreground\">\n More\n </span>\n <button\n type=\"button\"\n onClick={() => setMoreOpen(false)}\n className=\"flex items-center justify-center rounded-full p-1 text-muted-foreground hover:bg-sidebar-accent\"\n aria-label=\"Close\"\n >\n <FontAwesomeIcon icon={faXmark} className=\"size-5\" />\n </button>\n </div>\n <div className=\"px-2 pb-4\">\n {overflowItems.map((item) => {\n const isActive = isInSection(item, currentSlug);\n return (\n <button\n key={item.id ?? item.slug ?? item.label}\n type=\"button\"\n onClick={() => handleItemClick(item)}\n className={`flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors ${\n isActive\n ? \"bg-sidebar-primary text-sidebar-primary-foreground\"\n : \"text-sidebar-foreground hover:bg-sidebar-accent\"\n }`}\n >\n {item.icon && (\n <RepIcon name={item.icon} className=\"size-5\" />\n )}\n <span>{item.label}</span>\n </button>\n );\n })}\n </div>\n </div>\n </div>\n )}\n </>\n );\n}\n","import { useEffect } from \"react\";\n\nconst SPIN_STYLE_ID = \"fluid-app-shell-loading-spin\";\n\n/**\n * Inject the spin keyframes style once into the document head.\n */\nfunction ensureSpinStyle(): void {\n if (typeof document === \"undefined\") return;\n if (document.getElementById(SPIN_STYLE_ID)) return;\n\n const style = document.createElement(\"style\");\n style.id = SPIN_STYLE_ID;\n style.textContent = `@keyframes spin { to { transform: rotate(360deg); } }`;\n document.head.appendChild(style);\n}\n\n/**\n * Full-page loading spinner shown while AppShell is fetching app data\n * for the first time. Uses inline styles (not Tailwind) since the theme\n * hasn't loaded yet.\n */\nexport function AppShellLoading() {\n useEffect(() => {\n ensureSpinStyle();\n }, []);\n\n return (\n <div\n style={{\n display: \"flex\",\n flexDirection: \"column\",\n alignItems: \"center\",\n justifyContent: \"center\",\n minHeight: \"100vh\",\n fontFamily:\n '-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif',\n backgroundColor: \"#f9fafb\",\n }}\n >\n <div\n style={{\n width: \"40px\",\n height: \"40px\",\n border: \"3px solid #e5e7eb\",\n borderTopColor: \"#3b82f6\",\n borderRadius: \"50%\",\n animation: \"spin 1s linear infinite\",\n }}\n />\n <p\n style={{\n marginTop: \"1rem\",\n color: \"#6b7280\",\n fontSize: \"0.875rem\",\n }}\n >\n Loading...\n </p>\n </div>\n );\n}\n","import { normalizeSlug } from \"@fluid-app/rep-core/navigation/system-navigation-items\";\nimport type { NavigationItem } from \"../types/navigation\";\n\nexport interface SlugMatch {\n matchedSlug: string;\n rest: string;\n}\n\n/**\n * Extract all slugs from a navigation tree, sorted by segment count descending.\n * Longest slugs first enables greedy prefix matching (e.g. \"share/playlists\"\n * is checked before \"share\").\n */\nexport function collectNavSlugs(items: NavigationItem[]): string[] {\n const slugs: string[] = [];\n\n for (const item of items) {\n if (item.slug) slugs.push(normalizeSlug(item.slug));\n for (const child of item.children ?? []) {\n if (child.slug) slugs.push(normalizeSlug(child.slug));\n }\n }\n\n return [...slugs].sort((a, b) => b.split(\"/\").length - a.split(\"/\").length);\n}\n\n/**\n * Find the longest registered nav slug that is a prefix of `fullSlug`.\n * Uses segment-boundary checking to prevent \"shop\" from matching \"shopping\".\n */\nexport function matchSlugPrefix(\n fullSlug: string,\n navSlugs: string[],\n): SlugMatch | undefined {\n const normalized = normalizeSlug(fullSlug);\n if (!normalized) return undefined;\n\n for (const navSlug of navSlugs) {\n if (normalized === navSlug) {\n return { matchedSlug: navSlug, rest: \"\" };\n }\n if (normalized.startsWith(navSlug + \"/\")) {\n return {\n matchedSlug: navSlug,\n rest: normalized.slice(navSlug.length + 1),\n };\n }\n }\n\n return undefined;\n}\n\n/**\n * Extract the slug portion from a full pathname by stripping the basePath prefix.\n * Returns an empty string when the pathname equals the basePath exactly.\n *\n * Examples:\n * extractSlugFromPathname(\"/contacts/123\", \"/\") → \"contacts/123\"\n * extractSlugFromPathname(\"/portal/contacts\", \"/portal\") → \"contacts\"\n * extractSlugFromPathname(\"/portal\", \"/portal\") → \"\"\n * extractSlugFromPathname(\"/\", \"/\") → \"\"\n */\nexport function extractSlugFromPathname(\n pathname: string,\n basePath: string,\n): string {\n // For root basePath, just strip the leading slash\n if (basePath === \"/\") {\n return pathname.replace(/^\\//, \"\");\n }\n\n // Strip basePath prefix, then strip leading slash from remainder\n if (pathname.startsWith(basePath)) {\n return pathname.slice(basePath.length).replace(/^\\//, \"\");\n }\n\n // Fallback: return pathname without leading slash\n return pathname.replace(/^\\//, \"\");\n}\n\nexport function isSlugInSection(\n item: NavigationItem,\n currentSlug: string,\n navSlugs: string[],\n): boolean {\n const match = matchSlugPrefix(currentSlug, navSlugs);\n const baseSlug = match?.matchedSlug ?? normalizeSlug(currentSlug);\n\n if (normalizeSlug(item.slug) === baseSlug) return true;\n return (\n item.children?.some((child) => normalizeSlug(child.slug) === baseSlug) ??\n false\n );\n}\n","import {\n SidebarGroupLabel,\n SidebarMenu,\n SidebarMenuItem,\n SidebarMenuButton,\n} from \"@fluid-app/rep-core/shell/sidebar\";\nimport { RepIcon } from \"@fluid-app/rep-core/components/RepIcon\";\nimport { normalizeSlug } from \"@fluid-app/rep-core/navigation/system-navigation-items\";\nimport type { NavigationItem } from \"../types/navigation\";\nimport { isSlugInSection } from \"./slug-utils\";\n\nexport interface SdkNavigationProps {\n navItems: NavigationItem[];\n currentSlug: string;\n onNavigate: (slug: string) => void;\n navSlugs: string[];\n}\n\nexport function SdkNavigation({\n navItems,\n currentSlug,\n onNavigate,\n navSlugs,\n}: SdkNavigationProps) {\n return (\n <SidebarMenu>\n {navItems.map((item, index) => {\n // Skip items without slug AND without label\n if (!item.slug && !item.label) return null;\n\n // Items without a slug are section headers\n if (!item.slug) {\n return (\n <SidebarGroupLabel key={item.id ?? `section-${index}`}>\n {item.label}\n </SidebarGroupLabel>\n );\n }\n\n const itemSlug = normalizeSlug(item.slug);\n const isActive = isSlugInSection(item, currentSlug, navSlugs);\n\n return (\n <SidebarMenuItem key={item.id ?? itemSlug}>\n <SidebarMenuButton\n isActive={isActive}\n onClick={() => onNavigate(itemSlug)}\n >\n {item.icon && <RepIcon name={item.icon} />}\n <span className=\"truncate\">{item.label}</span>\n </SidebarMenuButton>\n </SidebarMenuItem>\n );\n })}\n </SidebarMenu>\n );\n}\n","import { useState, useRef, useEffect, useCallback } from \"react\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { faTableCellsLarge } from \"@fortawesome/pro-regular-svg-icons/faTableCellsLarge\";\nimport { RepIcon } from \"@fluid-app/rep-core/components/RepIcon\";\nimport { getSystemNavigationBySection } from \"@fluid-app/rep-core/navigation/system-navigation-items\";\n\nexport interface QuickLinksDropdownProps {\n onNavigate: (slug: string) => void;\n}\n\nexport function QuickLinksDropdown({ onNavigate }: QuickLinksDropdownProps) {\n const [open, setOpen] = useState(false);\n const panelRef = useRef<HTMLDivElement>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n\n const close = useCallback(() => setOpen(false), []);\n\n // Click-outside + Escape to dismiss\n useEffect(() => {\n if (!open) return;\n\n const handleMouseDown = (e: MouseEvent) => {\n if (\n panelRef.current &&\n !panelRef.current.contains(e.target as Node) &&\n buttonRef.current &&\n !buttonRef.current.contains(e.target as Node)\n ) {\n close();\n }\n };\n\n const handleKeyDown = (e: KeyboardEvent) => {\n if (e.key === \"Escape\") close();\n };\n\n document.addEventListener(\"mousedown\", handleMouseDown);\n document.addEventListener(\"keydown\", handleKeyDown);\n return () => {\n document.removeEventListener(\"mousedown\", handleMouseDown);\n document.removeEventListener(\"keydown\", handleKeyDown);\n };\n }, [open, close]);\n\n const sections = getSystemNavigationBySection();\n\n const handleItemClick = (slug: string) => {\n onNavigate(slug);\n close();\n };\n\n return (\n <div className=\"relative\">\n <button\n ref={buttonRef}\n type=\"button\"\n onClick={() => setOpen((prev) => !prev)}\n className=\"flex shrink-0 items-center justify-center rounded-md p-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground\"\n aria-label=\"Quick links\"\n aria-expanded={open}\n >\n <FontAwesomeIcon icon={faTableCellsLarge} className=\"h-4 w-4\" />\n </button>\n\n {open && (\n <div\n ref={panelRef}\n className=\"absolute top-full right-0 z-50 mt-1 w-[700px] max-w-[90vw] overflow-hidden rounded-lg border border-border bg-background shadow-lg\"\n >\n <div className=\"flex flex-col\">\n {/* Header */}\n <div className=\"flex items-center gap-2 border-b bg-background p-4\">\n <FontAwesomeIcon\n icon={faTableCellsLarge}\n className=\"h-5 w-5 text-muted-foreground\"\n />\n <h3 className=\"text-sm font-semibold text-foreground\">\n Shortcuts\n </h3>\n </div>\n\n {/* Sections */}\n <div className=\"space-y-6 bg-muted p-6\">\n {Object.entries(sections).map(([sectionName, items]) => (\n <div key={sectionName} className=\"space-y-3\">\n <h3 className=\"text-sm font-semibold text-foreground\">\n {sectionName}\n </h3>\n <div className=\"grid grid-cols-4 gap-2\">\n {items.map((item) => (\n <button\n key={item.slug}\n type=\"button\"\n onClick={() => handleItemClick(item.slug!)}\n className=\"flex items-center gap-2 rounded-lg px-3 py-2 text-sm text-sidebar-foreground transition-colors hover:bg-sidebar-primary hover:text-sidebar-primary-foreground\"\n >\n {item.icon && (\n <RepIcon\n name={item.icon}\n className=\"h-4 w-4 shrink-0 text-muted-foreground\"\n />\n )}\n <span className=\"truncate\">{item.label}</span>\n </button>\n ))}\n </div>\n </div>\n ))}\n </div>\n </div>\n </div>\n )}\n </div>\n );\n}\n","import { useSidebar } from \"@fluid-app/rep-core/shell/sidebar\";\nimport { useThemeMode } from \"@fluid-app/rep-core/shell/ThemeModeContext\";\nimport { FontAwesomeIcon } from \"@fortawesome/react-fontawesome\";\nimport { faBars } from \"@fortawesome/pro-regular-svg-icons/faBars\";\nimport { faSun } from \"@fortawesome/pro-regular-svg-icons/faSun\";\nimport { faMoon } from \"@fortawesome/pro-regular-svg-icons/faMoon\";\nimport { normalizeSlug } from \"@fluid-app/rep-core/navigation/system-navigation-items\";\nimport type { NavigationItem } from \"../types/navigation\";\nimport { matchSlugPrefix } from \"./slug-utils\";\nimport { QuickLinksDropdown } from \"./QuickLinksDropdown\";\n\nexport interface SdkHeaderProps {\n tabs: NavigationItem[];\n mobileTabs?: NavigationItem[];\n currentSlug: string;\n onNavigate: (slug: string) => void;\n navSlugs: string[];\n}\n\nexport function SdkHeader({\n tabs,\n mobileTabs,\n currentSlug,\n onNavigate,\n navSlugs,\n}: SdkHeaderProps) {\n const sidebar = useSidebar();\n const themeMode = useThemeMode();\n\n const match = matchSlugPrefix(currentSlug, navSlugs);\n const baseSlug = match?.matchedSlug ?? normalizeSlug(currentSlug);\n\n const themeIcon = themeMode.mode === \"dark\" ? faMoon : faSun;\n const activeTabs =\n sidebar.isMobile && sidebar.useBottomNav && mobileTabs ? mobileTabs : tabs;\n\n return (\n <header className=\"flex h-[52px] shrink-0 items-center gap-2 bg-sidebar px-6\">\n {/* Mobile hamburger — only show if NOT using bottom nav */}\n {sidebar.isMobile && !sidebar.useBottomNav && (\n <button\n type=\"button\"\n onClick={sidebar.toggleSidebar}\n className=\"mr-2 flex shrink-0 items-center justify-center rounded-md p-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground\"\n aria-label=\"Toggle sidebar\"\n >\n <FontAwesomeIcon icon={faBars} className=\"size-5\" />\n </button>\n )}\n\n {/* Scrollable sub-tabs */}\n <nav className=\"scrollbar-none flex flex-1 items-center gap-1 overflow-x-auto\">\n {activeTabs.map((tab) => {\n const tabSlug = normalizeSlug(tab.slug);\n if (!tabSlug) return null;\n\n const isActive = tabSlug === baseSlug;\n\n return (\n <button\n key={tab.id ?? tabSlug}\n type=\"button\"\n onClick={() => onNavigate(tabSlug)}\n className={`border-b-2 px-4 py-3 text-sm font-medium whitespace-nowrap transition-colors ${\n isActive\n ? \"border-primary text-foreground\"\n : \"border-transparent text-muted-foreground hover:border-border hover:text-foreground\"\n }`}\n >\n {tab.label}\n </button>\n );\n })}\n </nav>\n\n {/* Quick Links */}\n <QuickLinksDropdown onNavigate={onNavigate} />\n\n {/* Theme toggle */}\n <button\n type=\"button\"\n onClick={themeMode.cycleMode}\n className=\"ml-2 flex shrink-0 items-center justify-center rounded-md p-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground\"\n aria-label={`Switch theme (current: ${themeMode.mode})`}\n >\n <FontAwesomeIcon icon={themeIcon} className=\"size-3\" />\n </button>\n </header>\n );\n}\n","/**\n * BuilderScreenView — renders a builder screen's component_tree with\n * DataAwareWidget support for data-bound widgets.\n *\n * Uses the shared ScreenRenderer from rep-widgets under the hood,\n * but wraps data-bound widgets with DataAwareWidget from rep-core.\n */\n\nimport { memo } from \"react\";\nimport type { WidgetSchema } from \"@fluid-app/rep-core/types\";\nimport type { ScreenDefinition } from \"@fluid-app/rep-core/types\";\nimport { DataAwareWidget } from \"@fluid-app/rep-core/data-sources/DataAwareWidget\";\nimport { useRegistry } from \"@fluid-app/rep-widgets/contexts\";\n\ninterface WidgetRendererProps {\n widget: WidgetSchema;\n index: number;\n}\n\n/**\n * Renders a single widget, wrapping with DataAwareWidget if it has a dataSource.\n */\nfunction WidgetRenderer({ widget, index }: WidgetRendererProps) {\n const registry = useRegistry();\n const Component = registry[widget.type];\n\n if (!Component) {\n console.warn(\n `[BuilderScreenView] Widget type \"${String(widget.type)}\" not found in registry`,\n );\n return null;\n }\n\n if (widget.dataSource) {\n return (\n <div key={widget.id ?? index} className=\"h-full w-full overflow-x-hidden\">\n <DataAwareWidget widget={widget} Component={Component} />\n </div>\n );\n }\n\n return (\n <div key={widget.id ?? index} className=\"h-full w-full overflow-x-hidden\">\n <Component {...widget.props} />\n </div>\n );\n}\n\nexport interface BuilderScreenViewProps {\n /** The screen definition to render */\n screen: ScreenDefinition;\n /** Additional CSS classes for the wrapper div */\n className?: string;\n}\n\n/**\n * Renders a builder screen's component_tree with full data source support.\n * Widgets with `dataSource` config are automatically wrapped with `DataAwareWidget`\n * which fetches data and merges it with static props before rendering.\n */\nfunction BuilderScreenViewImpl({ screen, className }: BuilderScreenViewProps) {\n const widgets = screen.component_tree;\n\n if (!widgets || widgets.length === 0) {\n return (\n <div className={className ?? \"h-full w-full\"}>\n <div className=\"flex h-full items-center justify-center text-muted-foreground\">\n <p>This screen has no content yet.</p>\n </div>\n </div>\n );\n }\n\n return (\n <div className={className ?? \"h-full w-full\"}>\n {widgets.map((widget, index) => {\n if (!widget) return null;\n return (\n <WidgetRenderer\n key={widget.id ?? index}\n widget={widget}\n index={index}\n />\n );\n })}\n </div>\n );\n}\n\nexport const BuilderScreenView = memo(BuilderScreenViewImpl);\n","import { useMemo, type ComponentType } from \"react\";\nimport { isSystemNavigationItem } from \"@fluid-app/rep-core/navigation/system-navigation-items\";\nimport type { NavigationItem, ScreenDefinition } from \"../types/navigation\";\nimport { CoreScreenPlaceholder } from \"../screens/CoreScreenPlaceholder\";\nimport { MessagingScreen } from \"../screens/MessagingScreen\";\nimport { ContactsScreen } from \"../screens/ContactsScreen\";\nimport { OrdersScreen } from \"../screens/OrdersScreen\";\nimport { CustomersScreen } from \"../screens/CustomersScreen\";\nimport { ProductsScreen } from \"../screens/ProductsScreen\";\nimport { BuilderScreenView } from \"./BuilderScreenView\";\n\nconst SYSTEM_SLUG_SCREEN_MAP: Record<string, ComponentType> = {\n messages: MessagingScreen,\n contacts: ContactsScreen,\n shop: OrdersScreen,\n customers: CustomersScreen,\n products: ProductsScreen,\n};\n\nexport interface PageRouterProps {\n currentSlug: string;\n currentNavItem?: NavigationItem | undefined;\n customPages?:\n | Record<string, ComponentType<{ slug?: string; params?: string }>>\n | undefined;\n /** Builder screen definitions (from fluidos API) */\n screens?: ScreenDefinition[] | undefined;\n baseSlug: string;\n restParams: string;\n}\n\nexport function PageRouter({\n currentSlug,\n currentNavItem,\n customPages,\n screens,\n baseSlug,\n restParams,\n}: PageRouterProps) {\n // Build a screen lookup map by ID for O(1) access\n const screenById = useMemo(() => {\n if (!screens || screens.length === 0) return undefined;\n return new Map(screens.map((s) => [s.id, s]));\n }, [screens]);\n\n // Build a screen lookup map by slug for fallback resolution\n const screenBySlug = useMemo(() => {\n if (!screens || screens.length === 0) return undefined;\n return new Map(screens.filter((s) => s.slug).map((s) => [s.slug, s]));\n }, [screens]);\n\n // Resolve builder screen: screen_id first, then slug fallback\n const builderScreen = useMemo(() => {\n if (currentNavItem?.screen_id && screenById) {\n const byId = screenById.get(currentNavItem.screen_id);\n if (byId) return byId;\n }\n if (screenBySlug) {\n return (\n screenBySlug.get(currentSlug) ?? screenBySlug.get(baseSlug) ?? undefined\n );\n }\n return undefined;\n }, [\n currentNavItem?.screen_id,\n screenById,\n screenBySlug,\n currentSlug,\n baseSlug,\n ]);\n\n // 1. System navigation item with a dedicated screen component\n const SystemScreen = SYSTEM_SLUG_SCREEN_MAP[baseSlug];\n if (SystemScreen) {\n return <SystemScreen />;\n }\n\n // 2. System slug without a dedicated screen (account, my-site, share/*)\n if (isSystemNavigationItem(baseSlug)) {\n return <CoreScreenPlaceholder name={currentNavItem?.label ?? baseSlug} />;\n }\n\n // 3. Exact custom page match (full slug)\n const ExactCustomPage = customPages?.[currentSlug];\n if (ExactCustomPage) {\n return <ExactCustomPage slug={currentSlug} params={restParams} />;\n }\n\n // 4. Prefix custom page match (base slug with rest params)\n if (baseSlug !== currentSlug) {\n const PrefixCustomPage = customPages?.[baseSlug];\n if (PrefixCustomPage) {\n return <PrefixCustomPage slug={currentSlug} params={restParams} />;\n }\n }\n\n // 5. Builder screen (by screen_id or slug match)\n if (builderScreen) {\n return <BuilderScreenView screen={builderScreen} />;\n }\n\n // 6. Fallback\n return <CoreScreenPlaceholder name={currentNavItem?.label ?? currentSlug} />;\n}\n","import { createContext, useContext, useMemo, type ReactNode } from \"react\";\n\nexport interface AppNavigationContextValue {\n /** Current active slug (e.g. \"contacts/123\") */\n currentSlug: string;\n /** Base path for subpath deployments (e.g. \"/portal\"). Default: \"/\" */\n basePath: string;\n /** Navigate to a slug programmatically */\n navigate: (slug: string) => void;\n /** Build a full href for a slug (for use in <a> tags) */\n buildHref: (slug: string) => string;\n}\n\nconst AppNavigationContext = createContext<AppNavigationContextValue | null>(\n null,\n);\n\nexport interface AppNavigationProviderProps {\n currentSlug: string;\n basePath: string;\n navigate: (slug: string) => void;\n children: ReactNode;\n}\n\nexport function AppNavigationProvider({\n currentSlug,\n basePath,\n navigate,\n children,\n}: AppNavigationProviderProps) {\n const buildHref = useMemo(() => {\n return (slug: string) => {\n if (basePath === \"/\") return `/${slug}`;\n return `${basePath}/${slug}`;\n };\n }, [basePath]);\n\n const value = useMemo(\n () => ({ currentSlug, basePath, navigate, buildHref }),\n [currentSlug, basePath, navigate, buildHref],\n );\n\n return (\n <AppNavigationContext.Provider value={value}>\n {children}\n </AppNavigationContext.Provider>\n );\n}\n\nexport function useAppNavigation(): AppNavigationContextValue {\n const ctx = useContext(AppNavigationContext);\n if (!ctx) {\n throw new Error(\n \"useAppNavigation must be used within an <AppShell> or <AppNavigationProvider>\",\n );\n }\n return ctx;\n}\n","import {\n useState,\n useEffect,\n useCallback,\n useMemo,\n type ReactNode,\n type ComponentType,\n} from \"react\";\nimport { AppShellLayout } from \"@fluid-app/rep-core/shell/AppShellLayout\";\nimport {\n ThemeModeProvider,\n type ThemeMode,\n} from \"@fluid-app/rep-core/shell/ThemeModeContext\";\nimport { normalizeSlug } from \"@fluid-app/rep-core/navigation/system-navigation-items\";\nimport { SdkBottomNav } from \"./SdkBottomNav\";\nimport type { RepAppData, ScreenDefinition } from \"@fluid-app/rep-core/types\";\nimport {\n applyTheme,\n removeAllThemes,\n resolveTheme,\n} from \"@fluid-app/rep-core/theme\";\nimport { useFluidApp } from \"../hooks/use-fluid-app\";\nimport type { NavigationItem } from \"../types/navigation\";\nimport { AppShellLoading } from \"./AppShellLoading\";\nimport { SdkNavigation } from \"./SdkNavigation\";\nimport { SdkHeader } from \"./SdkHeader\";\nimport { PageRouter } from \"./PageRouter\";\nimport {\n collectNavSlugs,\n matchSlugPrefix,\n extractSlugFromPathname,\n} from \"./slug-utils\";\nimport { AppNavigationProvider } from \"./AppNavigationContext\";\n\nconst THEME_STORAGE_KEY = \"rep-theme-mode\";\n\nconst DEFAULT_NAVIGATION: NavigationItem[] = [\n { label: \"We Commerce\", children: [] },\n { slug: \"shop\", label: \"Shop\", icon: \"store\", children: [] },\n { slug: \"account\", label: \"Account\", icon: \"user-gear\", children: [] },\n { slug: \"messages\", label: \"Messaging\", icon: \"comment\", children: [] },\n { label: \"Marketing Assets\", children: [] },\n {\n slug: \"share/products\",\n label: \"Products\",\n icon: \"boxes-stacked\",\n children: [],\n },\n];\n\nfunction getInitialThemeMode(): ThemeMode {\n if (typeof window === \"undefined\") return \"light\";\n const stored = localStorage.getItem(THEME_STORAGE_KEY);\n if (stored === \"light\" || stored === \"dark\") return stored;\n return \"light\";\n}\n\nfunction findFirstNavigableSlug(items: NavigationItem[]): string {\n for (const item of items) {\n if (item.slug) return normalizeSlug(item.slug);\n for (const child of item.children ?? []) {\n if (child.slug) return normalizeSlug(child.slug);\n }\n }\n return \"\";\n}\n\nfunction findCurrentSection(\n items: NavigationItem[],\n slug: string,\n): NavigationItem | undefined {\n const normalized = normalizeSlug(slug);\n for (const item of items) {\n if (normalizeSlug(item.slug) === normalized) return item;\n if (\n item.children?.some((child) => normalizeSlug(child.slug) === normalized)\n ) {\n return item;\n }\n }\n return undefined;\n}\n\nfunction findNavItem(\n items: NavigationItem[],\n slug: string,\n): NavigationItem | undefined {\n const normalized = normalizeSlug(slug);\n for (const item of items) {\n if (normalizeSlug(item.slug) === normalized) return item;\n for (const child of item.children ?? []) {\n if (normalizeSlug(child.slug) === normalized) return child;\n }\n }\n return undefined;\n}\n\nexport interface AppShellProps {\n /** Pre-fetched app data (skips internal useFluidApp call if provided) */\n appData?: RepAppData;\n /** Override navigation items (otherwise derived from appData/API) */\n navigation?: NavigationItem[];\n /** Custom page components keyed by slug */\n customPages?: Record<\n string,\n ComponentType<{ slug?: string; params?: string }>\n >;\n /** Base path for subpath deployments (e.g. \"/portal\"). Default: \"/\" */\n basePath?: string;\n /** Controlled current slug */\n currentSlug?: string;\n /** Navigation callback */\n onNavigate?: (slug: string) => void;\n /** Custom sidebar header slot */\n sidebarHeader?: ReactNode;\n /** Custom sidebar footer slot */\n sidebarFooter?: ReactNode;\n /** Render prop or static children for the content area */\n children?:\n | ReactNode\n | ((props: {\n currentSlug: string;\n currentNavItem: NavigationItem | undefined;\n }) => ReactNode);\n}\n\nexport function AppShell({\n appData: appDataProp,\n navigation: navigationProp,\n customPages,\n basePath = \"/\",\n currentSlug: controlledSlug,\n onNavigate: onNavigateProp,\n sidebarHeader,\n sidebarFooter,\n children,\n}: AppShellProps) {\n // Normalize basePath: ensure leading slash, no trailing slash\n const normalizedBasePath = useMemo(() => {\n const stripped = basePath.replace(/^\\/|\\/$/g, \"\");\n return stripped ? `/${stripped}` : \"/\";\n }, [basePath]);\n\n // Fetch full app data from fluidos API (disabled when appData is provided)\n const { data: fetchedAppData, isLoading } = useFluidApp({\n enabled: !appDataProp,\n });\n const appData = appDataProp ?? fetchedAppData;\n\n // Resolve the active theme from app data\n const activeTheme = useMemo(() => {\n if (!appData?.profile?.themes?.length) return undefined;\n const themes = appData.profile.themes;\n const activeId = appData.profile.activeThemeId;\n return activeId\n ? (themes.find((t) => t.id === activeId) ?? themes[0])\n : themes[0];\n }, [appData?.profile?.themes, appData?.profile?.activeThemeId]);\n\n // Apply theme CSS via the shared theme pipeline\n useEffect(() => {\n if (!activeTheme) return;\n\n const resolved = resolveTheme(activeTheme);\n applyTheme(resolved);\n\n return () => {\n removeAllThemes();\n };\n }, [activeTheme]);\n\n // Resolve navigation items\n const navItems = useMemo(() => {\n if (navigationProp) return navigationProp;\n const profileNav = appData?.profile?.navigation?.navigation_items;\n if (profileNav && profileNav.length > 0) return profileNav;\n return DEFAULT_NAVIGATION;\n }, [navigationProp, appData?.profile?.navigation?.navigation_items]);\n\n // Resolve mobile navigation items (fall back to desktop nav)\n const mobileNavItems = useMemo(() => {\n const mobileNav = appData?.profile?.mobile_navigation?.navigation_items;\n if (mobileNav && mobileNav.length > 0) return mobileNav;\n return navItems;\n }, [appData?.profile?.mobile_navigation?.navigation_items, navItems]);\n\n // Resolve builder screen definitions\n const screens: ScreenDefinition[] | undefined = appData?.screens;\n\n // Collect all nav slugs for prefix matching (sorted longest-first)\n const navSlugs = useMemo(() => collectNavSlugs(navItems), [navItems]);\n\n // Theme mode state with localStorage persistence\n const [themeMode, setThemeMode] = useState<ThemeMode>(getInitialThemeMode);\n\n const handleThemeModeChange = useCallback((mode: ThemeMode) => {\n setThemeMode(mode);\n if (typeof window !== \"undefined\") {\n localStorage.setItem(THEME_STORAGE_KEY, mode);\n }\n }, []);\n\n // Path-based routing for uncontrolled mode\n const [pathSlug, setPathSlug] = useState<string>(() => {\n if (typeof window === \"undefined\") return \"\";\n return extractSlugFromPathname(\n window.location.pathname,\n normalizedBasePath,\n );\n });\n\n // Sync initial path when navItems load — redirect to first nav slug if at root\n useEffect(() => {\n if (controlledSlug !== undefined) return;\n if (typeof window === \"undefined\") return;\n\n const currentPath = extractSlugFromPathname(\n window.location.pathname,\n normalizedBasePath,\n );\n\n if (!currentPath) {\n const firstSlug = findFirstNavigableSlug(navItems);\n if (firstSlug) {\n const targetPath =\n normalizedBasePath === \"/\"\n ? `/${firstSlug}`\n : `${normalizedBasePath}/${firstSlug}`;\n // replaceState to avoid polluting back-button history\n history.replaceState(null, \"\", targetPath);\n setPathSlug(firstSlug);\n }\n }\n }, [navItems, controlledSlug, normalizedBasePath]);\n\n // Listen for popstate (browser back/forward)\n useEffect(() => {\n if (controlledSlug !== undefined) return;\n\n const handlePopState = () => {\n const slug = extractSlugFromPathname(\n window.location.pathname,\n normalizedBasePath,\n );\n setPathSlug(slug);\n };\n\n window.addEventListener(\"popstate\", handlePopState);\n return () => window.removeEventListener(\"popstate\", handlePopState);\n }, [controlledSlug, normalizedBasePath]);\n\n const activeSlug = controlledSlug ?? pathSlug;\n\n const handleNavigate = useCallback(\n (slug: string) => {\n if (onNavigateProp) {\n onNavigateProp(slug);\n return;\n }\n const targetPath =\n normalizedBasePath === \"/\"\n ? `/${slug}`\n : `${normalizedBasePath}/${slug}`;\n history.pushState(null, \"\", targetPath);\n setPathSlug(slug);\n },\n [onNavigateProp, normalizedBasePath],\n );\n\n // Derive base slug and rest params via prefix matching\n const slugMatch = useMemo(\n () => matchSlugPrefix(activeSlug, navSlugs),\n [activeSlug, navSlugs],\n );\n const baseSlug = slugMatch?.matchedSlug ?? normalizeSlug(activeSlug);\n const restParams = slugMatch?.rest ?? \"\";\n\n // Derive current section and sub-tabs using base slug\n const currentSection = findCurrentSection(navItems, baseSlug);\n const secondLevelTabs = currentSection?.children ?? [];\n const mobileCurrentSection = findCurrentSection(mobileNavItems, baseSlug);\n const mobileSecondLevelTabs = mobileCurrentSection?.children ?? [];\n const currentNavItem = findNavItem(navItems, baseSlug);\n\n // Determine content to render\n const content =\n typeof children === \"function\"\n ? children({ currentSlug: activeSlug, currentNavItem })\n : (children ?? (\n <PageRouter\n currentSlug={activeSlug}\n currentNavItem={currentNavItem}\n customPages={customPages}\n screens={screens}\n baseSlug={baseSlug}\n restParams={restParams}\n />\n ));\n\n // Show loading state while app data is being fetched for the first time.\n // This check is placed after all hooks to satisfy React's rules of hooks.\n if (isLoading && !appData) {\n return <AppShellLoading />;\n }\n\n return (\n <ThemeModeProvider\n mode={themeMode}\n onModeChange={handleThemeModeChange}\n autoModeEnabled={false}\n >\n <AppNavigationProvider\n currentSlug={activeSlug}\n basePath={normalizedBasePath}\n navigate={handleNavigate}\n >\n <div\n data-theme={activeTheme?.id}\n data-theme-mode={themeMode === \"auto\" ? undefined : themeMode}\n >\n <AppShellLayout\n sidebarContent={\n <SdkNavigation\n navItems={navItems}\n currentSlug={activeSlug}\n onNavigate={handleNavigate}\n navSlugs={navSlugs}\n />\n }\n headerContent={\n <SdkHeader\n tabs={secondLevelTabs}\n mobileTabs={mobileSecondLevelTabs}\n currentSlug={activeSlug}\n onNavigate={handleNavigate}\n navSlugs={navSlugs}\n />\n }\n sidebarHeader={sidebarHeader}\n sidebarFooter={sidebarFooter}\n useBottomNav\n afterContent={\n <SdkBottomNav\n navItems={mobileNavItems}\n currentSlug={activeSlug}\n onNavigate={handleNavigate}\n />\n }\n >\n {content}\n </AppShellLayout>\n </div>\n </AppNavigationProvider>\n </ThemeModeProvider>\n );\n}\n","import { forwardRef, type AnchorHTMLAttributes, type MouseEvent } from \"react\";\nimport { useAppNavigation } from \"./AppNavigationContext\";\n\nexport interface AppLinkProps\n extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> {\n /** Slug to navigate to (e.g. \"contacts/123\") */\n to: string;\n}\n\n/**\n * SPA-aware link that renders a real `<a href>` for accessibility\n * (right-click, ctrl+click, screen readers) but intercepts normal\n * clicks for client-side navigation.\n */\nexport const AppLink = forwardRef<HTMLAnchorElement, AppLinkProps>(\n function AppLink({ to, onClick, children, ...rest }, ref) {\n const { navigate, buildHref } = useAppNavigation();\n\n const handleClick = (e: MouseEvent<HTMLAnchorElement>) => {\n // Allow custom onClick handlers to run first\n onClick?.(e);\n if (e.defaultPrevented) return;\n\n // Skip SPA navigation for modifier keys, non-primary button, or external target\n if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;\n if (e.button !== 0) return;\n if (rest.target && rest.target !== \"_self\") return;\n\n e.preventDefault();\n navigate(to);\n };\n\n return (\n <a ref={ref} href={buildHref(to)} onClick={handleClick} {...rest}>\n {children}\n </a>\n );\n },\n);\n"]}
|