autoui-react 0.0.5-alpha → 0.1.1-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/utils.ts","../components/ui/button.tsx","../src/core/reducer.ts","../src/core/action-router.ts","../src/AutoUI.tsx","../src/core/state.ts","../src/core/planner.ts","../src/schema/ui.ts","../src/schema/components.ts","../src/core/system-events.ts","../src/env.ts","../src/adapters/shadcn.tsx","../components/ui/dialog.tsx","../components/ui/card.tsx","../components/ui/input.tsx","../components/ui/textarea.tsx","../components/ui/select.tsx","../components/ui/checkbox.tsx","../components/ui/radio-group.tsx","../components/ui/tabs.tsx","../components/ui/label.tsx","../src/core/renderer.tsx","../src/core/bindings.ts","../src/core/events.ts","../src/core/component-detection.ts","../src/adapters/schema/drizzle.ts","../src/adapters/schema/index.ts","../src/ai-utils.ts","../src/hooks/usePlanner.ts"],"names":["Button","jsx","path","parent","ActionType","plannerInput","useCallback","useEffect","z","SystemEventType","jsxs","CheckIcon","Label","uiEventType","processEvent","renderNode","MAX_CACHE_SIZE","CACHE_TTL","findNodeById","useState","useRef"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAA0B,YAAY;AACtC,SAAS,eAAe;AAMjB,SAAS,MAAM,QAAsB;AAC1C,SAAO,QAAQ,KAAK,MAAM,CAAC;AAC7B;AATA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA,gBAAAA;AAAA,EAAA;AAAA;AACA,SAAS,YAAY;AACrB,SAAS,WAA8B;AAgDnC,gBAAAC,aAAA;AAbJ,SAASD,QAAO;AAAA,EACd;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAU;AAAA,EACV,GAAG;AACL,GAGK;AACH,QAAM,OAAO,UAAU,OAAO;AAE9B,SACE,gBAAAC;AAAA,IAAC;AAAA;AAAA,MACC,aAAU;AAAA,MACV,WAAW,GAAG,eAAe,EAAE,SAAS,MAA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M,aAAa,YAAY;AAAA,EACvE;AAGA,EAAAC,WAAU,MAAM;AAKd,QACE,QAAQ,kBAAkB,UAC1B,WAAW,UACX,CAAC,sBAAsB,SACvB;AAEA,4BAAsB,UAAU;AAChC,4BAAsB;AAAA,IACxB;AAAA,EAGF,GAAG,CAAC,QAAQ,eAAe,QAAQ,qBAAqB,CAAC;AAEzD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF","sourcesContent":["import { type ClassValue, clsx } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\n/**\n * Utility function for conditional class name generation\n * Combines clsx and tailwind-merge for cleaner className assignment\n */\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n","import * as React from \"react\"\nimport { Slot } from \"@radix-ui/react-slot\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"../../src/lib/utils\"\n\nconst buttonVariants = cva(\n \"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive\",\n {\n variants: {\n variant: {\n default:\n \"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90\",\n destructive:\n \"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60\",\n outline:\n \"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50\",\n secondary:\n \"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80\",\n ghost:\n \"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50\",\n link: \"text-primary underline-offset-4 hover:underline\",\n },\n size: {\n default: \"h-9 px-4 py-2 has-[>svg]:px-3\",\n sm: \"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5\",\n lg: \"h-10 rounded-md px-6 has-[>svg]:px-4\",\n icon: \"size-9\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n size: \"default\",\n },\n }\n)\n\nfunction Button({\n className,\n variant,\n size,\n asChild = false,\n ...props\n}: React.ComponentProps<\"button\"> &\n VariantProps<typeof buttonVariants> & {\n asChild?: boolean\n }) {\n const Comp = asChild ? Slot : \"button\"\n\n return (\n <Comp\n data-slot=\"button\"\n className={cn(buttonVariants({ variant, size, className }))}\n {...props}\n />\n )\n}\n\nexport { Button, buttonVariants }\n","import { UIAction, UIState, UISpecNode } from \"../schema/ui\";\n\n/**\n * Deep clones a UI node tree\n * @param node - Node to clone\n * @returns Cloned node\n */\nfunction cloneNode(node: UISpecNode): UISpecNode {\n return {\n ...node,\n props: node.props ? { ...node.props } : null,\n bindings: node.bindings ? { ...node.bindings } : null,\n events: node.events ? { ...node.events } : null,\n children: node.children\n ? node.children.map((child) => cloneNode(child))\n : null,\n };\n}\n\n/**\n * Find a specific node in the UI tree by ID\n * @param tree - UI tree to search\n * @param nodeId - ID of the node to find\n * @returns The found node or undefined\n */\nexport function findNodeById(\n tree: UISpecNode | undefined,\n nodeId: string\n): UISpecNode | undefined {\n if (!tree) return undefined;\n if (tree.id === nodeId) return tree;\n\n if (tree.children) {\n for (const child of tree.children) {\n const found = findNodeById(child, nodeId);\n if (found) return found;\n }\n }\n\n return undefined;\n}\n\n/**\n * Updates a specific node in the UI tree\n * @param tree - Original UI tree\n * @param nodeId - ID of the node to update\n * @param updater - Function that returns the updated node\n * @returns Updated UI tree\n */\nexport function updateNodeById(\n tree: UISpecNode,\n nodeId: string,\n updater: (node: UISpecNode) => UISpecNode\n): UISpecNode {\n // Clone the tree to avoid mutations\n const result = cloneNode(tree);\n\n // Find the parent path to the node\n function findPath(\n node: UISpecNode,\n id: string,\n currentPath: UISpecNode[] = []\n ): UISpecNode[] | null {\n const newPath = [...currentPath, node];\n\n if (node.id === id) {\n return newPath;\n }\n\n if (node.children) {\n for (const child of node.children) {\n const path = findPath(child, id, newPath);\n if (path) return path;\n }\n }\n\n return null;\n }\n\n const path = findPath(result, nodeId);\n if (!path) return result; // Node not found, return original\n\n // The last item in the path is the node to update\n const nodeToUpdate = path[path.length - 1];\n const updatedNode = updater(nodeToUpdate);\n\n // If this is the root node, return the updated node\n if (path.length === 1) {\n return updatedNode;\n }\n\n // Otherwise, update the parent's children\n const parent = path[path.length - 2];\n const updatedParent = {\n ...parent,\n children: parent.children\n ? parent.children.map((child) =>\n child.id === nodeId ? updatedNode : child\n )\n : null,\n };\n\n // If the parent is root, return it\n if (path.length === 2) {\n return updatedParent;\n }\n\n // Otherwise, recursively update up the tree\n return updateNodeById(result, parent.id, () => updatedParent);\n}\n\n/**\n * Replace a specific node in the UI tree\n * @param tree - Original UI tree\n * @param nodeId - ID of the node to replace\n * @param newNode - New node to insert\n * @returns Updated UI tree\n */\nexport function replaceNodeById(\n tree: UISpecNode,\n nodeId: string,\n newNode: UISpecNode\n): UISpecNode {\n return updateNodeById(tree, nodeId, () => newNode);\n}\n\n/**\n * Add a child node to a specific parent node\n * @param tree - Original UI tree\n * @param parentId - ID of the parent node\n * @param newChild - Child node to add\n * @param index - Optional index to insert at (default: append)\n * @returns Updated UI tree\n */\nexport function addChildNode(\n tree: UISpecNode,\n parentId: string,\n newChild: UISpecNode,\n index?: number\n): UISpecNode {\n return updateNodeById(tree, parentId, (node) => {\n const children = node.children ? [...node.children] : [];\n\n if (index !== undefined && index >= 0 && index <= children.length) {\n children.splice(index, 0, newChild);\n } else {\n children.push(newChild);\n }\n\n return {\n ...node,\n children,\n };\n });\n}\n\n/**\n * Remove a node from the UI tree\n * @param tree - Original UI tree\n * @param nodeId - ID of the node to remove\n * @returns Updated UI tree\n */\nexport function removeNodeById(tree: UISpecNode, nodeId: string): UISpecNode {\n // Find the parent of the node\n function findParent(node: UISpecNode, id: string): UISpecNode | null {\n if (node.children) {\n if (node.children.some((child) => child.id === id)) {\n return node;\n }\n\n for (const child of node.children) {\n const parent = findParent(child, id);\n if (parent) return parent;\n }\n }\n\n return null;\n }\n\n // Clone the tree to avoid mutations\n const result = cloneNode(tree);\n\n // If trying to remove the root, return empty tree\n if (result.id === nodeId) {\n throw new Error(\"Cannot remove root node\");\n }\n\n const parent = findParent(result, nodeId);\n if (!parent) return result; // Node not found, return original\n\n // Update the parent by filtering out the node\n return updateNodeById(result, parent.id, (node) => ({\n ...node,\n children: node.children\n ? node.children.filter((child) => child.id !== nodeId)\n : null,\n }));\n}\n\n/**\n * Pure reducer function for the UI state engine\n * @param state - Current state\n * @param action - Action to apply\n * @returns New state\n */\nexport function uiReducer(state: UIState, action: UIAction): UIState {\n switch (action.type) {\n case \"UI_EVENT\": {\n // Add the event to history and set loading state\n return {\n ...state,\n loading: true,\n history: [...state.history, action.event],\n };\n }\n\n case \"AI_RESPONSE\": {\n // Replace the layout with the new node and set loading to false\n return {\n ...state,\n layout: action.node,\n loading: false,\n error: null,\n };\n }\n\n case \"PARTIAL_UPDATE\": {\n if (!state.layout) {\n return {\n ...state,\n layout: action.node,\n loading: false,\n error: null,\n };\n }\n\n // Find the node to update\n if (action.nodeId === \"root\" || action.nodeId === state.layout.id) {\n // Root node replacement\n return {\n ...state,\n layout: action.node,\n loading: false,\n error: null,\n };\n }\n\n // Replace a specific node in the tree\n return {\n ...state,\n layout: replaceNodeById(state.layout, action.nodeId, action.node),\n loading: false,\n error: null,\n };\n }\n\n case \"ADD_NODE\": {\n if (!state.layout) {\n // Cannot add to a null layout, perhaps set the new node as root or error\n return {\n ...state,\n error: \"Cannot add node: Layout is empty.\",\n loading: false,\n };\n }\n return {\n ...state,\n layout: addChildNode(\n state.layout,\n action.parentId,\n action.node,\n action.index === null ? undefined : action.index\n ),\n loading: false,\n error: null,\n };\n }\n\n case \"REMOVE_NODE\": {\n if (!state.layout) {\n return {\n ...state,\n error: \"Cannot remove node: Layout is empty.\",\n loading: false,\n };\n }\n try {\n return {\n ...state,\n layout: removeNodeById(state.layout, action.nodeId),\n loading: false,\n error: null,\n };\n } catch (e: unknown) {\n const errorMessage =\n e instanceof Error ? e.message : \"Failed to remove node.\";\n return {\n ...state,\n error: errorMessage,\n loading: false,\n };\n }\n }\n\n case \"ERROR\": {\n return {\n ...state,\n error: action.message,\n loading: false,\n };\n }\n\n case \"LOADING\": {\n return {\n ...state,\n loading: action.isLoading,\n };\n }\n\n default:\n return state;\n }\n}\n\n/**\n * Initial state for the UI state engine\n */\nexport const initialState: UIState = {\n layout: null,\n loading: false,\n history: [],\n error: null,\n};\n","import { UIEvent, UISpecNode, PlannerInput } from \"../schema/ui\";\nimport { DataContext } from \"./bindings\";\nimport { findNodeById } from \"./reducer\";\n\n// --- Constants for Prompt Generation ---\n\n// Base UI Guidance\nconst UI_GUIDANCE_BASE = `\nUI Guidance:\n1. Create a focused interface that directly addresses the goal\n2. Use appropriate UI patterns (lists, forms, details, etc.)\n3. Include navigation between related views when needed\n4. Keep the interface simple and intuitive\n5. Bind to schema data where appropriate\n6. Provide event handlers for user interactions - make sure to always include both action and target properties`;\n\n// Specific guidance for list bindings\nconst LIST_BINDING_GUIDANCE = `7. **CRITICAL:** For \\`ListView\\` or \\`Table\\` nodes, the \\`data\\` binding key **MUST** point to the *exact path* of the data *array* within the context.`;\n\n// Example for list binding\nconst LIST_BINDING_EXAMPLE = `Example: If the context has \\`{ tasks: { data: [...] } }\\`, the binding **MUST** be \\`{ \"bindings\": { \"data\": \"tasks.data\" } }\\`. If the context has \\`{ userList: [...] }\\`, the binding **MUST** be \\`{ \"bindings\": { \"data\": \"userList\" } }\\`. **NEVER** bind to the parent object containing the array (e.g., DO NOT USE \\`{ \"bindings\": { \"data\": \"tasks\" } }\\`).`;\n\n// Combined common UI guidance - THIS SHOULD BE EXPORTED\nexport const COMMON_UI_GUIDANCE =\n UI_GUIDANCE_BASE +\n \"\\n\" + // Add a newline separator\n LIST_BINDING_GUIDANCE + // Add the specific list binding rule\n \"\\n\" + // Add a newline separator\n LIST_BINDING_EXAMPLE; // Add the example\n\n// Function to process template strings (simple substitution)\nfunction processTemplate(\n template: string,\n values: Record<string, unknown>\n): string {\n return template.replace(/\\${(.*?)}/g, (match, key) => {\n const trimmedKey = key.trim();\n // Basic handling for simple keys; does not handle nested paths like eventPayload.detail\n return trimmedKey in values ? String(values[trimmedKey]) : match;\n });\n}\n\n// Moved from planner.ts\n/**\n * Builds the prompt for the LLM planner\n * @param input - Planner input including schema, goal, history, and userContext\n * @param promptTemplate - Optional prompt template string\n * @param templateValues - Optional values for the template string, used if promptTemplate is provided\n * @returns Formatted prompt string\n */\nexport function buildPrompt(\n input: PlannerInput,\n promptTemplate?: string,\n templateValues?: Record<string, unknown>\n): string {\n const { schema, goal, history, userContext } = input;\n\n // Extract schema information without actual data rows\n const schemaInfo = Object.entries(schema)\n .map(([tableName, tableSchema]) => {\n // Simple check if it looks like a structured schema object vs a simple type\n const schemaString =\n typeof tableSchema === \"object\" && tableSchema !== null\n ? JSON.stringify(tableSchema)\n : String(tableSchema);\n return `Table: ${tableName}\\nSchema: ${schemaString}`;\n })\n .join(\"\\n\\n\");\n\n // Format recent events for context\n const recentEvents =\n history && history.length > 0\n ? history\n .slice(-5) // Limit history length\n .map(\n (event) =>\n `Event: ${event.type} on node ${event.nodeId}${\n event.payload\n ? ` with payload ${JSON.stringify(event.payload)}`\n : \"\"\n }`\n )\n .join(\"\\n\")\n : \"No recent events\";\n\n // Build user context section if provided\n const userContextSection = userContext\n ? `\\n\\nUser Context:\\n${JSON.stringify(userContext)}`\n : \"\";\n\n // If a specific prompt template is provided, process it\n // This now becomes the primary way to use custom prompts via ActionRouteConfig\n if (promptTemplate && templateValues) {\n // Inject schema, history, userContext, and common guidance into values for template processing\n const fullTemplateValues = {\n ...templateValues,\n schemaInfo,\n recentEvents,\n userContextString: userContextSection.trim(), // Use trimmed version\n commonUIGuidance: COMMON_UI_GUIDANCE,\n goal, // Ensure goal is always available to templates\n };\n return processTemplate(promptTemplate, fullTemplateValues);\n }\n\n // --- Default Prompt Construction (used when no template is provided by a route, e.g. initial FULL_REFRESH) ---\n\n // Default interaction description: Check if history is empty\n const interactionDescription =\n history && history.length > 0\n ? `The user's last action was: ${\n history[history.length - 1].type\n } on node ${history[history.length - 1].nodeId}`\n : \"The user initiated the session for the goal\";\n\n // Assemble the full default prompt\n return `\nYou are an expert UI generator.\nCreate a user interface that achieves the following goal: \"${goal}\".\n${interactionDescription}.\n\nAvailable data schema:\n${schemaInfo}\n\nRecent user interactions:\n${recentEvents}${userContextSection}\n\nGenerate a complete UI specification in JSON format that matches the following TypeScript type:\ntype UISpecNode = { id: string; node_type: string; props?: Record<string, unknown>; bindings?: Record<string, unknown>; events?: Record<string, { action: string; target: string; payload?: Record<string, unknown>; }>; children?: UISpecNode[]; };\n${COMMON_UI_GUIDANCE}\n\nRespond ONLY with the JSON UI specification and no other text.\n `;\n}\n\n/**\n * Action types supported by the router\n */\nexport enum ActionType {\n FULL_REFRESH = \"FULL_REFRESH\", // Generate a completely new UI\n UPDATE_NODE = \"UPDATE_NODE\", // Update a specific node, potentially with new children\n ADD_DROPDOWN = \"ADD_DROPDOWN\", // Add a dropdown to a specific node\n SHOW_DETAIL = \"SHOW_DETAIL\", // Show a detail view\n HIDE_DETAIL = \"HIDE_DETAIL\", // Hide a detail view\n TOGGLE_STATE = \"TOGGLE_STATE\", // Toggle a boolean state (expanded, selected, etc.)\n UPDATE_FORM = \"UPDATE_FORM\", // Update a form based on selections\n NAVIGATE = \"NAVIGATE\", // Navigate to a different view\n}\n\n/**\n * Routing configuration for an action\n */\nexport interface ActionRouteConfig {\n actionType: ActionType;\n targetNodeId?: string; // Optional: target node for the action (e.g., where to place a new detail view)\n promptTemplate?: string; // Template for the LLM prompt, now optional\n contextKeys?: string[]; // Optional: keys to extract from DataContext and include in planner input\n}\n\n/**\n * Interface for route resolution\n */\nexport interface RouteResolution {\n actionType: ActionType;\n targetNodeId: string;\n plannerInput: PlannerInput;\n prompt: string;\n}\n\n/**\n * Action router class - handles determining what part of the UI to update\n */\nexport class ActionRouter {\n private routes: Record<string, ActionRouteConfig[]> = {};\n\n /**\n * Register a new action route\n * @param eventType - UI event type to route\n * @param config - Route configuration\n */\n public registerRoute(eventType: string, config: ActionRouteConfig): void {\n if (!this.routes[eventType]) {\n this.routes[eventType] = [];\n }\n\n this.routes[eventType].push(config);\n }\n\n /**\n * Find the appropriate route for an event\n * @param event - UI event\n * @param layout - Current UI layout\n * @param dataContext - Current data context\n * @returns Route resolution or null if no match\n */\n public resolveRoute(\n event: UIEvent,\n schema: Record<string, unknown>,\n layout: UISpecNode | null,\n dataContext: DataContext,\n goal: string,\n userContext?: Record<string, unknown>\n ): RouteResolution | null {\n console.log(\n `[ActionRouter Debug] resolveRoute called for event type: ${event.type}`\n );\n // Get all routes for this event type\n const routes = this.routes[event.type] || [];\n\n console.log(\n `[ActionRouter Debug] Found ${routes.length} routes for ${event.type}`\n );\n\n if (routes.length === 0) {\n // Default to full refresh if no routes defined\n console.log(\n `[ActionRouter Debug] No specific route found for ${event.type}, using default FULL_REFRESH.`\n );\n const defaultPlannerInput = {\n schema,\n goal,\n history: [event],\n userContext: userContext || null,\n };\n const defaultPrompt = buildPrompt(\n defaultPlannerInput,\n undefined,\n undefined\n );\n const defaultResolution = {\n actionType: ActionType.FULL_REFRESH,\n targetNodeId: layout?.id || \"root\",\n plannerInput: defaultPlannerInput,\n prompt: defaultPrompt,\n };\n console.log(\n \"[ActionRouter Debug] Default Resolution:\",\n defaultResolution\n );\n return defaultResolution;\n }\n\n // Try to find source node\n const sourceNode = layout ? findNodeById(layout, event.nodeId) : undefined;\n\n // Get the node configuration if available\n const nodeConfig = sourceNode?.events?.[event.type];\n\n // Try to find a matching route based on node configuration\n let matchingRoute: ActionRouteConfig | undefined;\n\n if (nodeConfig) {\n matchingRoute = routes.find(\n (route) => route.actionType.toString() === nodeConfig.action\n );\n }\n\n // If no match via node configuration, use the first route\n if (!matchingRoute) {\n matchingRoute = routes[0];\n }\n\n console.log(\"[ActionRouter Debug] Matching Route Config:\", matchingRoute);\n\n // Resolve target node ID\n const targetNodeId =\n nodeConfig?.target || matchingRoute.targetNodeId || event.nodeId;\n\n // Build additional context\n const additionalContext: Record<string, unknown> = {};\n\n if (matchingRoute.contextKeys) {\n matchingRoute.contextKeys.forEach((key) => {\n additionalContext[key] = dataContext[key];\n });\n }\n\n // Add source node info\n if (sourceNode) {\n additionalContext.sourceNode = sourceNode;\n }\n\n // Add target node info if available\n if (layout) {\n const targetNode = findNodeById(layout, targetNodeId);\n if (targetNode) {\n additionalContext.targetNode = targetNode;\n }\n }\n\n // Add event payload\n if (event.payload) {\n additionalContext.eventPayload = event.payload;\n }\n\n // Merge context with any payload from node config\n if (nodeConfig?.payload) {\n Object.entries(nodeConfig.payload).forEach(([key, value]) => {\n additionalContext[key] = value;\n });\n }\n\n // Build planner input\n const plannerInput: PlannerInput = {\n schema,\n goal,\n history: [event],\n userContext: {\n ...userContext,\n ...additionalContext,\n },\n };\n\n // Process prompt template\n const templateValues = {\n goal,\n eventType: event.type,\n nodeId: event.nodeId,\n targetNodeId,\n actionType: matchingRoute.actionType,\n ...(userContext || {}), // Spread the original userContext (passed to resolveRoute)\n ...additionalContext, // Spread additionalContext afterwards (can override userContext keys)\n };\n\n console.log(\"[ActionRouter Debug] Template Values:\", templateValues);\n\n // Generate final prompt using buildPrompt\n // It will use the template if provided, otherwise generate the default based on plannerInput.\n const finalPrompt = buildPrompt(\n plannerInput,\n matchingRoute.promptTemplate, // Pass template if it exists (can be undefined)\n templateValues // Pass templateValues (used only if promptTemplate exists)\n );\n console.log(\"[ActionRouter Debug] Generated Prompt:\", finalPrompt);\n\n const finalResolution = {\n actionType: matchingRoute.actionType,\n targetNodeId: targetNodeId,\n plannerInput,\n prompt: finalPrompt, // Use the generated prompt\n };\n\n console.log(\"[ActionRouter Debug] Final Resolution:\", finalResolution);\n return finalResolution;\n }\n\n /**\n * Process a prompt template with variables\n * @param template - Template string with ${var} placeholders\n * @param values - Values to substitute\n * @returns Processed string\n */\n private processTemplate(\n template: string,\n values: Record<string, unknown>\n ): string {\n return template.replace(/\\${(\\w+)}/g, (_, key) => {\n return values[key] !== undefined ? String(values[key]) : `\\${${key}}`;\n });\n }\n}\n\n// Create a default router with common routes\nexport function createDefaultRouter(): ActionRouter {\n const router = new ActionRouter();\n\n // Register a default route for CLICK events (will generate a full refresh prompt)\n router.registerRoute(\"CLICK\", {\n actionType: ActionType.FULL_REFRESH,\n targetNodeId: \"root\",\n });\n\n // Default route for INIT event (typically the first event)\n router.registerRoute(\"INIT\", {\n actionType: ActionType.FULL_REFRESH,\n targetNodeId: \"root\",\n });\n\n // Show detail route\n router.registerRoute(\"CLICK\", {\n actionType: ActionType.SHOW_DETAIL,\n targetNodeId: \"${targetNodeId}\",\n promptTemplate:\n \"Update the UI to show details for the selected item. Current node: ${nodeId}, Target node: ${targetNodeId}\",\n contextKeys: [\"selected\"],\n });\n\n // Navigate route\n router.registerRoute(\"CLICK\", {\n actionType: ActionType.NAVIGATE,\n targetNodeId: \"root\",\n promptTemplate:\n \"Navigate to a new view based on the user clicking ${nodeId}. Current goal: ${goal}\",\n });\n\n // Dropdown route\n router.registerRoute(\"CLICK\", {\n actionType: ActionType.ADD_DROPDOWN,\n targetNodeId: \"${targetNodeId}\",\n promptTemplate:\n \"Add a dropdown menu to node ${targetNodeId} with options relevant to the clicked element ${nodeId}\",\n });\n\n // Toggle state route\n router.registerRoute(\"CLICK\", {\n actionType: ActionType.TOGGLE_STATE,\n targetNodeId: \"${nodeId}\",\n promptTemplate:\n \"Toggle the state of node ${nodeId} (e.g., expanded/collapsed, selected/unselected)\",\n });\n\n // Form update route\n router.registerRoute(\"CHANGE\", {\n actionType: ActionType.UPDATE_FORM,\n targetNodeId: \"${targetNodeId}\",\n promptTemplate:\n \"Update the form based on the user changing the value of ${nodeId}\",\n });\n\n return router;\n}\n","import React, { useState, useCallback, useRef, useEffect } from \"react\";\nimport { UIEvent, UISpecNode, UIEventType, DataItem } from \"./schema/ui\";\nimport { useUIStateEngine, UseUIStateEngineOptions } from \"./core/state\";\nimport { renderNode, renderShimmer } from \"./core/renderer\";\nimport { resolveBindings, DataContext, executeAction } from \"./core/bindings\";\nimport { EventManager, EventHook } from \"./core/events\";\nimport {\n SystemEventType,\n SystemEventHook,\n systemEvents,\n} from \"./core/system-events\";\nimport { SchemaAdapter } from \"./adapters/schema\";\nimport {\n areShadcnComponentsAvailable,\n getMissingComponentsMessage,\n} from \"./core/component-detection\";\nimport \"./styles/autoui.css\";\n\n// Helper function to correct list bindings\nfunction correctListBindingsRecursive(\n node: UISpecNode,\n dataContext: DataContext\n): UISpecNode {\n // Deep clone to avoid mutating the original state.layout directly during correction\n // This is important because state.layout might be used elsewhere or in dependencies.\n const correctedNode = JSON.parse(JSON.stringify(node)) as UISpecNode;\n\n if (\n (correctedNode.node_type === \"ListView\" ||\n correctedNode.node_type === \"Table\") &&\n correctedNode.bindings?.data\n ) {\n const bindingPath = correctedNode.bindings.data;\n if (typeof bindingPath === \"string\") {\n const pathSegments = bindingPath.split(\".\");\n const mainKey = pathSegments[0]; // e.g., 'tasks'\n\n // Check if the binding path is just the main key (e.g., \"tasks\")\n // and if a .data sub-property exists and is an array in the context.\n if (pathSegments.length === 1) {\n const potentialDataContextEntry = dataContext[mainKey];\n if (\n potentialDataContextEntry &&\n typeof potentialDataContextEntry === \"object\" &&\n potentialDataContextEntry !== null &&\n \"data\" in potentialDataContextEntry &&\n Array.isArray((potentialDataContextEntry as { data: unknown }).data)\n ) {\n correctedNode.bindings.data = `${mainKey}.data`;\n console.log(\n `[AutoUI Debug] Corrected list binding for node '${correctedNode.id}': from '${mainKey}' to '${mainKey}.data'`\n );\n }\n }\n }\n }\n\n if (correctedNode.children) {\n correctedNode.children = correctedNode.children.map((child) =>\n correctListBindingsRecursive(child, dataContext)\n );\n }\n\n return correctedNode;\n}\n\n// Interface for DrizzleAdapterOptions\ninterface DrizzleAdapterOptions {\n schema: Record<string, unknown>;\n // Add other options as needed\n}\n\nexport interface AutoUIProps\n extends Omit<UseUIStateEngineOptions, \"router\" | \"dataContext\"> {\n // Extend options from the state engine, excluding ones managed internally\n // Schema definition (one of these is required)\n schema:\n | Record<string, unknown> // Direct schema object\n | { type: \"drizzle\"; options: DrizzleAdapterOptions } // Drizzle adapter\n | { type: \"custom\"; adapter: SchemaAdapter }; // Custom adapter\n\n // Required\n goal: string;\n\n // Optional configurations\n componentAdapter?: \"shadcn\";\n userContext?: Record<string, unknown>;\n onEvent?: (evt: UIEvent) => void;\n\n // UI Event hooks\n eventHooks?: {\n all?: EventHook[];\n [key: string]: EventHook[] | undefined;\n };\n\n // System Event hooks\n systemEventHooks?: {\n [key: string]: SystemEventHook[] | undefined;\n };\n\n // Enable partial UI updates (instead of regenerating entire UI on each interaction)\n enablePartialUpdates?: boolean;\n\n // Define custom UI update patterns\n updatePatterns?: {\n // Allow target components to show dropdowns\n enableDropdowns?: boolean;\n // Allow for showing/hiding detail views\n enableDetailViews?: boolean;\n // Allow for expanding/collapsing sections\n enableExpandCollapse?: boolean;\n // Allow for multi-step form navigation\n enableFormNavigation?: boolean;\n };\n\n // Integration configuration\n integration?: {\n // Whether to generate a standalone UI or a component for integration\n mode?: \"standalone\" | \"component\";\n // CSS class names to apply to the root element\n className?: string;\n // Inline styles to apply to the root element\n style?: React.CSSProperties;\n // ID of the root element\n id?: string;\n };\n\n // Scope of the generation - what kind of UI element to generate\n scope?: {\n // Type of component to generate\n type?: \"form\" | \"list\" | \"detail\" | \"dashboard\" | \"full-page\" | \"card\";\n // Specific focus for the generation\n focus?: string;\n };\n\n // Debug mode - shows system events in console\n debugMode?: boolean;\n\n mockMode?: boolean;\n\n // Database configuration\n databaseConfig?: Record<string, unknown>;\n\n // Planning configuration\n planningConfig?: {\n // Future planning depth (for v0.2)\n prefetchDepth?: number;\n // Custom temperature for the LLM (0.0 - 1.0)\n temperature?: number;\n // Whether to use streaming (otherwise wait for complete response)\n streaming?: boolean;\n };\n\n // Add the openaiApiKey prop here\n openaiApiKey?: string;\n}\n\n/**\n * AutoUI - Main component for generating goal-oriented UIs\n *\n * @example\n * ```tsx\n * import { AutoUI } from 'autoui-react';\n * import { emailsTable, usersTable } from './schema';\n *\n * function MyApp() {\n * return (\n * <AutoUI\n * schema={{ emails: emailsTable, users: usersTable }}\n * goal=\"Create an inbox view with email list and detail view\"\n * />\n * );\n * }\n * ```\n */\nexport const AutoUI: React.FC<AutoUIProps> = ({\n schema,\n goal,\n componentAdapter = \"shadcn\",\n userContext,\n onEvent,\n eventHooks,\n systemEventHooks,\n debugMode = false,\n mockMode = false,\n planningConfig,\n integration = {},\n scope = {},\n enablePartialUpdates = false,\n openaiApiKey,\n}) => {\n // Initialize schema adapter if provided\n const [schemaAdapterInstance] = useState<SchemaAdapter | null>(null);\n const [dataContext, setDataContext] = useState<DataContext>({});\n // Check if required components are available\n const [componentsAvailable, setComponentsAvailable] = useState(true);\n\n // Use direct schema as the effective schema\n const effectiveSchema = schema as Record<string, unknown>;\n const scopedGoal = goal;\n // Pass undefined for the router - it will use the default in the useUIStateEngine function\n\n // Check if required components are available\n useEffect(() => {\n if (componentAdapter === \"shadcn\") {\n setComponentsAvailable(areShadcnComponentsAvailable());\n }\n }, [componentAdapter]);\n\n // Register system event hooks\n useEffect(() => {\n const unregisters: Array<() => void> = [];\n\n // Register system event hooks\n if (systemEventHooks) {\n Object.entries(systemEventHooks).forEach(([eventType, hooks]) => {\n if (!hooks) return;\n\n (hooks as SystemEventHook[]).forEach((hook) => {\n const unregister = systemEvents.on(\n eventType as SystemEventType,\n hook\n );\n unregisters.push(unregister);\n });\n });\n }\n\n // Debug mode - log all system events to console EXCEPT FOR RENDER_START\n // to prevent infinite rendering loops\n if (debugMode) {\n const debugHook: SystemEventHook = (event) => {\n console.debug(`[AutoUI Debug] System Event:`, event);\n };\n\n // Register for all system event types EXCEPT RENDER_START and BINDING_RESOLUTION_START\n // which can cause infinite loops when debugging\n Object.values(SystemEventType)\n .filter(\n (eventType) =>\n eventType !== SystemEventType.RENDER_START &&\n eventType !== SystemEventType.BINDING_RESOLUTION_START\n )\n .forEach((eventType) => {\n const unregister = systemEvents.on(eventType, debugHook);\n unregisters.push(unregister);\n });\n }\n\n return () => {\n unregisters.forEach((unregister) => unregister());\n };\n }, [systemEventHooks, debugMode]);\n\n // Initialize data context based on schema\n useEffect(() => {\n const initializeDataContext = async () => {\n let initialData: DataContext = {};\n\n if (schemaAdapterInstance) {\n // Use schema adapter to initialize data context\n initialData = await schemaAdapterInstance.initializeDataContext();\n } else if (effectiveSchema) {\n // Initialize with direct schema object\n Object.entries(effectiveSchema).forEach(([key, tableSchema]) => {\n // Add schema information\n initialData[key] = {\n schema: tableSchema,\n // For development, add sample data if available\n data:\n (tableSchema as { sampleData?: DataItem[] })?.sampleData || [],\n selected: null,\n };\n });\n }\n\n // Add user context if provided\n if (userContext) {\n initialData.user = userContext;\n }\n\n setDataContext(initialData);\n };\n\n initializeDataContext();\n }, [effectiveSchema, schemaAdapterInstance, userContext]);\n\n // Initialize the UI state engine with scoped goal\n const { state, handleEvent } = useUIStateEngine({\n schema: effectiveSchema,\n goal: scopedGoal,\n userContext,\n mockMode,\n planningConfig,\n router: undefined,\n dataContext,\n enablePartialUpdates,\n openaiApiKey,\n });\n\n // Create event manager\n const eventManagerRef = useRef(new EventManager());\n\n // Register event hooks\n useEffect(() => {\n if (!eventHooks) return;\n\n const unregisters: Array<() => void> = [];\n\n // Register global hooks\n if (eventHooks.all) {\n const unregister = eventManagerRef.current.register(\n \"all\",\n async (ctx) => {\n for (const hook of eventHooks.all || []) {\n await hook(ctx);\n if (ctx.isPropagationStopped()) break;\n }\n }\n );\n unregisters.push(unregister);\n }\n\n // Register type-specific hooks\n Object.entries(eventHooks).forEach(([type, hooks]) => {\n if (type === \"all\" || !hooks) return;\n\n const unregister = eventManagerRef.current.register(\n [type as UIEventType],\n async (ctx) => {\n for (const hook of hooks as EventHook[]) {\n await hook(ctx);\n if (ctx.isPropagationStopped()) break;\n }\n }\n );\n unregisters.push(unregister);\n });\n\n // Cleanup on unmount or when hooks change\n return () => {\n unregisters.forEach((unregister) => unregister());\n };\n }, [eventHooks]);\n\n // Process events and update data context\n const processEvent = useCallback(\n async (event: UIEvent) => {\n // Process through event hooks\n const shouldProceed = await eventManagerRef.current.processEvent(event);\n\n // Call the external event handler if provided\n if (onEvent) {\n onEvent(event);\n }\n\n if (!shouldProceed) {\n console.info(\"Event processing was prevented by hooks\", event);\n return;\n }\n\n // Find the event configuration in the layout tree\n const findNodeById = (\n node: UISpecNode | undefined | null,\n id: string\n ): UISpecNode | undefined => {\n if (!node) return undefined;\n if (node.id === id) return node;\n if (node.children) {\n for (const child of node.children) {\n const found = findNodeById(child, id);\n if (found) return found;\n }\n }\n return undefined;\n };\n\n const sourceNode = findNodeById(state.layout, event.nodeId);\n if (!sourceNode) {\n console.warn(`Node not found for event: ${event.nodeId}`);\n handleEvent(event);\n return;\n }\n\n // Get the event configuration\n const eventConfig = sourceNode.events?.[event.type];\n if (!eventConfig) {\n console.warn(\n `No event config found for ${event.type} on node ${event.nodeId}`\n );\n handleEvent(event);\n return;\n }\n\n // Execute the action and update data context\n const newContext = executeAction(\n eventConfig.action,\n eventConfig.target || \"\", // Provide empty string as fallback if target is null\n {\n ...eventConfig.payload,\n ...event.payload,\n },\n dataContext,\n state.layout || undefined\n );\n\n // Update the data context\n setDataContext(newContext);\n\n // Forward the event to the UI state engine\n handleEvent(event);\n },\n [dataContext, handleEvent, onEvent, state.layout]\n );\n\n // Resolve bindings for the layout using the current data context\n const [resolvedLayout, setResolvedLayout] = useState<UISpecNode | undefined>(\n undefined\n );\n // Add state for rendered node\n const [renderedNode, setRenderedNode] = useState<React.ReactElement | null>(\n null\n );\n\n // Update the resolved layout whenever state.layout or dataContext changes\n // Create a stable function to avoid constantly re-running the effect\n const resolveLayoutBindings = useCallback(async () => {\n if (state.layout && dataContext) {\n // Existing logs\n console.log(\n \"[AutoUI Debug] DataContext before resolving bindings:\",\n JSON.stringify(dataContext, null, 2)\n );\n console.log(\n \"[AutoUI Debug] Raw layout before resolving (from planner):\",\n JSON.stringify(state.layout, null, 2)\n );\n\n // Correct list bindings before attempting to resolve them\n const correctedLayout = correctListBindingsRecursive(\n state.layout,\n dataContext\n );\n console.log(\n \"[AutoUI Debug] Layout after binding correction (before resolving):\",\n JSON.stringify(correctedLayout, null, 2)\n );\n\n const resolved = await resolveBindings(correctedLayout, dataContext);\n setResolvedLayout(resolved);\n console.log(\n \"[AutoUI Debug] Resolved layout after bindings:\",\n JSON.stringify(resolved, null, 2)\n );\n } else {\n setResolvedLayout(undefined);\n }\n }, [state.layout, dataContext]);\n\n // Call the stable function in the effect\n useEffect(() => {\n resolveLayoutBindings();\n }, [resolveLayoutBindings]);\n\n // Handle async rendering of the node with a stable reference\n const renderResolvedLayout = useCallback(async () => {\n if (resolvedLayout) {\n try {\n const rendered = await renderNode(\n resolvedLayout,\n componentAdapter as \"shadcn\",\n processEvent\n );\n setRenderedNode(rendered);\n } catch (err) {\n console.error(\"Error rendering node:\", err);\n }\n } else {\n setRenderedNode(null);\n }\n }, [resolvedLayout, componentAdapter, processEvent]);\n\n // Call the stable render function in the effect\n useEffect(() => {\n renderResolvedLayout();\n }, [renderResolvedLayout]);\n\n // If components are not available, show error message\n if (!componentsAvailable) {\n return (\n <div className=\"autoui-error p-4 border border-red-300 bg-red-50 text-red-700 rounded\">\n <p className=\"font-medium\">Component Library Not Found</p>\n <p className=\"text-sm whitespace-pre-line\">\n {getMissingComponentsMessage()}\n </p>\n </div>\n );\n }\n\n // Render UI\n return (\n <div\n className={`autoui-root ${integration.className || \"\"}`}\n id={integration.id}\n data-mode={integration.mode}\n data-scope={scope?.type || \"full\"}\n >\n {state.loading || !resolvedLayout ? (\n // Render shimmer loading state\n <div className=\"autoui-loading\">\n {state.layout ? (\n renderShimmer(state.layout, componentAdapter as \"shadcn\")\n ) : (\n <div className=\"autoui-shimmer-container\">\n <div className=\"autoui-shimmer-header\" />\n <div className=\"autoui-shimmer-content\" />\n </div>\n )}\n </div>\n ) : (\n // Render the resolved layout\n <div className=\"autoui-content\">{renderedNode}</div>\n )}\n\n {state.error && (\n <div className=\"autoui-error p-4 border border-red-300 bg-red-50 dark:bg-red-900 dark:border-red-700 rounded-md\">\n <p className=\"autoui-error-title text-lg font-semibold text-red-700 dark:text-red-300 mb-2\">\n Error generating UI\n </p>\n <p className=\"autoui-error-message text-sm text-red-600 dark:text-red-300\">\n {state.error}\n </p>\n\n {!mockMode && (\n <div className=\"mt-4 text-sm text-red-600 dark:text-red-300\">\n <p>This could be because:</p>\n <ul className=\"list-disc pl-5 mt-2\">\n <li>Your OpenAI API key is missing or invalid</li>\n <li>The OpenAI service is experiencing issues</li>\n <li>Your API rate limit has been exceeded</li>\n </ul>\n <p className=\"mt-2\">\n Try setting <code>mockMode=true</code> to use sample data\n instead.\n </p>\n </div>\n )}\n </div>\n )}\n </div>\n );\n};\n","import { useReducer, useCallback, useEffect } from \"react\";\n// Mock useChat hook for development\n// const useChat = (config: any) => { ... };\n\nimport {\n UIEvent,\n UISpecNode,\n // uiSpecNode, // Will be handled by planner.ts, not directly by state.ts for parsing\n PlannerInput,\n} from \"../schema/ui\";\nimport { uiReducer, initialState } from \"./reducer\";\nimport { mockPlanner, callPlannerLLM } from \"./planner\"; // Added callPlannerLLM\nimport {\n systemEvents,\n createSystemEvent,\n SystemEventType,\n} from \"./system-events\";\nimport { ActionRouter, ActionType, createDefaultRouter } from \"./action-router\";\n\nexport interface UseUIStateEngineOptions {\n schema: Record<string, unknown>;\n goal: string;\n openaiApiKey?: string | undefined;\n userContext?: Record<string, unknown> | undefined;\n mockMode?: boolean | undefined;\n planningConfig?:\n | {\n prefetchDepth?: number;\n temperature?: number;\n streaming?: boolean;\n }\n | undefined;\n router?: ActionRouter | undefined;\n dataContext?: Record<string, unknown> | undefined;\n enablePartialUpdates?: boolean | undefined;\n}\n\n/**\n * Custom hook for the UI state engine\n * @param options - Configuration options\n * @returns State and dispatcher\n */\nexport function useUIStateEngine({\n schema,\n goal,\n openaiApiKey,\n userContext,\n mockMode = false,\n planningConfig,\n router = createDefaultRouter(),\n dataContext = {},\n enablePartialUpdates = false,\n}: UseUIStateEngineOptions) {\n // Warn if userContext is explicitly null, as it's an edge case we want to discourage.\n // Consumers should use undefined if they mean to omit it.\n if (userContext === null) {\n console.warn(\n \"useUIStateEngine: userContext was explicitly set to null. \" +\n \"This is an allowed but discouraged value. Consider using undefined if you intend to omit the user context.\"\n );\n }\n\n const [state, dispatch] = useReducer(uiReducer, initialState);\n // const { append, data, isLoading, error, stop } = useChat(null); // REMOVE useChat\n\n // Function to handle UI events with routing\n const handleEvent = useCallback(\n async (event: UIEvent) => {\n // Make async\n dispatch({ type: \"UI_EVENT\", event });\n dispatch({ type: \"LOADING\", isLoading: true });\n\n try {\n let resolvedNode: UISpecNode;\n let actionTypeForDispatch: ActionType = ActionType.FULL_REFRESH; // Default\n let targetNodeIdForDispatch: string = \"root\"; // Default\n\n if (enablePartialUpdates) {\n const route = router.resolveRoute(\n event,\n schema,\n state.layout,\n dataContext,\n goal,\n userContext\n );\n\n if (route) {\n console.log(\"Resolved route:\", route);\n actionTypeForDispatch = route.actionType;\n targetNodeIdForDispatch = route.targetNodeId;\n\n systemEvents.emit(\n createSystemEvent(SystemEventType.PLAN_START, {\n plannerInput: route.plannerInput,\n })\n );\n\n if (mockMode) {\n resolvedNode = mockPlanner(\n route.plannerInput,\n route.targetNodeId,\n route.prompt\n );\n } else {\n // systemEvents.emit for PLAN_PROMPT_CREATED is handled inside callPlannerLLM\n resolvedNode = await callPlannerLLM(\n route.plannerInput,\n openaiApiKey || \"\",\n route\n );\n }\n } else {\n // Fallback if router.resolveRoute returns null (should not happen with default full refresh)\n const input: PlannerInput = {\n schema,\n goal,\n history: [...state.history, event],\n userContext,\n };\n if (mockMode) {\n resolvedNode = mockPlanner(input);\n } else {\n resolvedNode = await callPlannerLLM(\n input,\n openaiApiKey || \"\",\n undefined\n );\n }\n }\n } else {\n // Fallback to full refresh if partial updates disabled\n const input: PlannerInput = {\n schema,\n goal,\n history: [...state.history, event], // event is already in history from UI_EVENT dispatch\n userContext: userContext,\n };\n\n if (mockMode) {\n resolvedNode = mockPlanner(input);\n } else {\n // buildPrompt is handled inside callPlannerLLM if no route.prompt is provided\n resolvedNode = await callPlannerLLM(\n input,\n openaiApiKey || \"\",\n undefined\n );\n }\n }\n\n // Dispatch based on action type (derived from routing or default)\n switch (actionTypeForDispatch) {\n case ActionType.UPDATE_NODE:\n case ActionType.SHOW_DETAIL:\n case ActionType.HIDE_DETAIL:\n case ActionType.TOGGLE_STATE:\n case ActionType.ADD_DROPDOWN:\n case ActionType.UPDATE_FORM:\n case ActionType.NAVIGATE:\n dispatch({\n type: \"PARTIAL_UPDATE\",\n nodeId: targetNodeIdForDispatch,\n node: resolvedNode,\n });\n break;\n case ActionType.FULL_REFRESH:\n default:\n dispatch({ type: \"AI_RESPONSE\", node: resolvedNode });\n break;\n }\n // systemEvents.emit for PLAN_COMPLETE is handled by callPlannerLLM or should be added for mockPlanner path\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : String(e);\n dispatch({ type: \"ERROR\", message: errorMessage });\n systemEvents.emit(\n createSystemEvent(SystemEventType.PLAN_ERROR, {\n error: e instanceof Error ? e : new Error(String(e)),\n })\n );\n } finally {\n dispatch({ type: \"LOADING\", isLoading: false });\n }\n },\n [\n // append, // REMOVE\n goal,\n schema,\n state.history, // Keep state.history if input preparation needs it\n state.layout,\n // stop, // REMOVE\n userContext,\n router,\n mockMode,\n dataContext,\n openaiApiKey,\n enablePartialUpdates,\n dispatch, // Add dispatch\n ]\n );\n\n // Effect to process LLM responses - REMOVE THIS ENTIRE useEffect\n // useEffect(() => { ... }, [data.content, error, isLoading, enablePartialUpdates]);\n\n // Initial query on mount\n useEffect(() => {\n const initialFetch = async () => {\n dispatch({ type: \"LOADING\", isLoading: true });\n try {\n const input: PlannerInput = {\n schema,\n goal,\n history: [], // Initial history is empty\n userContext: userContext,\n };\n let node: UISpecNode;\n\n if (mockMode) {\n // For mock mode, we can still use the simpler mockPlanner directly\n // or simulate routing if necessary, but for now, let's keep it simple.\n node = mockPlanner(input);\n // Consider emitting PLAN_COMPLETE for mock path if needed\n } else {\n // For non-mock mode, we MUST go through the router to get a prompt\n const initEvent: UIEvent = {\n type: \"INIT\", // Assuming \"INIT\" is your initial event type\n nodeId: \"system\", // Or some other appropriate initial nodeId\n timestamp: Date.now(),\n payload: null,\n };\n\n // Resolve the route for the initial event\n const route = router.resolveRoute(\n initEvent,\n schema,\n null, // No existing layout on initial fetch\n dataContext,\n goal,\n userContext\n );\n\n if (!route || !route.prompt) {\n // This should ideally not happen if default routes are set up\n console.error(\n \"[UIStateEngine] Initial fetch: Failed to resolve route or get prompt for INIT event.\"\n );\n throw new Error(\"Failed to initialize UI due to routing error.\");\n }\n\n systemEvents.emit(\n createSystemEvent(SystemEventType.PLAN_START, {\n plannerInput: route.plannerInput,\n })\n );\n\n // Call planner with the resolved route (which includes the prompt)\n node = await callPlannerLLM(\n route.plannerInput, // Use plannerInput from the resolved route\n openaiApiKey || \"\",\n route // Pass the entire route object\n );\n }\n dispatch({ type: \"AI_RESPONSE\", node });\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : String(e);\n dispatch({ type: \"ERROR\", message: errorMessage });\n systemEvents.emit(\n // Also emit system event for initial load error\n createSystemEvent(SystemEventType.PLAN_ERROR, {\n error: e instanceof Error ? e : new Error(String(e)),\n })\n );\n } finally {\n dispatch({ type: \"LOADING\", isLoading: false });\n }\n };\n initialFetch();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [goal, schema, userContext, mockMode, dispatch, openaiApiKey]);\n\n return {\n state,\n dispatch,\n handleEvent,\n };\n}\n","import { createOpenAI } from \"@ai-sdk/openai\";\nimport { generateObject } from \"ai\";\nimport { PlannerInput, UISpecNode, openAIUISpec, UIEvent } from \"../schema/ui\";\nimport {\n createSystemEvent,\n systemEvents,\n SystemEventType,\n} from \"./system-events\";\nimport { env } from \"../env\";\nimport { ActionRouter, RouteResolution } from \"./action-router\";\nimport { DataContext } from \"./bindings\";\n\n// Helper function to create the OpenAI client REQUIRES an API key\nconst getOpenAIClient = (apiKey: string) => {\n return createOpenAI({\n apiKey: apiKey, // Use the provided key directly\n compatibility: \"strict\",\n });\n};\n\n/**\n * Mock planner for development and testing\n * @param input - Planner input\n * @param targetNodeId - Optional target node ID for partial updates\n * @param customPrompt - Optional custom prompt\n * @returns Promise resolving to a UISpecNode\n */\nexport function mockPlanner(\n input: PlannerInput,\n targetNodeId?: string,\n customPrompt?: string\n): UISpecNode {\n if (customPrompt) {\n console.log(\"mockPlanner received customPrompt:\", customPrompt);\n }\n const taskSchema = input.schema.tasks as\n | { sampleData?: unknown[] }\n | undefined;\n const taskData = taskSchema?.sampleData || [\n {\n id: \"1\",\n title: \"Example Task 1\",\n description: \"This is a sample task\",\n status: \"pending\",\n priority: \"medium\",\n },\n {\n id: \"2\",\n title: \"Example Task 2\",\n description: \"Another sample task\",\n status: \"completed\",\n priority: \"high\",\n },\n ];\n\n const mockNode: UISpecNode = {\n id: targetNodeId || \"root\",\n node_type: \"Container\",\n props: {\n className: \"p-4 space-y-6\",\n },\n bindings: null,\n events: null,\n children: [\n {\n id: \"header-1\",\n node_type: \"Header\",\n props: {\n title: \"Task Management Dashboard\",\n className: \"mb-4\",\n },\n bindings: null,\n events: null,\n children: null,\n },\n {\n id: \"main-content\",\n node_type: \"Container\",\n props: {\n className: \"grid grid-cols-1 gap-6 md:grid-cols-3\",\n },\n bindings: null,\n events: null,\n children: [\n {\n id: \"tasks-container\",\n node_type: \"Container\",\n props: {\n className: \"md:col-span-2\",\n },\n bindings: null,\n events: null,\n children: [\n {\n id: \"list-heading\",\n node_type: \"Container\",\n props: {\n className: \"flex justify-between items-center mb-4\",\n },\n bindings: null,\n events: null,\n children: [\n {\n id: \"list-title\",\n node_type: \"Header\",\n props: {\n title: \"Tasks\",\n className: \"border-none p-0 m-0\",\n },\n bindings: null,\n events: null,\n children: null,\n },\n {\n id: \"add-task-button\",\n node_type: \"Button\",\n props: {\n label: \"Add Task\",\n variant: \"default\",\n },\n bindings: null,\n events: {\n onClick: {\n action: \"ADD_TASK\",\n target: \"tasks-container\",\n payload: {},\n },\n },\n children: null,\n },\n ],\n },\n {\n id: \"task-list\",\n node_type: \"ListView\",\n props: {\n selectable: \"true\",\n },\n bindings: {\n data: \"tasks.data\",\n fields: JSON.stringify([\n { key: \"id\", label: \"ID\" },\n { key: \"title\", label: \"Title\" },\n { key: \"status\", label: \"Status\" },\n { key: \"priority\", label: \"Priority\" },\n ]),\n },\n events: {\n onSelect: {\n action: \"SELECT_TASK\",\n target: \"task-detail\",\n payload: {\n source: \"task-list\",\n },\n },\n },\n children: null,\n },\n ],\n },\n {\n id: \"task-detail\",\n node_type: \"Detail\",\n props: {\n title: \"Task Details\",\n visible: \"true\",\n },\n bindings: {\n data: JSON.stringify(taskData[0]),\n fields: JSON.stringify([\n { key: \"title\", label: \"Title\", type: \"heading\" },\n { key: \"description\", label: \"Description\", type: \"content\" },\n { key: \"status\", label: \"Status\" },\n { key: \"priority\", label: \"Priority\" },\n { key: \"dueDate\", label: \"Due Date\" },\n ]),\n },\n events: {\n onBack: {\n action: \"CLOSE_DETAIL\",\n target: \"task-detail\",\n payload: {},\n },\n },\n children: null,\n },\n ],\n },\n ],\n };\n\n return mockNode;\n}\n\n/**\n * Calls the LLM planner to generate a UI specification\n * @param input - Planner input\n * @param routeResolution - Optional route resolution for partial updates\n * @param openaiApiKey - Optional OpenAI API key\n * @returns Promise resolving to a UISpecNode\n */\nexport async function callPlannerLLM(\n input: PlannerInput,\n openaiApiKey: string,\n routeResolution?: RouteResolution\n): Promise<UISpecNode> {\n await systemEvents.emit(\n createSystemEvent(SystemEventType.PLAN_START, { plannerInput: input })\n );\n\n // Use mock planner if MOCK_PLANNER env var is set\n if (env.MOCK_PLANNER === \"1\") {\n console.warn(\n `Using mock planner because MOCK_PLANNER environment variable is set to \"1\".`\n );\n return mockPlanner(input);\n }\n\n // If not using mock planner via env var, API key is required for real LLM call\n if (!openaiApiKey) {\n console.warn(\n `OpenAI API key was not provided to callPlannerLLM. Falling back to mock planner.`\n );\n return mockPlanner(input);\n }\n\n const startTime = Date.now();\n\n // Use prompt from route resolution (must be provided by action-router)\n const prompt = routeResolution?.prompt;\n if (!prompt) {\n throw new Error(\"ActionRouter did not provide a prompt to callPlannerLLM.\");\n }\n\n // Emit prompt created event\n await systemEvents.emit(\n createSystemEvent(SystemEventType.PLAN_PROMPT_CREATED, { prompt })\n );\n\n try {\n // Use AI SDK's generateObject with structured outputs\n const { object: uiSpec } = await generateObject({\n model: getOpenAIClient(openaiApiKey)(\"gpt-4o\", {\n structuredOutputs: true,\n }),\n schema: openAIUISpec,\n messages: [{ role: \"user\", content: prompt }],\n temperature: 0.2,\n maxTokens: 4000,\n });\n\n // Emit planning complete event\n await systemEvents.emit(\n createSystemEvent(SystemEventType.PLAN_COMPLETE, {\n layout: uiSpec,\n executionTimeMs: Date.now() - startTime,\n })\n );\n\n return uiSpec;\n } catch (error) {\n console.error(\"Error calling LLM planner:\", error);\n\n // Emit error event\n await systemEvents.emit(\n createSystemEvent(SystemEventType.PLAN_ERROR, {\n error: error instanceof Error ? error : new Error(String(error)),\n })\n );\n\n throw error;\n }\n}\n\n/**\n * Process an event and generate an appropriate UI update\n * @param event - UI event that triggered the update\n * @param router - Action router to determine what to update\n * @param schema - Data schema\n * @param layout - Current UI layout\n * @param dataContext - Current data context\n * @param goal - The user's goal\n * @param userContext - Optional user context\n * @param openaiApiKey - Optional OpenAI API key\n * @returns Promise resolving to a UI spec node\n */\nexport async function processEvent(\n event: UIEvent,\n router: ActionRouter,\n schema: Record<string, unknown>,\n layout: UISpecNode | undefined,\n dataContext: DataContext,\n goal: string,\n userContext?: Record<string, unknown>,\n openaiApiKey?: string\n): Promise<UISpecNode> {\n // const startTime = Date.now(); // Commented out as it's currently unused\n\n const routeResolution = await router.resolveRoute(\n event,\n schema,\n layout || null,\n dataContext,\n goal,\n userContext\n );\n\n if (!routeResolution) {\n throw new Error(\n `No route found for event type: ${event.type}, node: ${event.nodeId}`\n );\n }\n\n if (routeResolution.actionType.toString() === \"NoOp\") {\n // Temporarily comment out SystemEvent calls\n // await systemEvents.emit(\n // createSystemEvent(SystemEventType.EVENT_PROCESSING_COMPLETE, {\n // event,\n // action: \"NoOp\",\n // executionTimeMs: Date.now() - startTime, // startTime would be used here\n // })\n // );\n if (!layout) throw new Error(\"Layout is undefined and action is NoOp\");\n return layout;\n }\n\n const plannerInputForLLM: PlannerInput = routeResolution.plannerInput;\n const newLayout = await callPlannerLLM(\n plannerInputForLLM,\n openaiApiKey || \"\",\n routeResolution\n );\n\n // Temporarily comment out SystemEvent calls\n // await systemEvents.emit(\n // createSystemEvent(SystemEventType.EVENT_PROCESSING_COMPLETE, {\n // event,\n // action: routeResolution.actionType.toString(),\n // targetNodeId: routeResolution.targetNodeId,\n // executionTimeMs: Date.now() - startTime, // startTime would be used here\n // })\n // );\n\n return newLayout;\n}\n","import { z } from \"zod\";\nimport { componentType } from \"./components\";\n\n/**\n * Event types that can be triggered by UI elements\n */\nexport const uiEventType = z.enum([\n \"INIT\",\n \"CLICK\",\n \"CHANGE\",\n \"SUBMIT\",\n \"MOUSEOVER\",\n \"MOUSEOUT\",\n \"FOCUS\",\n \"BLUR\",\n]);\n\nexport type UIEventType = z.infer<typeof uiEventType>;\n\n/**\n * Event payload schema\n */\nexport const uiEvent = z.object({\n type: uiEventType,\n nodeId: z.string(),\n timestamp: z.number().nullable(),\n payload: z.record(z.unknown()).nullable(),\n});\n\nexport type UIEvent = z.infer<typeof uiEvent>;\n\n/**\n * AI response types\n */\nexport const aiResponseType = z.enum([\"AI_RESPONSE\", \"ERROR\"]);\n\nexport type AIResponseType = z.infer<typeof aiResponseType>;\n\n// --- Runtime Specific Types ---\nconst runtimeRecord = z.record(z.any()).nullable();\n\n// --- OpenAI Specific Types (Simplified values, records can be null) ---\nconst openAISimplifiedValue = z.string().nullable(); // Values can only be string or null\n\n// For OpenAI: props/bindings are records of these simplified values, or null.\nconst openAIRecordSimplifiedNullable = z\n .record(openAISimplifiedValue)\n .nullable();\n\n// For OpenAI: event payloads can be null, or a record of these simplified values.\nconst openAIEventPayloadSimplifiedNullable = z\n .record(openAISimplifiedValue)\n .nullable(); // Already was nullable, name changed for clarity\n\n// --- Interface for Runtime UISpecNode ---\nexport interface UISpecNodeInterface {\n id: string;\n node_type: string;\n props: Record<string, any> | null;\n bindings: Record<string, any> | null;\n events: Record<\n string,\n {\n action: string;\n target: string;\n payload: Record<string, any> | null;\n }\n > | null;\n children: UISpecNodeInterface[] | null;\n}\n\n// --- OpenAI Schema Definition (All fields required by Zod default, complex fields are nullable) ---\nconst openAIBaseNode = z.object({\n id: z.string().describe(\"Unique identifier for the UI node.\"),\n node_type: componentType.describe(\n \"The type of UI component (e.g., Container, Text, Button, ListView).\"\n ),\n props: openAIRecordSimplifiedNullable.describe(\n 'Component-specific properties (attributes). Values should be strings or null. E.g., for Header use { \"title\": \"My Title\" }; for Text use { \"text\": \"My Text\" }.'\n ),\n bindings: openAIRecordSimplifiedNullable.describe(\n 'Data bindings map context paths to component props. Values are paths (e.g., \"user.name\") or templates (e.g., \"{{item.title}}\"). **CRITICAL for ListView/Table:** the `data` key MUST point to the *exact array path* (e.g., { \"data\": \"tasks.data\" } or { \"data\": \"userList\" }), NOT the parent object.'\n ),\n events: z\n .record(\n z.string(),\n z.object({\n action: z.string(),\n target: z.string(),\n payload: openAIEventPayloadSimplifiedNullable,\n })\n )\n .nullable(), // Entire events object is nullable\n children: z.null(), // Base children are null. When extended, it will be an array or null.\n});\n\nconst openAINodeL4 = openAIBaseNode;\n\nconst openAINodeL3 = openAIBaseNode.extend({\n children: z.array(openAINodeL4).nullable(),\n});\n\nconst openAINodeL2 = openAIBaseNode.extend({\n children: z.array(openAINodeL3).nullable(),\n});\n\nexport const openAIUISpec = openAIBaseNode.extend({\n children: z.array(openAINodeL2).nullable(),\n});\n\n// --- Runtime Schema Definition ---\nexport const uiSpecNode: z.ZodType<UISpecNodeInterface> = z.object({\n id: z.string(),\n node_type: z.string(),\n props: runtimeRecord,\n bindings: runtimeRecord,\n events: z\n .record(\n z.string(),\n z.object({\n action: z.string(),\n target: z.string(),\n payload: runtimeRecord,\n })\n )\n .nullable(),\n children: z.lazy(() => z.array(uiSpecNode)).nullable(),\n});\n\n// --- Exported Types ---\nexport type UISpecNode = z.infer<typeof uiSpecNode>;\nexport type OpenAIUISpec = z.infer<typeof openAIUISpec>;\n\n/**\n * Actions that can be dispatched to the reducer\n */\nexport const uiAction = z.discriminatedUnion(\"type\", [\n z.object({\n type: z.literal(\"UI_EVENT\"),\n event: uiEvent,\n }),\n z.object({\n type: z.literal(\"AI_RESPONSE\"),\n node: uiSpecNode,\n }),\n z.object({\n type: z.literal(\"PARTIAL_UPDATE\"),\n nodeId: z.string(),\n node: uiSpecNode,\n }),\n z.object({\n type: z.literal(\"ADD_NODE\"),\n parentId: z.string(),\n node: uiSpecNode,\n index: z.number().nullable(),\n }),\n z.object({\n type: z.literal(\"REMOVE_NODE\"),\n nodeId: z.string(),\n }),\n z.object({\n type: z.literal(\"ERROR\"),\n message: z.string(),\n }),\n z.object({\n type: z.literal(\"LOADING\"),\n isLoading: z.boolean(),\n }),\n]);\n\nexport type UIAction = z.infer<typeof uiAction>;\n\n/**\n * Application state for the UI engine\n */\nexport const uiState = z.object({\n layout: uiSpecNode.nullable(),\n loading: z.boolean(),\n history: z.array(uiEvent),\n error: z.string().nullable(),\n});\n\nexport type UIState = z.infer<typeof uiState>;\n\n/**\n * Input for the AI planner\n */\nexport const plannerInput = z.object({\n schema: z.record(z.unknown()),\n goal: z.string(),\n history: z.array(uiEvent).nullable(),\n userContext: z.record(z.unknown()).nullable().optional(),\n});\n\nexport type PlannerInput = z.infer<typeof plannerInput>;\n\n// Define a more specific type for data items\nexport type DataItem = Record<string, unknown>;\n","/**\n * Component definitions for shadcn/ui integration\n * This file defines which components from shadcn/ui are used by AutoUI\n */\n\nimport { z } from \"zod\";\n\n// Define all possible component types\nexport const componentType = z.enum([\n // Layout components\n \"Container\",\n \"Card\",\n \"Header\",\n\n // Input components\n \"Button\",\n \"Input\",\n \"Select\",\n \"Textarea\",\n \"Checkbox\",\n \"RadioGroup\",\n\n // Data display components\n \"ListView\",\n \"Detail\",\n \"Tabs\",\n \"Dialog\",\n\n // Typography\n \"Heading\",\n \"Text\",\n]);\n\nexport type ComponentType = z.infer<typeof componentType>;\n\n// Map component types to their shadcn component and required props\nexport const componentConfig = {\n Button: {\n component: \"Button\",\n requiredProps: [\"label\"],\n optionalProps: [\"variant\", \"size\", \"disabled\"],\n events: [\"onClick\"],\n },\n Card: {\n component: \"Card\",\n requiredProps: [],\n optionalProps: [\"className\"],\n events: [],\n },\n Input: {\n component: \"Input\",\n requiredProps: [\"name\"],\n optionalProps: [\"label\", \"placeholder\", \"disabled\", \"value\"],\n events: [\"onChange\", \"onFocus\", \"onBlur\"],\n },\n Select: {\n component: \"Select\",\n requiredProps: [\"name\", \"options\"],\n optionalProps: [\"label\", \"placeholder\", \"disabled\", \"value\"],\n events: [\"onChange\"],\n },\n Textarea: {\n component: \"Textarea\",\n requiredProps: [\"name\"],\n optionalProps: [\"label\", \"placeholder\", \"disabled\", \"value\", \"rows\"],\n events: [\"onChange\", \"onFocus\", \"onBlur\"],\n },\n Container: {\n component: \"div\",\n requiredProps: [],\n optionalProps: [\"className\", \"style\"],\n events: [],\n },\n Header: {\n component: \"header\",\n requiredProps: [\"title\"],\n optionalProps: [\"className\"],\n events: [],\n },\n ListView: {\n component: \"Table\",\n requiredProps: [\"fields\"],\n optionalProps: [\"items\", \"selectable\"],\n events: [\"onSelect\"],\n },\n Detail: {\n component: \"div\",\n requiredProps: [\"fields\"],\n optionalProps: [\"data\", \"title\", \"visible\"],\n events: [\"onBack\"],\n },\n Dialog: {\n component: \"Dialog\",\n requiredProps: [\"title\"],\n optionalProps: [\"open\", \"onClose\", \"description\"],\n events: [\"onClose\"],\n },\n Tabs: {\n component: \"Tabs\",\n requiredProps: [\"tabs\"],\n optionalProps: [\"defaultValue\"],\n events: [\"onChange\"],\n },\n Heading: {\n component: \"h2\",\n requiredProps: [\"text\"],\n optionalProps: [\"size\", \"className\"],\n events: [],\n },\n Text: {\n component: \"p\",\n requiredProps: [\"text\"],\n optionalProps: [\"size\", \"className\"],\n events: [],\n },\n Checkbox: {\n component: \"Checkbox\",\n requiredProps: [\"name\"],\n optionalProps: [\"label\", \"checked\", \"disabled\"],\n events: [\"onChange\"],\n },\n RadioGroup: {\n component: \"RadioGroup\",\n requiredProps: [\"name\", \"options\"],\n optionalProps: [\"label\", \"value\", \"disabled\"],\n events: [\"onChange\"],\n },\n};\n\n// List of required shadcn components for the setup script\nexport const shadcnComponents = [\n \"button\",\n \"card\",\n \"dialog\",\n \"dropdown-menu\",\n \"form\",\n \"input\",\n \"label\",\n \"select\",\n \"table\",\n \"tabs\",\n \"textarea\",\n \"checkbox\",\n \"radio-group\",\n \"container\",\n];\n","import { UISpecNode, PlannerInput } from \"../schema/ui\";\n\n/**\n * System event types that represent the internal AutoUI lifecycle\n */\nexport enum SystemEventType {\n // Planning events\n PLAN_START = \"PLAN_START\", // Before AI planning begins\n PLAN_PROMPT_CREATED = \"PLAN_PROMPT_CREATED\", // After prompt is built\n PLAN_RESPONSE_CHUNK = \"PLAN_RESPONSE_CHUNK\", // For each AI response chunk\n PLAN_COMPLETE = \"PLAN_COMPLETE\", // After planning is complete\n PLAN_ERROR = \"PLAN_ERROR\", // Planning error occurred\n\n // Binding events\n BINDING_RESOLUTION_START = \"BINDING_RESOLUTION_START\", // Before bindings are resolved\n BINDING_RESOLUTION_COMPLETE = \"BINDING_RESOLUTION_COMPLETE\", // After bindings are resolved\n\n // Data events\n DATA_FETCH_START = \"DATA_FETCH_START\", // Before data is fetched\n DATA_FETCH_COMPLETE = \"DATA_FETCH_COMPLETE\", // After data is fetched\n\n // Rendering events\n RENDER_START = \"RENDER_START\", // Before layout is rendered\n RENDER_COMPLETE = \"RENDER_COMPLETE\", // After layout is rendered\n\n // Prefetch events (for future use)\n PREFETCH_START = \"PREFETCH_START\", // Before prefetching begins\n PREFETCH_COMPLETE = \"PREFETCH_COMPLETE\", // After prefetching completes\n}\n\n/**\n * Base system event interface\n */\nexport interface SystemEvent {\n type: SystemEventType;\n timestamp: number;\n}\n\n/**\n * Planning events\n */\nexport interface PlanStartEvent extends SystemEvent {\n type: SystemEventType.PLAN_START;\n plannerInput: PlannerInput;\n}\n\nexport interface PlanPromptCreatedEvent extends SystemEvent {\n type: SystemEventType.PLAN_PROMPT_CREATED;\n prompt: string;\n}\n\nexport interface PlanResponseChunkEvent extends SystemEvent {\n type: SystemEventType.PLAN_RESPONSE_CHUNK;\n chunk: string;\n isComplete: boolean;\n}\n\nexport interface PlanCompleteEvent extends SystemEvent {\n type: SystemEventType.PLAN_COMPLETE;\n layout: UISpecNode;\n executionTimeMs: number;\n}\n\nexport interface PlanErrorEvent extends SystemEvent {\n type: SystemEventType.PLAN_ERROR;\n error: Error;\n}\n\n/**\n * Binding events\n */\nexport interface BindingResolutionStartEvent extends SystemEvent {\n type: SystemEventType.BINDING_RESOLUTION_START;\n layout: UISpecNode;\n}\n\nexport interface BindingResolutionCompleteEvent extends SystemEvent {\n type: SystemEventType.BINDING_RESOLUTION_COMPLETE;\n originalLayout: UISpecNode;\n resolvedLayout: UISpecNode;\n}\n\n/**\n * Data events\n */\nexport interface DataFetchStartEvent extends SystemEvent {\n type: SystemEventType.DATA_FETCH_START;\n tableName: string;\n query: unknown;\n}\n\nexport interface DataFetchCompleteEvent extends SystemEvent {\n type: SystemEventType.DATA_FETCH_COMPLETE;\n tableName: string;\n results: unknown[];\n executionTimeMs: number;\n}\n\n/**\n * Rendering events\n */\nexport interface RenderStartEvent extends SystemEvent {\n type: SystemEventType.RENDER_START;\n layout: UISpecNode;\n}\n\nexport interface RenderCompleteEvent extends SystemEvent {\n type: SystemEventType.RENDER_COMPLETE;\n layout: UISpecNode;\n renderTimeMs: number;\n}\n\n/**\n * Prefetch events\n */\nexport interface PrefetchStartEvent extends SystemEvent {\n type: SystemEventType.PREFETCH_START;\n depth: number;\n}\n\nexport interface PrefetchCompleteEvent extends SystemEvent {\n type: SystemEventType.PREFETCH_COMPLETE;\n prefetchedLayouts: Record<string, UISpecNode>;\n}\n\n/**\n * Union type of all system events\n */\nexport type AnySystemEvent =\n | PlanStartEvent\n | PlanPromptCreatedEvent\n | PlanResponseChunkEvent\n | PlanCompleteEvent\n | PlanErrorEvent\n | BindingResolutionStartEvent\n | BindingResolutionCompleteEvent\n | DataFetchStartEvent\n | DataFetchCompleteEvent\n | RenderStartEvent\n | RenderCompleteEvent\n | PrefetchStartEvent\n | PrefetchCompleteEvent;\n\n/**\n * System event hook type\n */\nexport type SystemEventHook<T extends SystemEvent = AnySystemEvent> = (\n event: T\n) => void | Promise<void>;\n\n/**\n * System event manager\n */\nexport class SystemEventManager {\n private listeners: Partial<Record<SystemEventType, SystemEventHook[]>> = {};\n\n /**\n * Register a listener for a specific system event type\n *\n * @param eventType - The system event type to listen for\n * @param listener - The listener function\n * @returns Function to unregister the listener\n */\n public on<T extends SystemEventType>(\n eventType: T,\n listener: SystemEventHook<Extract<AnySystemEvent, { type: T }>>\n ): () => void {\n if (!this.listeners[eventType]) {\n this.listeners[eventType] = [];\n }\n\n this.listeners[eventType]?.push(listener as SystemEventHook);\n\n return () => {\n if (this.listeners[eventType]) {\n this.listeners[eventType] = this.listeners[eventType]?.filter(\n (l) => l !== listener\n );\n }\n };\n }\n\n /**\n * Emit a system event to all registered listeners\n *\n * @param event - The system event to emit\n */\n public async emit<T extends AnySystemEvent>(event: T): Promise<void> {\n const listeners = this.listeners[event.type] || [];\n\n for (const listener of listeners) {\n await listener(event);\n }\n }\n}\n\n// Create a singleton instance for global access\nexport const systemEvents = new SystemEventManager();\n\n/**\n * Helper to create a typed system event\n *\n * @param type - The system event type\n * @param data - Additional event data\n * @returns A system event object\n */\nexport function createSystemEvent<T extends SystemEventType>(\n type: T,\n data: Omit<Extract<AnySystemEvent, { type: T }>, \"type\" | \"timestamp\">\n): Extract<AnySystemEvent, { type: T }> {\n return {\n type,\n timestamp: Date.now(),\n ...data,\n } as Extract<AnySystemEvent, { type: T }>;\n}\n","// Environment configuration\n\nconst rawApiKeyFromEnv = process.env.VITE_OPENAI_API_KEY;\n\nexport const env = {\n MOCK_PLANNER: process.env.VITE_MOCK_PLANNER || \"0\", // Simplified MOCK_PLANNER assignment\n NODE_ENV: process.env.VITE_NODE_ENV || \"production\", // Simplified NODE_ENV assignment\n OPENAI_API_KEY: rawApiKeyFromEnv || \"\",\n};\n","import React from \"react\";\nimport { UISpecNode, UIEvent, UIEventType } from \"../schema/ui\";\nimport { cn } from \"@/lib/utils\";\nimport {\n Dialog,\n DialogHeader,\n DialogTitle,\n DialogDescription,\n DialogContent,\n} from \"@/components/ui/dialog\";\nimport { Card, CardContent } from \"@/components/ui/card\";\nimport { Input } from \"@/components/ui/input\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from \"@/components/ui/select\";\nimport { Checkbox } from \"@/components/ui/checkbox\";\nimport { RadioGroup, RadioGroupItem } from \"@/components/ui/radio-group\";\nimport { Tabs, TabsList, TabsTrigger, TabsContent } from \"@/components/ui/tabs\";\nimport { Label } from \"@/components/ui/label\";\n\n// Utility to parse CSS style string into a React style object\nconst parseStyleString = (styleString: string): React.CSSProperties => {\n if (typeof styleString !== \"string\") {\n // If it's not a string (e.g., already an object or undefined), return it as is or an empty object\n return typeof styleString === \"object\" ? styleString : {};\n }\n const style: React.CSSProperties = {};\n styleString.split(\";\").forEach((declaration) => {\n const [property, value] = declaration.split(\":\");\n if (property && value) {\n const camelCasedProperty = property\n .trim()\n .replace(/-([a-z])/g, (g) => g[1].toUpperCase());\n // Revert to simple assignment, accepting the potential type mismatch flagged by linter.\n // Casting to 'any' is forbidden, and 'string' doesn't satisfy all properties.\n // @ts-expect-error // Suppressing complex type checking for dynamic style parsing\n style[camelCasedProperty as keyof React.CSSProperties] = value.trim();\n }\n });\n return style;\n};\n\nconst isArrayOf =\n <T,>(guard: (item: unknown) => item is T) =>\n (arr: unknown): arr is T[] =>\n Array.isArray(arr) && arr.every(guard);\n\n// Shimmer components\nexport const ShimmerBlock: React.FC = () => (\n <div className=\"w-full h-8 bg-gray-200 animate-pulse rounded\" />\n);\n\nexport const ShimmerTable: React.FC<{ rows?: number }> = ({ rows = 3 }) => (\n <div className=\"w-full space-y-2\">\n <div className=\"w-full h-10 bg-gray-200 animate-pulse rounded\" />\n {Array.from({ length: rows }).map((_, i) => (\n <div key={i} className=\"w-full h-12 bg-gray-200 animate-pulse rounded\" />\n ))}\n </div>\n);\n\nexport const ShimmerCard: React.FC = () => (\n <div className=\"w-full p-4 space-y-4 border rounded-lg\">\n <div className=\"w-3/4 h-6 bg-gray-200 animate-pulse rounded\" />\n <div className=\"space-y-2\">\n <div className=\"w-full h-4 bg-gray-200 animate-pulse rounded\" />\n <div className=\"w-full h-4 bg-gray-200 animate-pulse rounded\" />\n <div className=\"w-5/6 h-4 bg-gray-200 animate-pulse rounded\" />\n </div>\n </div>\n);\n\n// Mock ShadCN components for demonstration\nconst Container: React.FC<{\n style?: React.CSSProperties;\n className?: string;\n children?: React.ReactNode;\n}> = (props) => (\n <div className={`autoui-mock-container ${props.className || \"\"}`}>\n {props.children}\n </div>\n);\n\nconst Header: React.FC<{ title: string; className?: string }> = ({\n title,\n className,\n}) => (\n <header\n className={`py-4 px-6 border-b border-gray-300 mb-4 bg-gray-50 dark:bg-gray-800 ${\n className || \"\"\n }`}\n >\n <h1 className=\"text-xl font-semibold text-gray-800 dark:text-white\">\n {title}\n </h1>\n </header>\n);\n\nconst Button: React.FC<{\n onClick?: (() => void) | undefined;\n children: React.ReactNode;\n variant?: \"default\" | \"outline\" | \"destructive\" | undefined;\n}> = ({ onClick, children, variant = \"default\" }) => (\n <button\n className={`px-4 py-2 rounded-md font-medium transition-colors ${\n variant === \"default\"\n ? \"bg-blue-600 text-white hover:bg-blue-700\"\n : variant === \"outline\"\n ? \"border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800\"\n : \"bg-red-600 text-white hover:bg-red-700\"\n }`}\n onClick={() => onClick?.()}\n >\n {children}\n </button>\n);\n\nconst Detail: React.FC<{\n data?: Record<string, React.ReactNode> | undefined;\n fields?: { key: string; label: string; type?: string }[] | undefined;\n title?: string | undefined;\n visible?: boolean | undefined;\n onBack?: (() => void) | undefined;\n}> = ({ data, fields = [], title, visible = true, onBack }) => {\n if (!visible) return null;\n\n return (\n <div className=\"w-full border border-gray-300 dark:border-gray-700 rounded-lg p-6 space-y-4 bg-white dark:bg-gray-900 shadow-sm\">\n <div className=\"flex justify-between items-center border-b border-gray-200 dark:border-gray-700 pb-3\">\n {title && (\n <h2 className=\"text-lg font-medium text-gray-800 dark:text-white\">\n {title}\n </h2>\n )}\n {onBack && (\n <Button variant=\"outline\" onClick={onBack}>\n Back\n </Button>\n )}\n </div>\n\n <div className=\"space-y-4\">\n {fields.map((field) => {\n if (field.type === \"heading\") {\n return (\n <h3\n key={field.key}\n className=\"text-xl font-semibold text-gray-800 dark:text-white\"\n >\n {data?.[field.key] ?? \"\"}\n </h3>\n );\n }\n\n if (field.type === \"content\") {\n return (\n <div\n key={field.key}\n className=\"text-sm text-gray-700 dark:text-gray-300\"\n >\n {data?.[field.key] ?? \"\"}\n </div>\n );\n }\n\n return (\n <div\n key={field.key}\n className=\"flex flex-col border-b border-gray-100 dark:border-gray-800 py-2\"\n >\n {field.label && (\n <span className=\"text-xs text-gray-600 dark:text-gray-400 font-medium\">\n {field.label}\n </span>\n )}\n <span className=\"text-sm text-gray-800 dark:text-gray-200\">\n {data?.[field.key] ?? \"\"}\n </span>\n </div>\n );\n })}\n </div>\n </div>\n );\n};\n\nconst getSafeProp = <T, K extends string, D extends T>(\n props: Record<string, unknown> | null | undefined,\n key: K,\n validator: (value: unknown) => value is T,\n defaultValue: D\n): T | D => {\n if (props && typeof props === \"object\" && key in props) {\n const value = props[key];\n if (validator(value)) {\n return value;\n }\n }\n return defaultValue;\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\nconst isString = (value: unknown): value is string => typeof value === \"string\";\nconst isBoolean = (value: unknown): value is boolean =>\n typeof value === \"boolean\";\nconst isButtonVariant = (\n value: unknown\n): value is \"default\" | \"outline\" | \"destructive\" =>\n isString(value) && [\"default\", \"outline\", \"destructive\"].includes(value);\n\nconst getSafeBinding = <T, K extends string, D extends T>(\n bindings: Record<string, unknown> | null | undefined,\n key: K,\n validator: (value: unknown) => value is T,\n defaultValue: D\n): T | D => {\n if (bindings && typeof bindings === \"object\" && key in bindings) {\n const value = bindings[key];\n if (validator(value)) {\n return value;\n }\n }\n return defaultValue;\n};\n\nconst isReactNode = (value: unknown): value is React.ReactNode => {\n // This is a simplified check. A full check is complex.\n // For basic scenarios, we can check for string, number, boolean, null, undefined, or React elements.\n return (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n value === null ||\n typeof value === \"undefined\" ||\n (typeof value === \"object\" && value !== null && \"$$typeof\" in value) // Basic check for React element\n );\n};\n\nconst isRecordWithReactNodeValues = (\n value: unknown\n): value is Record<string, React.ReactNode> =>\n isObject(value) && Object.values(value).every(isReactNode);\n\nconst isSelectOptionObject = (\n item: unknown\n): item is { value: string; label: string } =>\n isObject(item) && isString(item.value) && isString(item.label);\n\nconst isTabObject = (\n item: unknown\n): item is { value: string; label: string; content?: UISpecNode } => // Allow content to be optional initially\n isObject(item) &&\n isString(item.value) &&\n isString(item.label) &&\n (item.content === undefined || isUISpecNode(item.content));\n\nconst isUISpecNode = (value: unknown): value is UISpecNode => {\n if (!isObject(value)) return false;\n return isString(value.id) && isString(value.node_type); // Basic check\n};\n\nconst isDetailFieldObject = (\n item: unknown\n): item is { key: string; label: string; type?: string } =>\n isObject(item) &&\n isString(item.key) &&\n isString(item.label) &&\n (item.type === undefined || isString(item.type));\n\n// Mock implementation - in a real application, this would dispatch events to your state engine\nconst createEventHandler = (\n node: UISpecNode,\n eventName: string,\n uiEventType: UIEventType,\n processEvent?: (event: UIEvent) => void\n) => {\n const eventConfig = node.events?.[uiEventType];\n if (!processEvent || !eventConfig) return undefined;\n\n return (eventPayload?: Record<string, unknown>) => {\n const fullEvent: UIEvent = {\n type: uiEventType,\n nodeId: node.id,\n timestamp: Date.now(),\n payload: {\n ...(eventConfig.payload || {}),\n ...(eventPayload || {}),\n },\n };\n processEvent(fullEvent);\n };\n};\n\nexport const adapterMap: Record<\n string,\n (\n node: UISpecNode,\n processEvent?: (event: UIEvent) => void\n ) => React.ReactElement\n> = {\n Container: (node, processEvent) => {\n // Extract key and style first\n const { className, style: styleProp, key, ...restProps } = node.props || {};\n // Ensure children are rendered with keys\n const children = node.children?.map((child) =>\n // Use React.cloneElement to add the key prop to the element returned by renderNode\n React.cloneElement(renderNode(child, processEvent), { key: child.id })\n );\n // Parse style string if necessary\n const style =\n typeof styleProp === \"string\"\n ? parseStyleString(styleProp)\n : (styleProp as React.CSSProperties | undefined);\n\n return (\n <div\n key={key as React.Key} // Pass key directly\n className={cn(\"autoui-container\", className as string)}\n style={style} // Use the parsed style object\n {...restProps}\n data-id={node.id}\n >\n {/* Add console log to see props during render */}\n {(() => {\n console.log(\n `[Adapter Debug] Rendering Container: id=${node.id}, props=`,\n node.props\n );\n return null;\n })()}\n {children}\n </div>\n );\n },\n\n Header: (node) => (\n <Header\n title={getSafeProp(node.props, \"title\", isString, \"Untitled\")}\n className={getSafeProp(node.props, \"className\", isString, \"\")}\n />\n ),\n\n Button: (node, processEvent) => (\n <Button\n variant={getSafeProp(node.props, \"variant\", isButtonVariant, \"default\")}\n onClick={createEventHandler(node, \"onClick\", \"CLICK\", processEvent)}\n >\n {getSafeProp(node.props, \"label\", isString, \"Button\")}\n </Button>\n ),\n\n ListView: (node, processEvent) => {\n // resolveBindings populates node.children with resolved items, each having a key.\n // We just need to render these children.\n // Extract key and style first\n const { className, style: styleProp, key, ...restProps } = node.props || {}; // Removed unused selectable\n\n // Parse style string if necessary\n const style =\n typeof styleProp === \"string\"\n ? parseStyleString(styleProp)\n : (styleProp as React.CSSProperties | undefined);\n\n // Add console log to see props during render\n console.log(\n `[Adapter Debug] Rendering ListView: id=${node.id}, props=`,\n node.props\n );\n\n // The children array from resolveBindings already contains React Elements with keys\n // if resolveBindings adds the key prop correctly.\n // If renderNode returns elements, they should retain their keys.\n // Fix: Add keys to children explicitly like in Container/Card\n const children = node.children?.map((child) =>\n React.cloneElement(renderNode(child, processEvent), { key: child.id })\n );\n\n return (\n <div\n key={key as React.Key} // Pass key directly\n className={cn(\n \"autoui-listview-container space-y-2\",\n className as string\n )}\n style={style} // Use the parsed style object\n {...restProps} // Spread remaining props (selectable, style, className, key are now excluded)\n data-id={node.id}\n >\n {children}\n </div>\n );\n },\n\n Detail: (node, processEvent) => {\n const data = getSafeBinding(\n node.bindings,\n \"data\",\n isRecordWithReactNodeValues,\n {}\n ) as Record<string, React.ReactNode>;\n const fields = getSafeBinding(\n node.bindings,\n \"fields\",\n isArrayOf(isDetailFieldObject),\n []\n );\n const title = getSafeProp(node.props, \"title\", isString, \"\");\n const visible = getSafeProp(node.props, \"visible\", isBoolean, true);\n\n return (\n <Detail\n data={data}\n fields={fields}\n title={title}\n visible={visible}\n onBack={createEventHandler(node, \"onBack\", \"CLICK\", processEvent)}\n />\n );\n },\n\n Card: (node, processEvent) => {\n // Extract key and style first\n const { className, style: styleProp, key, ...restProps } = node.props || {};\n // Ensure children are rendered with keys\n const children = node.children?.map((child) =>\n React.cloneElement(renderNode(child, processEvent), { key: child.id })\n );\n // Parse style string if necessary\n const style =\n typeof styleProp === \"string\"\n ? parseStyleString(styleProp)\n : (styleProp as React.CSSProperties | undefined);\n\n return (\n <Card\n key={key as React.Key} // Pass key directly\n className={cn(\"autoui-card\", className as string)}\n style={style} // Use parsed style object\n {...restProps} // Spread remaining props\n data-id={node.id}\n >\n {/* Using CardContent as a default wrapper, adjust if needed */}\n <CardContent className=\"p-0\">\n {\" \"}\n {/* Example: remove padding if children handle it */}\n {children}\n </CardContent>\n </Card>\n );\n },\n\n Input: (node, processEvent) => {\n const name = getSafeProp(node.props, \"name\", isString, \"inputName\");\n const label = getSafeProp(node.props, \"label\", isString, \"\");\n const value = getSafeBinding(node.bindings, \"value\", isString, \"\");\n const placeholder = getSafeProp(node.props, \"placeholder\", isString, \"\");\n const disabled = getSafeProp(node.props, \"disabled\", isBoolean, false);\n const className = getSafeProp(node.props, \"className\", isString, \"\");\n\n const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n const handler = createEventHandler(\n node,\n \"onChange\",\n \"CHANGE\",\n processEvent\n );\n if (handler) handler({ value: e.target.value });\n };\n\n const handleFocus = () => {\n const handler = createEventHandler(\n node,\n \"onFocus\",\n \"FOCUS\",\n processEvent\n );\n if (handler) handler({});\n };\n\n const handleBlur = () => {\n const handler = createEventHandler(node, \"onBlur\", \"BLUR\", processEvent);\n if (handler) handler({});\n };\n\n return (\n <div className=\"grid w-full max-w-sm items-center gap-1.5\">\n {label && <Label htmlFor={name}>{label}</Label>}\n <Input\n id={name} // Use name as id for label association\n name={name}\n placeholder={placeholder}\n disabled={disabled}\n value={value}\n onChange={handleChange}\n onFocus={handleFocus}\n onBlur={handleBlur}\n className={className}\n />\n </div>\n );\n },\n\n Select: (node, processEvent) => {\n const name = getSafeProp(node.props, \"name\", isString, \"selectName\");\n const label = getSafeProp(node.props, \"label\", isString, \"\");\n const placeholder = getSafeProp(\n node.props,\n \"placeholder\",\n isString,\n \"Select...\"\n );\n const disabled = getSafeProp(node.props, \"disabled\", isBoolean, false);\n const value = getSafeBinding(node.bindings, \"value\", isString, \"\");\n const options = getSafeBinding(\n node.bindings,\n \"options\",\n isArrayOf(isSelectOptionObject),\n []\n );\n const className = getSafeProp(node.props, \"className\", isString, \"\");\n\n const handleValueChange = (selectedValue: string) => {\n const handler = createEventHandler(\n node,\n \"onValueChange\",\n \"CHANGE\",\n processEvent\n );\n if (handler) handler({ value: selectedValue });\n };\n\n return (\n <div\n className={cn(\"grid w-full max-w-sm items-center gap-1.5\", className)}\n >\n {label && <Label htmlFor={name}>{label}</Label>}\n <Select\n name={name}\n value={value}\n onValueChange={handleValueChange}\n disabled={disabled}\n >\n <SelectTrigger id={name}>\n <SelectValue placeholder={placeholder} />\n </SelectTrigger>\n <SelectContent>\n {options.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n );\n },\n\n Textarea: (node, processEvent) => {\n // Extract key first (style is usually handled by className for Textarea, but handle just in case)\n const { key, ...propsWithoutKey } = node.props || {};\n const name = getSafeProp(propsWithoutKey, \"name\", isString, \"textareaName\");\n const label = getSafeProp(propsWithoutKey, \"label\", isString, \"\");\n const placeholder = getSafeProp(\n propsWithoutKey,\n \"placeholder\",\n isString,\n \"\"\n );\n const disabled = getSafeProp(propsWithoutKey, \"disabled\", isBoolean, false);\n const rows = getSafeProp(\n propsWithoutKey,\n \"rows\",\n (v): v is number => typeof v === \"number\",\n 3\n );\n const value = getSafeBinding(node.bindings, \"value\", isString, \"\");\n const className = getSafeProp(propsWithoutKey, \"className\", isString, \"\");\n\n const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n const handler = createEventHandler(\n node,\n \"onChange\",\n \"CHANGE\",\n processEvent\n );\n if (handler) handler({ value: e.target.value });\n };\n\n const handleFocus = () => {\n const handler = createEventHandler(\n node,\n \"onFocus\",\n \"FOCUS\",\n processEvent\n );\n if (handler) handler({});\n };\n\n const handleBlur = () => {\n const handler = createEventHandler(node, \"onBlur\", \"BLUR\", processEvent);\n if (handler) handler({});\n };\n\n return (\n <div key={key as React.Key} className=\"grid w-full gap-1.5\">\n {label && <Label htmlFor={name}>{label}</Label>}\n <Textarea\n id={name} // Use name as id for label association\n name={name}\n placeholder={placeholder}\n disabled={disabled}\n rows={rows}\n value={value}\n onChange={handleChange}\n onFocus={handleFocus}\n onBlur={handleBlur}\n className={className}\n />\n </div>\n );\n },\n\n Checkbox: (node, processEvent) => {\n // Extract key first (style is usually handled by className for Checkbox)\n const { key, ...propsWithoutKey } = node.props || {};\n const name = getSafeProp(propsWithoutKey, \"name\", isString, \"checkboxName\");\n const label = getSafeProp(propsWithoutKey, \"label\", isString, \"\");\n const checked = getSafeBinding(node.bindings, \"checked\", isBoolean, false);\n const disabled = getSafeProp(propsWithoutKey, \"disabled\", isBoolean, false);\n const className = getSafeProp(propsWithoutKey, \"className\", isString, \"\");\n\n const handleCheckedChange = (isChecked: boolean | \"indeterminate\") => {\n // Ensure we only pass boolean to our event handler\n if (typeof isChecked === \"boolean\") {\n const handler = createEventHandler(\n node,\n \"onCheckedChange\",\n \"CHANGE\",\n processEvent\n );\n if (handler) handler({ checked: isChecked });\n }\n };\n\n // Shadcn Checkbox often used with a Label\n return (\n <div\n key={key as React.Key}\n className={cn(\"flex items-center space-x-2\", className as string)}\n >\n <Checkbox\n id={name} // Use name as id for label association\n name={name}\n checked={checked}\n disabled={disabled}\n onCheckedChange={handleCheckedChange}\n />\n {/* Add the aria-label for accessibility if no visible label */}\n {label && (\n <Label htmlFor={name} className=\"cursor-pointer\">\n {label}\n </Label>\n )}\n </div>\n );\n },\n\n RadioGroup: (node, processEvent) => {\n // Extract key first (style is usually handled by className for RadioGroup)\n const { key, ...propsWithoutKey } = node.props || {};\n const name = getSafeProp(\n propsWithoutKey,\n \"name\",\n isString,\n \"radioGroupName\"\n );\n const label = getSafeProp(propsWithoutKey, \"label\", isString, \"\");\n const value = getSafeBinding(node.bindings, \"value\", isString, \"\");\n const options = getSafeBinding(\n node.bindings,\n \"options\",\n isArrayOf(isSelectOptionObject),\n []\n );\n const disabled = getSafeProp(propsWithoutKey, \"disabled\", isBoolean, false);\n const className = getSafeProp(propsWithoutKey, \"className\", isString, \"\");\n\n const handleValueChange = (selectedValue: string) => {\n const handler = createEventHandler(\n node,\n \"onValueChange\",\n \"CHANGE\",\n processEvent\n );\n if (handler) handler({ value: selectedValue });\n };\n\n return (\n <div\n key={key as React.Key}\n className={cn(\"grid gap-1.5\", className as string)}\n >\n {label && <Label className=\"mb-1\">{label}</Label>}\n <RadioGroup\n name={name}\n value={value}\n onValueChange={handleValueChange}\n disabled={disabled}\n className=\"flex flex-col space-y-1\"\n >\n {options.map((option) => (\n <div key={option.value} className=\"flex items-center space-x-2\">\n <RadioGroupItem\n value={option.value}\n id={`${name}-${option.value}`}\n />\n <Label\n htmlFor={`${name}-${option.value}`}\n className=\"cursor-pointer\"\n >\n {option.label}\n </Label>\n </div>\n ))}\n </RadioGroup>\n </div>\n );\n },\n\n Tabs: (node, processEvent) => {\n // Extract key first (style is usually handled by className for Tabs)\n const { key, ...propsWithoutKey } = node.props || {};\n // For Tabs, children are defined by the 'tabs' prop which includes content as UISpecNode\n // We need to render these UISpecNode children.\n const rawTabs = getSafeBinding(\n node.bindings,\n \"tabs\",\n isArrayOf(isTabObject),\n []\n );\n const defaultValue = getSafeProp(\n propsWithoutKey,\n \"defaultValue\",\n isString,\n rawTabs[0]?.value || \"\"\n ); // Default to first tab if available\n const className = getSafeProp(propsWithoutKey, \"className\", isString, \"\");\n\n const handleValueChange = (value: string) => {\n const handler = createEventHandler(\n node,\n \"onValueChange\",\n \"CHANGE\",\n processEvent\n );\n if (handler) handler({ value });\n };\n\n return (\n <Tabs\n key={key as React.Key}\n defaultValue={defaultValue}\n onValueChange={handleValueChange}\n className={cn(\"autoui-tabs w-full\", className)}\n data-id={node.id}\n >\n <TabsList>\n {rawTabs.map((tab) => (\n <TabsTrigger key={tab.value} value={tab.value}>\n {tab.label}\n </TabsTrigger>\n ))}\n </TabsList>\n {rawTabs.map((tab) => (\n <TabsContent key={tab.value} value={tab.value}>\n {tab.content ? renderNode(tab.content, processEvent) : null}\n </TabsContent>\n ))}\n </Tabs>\n );\n },\n\n Dialog: (node, processEvent) => {\n // Determine if the dialog should be open. Check bindings first, then props.\n // Default to false if neither is specified.\n const isOpen = getSafeBinding(\n node.bindings,\n \"open\",\n isBoolean,\n getSafeProp(node.props, \"open\", isBoolean, false)\n ); // Fallback to props, then false\n\n // Extract key and className first. Intentionally exclude styleProp and open (_open)\n const {\n title,\n description,\n className,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n style: _styleProp,\n key,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n open: _openProp,\n ...restProps\n } = node.props || {}; // Renamed unused styleProp to _styleProp, open to _openProp\n\n // Ensure children are rendered with keys\n const children = node.children?.map((child) =>\n React.cloneElement(renderNode(child, processEvent), { key: child.id })\n );\n\n const handleOpenChange = (open: boolean) => {\n if (!open) {\n // Only trigger onClose when dialog is closed\n const handler = createEventHandler(\n node,\n \"onClose\", // Assumed event name in UISpec\n \"CLICK\", // Use CLICK as the event type for closing dialogs\n processEvent\n );\n if (handler) {\n handler({}); // Trigger with empty payload or adjust as needed\n }\n }\n // We might need to update the state via an event if open is controlled by bindings\n // For now, assume direct control or one-way binding for visibility\n };\n\n // Add console log to see props during render\n console.log(\n `[Adapter Debug] Rendering Dialog: id=${node.id}, props=`,\n node.props,\n `isOpen=${isOpen}`\n );\n\n return (\n <Dialog\n key={key as React.Key}\n open={isOpen}\n onOpenChange={handleOpenChange}\n >\n <DialogContent\n className={cn(\"autoui-dialog-content\", className as string)}\n {...restProps} // Pass restProps to DialogContent\n data-id={node.id} // Add data-id for debugging/testing\n >\n {(title || description) && (\n <DialogHeader>\n {title && <DialogTitle>{title as string}</DialogTitle>}\n {description && (\n <DialogDescription>{description as string}</DialogDescription>\n )}\n </DialogHeader>\n )}\n {children}\n {/* Removed explicit Close button, rely on Shadcn's built-in close or trigger via handleOpenChange */}\n </DialogContent>\n </Dialog>\n );\n },\n\n Heading: (node) => {\n // Extract key and style first. Remove unused textProp, levelProp.\n const { className, style: styleProp, key, ...restProps } = node.props || {};\n const text = getSafeProp(node.props, \"text\", isString, \"Heading\");\n // Ensure level is a valid heading level (1-6), default to 2\n let level = getSafeProp(\n node.props,\n \"level\",\n (v): v is number => typeof v === \"number\" && v >= 1 && v <= 6,\n 2\n );\n if (typeof level !== \"number\" || level < 1 || level > 6) {\n level = 2; // Fallback to h2 if level is invalid\n }\n const Tag = `h${level}` as keyof JSX.IntrinsicElements;\n // Parse style string if necessary\n const style =\n typeof styleProp === \"string\"\n ? parseStyleString(styleProp)\n : (styleProp as React.CSSProperties | undefined);\n\n // Apply some default Shadcn-like heading styles based on level\n const headingStyles =\n {\n 1: \"scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl\",\n 2: \"scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0\",\n 3: \"scroll-m-20 text-2xl font-semibold tracking-tight\",\n 4: \"scroll-m-20 text-xl font-semibold tracking-tight\",\n // Add styles for h5, h6 if needed, using text-lg, text-base etc.\n }[level] || \"text-lg font-semibold\"; // Default style\n\n return (\n <Tag\n key={key as React.Key}\n className={cn(headingStyles, className as string)}\n style={style}\n {...restProps}\n >\n {text}\n </Tag>\n );\n },\n\n Text: (node) => {\n // Extract key and style first. Remove unused textProp.\n const { className, style: styleProp, key, ...restProps } = node.props || {};\n const text = getSafeProp(node.props, \"text\", isString, \"Some text\");\n // Parse style string if necessary\n const style =\n typeof styleProp === \"string\"\n ? parseStyleString(styleProp)\n : (styleProp as React.CSSProperties | undefined);\n\n // Apply default paragraph styling\n return (\n <p\n key={key as React.Key}\n className={cn(\"leading-7\", className as string)}\n style={style}\n {...restProps}\n >\n {text}\n </p>\n );\n },\n};\n\nexport function renderNode(\n node: UISpecNode,\n processEvent?: (event: UIEvent) => void\n): React.ReactElement {\n const mappedComponent = adapterMap[node.node_type];\n if (mappedComponent) {\n return mappedComponent(node, processEvent);\n }\n console.warn(`Unknown node type: ${node.node_type}`);\n return React.createElement(\n Container,\n {},\n `Unknown node type: ${node.node_type}`\n );\n}\n","import * as React from \"react\"\nimport * as DialogPrimitive from \"@radix-ui/react-dialog\"\nimport { XIcon } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Dialog({\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Root>) {\n return <DialogPrimitive.Root data-slot=\"dialog\" {...props} />\n}\n\nfunction DialogTrigger({\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {\n return <DialogPrimitive.Trigger data-slot=\"dialog-trigger\" {...props} />\n}\n\nfunction DialogPortal({\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Portal>) {\n return <DialogPrimitive.Portal data-slot=\"dialog-portal\" {...props} />\n}\n\nfunction DialogClose({\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Close>) {\n return <DialogPrimitive.Close data-slot=\"dialog-close\" {...props} />\n}\n\nfunction DialogOverlay({\n className,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {\n return (\n <DialogPrimitive.Overlay\n data-slot=\"dialog-overlay\"\n className={cn(\n \"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction DialogContent({\n className,\n children,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Content>) {\n return (\n <DialogPortal data-slot=\"dialog-portal\">\n <DialogOverlay />\n <DialogPrimitive.Content\n data-slot=\"dialog-content\"\n className={cn(\n \"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg\",\n className\n )}\n {...props}\n >\n {children}\n <DialogPrimitive.Close className=\"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\">\n <XIcon />\n <span className=\"sr-only\">Close</span>\n </DialogPrimitive.Close>\n </DialogPrimitive.Content>\n </DialogPortal>\n )\n}\n\nfunction DialogHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"dialog-header\"\n className={cn(\"flex flex-col gap-2 text-center sm:text-left\", className)}\n {...props}\n />\n )\n}\n\nfunction DialogFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"dialog-footer\"\n className={cn(\n \"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction DialogTitle({\n className,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Title>) {\n return (\n <DialogPrimitive.Title\n data-slot=\"dialog-title\"\n className={cn(\"text-lg leading-none font-semibold\", className)}\n {...props}\n />\n )\n}\n\nfunction DialogDescription({\n className,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Description>) {\n return (\n <DialogPrimitive.Description\n data-slot=\"dialog-description\"\n className={cn(\"text-muted-foreground text-sm\", className)}\n {...props}\n />\n )\n}\n\nexport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogOverlay,\n DialogPortal,\n DialogTitle,\n DialogTrigger,\n}\n","import * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Card({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card\"\n className={cn(\n \"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-header\"\n className={cn(\n \"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardTitle({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-title\"\n className={cn(\"leading-none font-semibold\", className)}\n {...props}\n />\n )\n}\n\nfunction CardDescription({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-description\"\n className={cn(\"text-muted-foreground text-sm\", className)}\n {...props}\n />\n )\n}\n\nfunction CardAction({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-action\"\n className={cn(\n \"col-start-2 row-span-2 row-start-1 self-start justify-self-end\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardContent({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-content\"\n className={cn(\"px-6\", className)}\n {...props}\n />\n )\n}\n\nfunction CardFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-footer\"\n className={cn(\"flex items-center px-6 [.border-t]:pt-6\", className)}\n {...props}\n />\n )\n}\n\nexport {\n Card,\n CardHeader,\n CardFooter,\n CardTitle,\n CardAction,\n CardDescription,\n CardContent,\n}\n","import * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Input({ className, type, ...props }: React.ComponentProps<\"input\">) {\n return (\n <input\n type={type}\n data-slot=\"input\"\n className={cn(\n \"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm\",\n \"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]\",\n \"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Input }\n","import * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Textarea({ className, ...props }: React.ComponentProps<\"textarea\">) {\n return (\n <textarea\n data-slot=\"textarea\"\n className={cn(\n \"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Textarea }\n","import * as React from \"react\"\nimport * as SelectPrimitive from \"@radix-ui/react-select\"\nimport { CheckIcon, ChevronDownIcon, ChevronUpIcon } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Select({\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Root>) {\n return <SelectPrimitive.Root data-slot=\"select\" {...props} />\n}\n\nfunction SelectGroup({\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Group>) {\n return <SelectPrimitive.Group data-slot=\"select-group\" {...props} />\n}\n\nfunction SelectValue({\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Value>) {\n return <SelectPrimitive.Value data-slot=\"select-value\" {...props} />\n}\n\nfunction SelectTrigger({\n className,\n size = \"default\",\n children,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {\n size?: \"sm\" | \"default\"\n}) {\n return (\n <SelectPrimitive.Trigger\n data-slot=\"select-trigger\"\n data-size={size}\n className={cn(\n \"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n className\n )}\n {...props}\n >\n {children}\n <SelectPrimitive.Icon asChild>\n <ChevronDownIcon className=\"size-4 opacity-50\" />\n </SelectPrimitive.Icon>\n </SelectPrimitive.Trigger>\n )\n}\n\nfunction SelectContent({\n className,\n children,\n position = \"popper\",\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Content>) {\n return (\n <SelectPrimitive.Portal>\n <SelectPrimitive.Content\n data-slot=\"select-content\"\n className={cn(\n \"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md\",\n position === \"popper\" &&\n \"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1\",\n className\n )}\n position={position}\n {...props}\n >\n <SelectScrollUpButton />\n <SelectPrimitive.Viewport\n className={cn(\n \"p-1\",\n position === \"popper\" &&\n \"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1\"\n )}\n >\n {children}\n </SelectPrimitive.Viewport>\n <SelectScrollDownButton />\n </SelectPrimitive.Content>\n </SelectPrimitive.Portal>\n )\n}\n\nfunction SelectLabel({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Label>) {\n return (\n <SelectPrimitive.Label\n data-slot=\"select-label\"\n className={cn(\"text-muted-foreground px-2 py-1.5 text-xs\", className)}\n {...props}\n />\n )\n}\n\nfunction SelectItem({\n className,\n children,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Item>) {\n return (\n <SelectPrimitive.Item\n data-slot=\"select-item\"\n className={cn(\n \"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2\",\n className\n )}\n {...props}\n >\n <span className=\"absolute right-2 flex size-3.5 items-center justify-center\">\n <SelectPrimitive.ItemIndicator>\n <CheckIcon className=\"size-4\" />\n </SelectPrimitive.ItemIndicator>\n </span>\n <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>\n </SelectPrimitive.Item>\n )\n}\n\nfunction SelectSeparator({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Separator>) {\n return (\n <SelectPrimitive.Separator\n data-slot=\"select-separator\"\n className={cn(\"bg-border pointer-events-none -mx-1 my-1 h-px\", className)}\n {...props}\n />\n )\n}\n\nfunction SelectScrollUpButton({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {\n return (\n <SelectPrimitive.ScrollUpButton\n data-slot=\"select-scroll-up-button\"\n className={cn(\n \"flex cursor-default items-center justify-center py-1\",\n className\n )}\n {...props}\n >\n <ChevronUpIcon className=\"size-4\" />\n </SelectPrimitive.ScrollUpButton>\n )\n}\n\nfunction SelectScrollDownButton({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {\n return (\n <SelectPrimitive.ScrollDownButton\n data-slot=\"select-scroll-down-button\"\n className={cn(\n \"flex cursor-default items-center justify-center py-1\",\n className\n )}\n {...props}\n >\n <ChevronDownIcon className=\"size-4\" />\n </SelectPrimitive.ScrollDownButton>\n )\n}\n\nexport {\n Select,\n SelectContent,\n SelectGroup,\n SelectItem,\n SelectLabel,\n SelectScrollDownButton,\n SelectScrollUpButton,\n SelectSeparator,\n SelectTrigger,\n SelectValue,\n}\n","import * as React from \"react\"\nimport * as CheckboxPrimitive from \"@radix-ui/react-checkbox\"\nimport { CheckIcon } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Checkbox({\n className,\n ...props\n}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {\n return (\n <CheckboxPrimitive.Root\n data-slot=\"checkbox\"\n className={cn(\n \"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50\",\n className\n )}\n {...props}\n >\n <CheckboxPrimitive.Indicator\n data-slot=\"checkbox-indicator\"\n className=\"flex items-center justify-center text-current transition-none\"\n >\n <CheckIcon className=\"size-3.5\" />\n </CheckboxPrimitive.Indicator>\n </CheckboxPrimitive.Root>\n )\n}\n\nexport { Checkbox }\n","import * as React from \"react\"\nimport * as RadioGroupPrimitive from \"@radix-ui/react-radio-group\"\nimport { CircleIcon } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction RadioGroup({\n className,\n ...props\n}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {\n return (\n <RadioGroupPrimitive.Root\n data-slot=\"radio-group\"\n className={cn(\"grid gap-3\", className)}\n {...props}\n />\n )\n}\n\nfunction RadioGroupItem({\n className,\n ...props\n}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {\n return (\n <RadioGroupPrimitive.Item\n data-slot=\"radio-group-item\"\n className={cn(\n \"border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50\",\n className\n )}\n {...props}\n >\n <RadioGroupPrimitive.Indicator\n data-slot=\"radio-group-indicator\"\n className=\"relative flex items-center justify-center\"\n >\n <CircleIcon className=\"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2\" />\n </RadioGroupPrimitive.Indicator>\n </RadioGroupPrimitive.Item>\n )\n}\n\nexport { RadioGroup, RadioGroupItem }\n","import * as React from \"react\"\nimport * as TabsPrimitive from \"@radix-ui/react-tabs\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Tabs({\n className,\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.Root>) {\n return (\n <TabsPrimitive.Root\n data-slot=\"tabs\"\n className={cn(\"flex flex-col gap-2\", className)}\n {...props}\n />\n )\n}\n\nfunction TabsList({\n className,\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.List>) {\n return (\n <TabsPrimitive.List\n data-slot=\"tabs-list\"\n className={cn(\n \"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction TabsTrigger({\n className,\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {\n return (\n <TabsPrimitive.Trigger\n data-slot=\"tabs-trigger\"\n className={cn(\n \"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction TabsContent({\n className,\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.Content>) {\n return (\n <TabsPrimitive.Content\n data-slot=\"tabs-content\"\n className={cn(\"flex-1 outline-none\", className)}\n {...props}\n />\n )\n}\n\nexport { Tabs, TabsList, TabsTrigger, TabsContent }\n","import * as React from \"react\"\nimport * as LabelPrimitive from \"@radix-ui/react-label\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Label({\n className,\n ...props\n}: React.ComponentProps<typeof LabelPrimitive.Root>) {\n return (\n <LabelPrimitive.Root\n data-slot=\"label\"\n className={cn(\n \"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Label }\n","import React from \"react\";\nimport { UISpecNode, UIEvent } from \"../schema/ui\";\nimport {\n renderNode as renderShadcnNode,\n ShimmerBlock,\n ShimmerTable,\n ShimmerCard,\n} from \"../adapters/shadcn\";\nimport {\n createSystemEvent,\n systemEvents,\n SystemEventType,\n} from \"./system-events\";\n\n// Simple LRU cache for rendered nodes to avoid re-rendering the same node multiple times\n// This helps prevent infinite loops in the rendering process\nconst renderedNodesCache = new Map<\n string,\n { element: React.ReactElement; timestamp: number }\n>();\nconst MAX_CACHE_SIZE = 10;\nconst CACHE_TTL = 5000; // 5 seconds\n\n/**\n * Renders a UI node using the appropriate adapter\n * @param node - UI specification node\n * @param adapter - Component adapter (default: \"shadcn\")\n * @param processEvent - Optional callback to handle UI events\n * @returns React element\n */\nexport async function renderNode(\n node: UISpecNode,\n adapter: \"shadcn\" = \"shadcn\",\n processEvent?: (event: UIEvent) => void\n): Promise<React.ReactElement> {\n const startTime = Date.now();\n const nodeId = node.id;\n\n // Check cache first\n const cachedItem = renderedNodesCache.get(nodeId);\n if (cachedItem && startTime - cachedItem.timestamp < CACHE_TTL) {\n // Return cached result if it's not too old\n return cachedItem.element;\n }\n\n // Emit render start event\n await systemEvents.emit(\n createSystemEvent(SystemEventType.RENDER_START, { layout: node })\n );\n\n // Select the right adapter based on the adapter parameter\n let result: React.ReactElement;\n\n switch (adapter) {\n case \"shadcn\":\n result = renderShadcnNode(node, processEvent);\n break;\n default:\n console.warn(`Unsupported adapter: ${adapter}, falling back to shadcn`);\n result = renderShadcnNode(node, processEvent);\n }\n\n // Emit render complete event\n await systemEvents.emit(\n createSystemEvent(SystemEventType.RENDER_COMPLETE, {\n layout: node,\n renderTimeMs: Date.now() - startTime,\n })\n );\n\n // Store in cache\n renderedNodesCache.set(nodeId, {\n element: result,\n timestamp: startTime,\n });\n\n // Clean cache if it gets too big\n if (renderedNodesCache.size > MAX_CACHE_SIZE) {\n // Delete oldest entry\n const oldestKey = [...renderedNodesCache.entries()].sort(\n ([, a], [, b]) => a.timestamp - b.timestamp\n )[0][0];\n renderedNodesCache.delete(oldestKey);\n }\n\n return result;\n}\n\n/**\n * Generates a shimmer placeholder for a UI node\n * @param node - UI specification node\n * @param adapter - Component adapter (default: \"shadcn\")\n * @returns React element\n */\nexport function renderShimmer(\n node?: UISpecNode,\n adapter: \"shadcn\" = \"shadcn\"\n): React.ReactElement {\n // If no node, render a default shimmer\n if (!node) {\n return <ShimmerBlock />;\n }\n\n // Generate appropriate shimmer based on node type\n switch (node.node_type) {\n case \"ListView\":\n return <ShimmerTable rows={3} />;\n case \"Detail\":\n return <ShimmerCard />;\n case \"Container\":\n return (\n <div className=\"space-y-4\">\n {node.children?.map((child, index) => (\n <div key={index}>{renderShimmer(child, adapter)}</div>\n ))}\n </div>\n );\n default:\n return <ShimmerBlock />;\n }\n}\n","import { UISpecNode } from \"../schema/ui\";\nimport {\n createSystemEvent,\n systemEvents,\n SystemEventType,\n} from \"./system-events\";\n\n/**\n * Interface for the runtime data context\n */\nexport interface DataContext {\n [key: string]: unknown;\n}\n\n// Create a cache to prevent redundant resolving of the same node with same context\n// This helps prevent infinite loops\n// interface CacheKey { // Commented out as CacheKey is unused\n// nodeId: string;\n// contextHash: string;\n// }\nconst bindingsCache = new Map<string, UISpecNode>();\nconst MAX_CACHE_SIZE = 50;\nconst CACHE_TTL = 2000; // 2 seconds\nconst nodeCacheTimestamps = new Map<string, number>();\n\n// Simple hash function for data context objects to create cache keys\nfunction hashDataContext(context: DataContext): string {\n return JSON.stringify(context);\n}\n\n// Create a cache key from node id and context\nfunction createCacheKey(nodeId: string, context: DataContext): string {\n return `${nodeId}:${hashDataContext(context)}`;\n}\n\n/**\n * Get a value from the data context by path\n * Supports dot notation for nested properties\n *\n * @param context - The data context object\n * @param path - The path to the value (e.g., \"emails.data\")\n * @returns The value at the path, or undefined if not found\n */\nexport function getValueByPath(context: DataContext, path: string): unknown {\n const parts = path.split(\".\");\n let current: unknown = context;\n\n for (const part of parts) {\n if (current === null || current === undefined) {\n return undefined;\n }\n\n if (typeof current !== \"object\") {\n return undefined;\n }\n\n current = (current as Record<string, unknown>)[part];\n }\n\n return current;\n}\n\n/**\n * Set a value in the data context by path\n * Creates intermediate objects if they don't exist\n *\n * @param context - The data context object\n * @param path - The path to set (e.g., \"emails.selected\")\n * @param value - The value to set\n * @returns Updated data context\n */\nexport function setValueByPath(\n context: DataContext,\n path: string,\n value: unknown\n): DataContext {\n if (!path) {\n return context;\n }\n\n const result = { ...context };\n const parts = path.split(\".\");\n let current: unknown = result;\n\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n\n // Ensure the current level is an object before trying to access/modify properties\n if (typeof current !== \"object\" || current === null) {\n console.warn(\n `setValueByPath: Cannot traverse path \"${path}\". Parent segment \"${\n parts[i - 1] || \"(root)\"\n }\" is not an object.`\n );\n return context;\n }\n const currentAsObject = current as Record<string, unknown>;\n const nextPartValue = currentAsObject[part];\n\n if (nextPartValue === undefined || nextPartValue === null) {\n // If the next part doesn't exist or is null, create an empty object\n currentAsObject[part] = {};\n } else if (typeof nextPartValue !== \"object\") {\n // If the next part exists but isn't an object, we cannot traverse further.\n console.warn(\n `setValueByPath: Cannot create nested path \"${path}\". Segment \"${part}\" is not an object.`\n );\n return context; // Prevent overwriting primitives during traversal\n } else {\n // It exists and is an object, make a copy for immutability\n currentAsObject[part] = { ...(nextPartValue as Record<string, unknown>) };\n }\n // Move to the next level (which is now guaranteed to be an object)\n current = currentAsObject[part];\n }\n\n // Set the value at the final property\n const lastPart = parts[parts.length - 1];\n if (typeof current === \"object\" && current !== null) {\n // Now we are at the direct parent, safe to assign the value\n (current as Record<string, unknown>)[lastPart] = value;\n } else {\n // This case implies the path was invalid (e.g., single segment, root not object)\n console.warn(\n `setValueByPath: Could not set value for path \"${path}\". Final segment parent is not an object.`\n );\n return context;\n }\n\n return result;\n}\n\n/**\n * Process a binding value from a UI node\n *\n * @param binding - The binding value (string path, template string, or direct value)\n * @param context - The main data context object\n * @param itemData - Optional data context for the current list item\n * @returns The resolved value\n */\nexport function processBinding(\n binding: unknown,\n context: DataContext,\n itemData?: Record<string, unknown> // Added item context\n): unknown {\n if (typeof binding === \"string\") {\n const exactMatchArr = binding.match(/^{{(.*)}}$/);\n const pathInsideExact = exactMatchArr ? exactMatchArr[1].trim() : null;\n\n // Case 1: True \"Exact Template\" like {{item.name}}\n if (\n pathInsideExact !== null &&\n !pathInsideExact.includes(\"{{\") &&\n !pathInsideExact.includes(\"}}\")\n ) {\n const pathToResolve = pathInsideExact;\n let resolvedValue: unknown = undefined;\n // --- DEBUG LOGGING ---\n console.log(\n `[processBinding Debug] Processing EXACT template: \"${binding}\", Path: \"${pathToResolve}\", Has itemData: ${!!itemData}`\n );\n if (itemData) {\n // Log itemData content for debugging\n try {\n console.log(\n `[processBinding Debug] itemData content (EXACT):`,\n JSON.parse(JSON.stringify(itemData))\n );\n } catch {\n /* ignore logging error */\n }\n }\n // --- DEBUG LOGGING END ---\n\n if (\n (pathToResolve.startsWith(\"item.\") ||\n pathToResolve.startsWith(\"row.\")) &&\n itemData\n ) {\n if (pathToResolve.startsWith(\"item.\")) {\n resolvedValue = getValueByPath(itemData, pathToResolve.substring(5));\n } else {\n // Starts with \"row.\"\n resolvedValue = getValueByPath(itemData, pathToResolve.substring(4));\n }\n } else if (itemData && pathToResolve in itemData) {\n // Direct access to itemData property if path doesn't have \"item.\" or \"row.\" prefix but exists in itemData\n resolvedValue = getValueByPath(itemData, pathToResolve);\n }\n\n if (resolvedValue === undefined) {\n resolvedValue = getValueByPath(context, pathToResolve);\n }\n return resolvedValue; // Return original type (or undefined)\n\n // Case 2: \"Embedded Template\" like \"Name: {{item.name}}\" or \"{{item.name}} has {{item.id}}\"\n } else if (binding.includes(\"{{\") && binding.includes(\"}}\")) {\n // --- DEBUG LOGGING ---\n console.log(\n `[processBinding Debug] Processing EMBEDDED templates: \"${binding}\", Has itemData: ${!!itemData}`\n );\n if (itemData) {\n // Log itemData content for debugging\n try {\n console.log(\n `[processBinding Debug] itemData content (EMBEDDED):`,\n JSON.parse(JSON.stringify(itemData))\n );\n } catch {\n /* ignore logging error */\n }\n }\n // --- DEBUG LOGGING END ---\n\n const resolvedString = binding.replaceAll(\n /{{(.*?)}}/g, // Non-greedy match inside braces\n (match, path): string => {\n const trimmedPath = path.trim();\n let resolvedValue: unknown = undefined;\n\n if (\n (trimmedPath.startsWith(\"item.\") ||\n trimmedPath.startsWith(\"row.\")) &&\n itemData\n ) {\n if (trimmedPath.startsWith(\"item.\")) {\n resolvedValue = getValueByPath(\n itemData,\n trimmedPath.substring(5)\n );\n } else {\n resolvedValue = getValueByPath(\n itemData,\n trimmedPath.substring(4)\n );\n }\n } else if (itemData && trimmedPath in itemData) {\n resolvedValue = getValueByPath(itemData, trimmedPath);\n }\n\n if (resolvedValue === undefined) {\n resolvedValue = getValueByPath(context, trimmedPath);\n }\n\n return resolvedValue === null || resolvedValue === undefined\n ? \"\" // Substitute with empty string for unresolved templates in embedded strings\n : String(resolvedValue);\n }\n );\n return resolvedString; // Return the modified string\n\n // Case 3: \"Path String\" like \"user.name\"\n } else {\n const pathToResolve = binding;\n let resolvedValue: unknown = undefined;\n // --- DEBUG LOGGING ---\n console.log(\n `[processBinding Debug] Processing PATH string: \"${pathToResolve}\", Has itemData: ${!!itemData}`\n );\n // --- DEBUG LOGGING END ---\n\n // For path strings, prefer context unless itemData is explicitly targeted (e.g. via \"item.\" prefix handled above)\n // or if it's a simple property name that might exist on itemData.\n // Given current logic, exact paths like \"item.name\" are handled by EXACT, \"title\" could be item or context.\n // If itemData exists and path is a direct property of itemData (no dots)\n if (\n itemData &&\n !pathToResolve.includes(\".\") &&\n pathToResolve in itemData\n ) {\n resolvedValue = getValueByPath(itemData, pathToResolve);\n }\n\n if (resolvedValue === undefined) {\n resolvedValue = getValueByPath(context, pathToResolve);\n }\n return resolvedValue; // Return resolved value or undefined\n }\n }\n\n // If binding is an array, process each item recursively\n if (Array.isArray(binding)) {\n return binding.map((item) => processBinding(item, context, itemData));\n }\n\n // If binding is an object, process each property recursively\n if (binding !== null && typeof binding === \"object\") {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(binding)) {\n // IMPORTANT: Recursively call processBinding on the VALUE, not the key\n result[key] = processBinding(value, context, itemData);\n }\n return result;\n }\n\n // Otherwise, return the binding as-is (e.g., boolean, number, null)\n return binding;\n}\n\n/**\n * Create a deep clone of a node with all bindings resolved\n * Handles standard bindings and list expansion based on 'data' binding.\n *\n * @param node - The UI specification node\n * @param context - The main data context object\n * @param itemData - Optional data context for the current list item being resolved\n * @returns A new node with bindings resolved to concrete values\n */\nexport async function resolveBindings(\n node: UISpecNode,\n context: DataContext,\n itemData?: Record<string, unknown> // Added item context for list items\n): Promise<UISpecNode> {\n // Determine the effective context for resolving this node's bindings\n const effectiveContext = itemData ? { ...context, item: itemData } : context;\n\n // --- Cache Logic (using effective context) ---\n const currentTime = Date.now();\n const cacheKey = createCacheKey(node.id, effectiveContext);\n const cachedNode = bindingsCache.get(cacheKey);\n const cachedTimestamp = nodeCacheTimestamps.get(cacheKey);\n\n if (\n cachedNode &&\n cachedTimestamp &&\n currentTime - cachedTimestamp < CACHE_TTL\n ) {\n return cachedNode;\n }\n\n if (!itemData) {\n await systemEvents.emit(\n createSystemEvent(SystemEventType.BINDING_RESOLUTION_START, {\n layout: node,\n })\n );\n }\n\n const result: UISpecNode = {\n ...node,\n props: node.props ? JSON.parse(JSON.stringify(node.props)) : null,\n events: node.events ? JSON.parse(JSON.stringify(node.events)) : null,\n bindings: node.bindings ? JSON.parse(JSON.stringify(node.bindings)) : null,\n children: null, // Initialize children to null\n };\n\n const resolvedBindings: Record<string, unknown> = {};\n if (node.bindings) {\n for (const [key, bindingValue] of Object.entries(node.bindings)) {\n const resolvedValue = processBinding(bindingValue, context, itemData);\n\n resolvedBindings[key] = resolvedValue;\n\n if (resolvedValue !== undefined) {\n if (!result.props) result.props = {};\n result.props[key] = resolvedValue;\n }\n }\n }\n\n result.bindings = null;\n\n if (node.events) {\n result.events = processBinding(\n node.events,\n context,\n itemData\n ) as UISpecNode[\"events\"];\n } else {\n result.events = null;\n }\n\n const dataBindingValue =\n resolvedBindings[\"data\"] ?? resolvedBindings[\"items\"];\n\n if (\n (node.node_type === \"ListView\" || node.node_type === \"Table\") &&\n Array.isArray(dataBindingValue) &&\n node.children &&\n node.children.length > 0\n ) {\n const templateChild = node.children[0];\n const mappedChildren = await Promise.all(\n dataBindingValue.map(async (currentItemData, index) => {\n try {\n if (typeof currentItemData !== \"object\" || currentItemData === null) {\n console.warn(\n `List item at index ${index} for node ${node.id} is not an object:`,\n currentItemData\n );\n return null;\n }\n // console.log(`[resolveBindings Debug] Mapping item ${index} for node ${node.id}:`, currentItemData);\n\n const currentItemAsRecord = currentItemData as Record<\n string,\n unknown\n >;\n const itemId = currentItemAsRecord.id as string | number | undefined;\n const instanceId = `${templateChild.id}-${itemId || index}`;\n\n const childNodeInstance: UISpecNode = JSON.parse(\n JSON.stringify(templateChild)\n );\n childNodeInstance.id = instanceId;\n\n const resolvedChild = await resolveBindings(\n childNodeInstance,\n context,\n currentItemAsRecord\n );\n // console.log(`[resolveBindings Debug] Resolved child for item ${index} (node ${node.id}):`, JSON.parse(JSON.stringify(resolvedChild)));\n\n if (!resolvedChild.props) resolvedChild.props = {};\n resolvedChild.props.key = itemId || `${node.id}-item-${index}`;\n\n return resolvedChild;\n } catch (error) {\n console.error(\n `[resolveBindings Error] Error processing item at index ${index} for node ${node.id}:`,\n error,\n \"Item Data:\",\n currentItemData\n );\n return null;\n }\n })\n );\n result.children = mappedChildren.filter(\n (child) => child !== null\n ) as UISpecNode[];\n // console.log(`[resolveBindings Debug] Final mapped children for node ${node.id}:`, JSON.parse(JSON.stringify(result.children)));\n } else if (node.children && node.children.length > 0) {\n result.children = await Promise.all(\n node.children.map((child) => resolveBindings(child, context, itemData))\n );\n } else {\n result.children = [];\n }\n\n if (!itemData) {\n await systemEvents.emit(\n createSystemEvent(SystemEventType.BINDING_RESOLUTION_COMPLETE, {\n originalLayout: node,\n resolvedLayout: result,\n })\n );\n }\n\n bindingsCache.set(cacheKey, result);\n nodeCacheTimestamps.set(cacheKey, currentTime);\n\n if (bindingsCache.size > MAX_CACHE_SIZE) {\n let oldestKey: string | null = null;\n let oldestTimestamp = currentTime;\n for (const [key, timestamp] of nodeCacheTimestamps.entries()) {\n if (timestamp < oldestTimestamp) {\n oldestTimestamp = timestamp;\n oldestKey = key;\n }\n }\n if (oldestKey) {\n bindingsCache.delete(oldestKey);\n nodeCacheTimestamps.delete(oldestKey);\n }\n }\n\n return result;\n}\n\n/**\n * Execute an action based on event configuration\n *\n * @param action - The action type (e.g., \"VIEW_DETAIL\")\n * @param targetId - The target node ID\n * @param payload - Optional payload for the action\n * @param context - The data context\n * @param layoutTree - The current UI layout tree\n * @returns Updated data context\n */\nexport function executeAction(\n action: string,\n targetId?: string,\n payload?: Record<string, unknown>,\n context: DataContext = {},\n layoutTree?: UISpecNode\n): DataContext {\n // Clone the context to avoid mutations\n let newContext = { ...context };\n\n switch (action) {\n case \"VIEW_DETAIL\": {\n // Set the selected item in the context\n if (payload?.item) {\n newContext = setValueByPath(newContext, \"selected\", payload.item);\n }\n\n // Update visibility of the target node if provided\n if (targetId && layoutTree) {\n // For now, we don't modify the layout tree directly\n // This would be handled by the reducer in a real implementation\n }\n break;\n }\n\n case \"HIDE_DETAIL\": {\n // Clear the selected item\n newContext = setValueByPath(newContext, \"selected\", null);\n\n // Update visibility of the target node if provided\n if (targetId && layoutTree) {\n // For now, we don't modify the layout tree directly\n // This would be handled by the reducer in a real implementation\n }\n break;\n }\n\n case \"SET_VALUE\": {\n // Set a value in the context\n if (payload?.path && \"value\" in payload) {\n const path = String(payload.path);\n newContext = setValueByPath(newContext, path, payload.value);\n }\n break;\n }\n\n // Add more actions as needed\n\n default:\n console.warn(`Unknown action: ${action}`);\n }\n\n return newContext;\n}\n","import { UIEvent, UIEventType } from \"../schema/ui\";\n\nexport interface EventHookOptions {\n preventDefault?: boolean;\n stopPropagation?: boolean;\n}\n\nexport interface EventHookContext {\n originalEvent: UIEvent;\n preventDefault: () => void;\n stopPropagation: () => void;\n isDefaultPrevented: () => boolean;\n isPropagationStopped: () => boolean;\n}\n\nexport type EventHook = (context: EventHookContext) => void | Promise<void>;\n\nexport interface EventHooksMap {\n // Global hooks for all events\n all?: EventHook[];\n\n // Specific event type hooks\n [key: string]: EventHook[] | undefined;\n}\n\n/**\n * Event manager to handle registration and execution of event hooks\n */\nexport class EventManager {\n private hooks: EventHooksMap = {};\n\n /**\n * Register a hook for specific event types\n *\n * @param eventTypes - Event types to register for, or 'all' for all events\n * @param hook - Hook function to execute\n * @returns Unregister function\n */\n public register(\n eventTypes: UIEventType[] | \"all\",\n hook: EventHook\n ): () => void {\n if (eventTypes === \"all\") {\n if (!this.hooks.all) {\n this.hooks.all = [];\n }\n this.hooks.all.push(hook);\n\n return () => {\n if (this.hooks.all) {\n this.hooks.all = this.hooks.all.filter((h) => h !== hook);\n }\n };\n }\n\n eventTypes.forEach((type) => {\n if (!this.hooks[type]) {\n this.hooks[type] = [];\n }\n this.hooks[type]?.push(hook);\n });\n\n return () => {\n eventTypes.forEach((type) => {\n if (this.hooks[type]) {\n this.hooks[type] = this.hooks[type]?.filter((h) => h !== hook);\n }\n });\n };\n }\n\n /**\n * Process an event through all registered hooks\n *\n * @param event - The UI event to process\n * @returns Whether the default action should proceed\n */\n public async processEvent(event: UIEvent): Promise<boolean> {\n let defaultPrevented = false;\n let propagationStopped = false;\n\n const context: EventHookContext = {\n originalEvent: event,\n preventDefault: () => {\n defaultPrevented = true;\n },\n stopPropagation: () => {\n propagationStopped = true;\n },\n isDefaultPrevented: () => defaultPrevented,\n isPropagationStopped: () => propagationStopped,\n };\n\n // Run global hooks first\n if (this.hooks.all) {\n for (const hook of this.hooks.all) {\n await hook(context);\n if (propagationStopped) break;\n }\n }\n\n // If propagation not stopped and we have specific hooks for this event type\n if (!propagationStopped && this.hooks[event.type]) {\n for (const hook of this.hooks[event.type] || []) {\n await hook(context);\n if (propagationStopped) break;\n }\n }\n\n return !defaultPrevented;\n }\n}\n\n/**\n * Create a hook to intercept specific events\n *\n * @example\n * ```tsx\n * const unregister = useEventHook(['CLICK'], (ctx) => {\n * if (ctx.originalEvent.nodeId === 'deleteButton') {\n * // Show confirmation dialog\n * const confirmed = window.confirm('Are you sure?');\n * if (!confirmed) {\n * ctx.preventDefault();\n * }\n * }\n * });\n * ```\n */\nexport function createEventHook(\n eventTypes: UIEventType[] | \"all\",\n hook: EventHook,\n options?: EventHookOptions\n): EventHook {\n return async (context) => {\n await hook(context);\n\n if (options?.preventDefault) {\n context.preventDefault();\n }\n\n if (options?.stopPropagation) {\n context.stopPropagation();\n }\n };\n}\n","/**\n * Checks if shadcn components are available in the project\n * @returns Boolean indicating whether shadcn components are available\n */\nexport function areShadcnComponentsAvailable(): boolean {\n try {\n // Try to require one of the shadcn components\n require(\"../../components/ui/button\");\n return true;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Provides helpful guidance for missing components\n */\nexport function getMissingComponentsMessage(): string {\n return `Missing required shadcn components. Please run:\n> npm run setup-shadcn`;\n}\n","import { DataContext } from \"../../core/bindings\";\n\n/**\n * Drizzle schema adapter types\n */\n\n// Simplified representation of Drizzle schema\nexport interface DrizzleColumn {\n name: string;\n dataType: string;\n notNull?: boolean;\n defaultValue?: unknown;\n primaryKey?: boolean;\n unique?: boolean;\n references?: {\n table: string;\n column: string;\n };\n}\n\nexport interface DrizzleTable {\n name: string;\n schema: string;\n columns: Record<string, DrizzleColumn>;\n}\n\nexport interface DrizzleSchema {\n [tableName: string]: DrizzleTable;\n}\n\n// Database client interface\nexport interface DrizzleClientConfig {\n connectionString?: string | undefined;\n client?: unknown | undefined; // The actual Drizzle client instance\n queryFn?: ((tableName: string, query: any) => Promise<unknown[]>) | undefined;\n}\n\n// Main adapter interface\nexport interface DrizzleAdapterOptions {\n schema: DrizzleSchema;\n client?: DrizzleClientConfig | undefined;\n useMockData?: boolean | undefined;\n mockData?: Record<string, unknown[]> | undefined;\n}\n\n/**\n * Adapter for Drizzle ORM schemas\n * Handles converting Drizzle schema to AutoUI schema format\n * and optionally connects to a database\n */\nexport class DrizzleAdapter {\n private schema: DrizzleSchema;\n private client: DrizzleClientConfig | undefined;\n private useMockData: boolean;\n private mockData: Record<string, unknown[]>;\n\n constructor(options: DrizzleAdapterOptions) {\n this.schema = options.schema;\n this.client = options.client;\n this.useMockData = options.useMockData ?? !options.client;\n this.mockData = options.mockData ?? {};\n }\n\n /**\n * Convert Drizzle schema to AutoUI schema format\n */\n public getSchema(): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n Object.entries(this.schema).forEach(([tableName, table]) => {\n result[tableName] = {\n tableName: table.name,\n schema: table.schema,\n columns: this.convertColumns(table.columns),\n // Include mock data if available and mock mode is enabled\n ...(this.useMockData && this.mockData[tableName]\n ? { sampleData: this.mockData[tableName] }\n : {}),\n };\n });\n\n return result;\n }\n\n /**\n * Convert Drizzle columns to AutoUI column format\n */\n private convertColumns(\n columns: Record<string, DrizzleColumn>\n ): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n Object.entries(columns).forEach(([columnName, column]) => {\n result[columnName] = {\n type: this.mapDataType(column.dataType),\n notNull: column.notNull,\n defaultValue: column.defaultValue,\n primaryKey: column.primaryKey,\n unique: column.unique,\n references: column.references,\n };\n });\n\n return result;\n }\n\n /**\n * Map Drizzle data types to standard types\n */\n private mapDataType(drizzleType: string): string {\n const typeMap: Record<string, string> = {\n serial: \"integer\",\n integer: \"integer\",\n int: \"integer\",\n bigint: \"integer\",\n text: \"string\",\n varchar: \"string\",\n char: \"string\",\n boolean: \"boolean\",\n bool: \"boolean\",\n timestamp: \"datetime\",\n timestamptz: \"datetime\",\n date: \"date\",\n time: \"time\",\n json: \"object\",\n jsonb: \"object\",\n real: \"number\",\n float: \"number\",\n double: \"number\",\n numeric: \"number\",\n decimal: \"number\",\n };\n\n return typeMap[drizzleType.toLowerCase()] || \"string\";\n }\n\n /**\n * Execute a query against the database\n */\n public async query(tableName: string, query: any): Promise<unknown[]> {\n if (this.useMockData) {\n return this.mockData[tableName] || [];\n }\n\n if (!this.client) {\n throw new Error(\"No database client provided and mock mode is disabled\");\n }\n\n if (this.client.queryFn) {\n return this.client.queryFn(tableName, query);\n }\n\n throw new Error(\"No query function provided in client config\");\n }\n\n /**\n * Initialize the data context with schema information and optional mock data\n */\n public async initializeDataContext(): Promise<DataContext> {\n const context: DataContext = {};\n\n for (const [tableName, table] of Object.entries(this.schema)) {\n context[tableName] = {\n schema: table,\n data: this.useMockData ? this.mockData[tableName] || [] : [],\n selected: null,\n };\n }\n\n return context;\n }\n}\n","import { DataContext } from \"../../core/bindings\";\nimport { DrizzleAdapter, DrizzleAdapterOptions } from \"./drizzle\";\n\n/**\n * Generic schema adapter interface\n */\nexport interface SchemaAdapter {\n getSchema(): Record<string, unknown>;\n query(tableName: string, query: any): Promise<unknown[]>;\n initializeDataContext(): Promise<DataContext>;\n}\n\n/**\n * Schema adapter options union type\n */\nexport type SchemaAdapterOptions =\n | { type: \"drizzle\"; options: DrizzleAdapterOptions }\n | { type: \"custom\"; adapter: SchemaAdapter };\n\n/**\n * Factory function to create the appropriate schema adapter\n */\nexport function createSchemaAdapter(\n options: SchemaAdapterOptions\n): SchemaAdapter {\n switch (options.type) {\n case \"drizzle\":\n return new DrizzleAdapter(options.options);\n case \"custom\":\n return options.adapter;\n default:\n throw new Error(\n `Unsupported schema adapter type: ${(options as any).type}`\n );\n }\n}\n\nexport { DrizzleAdapter, type DrizzleAdapterOptions };\n","/**\n * AI Utilities for AutoUI React\n * Provides AI-powered UI generation functionality\n */\n\n// Temporary placeholder implementations for the exported functions\n// These will be replaced with actual implementations later\n\n/**\n * Generates a component using AI\n */\nexport const generateComponent = async (prompt: string) => {\n console.warn(\n \"generateComponent is a placeholder and will be implemented in a future version\"\n );\n return `<div>Generated Component for: ${prompt}</div>`;\n};\n\n/**\n * Generates a UI description using AI\n */\nexport const generateUIDescription = async (prompt: string) => {\n console.warn(\n \"generateUIDescription is a placeholder and will be implemented in a future version\"\n );\n return `Description for ${prompt}`;\n};\n\n/**\n * Generates a UI component using AI\n */\nexport const generateUIComponent = async (prompt: string) => {\n console.warn(\n \"generateUIComponent is a placeholder and will be implemented in a future version\"\n );\n return `<div>Generated UI Component for: ${prompt}</div>`;\n};\n","import { useState, useEffect, useCallback, useRef } from \"react\";\nimport {\n ActionRouter,\n callPlannerLLM,\n createDefaultRouter,\n processEvent,\n mockPlanner,\n} from \"../core\";\nimport { PlannerInput, UIEvent, UISpecNode } from \"../schema/ui\";\n\nexport interface UsePlannerOptions {\n goal: string;\n schema: Record<string, unknown>;\n openaiApiKey?: string;\n userContext?: Record<string, unknown>;\n router?: ActionRouter;\n modelProvider?: unknown; // To be expanded for different providers\n initialLayout?: UISpecNode;\n mockMode?: boolean;\n}\n\ninterface UsePlannerResult {\n layout: UISpecNode | undefined;\n loading: boolean;\n error: Error | null;\n handleEvent: (event: UIEvent) => Promise<void>;\n generateInitialLayout: () => Promise<void>;\n}\n\n/**\n * React hook for utilizing the AI planner functionality\n */\nexport function usePlanner(options: UsePlannerOptions): UsePlannerResult {\n const {\n schema,\n goal,\n openaiApiKey,\n userContext,\n initialLayout,\n mockMode: optionsMockMode,\n } = options;\n\n // State for UI layout\n const [layout, setLayout] = useState<UISpecNode | undefined>(\n initialLayout || undefined\n );\n\n // State for loading and error tracking\n const [loading, setLoading] = useState<boolean>(false);\n const [error, setError] = useState<Error | null>(null);\n\n // Use provided router or create a default one\n const router = options.router || createDefaultRouter();\n\n // Data context for bindings (simplified for now)\n const dataContext: Record<string, unknown> = {};\n\n // Ref to track if initial fetch has been attempted\n const initialFetchAttempted = useRef(false);\n\n // Determine actual mock mode based on option OR missing API key\n const mockMode = optionsMockMode || !openaiApiKey;\n\n /**\n * Generate the initial UI layout\n */\n const generateInitialLayout = useCallback(async () => {\n setLoading(true);\n setError(null);\n\n try {\n // Create initial planner input\n const plannerInput: PlannerInput = {\n schema,\n goal,\n userContext: userContext || null,\n history: null,\n };\n\n let generatedLayout: UISpecNode;\n if (mockMode) {\n console.warn(\n \"Using mock planner in usePlanner hook (mockMode enabled or API key missing).\"\n );\n generatedLayout = mockPlanner(plannerInput);\n } else {\n // We know openaiApiKey is defined here because mockMode is false\n generatedLayout = await callPlannerLLM(\n plannerInput,\n openaiApiKey as string,\n undefined\n );\n }\n setLayout(generatedLayout);\n } catch (err) {\n setError(err instanceof Error ? err : new Error(String(err)));\n } finally {\n setLoading(false);\n }\n }, [schema, goal, userContext, openaiApiKey, mockMode]);\n\n /**\n * Handle UI events and update the layout\n */\n const handleEvent = useCallback(\n async (event: UIEvent) => {\n if (!layout) {\n setError(new Error(\"Cannot handle event - no layout exists\"));\n return;\n }\n\n setLoading(true);\n setError(null);\n\n try {\n // Process the event using the router and generate an updated UI\n const updatedLayout = await processEvent(\n event,\n router,\n schema,\n layout,\n dataContext,\n goal,\n userContext,\n openaiApiKey\n );\n\n setLayout(updatedLayout);\n } catch (err) {\n setError(err instanceof Error ? err : new Error(String(err)));\n } finally {\n setLoading(false);\n }\n },\n [layout, router, schema, dataContext, goal, userContext, openaiApiKey]\n );\n\n // Effect for initial fetch\n useEffect(() => {\n // Only attempt initial fetch if:\n // 1. No initialLayout was provided via options.\n // 2. We haven't set a layout state yet.\n // 3. We haven't already attempted the initial fetch.\n if (\n options.initialLayout === undefined &&\n layout === undefined &&\n !initialFetchAttempted.current\n ) {\n // Mark that we are attempting the fetch\n initialFetchAttempted.current = true;\n generateInitialLayout();\n }\n // Dependencies are minimal now, just checking if an initial layout was provided\n // or if generateInitialLayout function identity changes (which it shouldn't often).\n }, [options.initialLayout, layout, generateInitialLayout]); // Removed loading from deps\n\n return {\n layout,\n loading,\n error,\n handleEvent,\n generateInitialLayout,\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/lib/utils.ts","../components/ui/button.tsx","../src/core/reducer.ts","../src/schema/action-types.ts","../src/core/planner.ts","../src/core/system-events.ts","../src/schema/openai-ui-spec.ts","../src/schema/components.ts","../src/core/bindings.ts","../src/core/action-router.ts","../src/AutoUI.tsx","../src/core/state.ts","../src/adapters/shadcn.tsx","../components/ui/dialog.tsx","../components/ui/card.tsx","../components/ui/input.tsx","../components/ui/textarea.tsx","../components/ui/select.tsx","../components/ui/checkbox.tsx","../components/ui/radio-group.tsx","../components/ui/tabs.tsx","../components/ui/label.tsx","../src/core/renderer.tsx","../src/core/events.ts","../src/core/component-detection.ts","../src/schema/ui.ts","../src/adapters/schema/drizzle.ts","../src/adapters/schema/index.ts","../src/ai-utils.ts"],"names":["Button","jsx","path","parent","ActionType","SystemEventType","z","plannerInput","React","useCallback","useRef","useEffect","jsxs","CheckIcon","Label","uiEventType","renderNode","componentType"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAA0B,YAAY;AACtC,SAAS,eAAe;AAMjB,SAAS,MAAM,QAAsB;AAC1C,SAAO,QAAQ,KAAK,MAAM,CAAC;AAC7B;AATA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA,gBAAAA;AAAA,EAAA;AAAA;AACA,SAAS,YAAY;AACrB,SAAS,WAA8B;AAgDnC,gBAAAC,aAAA;AAbJ,SAASD,QAAO;AAAA,EACd;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAU;AAAA,EACV,GAAG;AACL,GAGK;AACH,QAAM,OAAO,UAAU,OAAO;AAE9B,SACE,gBAAAC;AAAA,IAAC;AAAA;AAAA,MACC,aAAU;AAAA,MACV,WAAW,GAAG,eAAe,EAAE,SAAS,MAAM,UAAU,CAAC,CAAC;AAAA,MACzD,GAAG;AAAA;AAAA,EACN;AAEJ;AAxDA,IAMM;AANN;AAAA;AAAA;AAIA;AAEA,IAAM,iBAAiB;AAAA,MACrB;AAAA,MACA;AAAA,QACE,UAAU;AAAA,UACR,SAAS;AAAA,YACP,SACE;AAAA,YACF,aACE;AAAA,YACF,SACE;AAAA,YACF,WACE;AAAA,YACF,OACE;AAAA,YACF,MAAM;AAAA,UACR;AAAA,UACA,MAAM;AAAA,YACJ,SAAS;AAAA,YACT,IAAI;AAAA,YACJ,IAAI;AAAA,YACJ,MAAM;AAAA,UACR;AAAA,QACF;AAAA,QACA,iBAAiB;AAAA,UACf,SAAS;AAAA,UACT,MAAM;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAAA;AAAA;;;AC5BA,SAAS,UAAU,M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\n/**\n * Utility function for conditional class name generation\n * Combines clsx and tailwind-merge for cleaner className assignment\n */\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n","import * as React from \"react\"\nimport { Slot } from \"@radix-ui/react-slot\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"../../src/lib/utils\"\n\nconst buttonVariants = cva(\n \"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive\",\n {\n variants: {\n variant: {\n default:\n \"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90\",\n destructive:\n \"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60\",\n outline:\n \"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50\",\n secondary:\n \"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80\",\n ghost:\n \"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50\",\n link: \"text-primary underline-offset-4 hover:underline\",\n },\n size: {\n default: \"h-9 px-4 py-2 has-[>svg]:px-3\",\n sm: \"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5\",\n lg: \"h-10 rounded-md px-6 has-[>svg]:px-4\",\n icon: \"size-9\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n size: \"default\",\n },\n }\n)\n\nfunction Button({\n className,\n variant,\n size,\n asChild = false,\n ...props\n}: React.ComponentProps<\"button\"> &\n VariantProps<typeof buttonVariants> & {\n asChild?: boolean\n }) {\n const Comp = asChild ? Slot : \"button\"\n\n return (\n <Comp\n data-slot=\"button\"\n className={cn(buttonVariants({ variant, size, className }))}\n {...props}\n />\n )\n}\n\nexport { Button, buttonVariants }\n","import { UIAction, UIState, UISpecNode } from \"../schema/ui\";\n\n/**\n * Deep clones a UI node tree\n * @param node - Node to clone\n * @returns Cloned node\n */\nfunction cloneNode(node: UISpecNode): UISpecNode {\n return {\n ...node,\n props: node.props ? { ...node.props } : null,\n bindings: node.bindings ? { ...node.bindings } : null,\n events: node.events ? { ...node.events } : null,\n children: node.children\n ? node.children.map((child) => cloneNode(child))\n : null,\n };\n}\n\n/**\n * Find a specific node in the UI tree by ID\n * @param tree - UI tree to search\n * @param nodeId - ID of the node to find\n * @returns The found node or undefined\n */\nexport function findNodeById(\n tree: UISpecNode | undefined,\n nodeId: string\n): UISpecNode | undefined {\n if (!tree) return undefined;\n if (tree.id === nodeId) return tree;\n\n if (tree.children) {\n for (const child of tree.children) {\n const found = findNodeById(child, nodeId);\n if (found) return found;\n }\n }\n\n return undefined;\n}\n\n/**\n * Updates a specific node in the UI tree\n * @param tree - Original UI tree\n * @param nodeId - ID of the node to update\n * @param updater - Function that returns the updated node\n * @returns Updated UI tree\n */\nexport function updateNodeById(\n tree: UISpecNode,\n nodeId: string,\n updater: (node: UISpecNode) => UISpecNode\n): UISpecNode {\n // Clone the tree to avoid mutations\n const result = cloneNode(tree);\n\n // Find the parent path to the node\n function findPath(\n node: UISpecNode,\n id: string,\n currentPath: UISpecNode[] = []\n ): UISpecNode[] | null {\n const newPath = [...currentPath, node];\n\n if (node.id === id) {\n return newPath;\n }\n\n if (node.children) {\n for (const child of node.children) {\n const path = findPath(child, id, newPath);\n if (path) return path;\n }\n }\n\n return null;\n }\n\n const path = findPath(result, nodeId);\n if (!path) return result; // Node not found, return original\n\n // The last item in the path is the node to update\n const nodeToUpdate = path[path.length - 1];\n const updatedNode = updater(nodeToUpdate);\n\n // If this is the root node, return the updated node\n if (path.length === 1) {\n return updatedNode;\n }\n\n // Otherwise, update the parent's children\n const parent = path[path.length - 2];\n const updatedParent = {\n ...parent,\n children: parent.children\n ? parent.children.map((child) =>\n child.id === nodeId ? updatedNode : child\n )\n : null,\n };\n\n // If the parent is root, return it\n if (path.length === 2) {\n return updatedParent;\n }\n\n // Otherwise, recursively update up the tree\n return updateNodeById(result, parent.id, () => updatedParent);\n}\n\n/**\n * Replace a specific node in the UI tree\n * @param tree - Original UI tree\n * @param nodeId - ID of the node to replace\n * @param newNode - New node to insert\n * @returns Updated UI tree\n */\nexport function replaceNodeById(\n tree: UISpecNode,\n nodeId: string,\n newNode: UISpecNode\n): UISpecNode {\n return updateNodeById(tree, nodeId, () => newNode);\n}\n\n/**\n * Add a child node to a specific parent node\n * @param tree - Original UI tree\n * @param parentId - ID of the parent node\n * @param newChild - Child node to add\n * @param index - Optional index to insert at (default: append)\n * @returns Updated UI tree\n */\nexport function addChildNode(\n tree: UISpecNode,\n parentId: string,\n newChild: UISpecNode,\n index?: number\n): UISpecNode {\n return updateNodeById(tree, parentId, (node) => {\n const children = node.children ? [...node.children] : [];\n\n if (index !== undefined && index >= 0 && index <= children.length) {\n children.splice(index, 0, newChild);\n } else {\n children.push(newChild);\n }\n\n return {\n ...node,\n children,\n };\n });\n}\n\n/**\n * Remove a node from the UI tree\n * @param tree - Original UI tree\n * @param nodeId - ID of the node to remove\n * @returns Updated UI tree\n */\nexport function removeNodeById(tree: UISpecNode, nodeId: string): UISpecNode {\n // Find the parent of the node\n function findParent(node: UISpecNode, id: string): UISpecNode | null {\n if (node.children) {\n if (node.children.some((child) => child.id === id)) {\n return node;\n }\n\n for (const child of node.children) {\n const parent = findParent(child, id);\n if (parent) return parent;\n }\n }\n\n return null;\n }\n\n // Clone the tree to avoid mutations\n const result = cloneNode(tree);\n\n // If trying to remove the root, return empty tree\n if (result.id === nodeId) {\n throw new Error(\"Cannot remove root node\");\n }\n\n const parent = findParent(result, nodeId);\n if (!parent) return result; // Node not found, return original\n\n // Update the parent by filtering out the node\n return updateNodeById(result, parent.id, (node) => ({\n ...node,\n children: node.children\n ? node.children.filter((child) => child.id !== nodeId)\n : null,\n }));\n}\n\n/**\n * Pure reducer function for the UI state engine\n * @param state - Current state\n * @param action - Action to apply\n * @returns New state\n */\nexport function uiReducer(state: UIState, action: UIAction): UIState {\n switch (action.type) {\n case \"UI_EVENT\": {\n // Prevent duplicate INIT events\n if (\n action.event.type === \"INIT\" &&\n state.history.some((e) => e.type === \"INIT\")\n ) {\n console.log(\"[AutoUI uiReducer] Ignoring duplicate INIT event\");\n return state; // Ignore duplicate INIT\n }\n // Add the event to history and set loading state\n return {\n ...state,\n loading: true,\n history: [...state.history, action.event],\n };\n }\n\n case \"AI_RESPONSE\": {\n // Replace the layout with the new node and set loading to false\n return {\n ...state,\n layout: action.node,\n loading: false,\n error: null,\n };\n }\n\n case \"PARTIAL_UPDATE\": {\n if (!state.layout) {\n return {\n ...state,\n layout: action.node,\n loading: false,\n error: null,\n };\n }\n\n // Find the node to update\n if (action.nodeId === \"root\" || action.nodeId === state.layout.id) {\n // Root node replacement\n return {\n ...state,\n layout: action.node,\n loading: false,\n error: null,\n };\n }\n\n // Replace a specific node in the tree\n return {\n ...state,\n layout: replaceNodeById(state.layout, action.nodeId, action.node),\n loading: false,\n error: null,\n };\n }\n\n case \"ADD_NODE\": {\n if (!state.layout) {\n // Cannot add to a null layout, perhaps set the new node as root or error\n return {\n ...state,\n error: \"Cannot add node: Layout is empty.\",\n loading: false,\n };\n }\n return {\n ...state,\n layout: addChildNode(\n state.layout,\n action.parentId,\n action.node,\n action.index === null ? undefined : action.index\n ),\n loading: false,\n error: null,\n };\n }\n\n case \"REMOVE_NODE\": {\n if (!state.layout) {\n return {\n ...state,\n error: \"Cannot remove node: Layout is empty.\",\n loading: false,\n };\n }\n try {\n return {\n ...state,\n layout: removeNodeById(state.layout, action.nodeId),\n loading: false,\n error: null,\n };\n } catch (e: unknown) {\n const errorMessage =\n e instanceof Error ? e.message : \"Failed to remove node.\";\n return {\n ...state,\n error: errorMessage,\n loading: false,\n };\n }\n }\n\n case \"ERROR\": {\n return {\n ...state,\n error: action.message,\n loading: false,\n };\n }\n\n case \"LOADING\": {\n return {\n ...state,\n loading: action.isLoading,\n };\n }\n\n case \"SET_DATA_CONTEXT\": {\n return {\n ...state,\n dataContext: action.payload,\n };\n }\n\n default:\n return state;\n }\n}\n\n/**\n * Initial state for the UI state engine\n */\nexport const initialState: UIState = {\n layout: null,\n loading: true,\n error: null,\n history: [],\n dataContext: {},\n};\n","// Centralized enums for UI event and action types\n\nexport enum UIEventType {\n INIT = \"INIT\",\n CLICK = \"CLICK\",\n CHANGE = \"CHANGE\",\n SUBMIT = \"SUBMIT\",\n MOUSEOVER = \"MOUSEOVER\",\n MOUSEOUT = \"MOUSEOUT\",\n FOCUS = \"FOCUS\",\n BLUR = \"BLUR\",\n}\n\nexport enum ActionType {\n FULL_REFRESH = \"FULL_REFRESH\", // Generate a completely new UI\n UPDATE_NODE = \"UPDATE_NODE\", // Update a specific node, potentially with new children\n UPDATE_DATA = \"UPDATE_DATA\", // Add this for input changes\n ADD_ITEM = \"ADD_ITEM\", // Add an item to a list\n DELETE_ITEM = \"DELETE_ITEM\", // Delete an item from a list\n ADD_DROPDOWN = \"ADD_DROPDOWN\", // Add a dropdown to a specific node\n SHOW_DETAIL = \"SHOW_DETAIL\", // Show a detail view\n HIDE_DETAIL = \"HIDE_DETAIL\", // Hide a detail view\n HIDE_DIALOG = \"HIDE_DIALOG\", // Explicitly add HIDE_DIALOG\n SAVE_TASK_CHANGES = \"SAVE_TASK_CHANGES\", // Add action for saving\n TOGGLE_STATE = \"TOGGLE_STATE\", // Toggle a boolean state (expanded, selected, etc.)\n UPDATE_FORM = \"UPDATE_FORM\", // Update a form based on selections\n NAVIGATE = \"NAVIGATE\", // Navigate to a different view\n OPEN_DIALOG = \"OPEN_DIALOG\", // Open a dialog (for clarity)\n CLOSE_DIALOG = \"CLOSE_DIALOG\", // Close a dialog (for clarity)\n UPDATE_CONTEXT = \"UPDATE_CONTEXT\", // Generic context update\n}\n","import { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { generateObject } from \"ai\";\nimport { PlannerInput, UISpecNode } from \"../schema/ui\";\nimport {\n createSystemEvent,\n systemEvents,\n SystemEventType,\n} from \"./system-events\";\nimport { buildPrompt } from \"./action-router\";\nimport { openAIUISpec } from \"../schema/openai-ui-spec\";\n\n// Helper function to create the Anthropic client - REQUIRES an API key\nconst getAnthropicClient = (apiKey: string) => {\n return createAnthropic({\n apiKey: apiKey,\n });\n};\n\n/**\n * Mock planner that returns a realistic task dashboard UI for testing\n */\nfunction mockPlanner(_input: PlannerInput): UISpecNode {\n return {\n id: \"task-dashboard\",\n node_type: \"Container\",\n props: { className: \"p-4 space-y-4\" },\n bindings: null,\n events: null,\n children: [\n {\n id: \"header\",\n node_type: \"Container\",\n props: { className: \"flex justify-between items-center mb-4\" },\n bindings: null,\n events: null,\n children: [\n {\n id: \"title\",\n node_type: \"Text\",\n props: { text: \"Task Dashboard\", className: \"text-2xl font-bold\" },\n bindings: null,\n events: null,\n children: null,\n },\n {\n id: \"add-task-button\",\n node_type: \"Button\",\n props: { label: \"Add Task\", variant: \"default\" },\n bindings: null,\n events: {\n CLICK: { action: \"SHOW_DETAIL\", target: \"new-task-form\" },\n },\n children: null,\n },\n ],\n },\n {\n id: \"main-content\",\n node_type: \"Container\",\n props: { className: \"flex gap-4\" },\n bindings: null,\n events: null,\n children: [\n {\n id: \"tasks-container\",\n node_type: \"Container\",\n props: { className: \"flex-1\" },\n bindings: null,\n events: null,\n children: [\n {\n id: \"task-list\",\n node_type: \"ListView\",\n props: { className: \"space-y-2\" },\n bindings: { data: \"tasks.data\" },\n events: null,\n children: [\n {\n id: \"task-item-{{index}}\",\n node_type: \"Card\",\n props: { className: \"p-3 border rounded\" },\n bindings: null,\n events: null,\n children: [\n {\n id: \"task-title-{{index}}\",\n node_type: \"Text\",\n props: { className: \"font-medium\" },\n bindings: { text: \"item.title\" },\n events: null,\n children: null,\n },\n {\n id: \"task-status-{{index}}\",\n node_type: \"Badge\",\n props: {},\n bindings: { text: \"item.status\" },\n events: null,\n children: null,\n },\n {\n id: \"view-details-button-{{index}}\",\n node_type: \"Button\",\n props: { label: \"View Details\", variant: \"outline\", size: \"sm\" },\n bindings: null,\n events: {\n CLICK: { action: \"SHOW_DETAIL\", target: \"task-detail\" },\n },\n children: null,\n },\n ],\n },\n ],\n },\n ],\n },\n {\n id: \"task-detail\",\n node_type: \"Container\",\n props: { className: \"w-1/3 border-l pl-4\", visible: false },\n bindings: null,\n events: null,\n children: [\n {\n id: \"detail-title\",\n node_type: \"Text\",\n props: { text: \"Task Details\", className: \"text-lg font-bold mb-2\" },\n bindings: null,\n events: null,\n children: null,\n },\n {\n id: \"detail-content\",\n node_type: \"Text\",\n props: {},\n bindings: { text: \"tasks.selected.description\" },\n events: null,\n children: null,\n },\n {\n id: \"close-detail-button\",\n node_type: \"Button\",\n props: { label: \"Close\", variant: \"ghost\" },\n bindings: null,\n events: {\n CLICK: { action: \"HIDE_DETAIL\", target: \"task-detail\" },\n },\n children: null,\n },\n ],\n },\n ],\n },\n ],\n };\n}\n\n/**\n * Calls the LLM planner to generate a UI specification\n * @param input - Planner input\n * @param apiKey - Anthropic API key\n * @param useMock - Optional flag to use mock planner (for testing)\n * @returns Promise resolving to a UISpecNode\n */\nexport async function callPlannerLLM(\n input: PlannerInput,\n apiKey: string,\n useMock?: boolean\n): Promise<UISpecNode> {\n await systemEvents.emit(\n createSystemEvent(SystemEventType.PLAN_START, { plannerInput: input })\n );\n\n // Use mock planner if useMock flag is set or MOCK_PLANNER env var is set\n if (useMock || (typeof window !== 'undefined' && (window as any).__USE_MOCK_PLANNER)) {\n console.log(\"[Mock Planner] Using mock planner for testing\");\n const mockLayout = mockPlanner(input);\n await systemEvents.emit(\n createSystemEvent(SystemEventType.PLAN_COMPLETE, {\n layout: mockLayout,\n executionTimeMs: 0,\n })\n );\n return mockLayout;\n }\n\n // If not using mock planner via env var, API key is required for real LLM call\n if (!apiKey) {\n console.warn(\n `Anthropic API key was not provided to callPlannerLLM. Returning a placeholder UI.`\n );\n // Return a simple placeholder UI instead of throwing an error or calling a mock\n return {\n id: \"root-no-api-key\",\n node_type: \"Container\",\n props: {\n className: \"p-4 flex flex-col items-center justify-center h-full\",\n },\n bindings: null,\n events: null,\n children: [\n {\n id: \"no-api-key-message\",\n node_type: \"Text\",\n props: {\n text: \"Anthropic API Key is required to generate the UI. Please provide one in your environment configuration.\",\n className: \"text-red-500 text-center\",\n },\n bindings: null,\n events: null,\n children: null,\n },\n ],\n };\n }\n\n const startTime = Date.now();\n\n // Use userContext from the main input for template processing\n const templateValuesForPrompt = input.userContext ? { ...input.userContext } : undefined;\n const promptTemplateFromInput = typeof input.userContext?.promptTemplate === 'string'\n ? input.userContext.promptTemplate\n : undefined;\n\n const prompt = buildPrompt(\n input,\n promptTemplateFromInput, // Use template from input.userContext\n templateValuesForPrompt // Use values from input.userContext\n );\n\n // Emit prompt created event\n await systemEvents.emit(\n createSystemEvent(SystemEventType.PLAN_PROMPT_CREATED, { prompt })\n );\n\n try {\n let uiSpec: UISpecNode;\n\n // Check if we're in a browser environment - use API route to avoid CORS\n if (typeof window !== 'undefined') {\n // Browser environment - call the API route\n const response = await fetch('/api/generate-ui', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ prompt, apiKey }),\n });\n\n if (!response.ok) {\n const errorData = await response.json();\n throw new Error(errorData.error || `HTTP error! status: ${response.status}`);\n }\n\n const data = await response.json();\n uiSpec = data.uiSpec;\n } else {\n // Server environment - call Anthropic directly\n // Use AI SDK's generateObject with Claude Haiku 4.5 (fastest small model)\n // Anthropic requires explicit mode - using 'tool' for structured outputs\n const { object } = await generateObject({\n model: getAnthropicClient(apiKey)(\"claude-haiku-4-5\"),\n schema: openAIUISpec,\n mode: 'tool',\n messages: [{ role: \"user\", content: prompt }],\n temperature: 0.2,\n maxTokens: 4000,\n });\n uiSpec = object;\n }\n\n // Emit planning complete event\n await systemEvents.emit(\n createSystemEvent(SystemEventType.PLAN_COMPLETE, {\n layout: uiSpec,\n executionTimeMs: Date.now() - startTime,\n })\n );\n\n return uiSpec;\n } catch (error) {\n console.error(\"Error calling LLM planner:\", error);\n\n // Emit error event\n await systemEvents.emit(\n createSystemEvent(SystemEventType.PLAN_ERROR, {\n error: error instanceof Error ? error : new Error(String(error)),\n })\n );\n\n throw error;\n }\n}\n","import { UISpecNode, PlannerInput } from \"../schema/ui\";\n\n/**\n * System event types that represent the internal AutoUI lifecycle\n */\nexport enum SystemEventType {\n // Planning events\n PLAN_START = \"PLAN_START\", // Before AI planning begins\n PLAN_PROMPT_CREATED = \"PLAN_PROMPT_CREATED\", // After prompt is built\n PLAN_RESPONSE_CHUNK = \"PLAN_RESPONSE_CHUNK\", // For each AI response chunk\n PLAN_COMPLETE = \"PLAN_COMPLETE\", // After planning is complete\n PLAN_ERROR = \"PLAN_ERROR\", // Planning error occurred\n\n // Binding events\n BINDING_RESOLUTION_START = \"BINDING_RESOLUTION_START\", // Before bindings are resolved\n BINDING_RESOLUTION_COMPLETE = \"BINDING_RESOLUTION_COMPLETE\", // After bindings are resolved\n\n // Data events\n DATA_FETCH_START = \"DATA_FETCH_START\", // Before data is fetched\n DATA_FETCH_COMPLETE = \"DATA_FETCH_COMPLETE\", // After data is fetched\n\n // Rendering events\n RENDER_START = \"RENDER_START\", // Before layout is rendered\n RENDER_COMPLETE = \"RENDER_COMPLETE\", // After layout is rendered\n\n // Prefetch events (for future use)\n PREFETCH_START = \"PREFETCH_START\", // Before prefetching begins\n PREFETCH_COMPLETE = \"PREFETCH_COMPLETE\", // After prefetching completes\n}\n\n/**\n * Base system event interface\n */\nexport interface SystemEvent {\n type: SystemEventType;\n timestamp: number;\n}\n\n/**\n * Planning events\n */\nexport interface PlanStartEvent extends SystemEvent {\n type: SystemEventType.PLAN_START;\n plannerInput: PlannerInput;\n}\n\nexport interface PlanPromptCreatedEvent extends SystemEvent {\n type: SystemEventType.PLAN_PROMPT_CREATED;\n prompt: string;\n}\n\nexport interface PlanResponseChunkEvent extends SystemEvent {\n type: SystemEventType.PLAN_RESPONSE_CHUNK;\n chunk: string;\n isComplete: boolean;\n}\n\nexport interface PlanCompleteEvent extends SystemEvent {\n type: SystemEventType.PLAN_COMPLETE;\n layout: UISpecNode;\n executionTimeMs: number;\n}\n\nexport interface PlanErrorEvent extends SystemEvent {\n type: SystemEventType.PLAN_ERROR;\n error: Error;\n}\n\n/**\n * Binding events\n */\nexport interface BindingResolutionStartEvent extends SystemEvent {\n type: SystemEventType.BINDING_RESOLUTION_START;\n layout: UISpecNode;\n}\n\nexport interface BindingResolutionCompleteEvent extends SystemEvent {\n type: SystemEventType.BINDING_RESOLUTION_COMPLETE;\n originalLayout: UISpecNode;\n resolvedLayout: UISpecNode;\n}\n\n/**\n * Data events\n */\nexport interface DataFetchStartEvent extends SystemEvent {\n type: SystemEventType.DATA_FETCH_START;\n tableName: string;\n query: unknown;\n}\n\nexport interface DataFetchCompleteEvent extends SystemEvent {\n type: SystemEventType.DATA_FETCH_COMPLETE;\n tableName: string;\n results: unknown[];\n executionTimeMs: number;\n}\n\n/**\n * Rendering events\n */\nexport interface RenderStartEvent extends SystemEvent {\n type: SystemEventType.RENDER_START;\n layout: UISpecNode;\n}\n\nexport interface RenderCompleteEvent extends SystemEvent {\n type: SystemEventType.RENDER_COMPLETE;\n layout: UISpecNode;\n renderTimeMs: number;\n}\n\n/**\n * Prefetch events\n */\nexport interface PrefetchStartEvent extends SystemEvent {\n type: SystemEventType.PREFETCH_START;\n depth: number;\n}\n\nexport interface PrefetchCompleteEvent extends SystemEvent {\n type: SystemEventType.PREFETCH_COMPLETE;\n prefetchedLayouts: Record<string, UISpecNode>;\n}\n\n/**\n * Union type of all system events\n */\nexport type AnySystemEvent =\n | PlanStartEvent\n | PlanPromptCreatedEvent\n | PlanResponseChunkEvent\n | PlanCompleteEvent\n | PlanErrorEvent\n | BindingResolutionStartEvent\n | BindingResolutionCompleteEvent\n | DataFetchStartEvent\n | DataFetchCompleteEvent\n | RenderStartEvent\n | RenderCompleteEvent\n | PrefetchStartEvent\n | PrefetchCompleteEvent;\n\n/**\n * System event hook type\n */\nexport type SystemEventHook<T extends SystemEvent = AnySystemEvent> = (\n event: T\n) => void | Promise<void>;\n\n/**\n * System event manager\n */\nexport class SystemEventManager {\n private listeners: Partial<Record<SystemEventType, SystemEventHook[]>> = {};\n\n /**\n * Register a listener for a specific system event type\n *\n * @param eventType - The system event type to listen for\n * @param listener - The listener function\n * @returns Function to unregister the listener\n */\n public on<T extends SystemEventType>(\n eventType: T,\n listener: SystemEventHook<Extract<AnySystemEvent, { type: T }>>\n ): () => void {\n if (!this.listeners[eventType]) {\n this.listeners[eventType] = [];\n }\n\n this.listeners[eventType]?.push(listener as SystemEventHook);\n\n return () => {\n if (this.listeners[eventType]) {\n this.listeners[eventType] = this.listeners[eventType]?.filter(\n (l) => l !== listener\n );\n }\n };\n }\n\n /**\n * Emit a system event to all registered listeners\n *\n * @param event - The system event to emit\n */\n public async emit<T extends AnySystemEvent>(event: T): Promise<void> {\n const listeners = this.listeners[event.type] || [];\n\n for (const listener of listeners) {\n await listener(event);\n }\n }\n}\n\n// Create a singleton instance for global access\nexport const systemEvents = new SystemEventManager();\n\n/**\n * Helper to create a typed system event\n *\n * @param type - The system event type\n * @param data - Additional event data\n * @returns A system event object\n */\nexport function createSystemEvent<T extends SystemEventType>(\n type: T,\n data: Omit<Extract<AnySystemEvent, { type: T }>, \"type\" | \"timestamp\">\n): Extract<AnySystemEvent, { type: T }> {\n return {\n type,\n timestamp: Date.now(),\n ...data,\n } as Extract<AnySystemEvent, { type: T }>;\n}\n","import { z } from \"zod\";\nimport { componentType } from \"./components\";\n\n// Zod enum for ActionType using the values from the TypeScript enum\nconst actionTypeEnum = z.enum([\n \"FULL_REFRESH\",\n \"UPDATE_NODE\",\n \"UPDATE_DATA\",\n \"ADD_DROPDOWN\",\n \"SHOW_DETAIL\",\n \"HIDE_DETAIL\",\n \"HIDE_DIALOG\",\n \"SAVE_TASK_CHANGES\",\n \"TOGGLE_STATE\",\n \"UPDATE_FORM\",\n \"NAVIGATE\",\n \"OPEN_DIALOG\",\n \"CLOSE_DIALOG\",\n \"UPDATE_CONTEXT\",\n]);\n\n// For OpenAI: props/bindings are records of these simplified values, or null.\nconst openAISimplifiedValue = z.string().nullable();\nconst openAIRecordSimplifiedNullable = z\n .record(openAISimplifiedValue)\n .nullable();\nconst openAIEventPayloadSimplifiedNullable = z\n .record(openAISimplifiedValue)\n .nullable();\n\nconst openAIBaseNode = z.object({\n id: z.string().describe(\"Unique identifier for the UI node.\"),\n node_type: componentType.describe(\n \"The type of UI component (e.g., Container, Text, Button, ListView).\"\n ),\n props: openAIRecordSimplifiedNullable.describe(\n 'Component-specific properties (attributes). Values should be strings or null. E.g., for Header use { \"title\": \"My Title\" }; for Text use { \"text\": \"My Text\" }; for Button use { \"label\": \"My Button Label\" }.'\n ),\n bindings: openAIRecordSimplifiedNullable.describe(\n 'Data bindings map context paths to component props. Values are paths (e.g., \"user.name\") or templates (e.g., \"{{item.title}}\")...'\n ),\n events: z\n .record(\n z.string(),\n z.object({\n action: actionTypeEnum.describe(\n 'Action identifier (e.g., \"UPDATE_DATA\", \"ADD_ITEM\", \"DELETE_ITEM\", \"VIEW_DETAIL\", \"HIDE_DETAIL\"). Defines what operation to perform when the event occurs.'\n ),\n target: z.string().describe(\"Target identifier.\"),\n payload: openAIEventPayloadSimplifiedNullable.describe(\n \"Static payload to merge with the event's runtime payload.\"\n ),\n })\n )\n .nullable()\n .describe(\n 'Defines event handlers mapped from UIEventType (e.g., \"CLICK\", \"CHANGE\") to an action configuration.'\n ),\n children: z.null(),\n});\n\nconst openAINodeL4 = openAIBaseNode;\nconst openAINodeL3 = openAIBaseNode.extend({\n children: z.array(openAINodeL4).nullable(),\n});\nconst openAINodeL2 = openAIBaseNode.extend({\n children: z.array(openAINodeL3).nullable(),\n});\n\nexport const openAIUISpec = openAIBaseNode.extend({\n children: z.array(openAINodeL2).nullable(),\n});\n\nexport type OpenAIUISpec = z.infer<typeof openAIUISpec>;\n","/**\n * Component definitions for shadcn/ui integration\n * This file defines which components from shadcn/ui are used by AutoUI\n */\n\nimport { z } from \"zod\";\n\n// Define all possible component types\nexport const componentType = z.enum([\n // Layout components\n \"Container\",\n \"Card\",\n \"Header\",\n\n // Input components\n \"Button\",\n \"Input\",\n \"Select\",\n \"Textarea\",\n \"Checkbox\",\n \"RadioGroup\",\n\n // Data display components\n \"ListView\",\n \"Detail\",\n \"Tabs\",\n \"Dialog\",\n \"Badge\",\n\n // Typography\n \"Heading\",\n \"Text\",\n]);\n\nexport type ComponentType = z.infer<typeof componentType>;\n\n// Map component types to their shadcn component and required props\nexport const componentConfig = {\n Button: {\n component: \"Button\",\n requiredProps: [\"label\"],\n optionalProps: [\"variant\", \"size\", \"disabled\"],\n events: [\"onClick\"],\n },\n Card: {\n component: \"Card\",\n requiredProps: [],\n optionalProps: [\"className\"],\n events: [],\n },\n Input: {\n component: \"Input\",\n requiredProps: [\"name\"],\n optionalProps: [\"label\", \"placeholder\", \"disabled\", \"value\"],\n events: [\"onChange\", \"onFocus\", \"onBlur\"],\n },\n Select: {\n component: \"Select\",\n requiredProps: [\"name\", \"options\"],\n optionalProps: [\"label\", \"placeholder\", \"disabled\", \"value\"],\n events: [\"onChange\"],\n },\n Textarea: {\n component: \"Textarea\",\n requiredProps: [\"name\"],\n optionalProps: [\"label\", \"placeholder\", \"disabled\", \"value\", \"rows\"],\n events: [\"onChange\", \"onFocus\", \"onBlur\"],\n },\n Container: {\n component: \"div\",\n requiredProps: [],\n optionalProps: [\"className\", \"style\"],\n events: [],\n },\n Header: {\n component: \"header\",\n requiredProps: [\"title\"],\n optionalProps: [\"className\"],\n events: [],\n },\n ListView: {\n component: \"Table\",\n requiredProps: [\"fields\"],\n optionalProps: [\"items\", \"selectable\"],\n events: [\"onSelect\"],\n },\n Detail: {\n component: \"div\",\n requiredProps: [\"fields\"],\n optionalProps: [\"data\", \"title\", \"visible\"],\n events: [\"onBack\"],\n },\n Dialog: {\n component: \"Dialog\",\n requiredProps: [\"title\"],\n optionalProps: [\"open\", \"onClose\", \"description\"],\n events: [\"onClose\"],\n },\n Tabs: {\n component: \"Tabs\",\n requiredProps: [\"tabs\"],\n optionalProps: [\"defaultValue\"],\n events: [\"onChange\"],\n },\n Heading: {\n component: \"h2\",\n requiredProps: [\"text\"],\n optionalProps: [\"size\", \"className\"],\n events: [],\n },\n Text: {\n component: \"p\",\n requiredProps: [\"text\"],\n optionalProps: [\"size\", \"className\"],\n events: [],\n },\n Checkbox: {\n component: \"Checkbox\",\n requiredProps: [\"name\"],\n optionalProps: [\"label\", \"checked\", \"disabled\"],\n events: [\"onChange\"],\n },\n RadioGroup: {\n component: \"RadioGroup\",\n requiredProps: [\"name\", \"options\"],\n optionalProps: [\"label\", \"value\", \"disabled\"],\n events: [\"onChange\"],\n },\n Badge: {\n component: \"span\",\n requiredProps: [\"text\"],\n optionalProps: [\"className\", \"variant\"],\n events: [],\n },\n};\n\n// List of required shadcn components for the setup script\nexport const shadcnComponents = [\n \"button\",\n \"card\",\n \"dialog\",\n \"dropdown-menu\",\n \"form\",\n \"input\",\n \"label\",\n \"select\",\n \"table\",\n \"tabs\",\n \"textarea\",\n \"checkbox\",\n \"radio-group\",\n \"container\",\n];\n","import { UISpecNode, DataItem } from \"../schema/ui\";\nimport { ActionType } from \"../schema/action-types\";\n\n/**\n * Interface for the runtime data context\n */\nexport interface DataContext {\n [key: string]: unknown;\n}\n\n/**\n * Get a value from the data context by path\n * Supports dot notation for nested properties\n *\n * @param context - The data context object\n * @param path - The path to the value (e.g., \"emails.data\")\n * @returns The value at the path, or undefined if not found\n */\nexport function getValueByPath(context: DataContext, path: string): unknown {\n const parts = path.split(\".\");\n let current: unknown = context;\n\n for (const part of parts) {\n if (current === null || current === undefined) {\n return undefined;\n }\n\n if (typeof current !== \"object\") {\n return undefined;\n }\n\n current = (current as Record<string, unknown>)[part];\n }\n\n return current;\n}\n\n/**\n * Set a value in the data context by path\n * Creates intermediate objects if they don't exist\n *\n * @param context - The data context object\n * @param path - The path to set (e.g., \"emails.selected\")\n * @param value - The value to set\n * @returns Updated data context\n */\nexport function setValueByPath(\n context: DataContext,\n path: string,\n value: unknown\n): DataContext {\n if (!path) {\n return context;\n }\n\n const result = { ...context };\n const parts = path.split(\".\");\n let current: unknown = result;\n\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n\n // Ensure the current level is an object before trying to access/modify properties\n if (typeof current !== \"object\" || current === null) {\n console.warn(\n `setValueByPath: Cannot traverse path \"${path}\". Parent segment \"${\n parts[i - 1] || \"(root)\"\n }\" is not an object.`\n );\n return context;\n }\n const currentAsObject = current as Record<string, unknown>;\n const nextPartValue = currentAsObject[part];\n\n if (nextPartValue === undefined || nextPartValue === null) {\n // If the next part doesn't exist or is null, create an empty object\n currentAsObject[part] = {};\n } else if (typeof nextPartValue !== \"object\") {\n // If the next part exists but isn't an object, we cannot traverse further.\n console.warn(\n `setValueByPath: Cannot create nested path \"${path}\". Segment \"${part}\" is not an object.`\n );\n return context; // Prevent overwriting primitives during traversal\n } else {\n // It exists and is an object, make a copy for immutability\n currentAsObject[part] = { ...(nextPartValue as Record<string, unknown>) };\n }\n // Move to the next level (which is now guaranteed to be an object)\n current = currentAsObject[part];\n }\n\n // Set the value at the final property\n const lastPart = parts[parts.length - 1];\n if (typeof current === \"object\" && current !== null) {\n // Now we are at the direct parent, safe to assign the value\n (current as Record<string, unknown>)[lastPart] = value;\n } else {\n // This case implies the path was invalid (e.g., single segment, root not object)\n console.warn(\n `setValueByPath: Could not set value for path \"${path}\". Final segment parent is not an object.`\n );\n return context;\n }\n\n return result;\n}\n\n/**\n * Process a binding value from a UI node\n *\n * @param binding - The binding value (string path, template string, or direct value)\n * @param context - The main data context object\n * @param itemData - Optional data context for the current list item\n * @returns The resolved value\n */\nexport function processBinding(\n binding: unknown,\n context: DataContext,\n itemData?: Record<string, unknown> // Added item context\n): unknown {\n if (typeof binding === \"string\") {\n const exactMatchArr = binding.match(/^{{(.*)}}$/);\n const pathInsideExact = exactMatchArr ? exactMatchArr[1].trim() : null;\n\n // Case 1: True \"Exact Template\" like {{item.name}}\n if (\n pathInsideExact !== null &&\n !pathInsideExact.includes(\"{{\") &&\n !pathInsideExact.includes(\"}}\")\n ) {\n const pathToResolve = pathInsideExact;\n let resolvedValue: unknown = undefined;\n // --- DEBUG LOGGING ---\n // console.log(\n // `[processBinding Debug] Processing EXACT template: \"${binding}\", Path: \"${pathToResolve}\", Has itemData: ${!!itemData}`\n // );\n // if (itemData) {\n // // Log itemData content for debugging\n // try {\n // console.log(\n // `[processBinding Debug] itemData content (EXACT):`,\n // JSON.parse(JSON.stringify(itemData))\n // );\n // } catch {\n // /* ignore logging error */\n // }\n // }\n // --- DEBUG LOGGING END ---\n\n if (\n (pathToResolve.startsWith(\"item.\") ||\n pathToResolve.startsWith(\"row.\")) &&\n itemData\n ) {\n if (pathToResolve.startsWith(\"item.\")) {\n resolvedValue = getValueByPath(itemData, pathToResolve.substring(5));\n } else {\n // Starts with \"row.\"\n resolvedValue = getValueByPath(itemData, pathToResolve.substring(4));\n }\n } else if (itemData && pathToResolve in itemData) {\n // Direct access to itemData property if path doesn't have \"item.\" or \"row.\" prefix but exists in itemData\n resolvedValue = getValueByPath(itemData, pathToResolve);\n }\n\n if (resolvedValue === undefined) {\n resolvedValue = getValueByPath(context, pathToResolve);\n }\n return resolvedValue; // Return original type (or undefined)\n\n // Case 2: \"Embedded Template\" like \"Name: {{item.name}}\" or \"{{item.name}} has {{item.id}}\"\n } else if (binding.includes(\"{{\") && binding.includes(\"}}\")) {\n // --- DEBUG LOGGING ---\n // console.log(\n // `[processBinding Debug] Processing EMBEDDED templates: \"${binding}\", Has itemData: ${!!itemData}`\n // );\n // if (itemData) {\n // // Log itemData content for debugging\n // try {\n // console.log(\n // `[processBinding Debug] itemData content (EMBEDDED):`,\n // JSON.parse(JSON.stringify(itemData))\n // );\n // } catch {\n // /* ignore logging error */\n // }\n // }\n // --- DEBUG LOGGING END ---\n\n const resolvedString = binding.replaceAll(\n /{{(.*?)}}/g, // Non-greedy match inside braces\n (match, path): string => {\n const trimmedPath = path.trim();\n let resolvedValue: unknown = undefined;\n\n if (\n (trimmedPath.startsWith(\"item.\") ||\n trimmedPath.startsWith(\"row.\")) &&\n itemData\n ) {\n if (trimmedPath.startsWith(\"item.\")) {\n resolvedValue = getValueByPath(\n itemData,\n trimmedPath.substring(5)\n );\n } else {\n resolvedValue = getValueByPath(\n itemData,\n trimmedPath.substring(4)\n );\n }\n } else if (itemData && trimmedPath in itemData) {\n resolvedValue = getValueByPath(itemData, trimmedPath);\n }\n\n if (resolvedValue === undefined) {\n resolvedValue = getValueByPath(context, trimmedPath);\n }\n\n return resolvedValue === null || resolvedValue === undefined\n ? \"\" // Substitute with empty string for unresolved templates in embedded strings\n : String(resolvedValue);\n }\n );\n return resolvedString; // Return the modified string\n\n // Case 3: \"Path String\" like \"user.name\"\n } else {\n const pathToResolve = binding;\n let resolvedValue: unknown = undefined;\n // --- DEBUG LOGGING ---\n // console.log(\n // `[processBinding Debug] Processing PATH string: \"${pathToResolve}\", Has itemData: ${!!itemData}`\n // );\n // --- DEBUG LOGGING END ---\n\n // Handle plain path bindings (without {{}}) that reference item data\n // Check for \"item.\" or \"row.\" prefix first\n if (\n (pathToResolve.startsWith(\"item.\") || pathToResolve.startsWith(\"row.\")) &&\n itemData\n ) {\n if (pathToResolve.startsWith(\"item.\")) {\n resolvedValue = getValueByPath(itemData, pathToResolve.substring(5));\n } else {\n resolvedValue = getValueByPath(itemData, pathToResolve.substring(4));\n }\n if (resolvedValue !== undefined) {\n return resolvedValue;\n }\n }\n\n // If itemData exists and path is a direct property of itemData (no dots)\n if (\n itemData &&\n !pathToResolve.includes(\".\") &&\n pathToResolve in itemData\n ) {\n resolvedValue = getValueByPath(itemData, pathToResolve);\n }\n\n if (resolvedValue === undefined) {\n resolvedValue = getValueByPath(context, pathToResolve);\n }\n return resolvedValue; // Return resolved value or undefined\n }\n }\n\n // If binding is an array, process each item recursively\n if (Array.isArray(binding)) {\n return binding.map((item) => processBinding(item, context, itemData));\n }\n\n // If binding is an object, process each property recursively\n if (binding !== null && typeof binding === \"object\") {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(binding)) {\n // IMPORTANT: Recursively call processBinding on the VALUE, not the key\n result[key] = processBinding(value, context, itemData);\n }\n return result;\n }\n\n // Otherwise, return the binding as-is (e.g., boolean, number, null)\n return binding;\n}\n\n/**\n * Create a deep clone of a node with all bindings resolved\n * Handles standard bindings and list expansion based on 'data' binding.\n *\n * @param node - The UI specification node\n * @param context - The main data context object\n * @param itemData - Optional data context for the current list item being resolved\n * @returns A new node with bindings resolved to concrete values\n */\nexport async function resolveBindings(\n node: UISpecNode,\n context: DataContext,\n itemData?: DataItem | null\n // ...\n): Promise<UISpecNode> {\n if (node.id === \"task-detail\") {\n console.log(\n `[resolveBindings task-detail SPECIFIC CHECK] Context for task-detail:`,\n JSON.stringify(context)\n );\n console.log(\n `[resolveBindings task-detail SPECIFIC CHECK] context.isTaskDetailDialogVisible = ${context.isTaskDetailDialogVisible}`\n );\n console.log(\n `[resolveBindings task-detail SPECIFIC CHECK] context.selectedTask = ${JSON.stringify(\n context.selectedTask\n )}`\n );\n }\n\n // Existing log:\n console.log(\n `[resolveBindings ENTRY] Node ID: ${node.id}, Type: ${\n node.node_type\n }, Has itemData: ${!!itemData}, Context keys: ${Object.keys(\n context || {} // Ensure context is not null before Object.keys\n ).join(\", \")}`\n );\n\n const result: UISpecNode = {\n ...node,\n props: node.props ? JSON.parse(JSON.stringify(node.props)) : null,\n events: node.events ? JSON.parse(JSON.stringify(node.events)) : null,\n bindings: node.bindings ? JSON.parse(JSON.stringify(node.bindings)) : null,\n children: null, // Initialize children to null\n };\n\n let mergedProps: Record<string, unknown> | null = node.props\n ? { ...JSON.parse(JSON.stringify(node.props)) }\n : null;\n\n const PROP_KEYS_TO_RESOLVE = new Set([\n \"text\",\n \"label\",\n \"title\",\n \"placeholder\",\n \"value\",\n ]);\n\n if (node.props) {\n for (const [key, value] of Object.entries(node.props)) {\n if (!mergedProps) mergedProps = {}; // Ensure mergedProps is initialized here\n\n if (PROP_KEYS_TO_RESOLVE.has(key)) {\n const resolvedPropValue = processBinding(\n value,\n context,\n itemData ?? undefined\n );\n if (resolvedPropValue !== undefined) {\n mergedProps[key] = resolvedPropValue;\n } else {\n // If a prop in PROP_KEYS_TO_RESOLVE was a path/template that resolved to undefined,\n // set it to an empty string. Otherwise, preserve its original literal value.\n if (\n typeof value === \"string\" &&\n (value.includes(\"{{\") || value.includes(\".\"))\n ) {\n mergedProps[key] = \"\"; // It was a path/template, make it empty\n } else {\n mergedProps[key] = value; // It was a literal or something else, preserve original node.props value if binding failed/absent for this key\n }\n }\n } else if (value !== undefined) {\n // For props not in PROP_KEYS_TO_RESOLVE, carry them over if they are defined.\n mergedProps[key] = value;\n } else {\n // If original prop value was undefined, ensure it's not on mergedProps unless explicitly set later by bindings\n delete mergedProps[key];\n }\n }\n }\n\n result.props = mergedProps;\n\n if (node.bindings) {\n for (const [key, bindingValue] of Object.entries(node.bindings)) {\n const resolvedValue = processBinding(\n bindingValue,\n context,\n itemData ?? undefined\n );\n if (node.id === \"task-detail\") {\n // Log specifically for task-detail\n console.log(\n `[resolveBindings - ${node.id}] Binding for '${key}': '${String(\n bindingValue\n )}' -> Resolved:`,\n resolvedValue\n );\n }\n\n if (resolvedValue !== undefined) {\n if (!result.props) result.props = {};\n result.props[key] = resolvedValue;\n if (node.id === \"task-detail\") {\n // Log specifically for task-detail\n console.log(\n `[resolveBindings - ${node.id}] Set result.props.${key} =`,\n resolvedValue\n );\n }\n } else {\n if (node.id === \"task-detail\") {\n // Log specifically for task-detail\n console.log(\n `[resolveBindings - ${node.id}] Binding for '${key}' ('${String(\n bindingValue\n )}') resolved to undefined. Not setting prop.`\n );\n }\n }\n }\n }\n\n // Process event payloads if events exist\n if (node.events) {\n const processedEvents: UISpecNode[\"events\"] = {};\n for (const eventType in node.events) {\n const eventConfig = node.events[eventType];\n processedEvents[eventType] = {\n ...eventConfig,\n payload: eventConfig.payload\n ? (processBinding(\n eventConfig.payload,\n context,\n itemData ?? undefined\n ) as Record<string, unknown> | null)\n : null,\n };\n }\n result.events = processedEvents;\n } else {\n result.events = null;\n }\n\n const dataBindingValue = result.props?.data ?? result.props?.items;\n\n // // Add detailed logs before the ListView processing condition\n // if (node.id === \"task-list\") {\n // // Log only for the specific ListView we are interested in\n // console.log(\n // `[resolveBindings Debug] Checking node ${node.id} (${node.node_type}) for ListView processing eligibility:`\n // );\n // console.log(\n // `[resolveBindings Debug] Is ListView or Table type: ${\n // node.node_type === \"ListView\" || node.node_type === \"Table\"\n // }`\n // );\n // console.log(\n // `[resolveBindings Debug] Is dataBindingValue an array: ${Array.isArray(\n // dataBindingValue\n // )}`\n // );\n // if (Array.isArray(dataBindingValue)) {\n // console.log(\n // `[resolveBindings Debug] dataBindingValue length: ${dataBindingValue.length}`\n // );\n // }\n // console.log(\n // `[resolveBindings Debug] Original node.children (template) exists: ${!!node.children}`\n // );\n // if (node.children) {\n // console.log(\n // `[resolveBindings Debug] Original node.children.length (template count): ${node.children.length}`\n // );\n // }\n // }\n\n if (\n (node.node_type === \"ListView\" || node.node_type === \"Table\") &&\n Array.isArray(dataBindingValue) &&\n node.children &&\n node.children.length > 0\n ) {\n // if (node.id === \"task-list\") {\n // console.log(\n // `[resolveBindings Debug] ENTERED ListView processing for ${node.id}`\n // );\n // }\n\n // Check if the children are already instantiated items or a template\n // A template has exactly 1 child with template markers ({{index}}, {{item, etc.) in the ID\n // Expanded lists have multiple children with concrete IDs\n const templateChild = node.children[0];\n const looksLikeTemplate =\n node.children.length === 1 &&\n (templateChild.id.includes(\"{{\") || templateChild.id.includes(\"-template\"));\n const isAlreadyExpanded = !looksLikeTemplate && node.children.length > 1;\n\n if (isAlreadyExpanded) {\n // console.log(\n // `[resolveBindings Debug] ListView ${node.id} appears to be already expanded. Re-resolving its existing children.`\n // );\n // If already expanded, just re-resolve bindings on existing children\n // This might happen if the parent re-renders and passes the already processed ListView node.\n result.children = await Promise.all(\n node.children.map((existingChild) =>\n resolveBindings(existingChild, context, itemData)\n ) // itemData is tricky here, should it be from parent or is it irrelevant?\n // For now, assume itemData is not applicable for re-resolving top-level list items this way.\n );\n } else {\n // Standard expansion logic using templateChild\n // if (node.id === \"task-list\") {\n // console.log(\n // `[resolveBindings Debug] ListView ${node.id} is using template: ${templateChild.id}`\n // );\n // }\n const mappedChildren = await Promise.all(\n dataBindingValue.map(async (currentItemData, index) => {\n try {\n if (\n typeof currentItemData !== \"object\" ||\n currentItemData === null\n ) {\n console.warn(\n `List item at index ${index} for node ${node.id} is not an object:`,\n currentItemData\n );\n return null;\n }\n const currentItemAsRecord = currentItemData as Record<\n string,\n unknown\n >;\n const itemId = currentItemAsRecord.id as\n | string\n | number\n | undefined;\n const instanceId = `${templateChild.id}-${itemId || index}`;\n\n const childNodeInstance: UISpecNode = JSON.parse(\n JSON.stringify(templateChild)\n );\n childNodeInstance.id = instanceId;\n\n makeChildIdsUniqueInInstance(\n childNodeInstance,\n instanceId,\n templateChild.id\n );\n\n const resolvedChild = await resolveBindings(\n childNodeInstance,\n context,\n currentItemAsRecord\n );\n\n if (resolvedChild && !resolvedChild.props) resolvedChild.props = {};\n if (resolvedChild && resolvedChild.props) {\n resolvedChild.props.key = itemId || `${node.id}-item-${index}`;\n }\n return resolvedChild;\n } catch (error) {\n console.error(\n `[resolveBindings Error] Error processing item at index ${index} for node ${node.id}:`,\n error,\n \"Item Data:\",\n currentItemData\n );\n return null;\n }\n })\n );\n // console.log(\n // `[resolveBindings Debug] ListView ${node.id} - mappedChildren:`,\n // JSON.stringify(mappedChildren, null, 2)\n // );\n result.children = mappedChildren.filter(\n (child) => child !== null\n ) as UISpecNode[];\n }\n } else if (node.children && node.children.length > 0) {\n result.children = await Promise.all(\n node.children.map((child) => resolveBindings(child, context, itemData))\n );\n } else {\n result.children = [];\n }\n\n // // Add this for task-detail just before returning\n // if (node.id === \"task-detail\") {\n // console.log(\n // `[resolveBindings RETURN Debug] task-detail final result.props:`,\n // JSON.stringify(result.props)\n // );\n // console.log(\n // `[resolveBindings RETURN Debug] task-detail final result.bindings:`,\n // JSON.stringify(result.bindings)\n // );\n // }\n\n return result;\n}\n\n/**\n * Execute an action based on event configuration\n *\n * @param action - The action type (e.g., \"VIEW_DETAIL\", \"UPDATE_DATA\")\n * @param target - The target data path (e.g., \"tasks.data\", \"user.name\") or node ID (for specific actions)\n * @param payload - Optional payload for the action (e.g., { value: \"new\" }, { item: {...} }, { id: \"...\" })\n * @param context - The data context\n * @returns Updated data context\n */\nexport function executeAction(\n action: string,\n target?: string,\n payload?: Record<string, unknown>,\n context: DataContext = {}\n): DataContext {\n // console.log(\n // `[executeAction ENTRY] Received action string: \"${action}\" (type: ${typeof action}), Target: ${target}`\n // );\n // console.log(\n // `[executeAction ENTRY] Comparing with ActionType.SHOW_DETAIL (enum): \"${ActionType.SHOW_DETAIL}\"`\n // );\n // console.log(\n // `[executeAction ENTRY] Comparing with ActionType.HIDE_DIALOG (enum): \"${ActionType.HIDE_DIALOG}\"`\n // );\n\n let newContext = { ...context };\n\n switch (action as ActionType | string) {\n case ActionType.SHOW_DETAIL: {\n const taskId = payload?.taskId as string | undefined;\n const dialogNodeId = target;\n\n if (taskId && dialogNodeId) {\n const tasksData = getValueByPath(context, \"tasks.data\"); // Use original context for reading tasks\n if (Array.isArray(tasksData)) {\n const foundTask = (tasksData as DataItem[]).find(\n (t) => t.id === taskId\n );\n if (foundTask) {\n newContext = setValueByPath(newContext, \"selectedTask\", foundTask);\n // console.log(\n // `[executeAction] ${ActionType.SHOW_DETAIL}: Set selectedTask to:`,\n // foundTask\n // );\n } else {\n console.warn(\n `[executeAction] ${ActionType.SHOW_DETAIL}: Task with id \"${taskId}\" not found in tasks.data.`\n );\n newContext = setValueByPath(newContext, \"selectedTask\", null);\n }\n } else {\n console.warn(\n `[executeAction] ${ActionType.SHOW_DETAIL}: context.tasks.data is not an array or not found.`\n );\n newContext = setValueByPath(newContext, \"selectedTask\", null);\n }\n } else {\n console.warn(\n `[executeAction] ${ActionType.SHOW_DETAIL}: payload.taskId or target (dialogNodeId) was missing. Dialog will be shown without a selected task.`\n );\n newContext = setValueByPath(newContext, \"selectedTask\", null); // Ensure selectedTask is null if no taskId\n }\n\n // Always attempt to set the dialog visibility flag to true for SHOW_DETAIL action\n newContext = setValueByPath(\n newContext, // Use the potentially modified newContext (with selectedTask set or cleared)\n \"isTaskDetailDialogVisible\",\n true\n );\n // console.log(\n // `[executeAction] ${ActionType.SHOW_DETAIL}: set isTaskDetailDialogVisible to true. Dialog target: ${dialogNodeId}, Payload:`,\n // payload\n // );\n break;\n }\n\n case ActionType.HIDE_DIALOG: {\n newContext = setValueByPath(newContext, \"selectedTask\", null);\n newContext = setValueByPath(\n newContext,\n \"isTaskDetailDialogVisible\",\n false\n );\n // console.log(\n // `[executeAction] ${ActionType.HIDE_DIALOG}: set isTaskDetailDialogVisible to false.`\n // );\n break;\n }\n\n case ActionType.HIDE_DETAIL: {\n newContext = setValueByPath(newContext, \"selectedItemForDetail\", null); // Example general detail item\n newContext = setValueByPath(newContext, \"isDetailViewOpen\", false); // Example general detail flag\n // console.log(\n // `[executeAction] ${ActionType.HIDE_DETAIL}: Detail view hidden.`\n // );\n break;\n }\n\n case ActionType.OPEN_DIALOG: {\n const dialogId = target || (payload?.dialogId as string | undefined);\n // For now, assume it refers to the task detail dialog for simplicity, adjust if more dialogs exist\n if (dialogId === \"taskDetailDialogNodeId\" || !dialogId) {\n // Default to task detail if no specific id or it matches\n newContext = setValueByPath(\n newContext,\n \"isTaskDetailDialogVisible\",\n true\n );\n // If a specific item should be loaded, SHOW_DETAIL with taskId is more appropriate.\n // OPEN_DIALOG might just make a generic, perhaps empty, dialog visible.\n // console.log(\n // `[executeAction] ${ActionType.OPEN_DIALOG}: Dialog ${\n // dialogId || \"taskDetailDialogNodeId\"\n // } opened (isTaskDetailDialogVisible: true).`\n // );\n } else {\n // Logic for other dialogs if their visibility is controlled by different flags\n console.warn(\n `[executeAction] ${ActionType.OPEN_DIALOG}: Unhandled dialogId: ${dialogId}.`\n );\n }\n break;\n }\n\n case ActionType.CLOSE_DIALOG: {\n const dialogId = target || (payload?.dialogId as string | undefined);\n if (dialogId === \"taskDetailDialogNodeId\" || !dialogId) {\n newContext = setValueByPath(\n newContext,\n \"isTaskDetailDialogVisible\",\n false\n );\n newContext = setValueByPath(newContext, \"selectedTask\", null); // Clear task for this specific dialog\n // console.log(\n // `[executeAction] ${ActionType.CLOSE_DIALOG}: Dialog ${\n // dialogId || \"taskDetailDialogNodeId\"\n // } closed and selectedTask cleared.`\n // );\n } else {\n // Logic for other dialogs\n console.warn(\n `[executeAction] ${ActionType.CLOSE_DIALOG}: Unhandled dialogId: ${dialogId}.`\n );\n }\n break;\n }\n\n case ActionType.UPDATE_DATA: {\n // console.log(\n // \"[executeAction UPDATE_DATA] Context BEFORE setValueByPath:\",\n // JSON.stringify(context, null, 2)\n // );\n // console.log(\n // `[executeAction UPDATE_DATA] Target path: ${target}, Payload value: ${payload?.value}`\n // );\n let updatedContext = context; // Start with the passed context\n if (target && payload && \"value\" in payload) {\n updatedContext = setValueByPath(context, target, payload.value); // Use original context as base for setValueByPath\n } else {\n console.warn(\n `[executeAction] ${ActionType.UPDATE_DATA} requires targetPath (data path) and payload with 'value' property.`\n );\n // newContext will remain a clone of the original context if conditions aren't met\n }\n // console.log(\n // \"[executeAction UPDATE_DATA] Context AFTER setValueByPath (assigned to newContext):\",\n // JSON.stringify(updatedContext, null, 2)\n // );\n newContext = updatedContext; // Assign the result to newContext which is returned by the function\n break;\n }\n\n case ActionType.ADD_ITEM: {\n // Adds an item to an array specified by the target path\n if (!target) {\n console.warn(`[executeAction] ADD_ITEM requires target path.`);\n break;\n }\n if (!payload?.item) {\n console.warn(\n `[executeAction] ADD_ITEM requires payload with item property.`\n );\n break;\n }\n\n const list = getValueByPath(newContext, target);\n if (!Array.isArray(list)) {\n console.warn(\n `[executeAction] ADD_ITEM failed: target path \"${target}\" does not resolve to an array.`\n );\n break;\n }\n\n const newItem = payload.item;\n const position = payload.position as string | undefined;\n let newList;\n if (position === \"start\") {\n newList = [newItem, ...list];\n } else {\n newList = [...list, newItem];\n }\n\n newContext = setValueByPath(newContext, target, newList);\n break;\n }\n\n case ActionType.DELETE_ITEM: {\n // Deletes an item (identified by id) from an array specified by the target path\n if (!target) {\n console.warn(`[executeAction] DELETE_ITEM requires target path.`);\n break;\n }\n const itemId = payload?.id as string | number | undefined;\n if (itemId === undefined || itemId === null) {\n console.warn(\n `[executeAction] DELETE_ITEM requires payload with id property.`\n );\n break;\n }\n\n const list = getValueByPath(newContext, target);\n if (!Array.isArray(list)) {\n console.warn(\n `[executeAction] DELETE_ITEM failed: target path \"${target}\" does not resolve to an array.`\n );\n break;\n }\n\n // Filter out the item with the matching id\n const newList = list.filter(\n (item: { id?: string | number | undefined }) => item?.id !== itemId\n );\n\n // Only update if the list actually changed\n if (newList.length !== list.length) {\n newContext = setValueByPath(newContext, target, newList);\n } else {\n console.warn(\n `[executeAction] DELETE_ITEM: Item with id \"${itemId}\" not found in list at path \"${target}\".`\n );\n }\n break;\n }\n\n case ActionType.SAVE_TASK_CHANGES: {\n if (!target) {\n // target here would be the selectedTask.id passed from payload or event\n console.warn(\n \"[executeAction] SAVE_TASK_CHANGES requires target (task ID).\"\n );\n break;\n }\n const taskIdToSave = target;\n const currentTasks = getValueByPath(newContext, \"tasks.data\") as\n | DataItem[]\n | undefined;\n const selectedTaskData = getValueByPath(newContext, \"selectedTask\") as\n | DataItem\n | undefined;\n\n if (\n currentTasks &&\n selectedTaskData &&\n selectedTaskData.id === taskIdToSave\n ) {\n const updatedTasks = currentTasks.map(\n (task) =>\n task.id === taskIdToSave\n ? { ...task, ...selectedTaskData, ...payload }\n : task // Merge selectedTaskData and any direct payload changes\n );\n newContext = setValueByPath(newContext, \"tasks.data\", updatedTasks);\n newContext = setValueByPath(newContext, \"selectedTask\", null); // Clear selected task\n newContext = setValueByPath(\n newContext,\n \"isTaskDetailDialogVisible\",\n false\n ); // Hide dialog\n // console.log(\n // `[executeAction] SAVE_TASK_CHANGES: Updated task ${taskIdToSave} and hid dialog.`\n // );\n } else {\n console.warn(\n \"[executeAction] SAVE_TASK_CHANGES: Could not save. Task list, selected task, or ID mismatch.\",\n {\n taskIdToSave,\n selectedTaskDataId: selectedTaskData?.id,\n currentTasksExists: !!currentTasks,\n }\n );\n }\n break;\n }\n\n default:\n console.warn(`[executeAction] Unhandled action type: ${action}`);\n }\n\n return newContext;\n}\n\n// Helper function to recursively make all child IDs within an instance unique\n// Moved here to satisfy linter and define it once per resolveBindings call for a list parent\nfunction makeChildIdsUniqueInInstance(\n parentNode: UISpecNode,\n baseInstanceId: string,\n originalTemplateRootId: string\n) {\n if (parentNode.children) {\n parentNode.children = parentNode.children.map((child) => {\n // Attempt to get the original ID part, removing any previously prefixed instance ID\n let originalChildId = child.id;\n // This check is a bit heuristic; assumes original IDs don't naturally contain the template root ID with a dash.\n // A more robust way might involve storing original IDs separately if this becomes problematic.\n if (child.id.startsWith(originalTemplateRootId + \"-\")) {\n const parts = child.id.split(\"-\");\n if (parts.length > 1) {\n // Takes the last part assuming it's the original specific ID part if multiple hyphens exist from prior processing\n originalChildId = parts[parts.length - 1];\n }\n }\n\n const newChildId = `${baseInstanceId}-${originalChildId}`;\n const newChild = {\n ...JSON.parse(JSON.stringify(child)), // Deep clone child\n id: newChildId,\n };\n makeChildIdsUniqueInInstance(\n newChild,\n baseInstanceId,\n originalTemplateRootId\n ); // Recurse with the same baseInstanceId\n return newChild;\n });\n }\n}\n","import { UIEvent, UISpecNode, PlannerInput } from \"../schema/ui\";\nimport { DataContext } from \"./bindings\";\nimport { findNodeById } from \"./reducer\";\nimport { ActionType } from \"../schema/action-types\";\nimport { callPlannerLLM } from \"./planner\";\nimport { executeAction } from \"./bindings\";\n\n\nexport interface PlanningConfig {\n prefetchDepth: number;\n temperature: number;\n streaming: boolean;\n}\n\n// --- Constants for Prompt Generation ---\n\n// Base UI Guidance\nconst UI_GUIDANCE_BASE = `\nUI Guidance:\n1. Create a focused interface that directly addresses the goal\n2. Use appropriate UI patterns (lists, forms, details, etc.)\n3. Include navigation between related views when needed\n4. Keep the interface simple and intuitive\n5. Bind to schema data where appropriate\n6. **CRITICAL for Buttons:** All \\`Button\\` nodes **MUST** include a \\`label\\` property in their \\`props\\` (e.g., \\`{ \"props\": { \"label\": \"Click Me\" } }\\`).\n7. Provide event handlers for user interactions - make sure to always include both action and target properties`;\n\n// Specific guidance for list bindings\nconst LIST_BINDING_GUIDANCE = `8. **CRITICAL:** For \\`ListView\\` or \\`Table\\` nodes, the \\`data\\` binding key **MUST** point to the *exact path* of the data *array* within the context.`;\n\n// Example for list binding\nconst LIST_BINDING_EXAMPLE = `Example: If the context has \\`{ tasks: { data: [...] } }\\`, the binding **MUST** be \\`{ \"bindings\": { \"data\": \"tasks.data\" } }\\`. If the context has \\`{ userList: [...] }\\`, the binding **MUST** be \\`{ \"bindings\": { \"data\": \"userList\" } }\\`. **NEVER** bind to the parent object containing the array (e.g., DO NOT USE \\`{ \"bindings\": { \"data\": \"tasks\" } }\\`).`;\n\n// Combined common UI guidance - THIS SHOULD BE EXPORTED\nexport const COMMON_UI_GUIDANCE =\n UI_GUIDANCE_BASE +\n \"\\n\" + // Add a newline separator\n LIST_BINDING_GUIDANCE + // Add the specific list binding rule\n \"\\n\" + // Add a newline separator\n LIST_BINDING_EXAMPLE; // Add the example\n\n// Function to process template strings (simple substitution)\nfunction processTemplate(\n template: string,\n values: Record<string, unknown>\n): string {\n return template.replace(/\\${(.*?)}/g, (match, key) => {\n const trimmedKey = key.trim();\n // Basic handling for simple keys; does not handle nested paths like eventPayload.detail\n return trimmedKey in values ? String(values[trimmedKey]) : match;\n });\n}\n\n// Moved from planner.ts\n/**\n * Builds the prompt for the LLM planner\n * @param input - Planner input including schema, goal, history, and userContext\n * @param promptTemplate - Optional prompt template string\n * @param templateValues - Optional values for the template string, used if promptTemplate is provided\n * @returns Formatted prompt string\n */\nexport function buildPrompt(\n input: PlannerInput,\n promptTemplate?: string,\n templateValues?: Record<string, unknown>\n): string {\n const { schema, goal, history, userContext } = input;\n\n // Extract schema information without actual data rows\n const schemaInfo = Object.entries(schema)\n .map(([tableName, tableSchema]) => {\n // Simple check if it looks like a structured schema object vs a simple type\n const schemaString =\n typeof tableSchema === \"object\" && tableSchema !== null\n ? JSON.stringify(tableSchema)\n : String(tableSchema);\n return `Table: ${tableName}\\nSchema: ${schemaString}`;\n })\n .join(\"\\n\\n\");\n\n // Format recent events for context\n const recentEvents =\n history && history.length > 0\n ? history\n .slice(-5) // Limit history length\n .map(\n (event) =>\n `Event: ${event.type} on node ${event.nodeId}${\n event.payload\n ? ` with payload ${JSON.stringify(event.payload)}`\n : \"\"\n }`\n )\n .join(\"\\n\")\n : \"No recent events\";\n\n // Build user context section if provided\n const userContextSection = userContext\n ? `\\n\\nUser Context:\\n${JSON.stringify(userContext)}`\n : \"\";\n\n // If a specific prompt template is provided, process it\n // This now becomes the primary way to use custom prompts via ActionRouteConfig\n if (promptTemplate && templateValues) {\n // Inject schema, history, userContext, and common guidance into values for template processing\n const fullTemplateValues = {\n ...templateValues,\n schemaInfo,\n recentEvents,\n userContextString: userContextSection.trim(), // Use trimmed version\n commonUIGuidance: COMMON_UI_GUIDANCE,\n goal, // Ensure goal is always available to templates\n };\n return processTemplate(promptTemplate, fullTemplateValues);\n }\n\n // --- Default Prompt Construction (used when no template is provided by a route, e.g. initial FULL_REFRESH) ---\n\n // Default interaction description: Check if history is empty\n const interactionDescription =\n history && history.length > 0\n ? `The user's last action was: ${\n history[history.length - 1].type\n } on node ${history[history.length - 1].nodeId}`\n : \"The user initiated the session for the goal\";\n\n // Assemble the full default prompt\n return `\nYou are an expert UI generator.\nCreate a user interface that achieves the following goal: \"${goal}\".\n${interactionDescription}.\n\nAvailable data schema:\n${schemaInfo}\n\nRecent user interactions:\n${recentEvents}${userContextSection}\n\nGenerate a complete UI specification in JSON format that matches the following TypeScript type:\ntype UISpecNode = { id: string; node_type: string; props?: Record<string, unknown>; bindings?: Record<string, unknown>; events?: Record<string, { action: string; target: string; payload?: Record<string, unknown>; }>; children?: UISpecNode[]; };\n${COMMON_UI_GUIDANCE}\n\nRespond ONLY with the JSON UI specification and no other text.\n `;\n}\n\n/**\n * Routing configuration for an action\n */\nexport interface ActionRouteConfig {\n actionType: ActionType;\n targetNodeId?: string; // Optional: target node for the action (e.g., where to place a new detail view)\n contextKeys?: string[]; // Optional: keys to extract from DataContext and include in planner input\n}\n\n/**\n * Interface for route resolution\n */\nexport interface RouteResolution {\n actionType: ActionType;\n targetNodeId: string;\n updatedNode: UISpecNode;\n updatedDataContext?: DataContext;\n}\n\n/**\n * Action router class - handles determining what part of the UI to update\n */\nexport class ActionRouter {\n private apiKey: string;\n private planningConfig: PlanningConfig;\n\n constructor(apiKey: string, planningConfig?: PlanningConfig) {\n this.apiKey = apiKey;\n this.planningConfig = planningConfig || {\n prefetchDepth: 1,\n temperature: 0.5,\n streaming: false,\n };\n }\n\n /**\n * Find the appropriate route for an event\n * @param event - UI event\n * @param layout - Current UI layout\n * @param dataContext - Current data context\n * @returns Route resolution or null if no match\n */\n public async resolveRoute(\n event: UIEvent,\n schema: Record<string, unknown>,\n layout: UISpecNode | null,\n dataContext: DataContext,\n goal: string,\n apiKey: string,\n userContext?: Record<string, unknown>,\n ): Promise<RouteResolution> {\n console.log(\n `[ActionRouter Debug] resolveRoute called for event type: ${event.type}, nodeId: ${event.nodeId}`\n );\n\n const sourceNode = layout ? findNodeById(layout, event.nodeId) : undefined;\n const nodeConfig = sourceNode?.events?.[event.type];\n\n let actionType: ActionType;\n let determinedTargetNodeId: string;\n let determinedNodeConfigPayload: Record<string, unknown> | null = null;\n\n // Determine initial action type and target\n if (nodeConfig?.action) {\n actionType = nodeConfig.action as ActionType;\n determinedTargetNodeId = nodeConfig.target || sourceNode?.id || \"root\";\n determinedNodeConfigPayload = nodeConfig.payload ? { ...nodeConfig.payload } : null;\n } else {\n switch (event.type) {\n case \"INIT\":\n actionType = ActionType.FULL_REFRESH;\n determinedTargetNodeId = \"root\";\n break;\n case \"CLICK\":\n actionType = ActionType.FULL_REFRESH;\n determinedTargetNodeId = \"root\";\n break;\n case \"CHANGE\":\n if (sourceNode && [\"Input\", \"Select\", \"Textarea\", \"Checkbox\", \"RadioGroup\"].includes(sourceNode.node_type)) {\n actionType = ActionType.UPDATE_DATA;\n determinedTargetNodeId = sourceNode.id;\n } else {\n actionType = ActionType.FULL_REFRESH;\n determinedTargetNodeId = \"root\";\n }\n break;\n default:\n actionType = ActionType.FULL_REFRESH;\n determinedTargetNodeId = \"root\";\n break;\n }\n }\n\n // Validate action type early\n if (!Object.values(ActionType).includes(actionType)) {\n throw new Error(`Invalid action type: ${actionType}`);\n }\n\n // Build additional context\n const additionalContext: Record<string, unknown> = {};\n if (sourceNode) {\n additionalContext.sourceNode = sourceNode;\n }\n const targetNode = layout ? findNodeById(layout, determinedTargetNodeId) : undefined;\n if (targetNode) {\n additionalContext.targetNode = targetNode;\n }\n\n // Handle event payload\n let finalEventPayload = event.payload && Object.keys(event.payload).length > 0 ? { ...event.payload } : null;\n if (determinedNodeConfigPayload) {\n finalEventPayload = { ...(finalEventPayload || {}), ...determinedNodeConfigPayload };\n }\n if (finalEventPayload) {\n additionalContext.eventPayload = finalEventPayload;\n }\n\n const plannerInput: PlannerInput = {\n schema,\n goal,\n history: [event],\n userContext: { ...(userContext || {}), ...additionalContext },\n };\n\n // Handle SHOW_DETAIL action\n if (actionType === ActionType.SHOW_DETAIL) {\n const itemData = (dataContext.tasks as { data?: Array<Record<string, unknown>> })?.data?.find(\n task => task.id === (event.payload?.itemId || event.payload?.taskId)\n );\n\n const updatedDataContext = {\n ...dataContext,\n selectedTask: itemData,\n isTaskDetailDialogVisible: true,\n };\n\n const layoutFromLLM = await callPlannerLLM(plannerInput, apiKey);\n\n return {\n actionType: ActionType.UPDATE_CONTEXT,\n targetNodeId: determinedTargetNodeId,\n updatedDataContext,\n updatedNode: layoutFromLLM,\n };\n }\n\n // Handle HIDE_DIALOG action\n if (actionType === ActionType.HIDE_DIALOG) {\n if (!layout) {\n // This case should ideally not happen for HIDE_DIALOG if a UI is already rendered.\n // If it can, a default placeholder node might be needed or an error thrown.\n // For now, throwing an error if layout is null, as HIDE_DIALOG implies existing UI.\n throw new Error(\"Layout cannot be null when handling HIDE_DIALOG\");\n }\n return {\n actionType: ActionType.UPDATE_CONTEXT,\n targetNodeId: determinedTargetNodeId,\n updatedDataContext: {\n ...dataContext,\n selectedTask: null,\n isTaskDetailDialogVisible: false,\n },\n updatedNode: layout,\n };\n }\n\n // Handle data update actions\n if ([ActionType.UPDATE_DATA, ActionType.ADD_ITEM, ActionType.DELETE_ITEM, ActionType.SAVE_TASK_CHANGES].includes(actionType)) {\n if (!layout) {\n // Similar to HIDE_DIALOG, data updates imply existing UI.\n throw new Error(\"Layout cannot be null when handling data update actions\");\n }\n const targetPathOrId = actionType === ActionType.UPDATE_DATA\n ? (sourceNode?.bindings?.value as string) || determinedTargetNodeId\n : determinedTargetNodeId;\n\n return {\n actionType,\n targetNodeId: determinedTargetNodeId,\n updatedNode: layout,\n updatedDataContext: executeAction(actionType, targetPathOrId, finalEventPayload || {}, dataContext),\n };\n }\n\n // Handle LLM-based actions\n if ([\n ActionType.FULL_REFRESH,\n ActionType.UPDATE_NODE,\n ActionType.ADD_DROPDOWN,\n ActionType.TOGGLE_STATE,\n ActionType.UPDATE_FORM,\n ActionType.NAVIGATE,\n ActionType.UPDATE_CONTEXT\n ].includes(actionType)) {\n const layoutFromLLM = await callPlannerLLM(plannerInput, apiKey);\n\n return {\n actionType,\n targetNodeId: determinedTargetNodeId,\n updatedNode: layoutFromLLM,\n updatedDataContext: dataContext,\n };\n }\n\n throw new Error(`Unhandled action type: ${actionType}`);\n }\n}\n","import React, { useState, useCallback, useRef, useEffect, useMemo } from \"react\";\nimport { UIEvent, UISpecNode, UIEventType, DataItem } from \"./schema/ui\";\nimport { ActionType } from \"./schema/action-types\";\nimport { useUIStateEngine, UseUIStateEngineOptions } from \"./core/state\";\nimport {\n renderNode,\n renderShimmer,\n clearRenderedNodeCacheEntry,\n} from \"./core/renderer\";\nimport { resolveBindings, DataContext } from \"./core/bindings\";\nimport { EventManager, EventHook } from \"./core/events\";\nimport {\n SystemEventType,\n SystemEventHook,\n systemEvents,\n createSystemEvent,\n} from \"./core/system-events\";\nimport { SchemaAdapter } from \"./adapters/schema\";\nimport {\n areShadcnComponentsAvailable,\n getMissingComponentsMessage,\n} from \"./core/component-detection\";\nimport \"./styles/autoui.css\";\nimport { PlanningConfig } from \"./core/action-router\";\n\n// Helper function to correct list bindings\nfunction correctListBindingsRecursive(\n node: UISpecNode,\n dataContext: DataContext\n): UISpecNode {\n // Deep clone to avoid mutating the original state.layout directly during correction\n // This is important because state.layout might be used elsewhere or in dependencies.\n const correctedNode = JSON.parse(JSON.stringify(node)) as UISpecNode;\n\n if (\n (correctedNode.node_type === \"ListView\" ||\n correctedNode.node_type === \"Table\") &&\n correctedNode.bindings?.data\n ) {\n const bindingPath = correctedNode.bindings.data;\n if (typeof bindingPath === \"string\") {\n const pathSegments = bindingPath.split(\".\");\n const mainKey = pathSegments[0]; // e.g., 'tasks'\n\n // Check if the binding path is just the main key (e.g., \"tasks\")\n // and if a .data sub-property exists and is an array in the context.\n if (pathSegments.length === 1) {\n const potentialDataContextEntry = dataContext[mainKey];\n if (\n potentialDataContextEntry &&\n typeof potentialDataContextEntry === \"object\" &&\n potentialDataContextEntry !== null &&\n \"data\" in potentialDataContextEntry &&\n Array.isArray((potentialDataContextEntry as { data: unknown }).data)\n ) {\n correctedNode.bindings.data = `${mainKey}.data`;\n console.log(\n `[AutoUI Debug] Corrected list binding for node '${correctedNode.id}': from '${mainKey}' to '${mainKey}.data'`\n );\n }\n }\n }\n }\n\n if (correctedNode.children) {\n correctedNode.children = correctedNode.children.map((child) =>\n correctListBindingsRecursive(child, dataContext)\n );\n }\n\n return correctedNode;\n}\n\n// Interface for DrizzleAdapterOptions\ninterface DrizzleAdapterOptions {\n schema: Record<string, unknown>;\n // Add other options as needed\n}\n\nexport interface AutoUIProps\n extends Omit<UseUIStateEngineOptions, \"router\" | \"dataContext\"> {\n // Extend options from the state engine, excluding ones managed internally\n // Schema definition (one of these is required)\n schema:\n | Record<string, unknown> // Direct schema object\n | { type: \"drizzle\"; options: DrizzleAdapterOptions } // Drizzle adapter\n | { type: \"custom\"; adapter: SchemaAdapter }; // Custom adapter\n\n // Required\n goal: string;\n\n // Optional configurations\n componentAdapter?: \"shadcn\";\n userContext?: Record<string, unknown>;\n onEvent?: (evt: UIEvent) => void;\n\n // UI Event hooks\n eventHooks?: {\n all?: EventHook[];\n [key: string]: EventHook[] | undefined;\n };\n\n // System Event hooks\n systemEventHooks?: {\n [key: string]: SystemEventHook[] | undefined;\n };\n\n // Enable partial UI updates (instead of regenerating entire UI on each interaction)\n enablePartialUpdates?: boolean;\n\n // Define custom UI update patterns\n updatePatterns?: {\n // Allow target components to show dropdowns\n enableDropdowns?: boolean;\n // Allow for showing/hiding detail views\n enableDetailViews?: boolean;\n // Allow for expanding/collapsing sections\n enableExpandCollapse?: boolean;\n // Allow for multi-step form navigation\n enableFormNavigation?: boolean;\n };\n\n // Integration configuration\n integration?: {\n // Whether to generate a standalone UI or a component for integration\n mode?: \"standalone\" | \"component\";\n // CSS class names to apply to the root element\n className?: string;\n // Inline styles to apply to the root element\n style?: React.CSSProperties;\n // ID of the root element\n id?: string;\n };\n\n // Scope of the generation - what kind of UI element to generate\n scope?: {\n // Type of component to generate\n type?: \"form\" | \"list\" | \"detail\" | \"dashboard\" | \"full-page\" | \"card\";\n // Specific focus for the generation\n focus?: string;\n };\n\n // Debug mode - shows system events in console\n debugMode?: boolean;\n\n mockMode?: boolean;\n\n // Database configuration\n databaseConfig?: Record<string, unknown>;\n\n // Planning configuration\n planningConfig?: PlanningConfig;\n\n // API key for the LLM (Anthropic)\n apiKey: string;\n}\n\n/**\n * AutoUI - Main component for generating goal-oriented UIs\n *\n * @example\n * ```tsx\n * import { AutoUI } from 'autoui-react';\n * import { emailsTable, usersTable } from './schema';\n *\n * function MyApp() {\n * return (\n * <AutoUI\n * schema={{ emails: emailsTable, users: usersTable }}\n * goal=\"Create an inbox view with email list and detail view\"\n * />\n * );\n * }\n * ```\n */\nexport const AutoUI: React.FC<AutoUIProps> = ({\n schema,\n goal,\n componentAdapter = \"shadcn\",\n userContext,\n onEvent,\n eventHooks,\n systemEventHooks,\n debugMode = false,\n planningConfig,\n integration = {},\n enablePartialUpdates = true,\n apiKey,\n}) => {\n const stableGoal = React.useMemo(() => goal, [goal]);\n\n // Memoize the schema prop to stabilize its reference if its content doesn't change.\n // First, memoize the stringified version of the schema.\n const schemaStringified = React.useMemo(() => JSON.stringify(schema), [schema]);\n // Then, memoize the schema object itself, depending on the stringified version.\n // stableSchemaProp will only get a new reference if the content of the schema prop changes.\n const stableSchemaProp = React.useMemo(() => schema, [schemaStringified]);\n\n const [schemaAdapterInstance] = useState<SchemaAdapter | null>(null);\n const [dataContext, setDataContext] = useState<DataContext>({});\n const [componentsAvailable, setComponentsAvailable] = useState(true);\n\n const [uiStatus, setUiStatus] = useState<\n | \"idle\"\n | \"initializing\"\n | \"resolving_bindings\"\n | \"rendering\"\n | \"event_processing\"\n | \"error\"\n >(\"initializing\");\n\n const [currentResolvedLayoutForRender, setCurrentResolvedLayoutForRender] =\n useState<UISpecNode | null>(null);\n const [isResolvingBindings, setIsResolvingBindings] =\n useState<boolean>(false);\n\n const [renderedNode, setRenderedNode] = useState<React.ReactElement | null>(\n null\n );\n\n // Use a ref to track the current resolved layout for event processing\n // This prevents processEvent from being recreated when layout changes\n const currentResolvedLayoutRef = useRef<UISpecNode | null>(null);\n\n // Restore effectiveSchema and scopedGoal definitions using stable versions\n const effectiveSchema = stableSchemaProp as Record<string, unknown>;\n const scopedGoal = stableGoal;\n\n useEffect(() => {\n if (componentAdapter === \"shadcn\") {\n setComponentsAvailable(areShadcnComponentsAvailable());\n }\n }, [componentAdapter]);\n\n useEffect(() => {\n const unregisters: Array<() => void> = [];\n if (systemEventHooks) {\n Object.entries(systemEventHooks).forEach(([eventType, hooks]) => {\n if (!hooks) return;\n (hooks as SystemEventHook[]).forEach((hook) => {\n const unregister = systemEvents.on(\n eventType as SystemEventType,\n hook\n );\n unregisters.push(unregister);\n });\n });\n }\n if (debugMode) {\n const debugHook: SystemEventHook = (event) => {\n console.debug(`[AutoUI Debug] System Event:`, event);\n };\n Object.values(SystemEventType)\n .filter(\n (eventType) =>\n eventType !== SystemEventType.RENDER_START &&\n eventType !== SystemEventType.BINDING_RESOLUTION_START\n )\n .forEach((eventType) => {\n const unregister = systemEvents.on(eventType, debugHook);\n unregisters.push(unregister);\n });\n }\n return () => {\n unregisters.forEach((unregister) => unregister());\n };\n }, [systemEventHooks, debugMode]);\n\n useEffect(() => {\n const initializeDataContext = async () => {\n let initialData: DataContext = {};\n if (schemaAdapterInstance) {\n initialData = await schemaAdapterInstance.initializeDataContext();\n } else if (effectiveSchema) {\n Object.entries(effectiveSchema).forEach(([key, tableSchema]) => {\n initialData[key] = {\n schema: tableSchema,\n data:\n (tableSchema as { sampleData?: DataItem[] })?.sampleData || [],\n selected: null,\n };\n });\n }\n if (userContext) {\n initialData.user = userContext;\n }\n setDataContext(initialData);\n };\n initializeDataContext();\n }, [effectiveSchema, schemaAdapterInstance, userContext]);\n\n const { state, handleEvent } = useUIStateEngine({\n schema: effectiveSchema,\n goal: scopedGoal,\n userContext,\n planningConfig,\n dataContext, // Pass the local dataContext here, engine will use it if its own is empty initially\n enablePartialUpdates,\n apiKey,\n });\n\n const eventManagerRef = useRef(new EventManager());\n\n useEffect(() => {\n if (!eventHooks) return;\n const unregisters: Array<() => void> = [];\n if (eventHooks.all) {\n const unregister = eventManagerRef.current.register(\n \"all\",\n async (ctx) => {\n for (const hook of eventHooks.all || []) {\n await hook(ctx);\n if (ctx.isPropagationStopped()) break;\n }\n }\n );\n unregisters.push(unregister);\n }\n Object.entries(eventHooks).forEach(([type, hooks]) => {\n if (type === \"all\" || !hooks) return;\n const unregister = eventManagerRef.current.register(\n [type as UIEventType],\n async (ctx) => {\n for (const hook of hooks as EventHook[]) {\n await hook(ctx);\n if (ctx.isPropagationStopped()) break;\n }\n }\n );\n unregisters.push(unregister);\n });\n return () => {\n unregisters.forEach((unregister) => unregister());\n };\n }, [eventHooks]);\n\n // Keep ref in sync with state\n useEffect(() => {\n currentResolvedLayoutRef.current = currentResolvedLayoutForRender;\n }, [currentResolvedLayoutForRender]);\n\n const processEvent = useCallback(\n async (event: UIEvent) => {\n setUiStatus(\"event_processing\");\n // Use ref to get layout without causing callback to be recreated when layout changes\n const layoutAtEventTime = currentResolvedLayoutRef.current;\n\n const shouldProceed = await eventManagerRef.current.processEvent(event);\n if (onEvent) onEvent(event);\n\n if (!shouldProceed) {\n console.info(\n \"[AutoUI.processEvent] Event processing stopped by local hooks\",\n event\n );\n setUiStatus(\"idle\");\n return;\n }\n\n if (\n event.type === \"CLICK\" &&\n layoutAtEventTime &&\n event.nodeId.includes(\"view-details-button\")\n ) {\n const mainContent = layoutAtEventTime.children?.find(\n (c) => c.id === \"main-content\"\n );\n const taskList = mainContent?.children\n ?.find((c) => c.id === \"tasks-container\")\n ?.children?.find((c) => c.id === \"task-list\");\n const eventSourceListItemCard = taskList?.children?.find((item) =>\n item.children?.some((btn) => btn.id === event.nodeId)\n );\n const buttonNode = eventSourceListItemCard?.children?.find(\n (btn) => btn.id === event.nodeId\n );\n\n if (\n buttonNode?.events?.CLICK?.action === ActionType.SHOW_DETAIL &&\n buttonNode?.events?.CLICK?.target === \"task-detail\"\n ) {\n const cacheKeyToClear = `task-detail:false:no-data-selected`;\n clearRenderedNodeCacheEntry(cacheKeyToClear);\n console.log(\n `[AutoUI.processEvent] Attempted to clear cache for task-detail using simplified key: ${cacheKeyToClear}`\n );\n }\n }\n\n console.log(\n \"[AutoUI.processEvent] Forwarding event to engine:\",\n JSON.stringify(event, null, 2)\n );\n console.log(\n \"[AutoUI.processEvent] Passing currentLayout ID (at event time):\",\n layoutAtEventTime?.id\n );\n console.log(\n \"[AutoUI.processEvent] Passing dataContext keys to engine:\",\n Object.keys(dataContext)\n );\n\n // Pass layoutAtEventTime and the current dataContext to the engine.\n // The engine will use layoutAtEventTime to find the event source node.\n handleEvent(event, layoutAtEventTime, dataContext);\n\n // uiStatus will be managed by other effects based on state changes from the engine\n // No longer setting uiStatus to 'idle' here directly.\n },\n [\n dataContext,\n handleEvent,\n onEvent,\n eventManagerRef,\n // currentResolvedLayoutForRender removed - using ref instead to prevent infinite loops\n // setUiStatus is implicitly available\n ]\n );\n\n // Effect to update AutoUI's local dataContext when the engine's dataContext changes\n useEffect(() => {\n if (state.dataContext && Object.keys(state.dataContext).length > 0) {\n if (JSON.stringify(dataContext) !== JSON.stringify(state.dataContext)) {\n console.log(\n \"[AutoUI] Syncing local dataContext from engine state. New keys:\",\n Object.keys(state.dataContext),\n \"Old keys:\",\n Object.keys(dataContext)\n );\n setDataContext(state.dataContext);\n }\n }\n }, [state.dataContext, dataContext]);\n\n // Effect to resolve bindings when state.layout or local dataContext changes\n useEffect(() => {\n const resolveAndSetLayout = async () => {\n const hasMeaningfulDataContext =\n dataContext &&\n Object.keys(dataContext).some(\n (key) =>\n key !== \"user\" ||\n Object.keys(dataContext[\"user\"] as object).length > 0\n );\n\n if (state.layout && hasMeaningfulDataContext) {\n console.log(\n `[AutoUI resolveAndSetLayout] Calling core resolveBindings for layout ID: ${\n state.layout.id\n }. DataContext keys: ${Object.keys(dataContext).join(\", \")}`\n );\n setIsResolvingBindings(true);\n setUiStatus(\"resolving_bindings\");\n try {\n const correctedLayout = correctListBindingsRecursive(\n state.layout,\n dataContext\n );\n\n systemEvents.emit(\n createSystemEvent(SystemEventType.BINDING_RESOLUTION_START, {\n layout: correctedLayout, // Log corrected layout before resolving\n })\n );\n\n const resolved = await resolveBindings(correctedLayout, dataContext);\n setCurrentResolvedLayoutForRender(resolved);\n\n systemEvents.emit(\n createSystemEvent(SystemEventType.BINDING_RESOLUTION_COMPLETE, {\n originalLayout: correctedLayout, // Log corrected layout\n resolvedLayout: resolved,\n })\n );\n } catch (err) {\n console.error(\"Error resolving bindings:\", err);\n setUiStatus(\"error\");\n setCurrentResolvedLayoutForRender(null);\n } finally {\n setIsResolvingBindings(false);\n // setUiStatus(\"idle\"); // Will be set by render effect or if no layout\n }\n } else {\n if (!state.layout)\n console.log(\n \"[AutoUI] Skipping resolveBindings: state.layout is null/undefined\"\n );\n if (!hasMeaningfulDataContext)\n console.log(\n \"[AutoUI] Skipping resolveBindings: dataContext is not meaningfully populated yet\"\n );\n setCurrentResolvedLayoutForRender(null);\n if (\n !state.loading &&\n uiStatus !== \"initializing\" &&\n !isResolvingBindings\n )\n setUiStatus(\"idle\");\n }\n };\n\n resolveAndSetLayout();\n }, [state.layout, dataContext]); // Removed resolveLayoutBindings from deps, uiStatus\n\n // Effect to render the resolved layout\n useEffect(() => {\n const renderLayout = async () => {\n if (currentResolvedLayoutForRender && !isResolvingBindings) {\n setUiStatus(\"rendering\");\n console.log(\n \"[AutoUI Debug] Rendering with currentResolvedLayoutForRender:\",\n JSON.stringify(currentResolvedLayoutForRender, null, 2)\n );\n try {\n systemEvents.emit(\n createSystemEvent(SystemEventType.RENDER_START, {\n layout: currentResolvedLayoutForRender,\n })\n );\n const rendered = await renderNode(\n currentResolvedLayoutForRender,\n componentAdapter as \"shadcn\",\n processEvent\n );\n setRenderedNode(rendered);\n systemEvents.emit(\n createSystemEvent(SystemEventType.RENDER_COMPLETE, {\n layout: currentResolvedLayoutForRender,\n renderTimeMs: 0, // Placeholder, actual timing would be more complex\n })\n );\n setUiStatus(\"idle\");\n } catch (err) {\n console.error(\"Error rendering node:\", err);\n setUiStatus(\"error\");\n }\n } else if (\n !currentResolvedLayoutForRender &&\n !state.loading &&\n !isResolvingBindings &&\n uiStatus !== \"initializing\"\n ) {\n setRenderedNode(null);\n setUiStatus(\"idle\");\n }\n };\n renderLayout();\n // Note: uiStatus intentionally removed from deps to prevent infinite loop\n // (this effect sets uiStatus, so having it as dep causes re-run)\n }, [\n currentResolvedLayoutForRender,\n componentAdapter,\n processEvent,\n isResolvingBindings,\n state.loading,\n ]);\n\n // Initial status setting\n useEffect(() => {\n // Set to initializing only once on mount if not already an error\n if (uiStatus !== \"error\") {\n setUiStatus(\"initializing\");\n }\n }, []); // Empty dependency array means this runs once on mount\n\n // Handle transitions from initializing based on engine state\n useEffect(() => {\n if (uiStatus === \"initializing\") {\n if (state.loading) {\n // Still initializing or engine is fetching initial layout\n } else if (state.layout && !isResolvingBindings) {\n // Layout received, bindings might be resolving or done, defer to other effects\n } else if (!state.layout && !state.loading && !isResolvingBindings) {\n // No layout, not loading, not resolving -> idle (or error if state.error)\n if (state.error) {\n setUiStatus(\"error\");\n } else {\n setUiStatus(\"idle\");\n }\n }\n }\n }, [state.loading, state.layout, state.error, uiStatus, isResolvingBindings]);\n\n // Debug instrumentation: Expose pipeline state to browser for Playwright debugging\n useEffect(() => {\n if (!debugMode) return;\n\n const pipelineState = {\n uiStatus,\n hasLayout: !!state.layout,\n layoutId: state.layout?.id || null,\n hasResolvedLayout: !!currentResolvedLayoutForRender,\n resolvedLayoutId: currentResolvedLayoutForRender?.id || null,\n hasRenderedNode: !!renderedNode,\n isResolvingBindings,\n isLoading: state.loading,\n hasError: !!state.error,\n error: state.error || null,\n dataContextKeys: Object.keys(dataContext),\n timestamp: Date.now(),\n };\n\n // Expose to window for Playwright\n if (typeof window !== 'undefined') {\n (window as any).__autoui_pipeline_state = pipelineState;\n (window as any).__autoui_pipeline_history = (window as any).__autoui_pipeline_history || [];\n (window as any).__autoui_pipeline_history.push(pipelineState);\n\n // Log state changes for debugging\n console.log('[PIPELINE_STATE]', JSON.stringify(pipelineState));\n }\n }, [\n debugMode,\n uiStatus,\n state.layout,\n state.loading,\n state.error,\n currentResolvedLayoutForRender,\n renderedNode,\n isResolvingBindings,\n dataContext,\n ]);\n\n if (!componentsAvailable) {\n return (\n <div className=\"autoui-error p-4 border border-red-300 bg-red-50 text-red-700 rounded\">\n <p className=\"font-medium\">Component Library Not Found</p>\n <p className=\"text-sm whitespace-pre-line\">\n {getMissingComponentsMessage()}\n </p>\n </div>\n );\n }\n\n const showShimmer =\n (uiStatus === \"initializing\" || state.loading || isResolvingBindings) &&\n !state.error;\n\n return (\n <div\n className={`autoui-root ${integration.className || \"\"}`}\n id={integration.id}\n >\n <div>Current Status: {uiStatus}</div>\n {uiStatus === \"idle\" && !isResolvingBindings && renderedNode && (\n <div className=\"autoui-content\">{renderedNode}</div>\n )}\n {state.error && <div className=\"autoui-error\">Error: {state.error}</div>}\n\n {showShimmer &&\n state.layout && ( // Show shimmer if we have a layout to base it on\n <div className=\"autoui-loading\">\n {renderShimmer(state.layout, componentAdapter as \"shadcn\")}\n </div>\n )}\n {showShimmer &&\n !state.layout && ( // Fallback shimmer if no layout yet\n <div className=\"autoui-loading p-4\">\n <div className=\"w-full h-20 bg-gray-200 animate-pulse rounded mb-4\" />\n <div className=\"w-full h-40 bg-gray-200 animate-pulse rounded\" />\n </div>\n )}\n </div>\n );\n};\n","import { useReducer, useCallback, useEffect, useRef } from \"react\";\n\nimport { UIEvent, UISpecNode, UIState } from \"../schema/ui\";\nimport { uiReducer, initialState } from \"./reducer\";\nimport {\n systemEvents,\n createSystemEvent,\n SystemEventType,\n} from \"./system-events\";\nimport { ActionRouter, PlanningConfig } from \"./action-router\";\nimport { ActionType } from \"../schema/action-types\";\nimport { DataContext } from \"./bindings\"; // Import DataContext\n\nexport interface UseUIStateEngineOptions {\n schema: Record<string, unknown>;\n goal: string;\n apiKey: string;\n userContext?: Record<string, unknown> | undefined;\n planningConfig?: PlanningConfig | undefined;\n dataContext?: Record<string, unknown> | undefined;\n enablePartialUpdates?: boolean | undefined;\n}\n\n/**\n * Custom hook for the UI state engine\n * @param options - Configuration options\n * @returns State and dispatcher\n */\nexport function useUIStateEngine({\n schema,\n goal,\n apiKey = \"\",\n userContext,\n planningConfig,\n dataContext = {},\n enablePartialUpdates = true,\n}: UseUIStateEngineOptions) {\n // Warn if userContext is explicitly null, as it's an edge case we want to discourage.\n // Consumers should use undefined if they mean to omit it.\n if (userContext === null) {\n console.warn(\n \"useUIStateEngine: userContext was explicitly set to null. \" +\n \"This is an allowed but discouraged value. Consider using undefined if you intend to omit the user context.\"\n );\n }\n\n const [state, dispatch] = useReducer(uiReducer, initialState);\n const stateRef = useRef<UIState>(state); // Ref to hold the current state\n const router = new ActionRouter(apiKey, planningConfig);\n\n useEffect(() => {\n stateRef.current = state; // Keep the ref updated with the latest state\n }, [state]);\n\n // Function to handle UI events with routing\n const handleEvent = useCallback(\n async (\n event: UIEvent,\n currentResolvedLayout?: UISpecNode | null,\n updatedDataContext?: DataContext\n ) => {\n dispatch({ type: \"UI_EVENT\", event });\n dispatch({ type: \"LOADING\", isLoading: true });\n\n try {\n let resolvedNode: UISpecNode;\n let actionTypeForDispatch: ActionType = ActionType.FULL_REFRESH;\n let targetNodeIdForDispatch: string = \"root\";\n\n const layoutForRouting =\n currentResolvedLayout || stateRef.current.layout;\n const contextForRouting = updatedDataContext || dataContext;\n\n // ADD LOGS BEFORE AND AFTER router.resolveRoute\n console.log(\n \"[state.ts handleEvent] About to call router.resolveRoute. enablePartialUpdates:\",\n enablePartialUpdates\n );\n console.log(\n \"[state.ts handleEvent] layoutForRouting ID (if exists):\",\n layoutForRouting?.id\n );\n console.log(\n \"[state.ts handleEvent] contextForRouting:\",\n JSON.stringify(contextForRouting, null, 2)\n ); // Can be large\n\n // Always call router.resolveRoute for every event\n const route = await router.resolveRoute(\n event,\n schema,\n layoutForRouting,\n contextForRouting,\n goal,\n apiKey,\n userContext\n );\n\n // ADD THIS LOG STRATEGICALLY\n console.log(\n \"[state.ts handleEvent] router.resolveRoute returned:\",\n route\n );\n\n if (route) {\n console.log(\"Resolved route:\", route);\n actionTypeForDispatch = route.actionType;\n targetNodeIdForDispatch = route.targetNodeId;\n\n // If router provided an updated data context, dispatch an action to set it\n if (route.updatedDataContext) {\n dispatch({\n type: \"SET_DATA_CONTEXT\",\n payload: route.updatedDataContext,\n });\n }\n\n // Use directUpdateLayout if present, otherwise call LLM\n if (!route.updatedNode) {\n throw new Error(\n \"No updatedNode returned from router.resolveRoute. This should not happen.\"\n );\n }\n\n resolvedNode = route.updatedNode;\n } else {\n throw new Error(\"No route returned from router.resolveRoute\");\n }\n\n // Dispatch based on action type (derived from routing or default)\n switch (actionTypeForDispatch) {\n case ActionType.UPDATE_NODE:\n case ActionType.SHOW_DETAIL:\n case ActionType.TOGGLE_STATE:\n case ActionType.ADD_DROPDOWN:\n case ActionType.UPDATE_FORM:\n case ActionType.NAVIGATE:\n dispatch({\n type: \"PARTIAL_UPDATE\",\n nodeId: targetNodeIdForDispatch,\n node: resolvedNode,\n });\n break;\n case ActionType.HIDE_DIALOG:\n dispatch({\n type: \"PARTIAL_UPDATE\",\n nodeId: targetNodeIdForDispatch,\n node: resolvedNode,\n });\n break;\n case ActionType.SAVE_TASK_CHANGES:\n dispatch({ type: \"AI_RESPONSE\", node: resolvedNode });\n break;\n case ActionType.FULL_REFRESH:\n default:\n dispatch({ type: \"AI_RESPONSE\", node: resolvedNode });\n break;\n // systemEvents.emit for PLAN_COMPLETE is handled by callPlannerLLM or should be added for mockPlanner path\n }\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : String(e);\n dispatch({ type: \"ERROR\", message: errorMessage });\n systemEvents.emit(\n createSystemEvent(SystemEventType.PLAN_ERROR, {\n error: e instanceof Error ? e : new Error(String(e)),\n })\n );\n } finally {\n dispatch({ type: \"LOADING\", isLoading: false });\n }\n },\n [\n goal,\n schema,\n userContext,\n dataContext,\n apiKey,\n enablePartialUpdates,\n dispatch,\n ]\n );\n\n // Initial query on mount\n useEffect(() => {\n const initialFetch = async () => {\n dispatch({ type: \"LOADING\", isLoading: true });\n try {\n const initEvent: UIEvent = {\n type: \"INIT\",\n nodeId: \"system\",\n timestamp: Date.now(),\n payload: null,\n };\n\n const route = await router.resolveRoute(\n initEvent,\n schema,\n stateRef.current.layout,\n dataContext,\n goal,\n apiKey,\n userContext\n );\n\n if (!route) {\n console.error(\n \"[UIStateEngine] Initial fetch: Failed to resolve route for INIT event.\"\n );\n throw new Error(\"Failed to initialize UI due to routing error.\");\n }\n\n // If router provided an updated data context on initial load, set it.\n // This is less common for INIT but good practice.\n if (route.updatedDataContext) {\n dispatch({\n type: \"SET_DATA_CONTEXT\",\n payload: route.updatedDataContext,\n });\n }\n\n if (!route.updatedNode) {\n throw new Error(\n \"No updatedNode returned from router.resolveRoute on initial fetch. This should not happen.\"\n );\n }\n\n const node = route.updatedNode;\n\n dispatch({ type: \"AI_RESPONSE\", node });\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : String(e);\n dispatch({ type: \"ERROR\", message: errorMessage });\n systemEvents.emit(\n createSystemEvent(SystemEventType.PLAN_ERROR, {\n error: e instanceof Error ? e : new Error(String(e)),\n })\n );\n } finally {\n dispatch({ type: \"LOADING\", isLoading: false });\n }\n };\n initialFetch();\n // For diagnostic purposes in tests, temporarily making dependencies very minimal.\n // If tests pass, we need to carefully evaluate which of these truly need to trigger a re-fetch.\n // `goal` and `schema` are strong candidates for re-fetching. `dispatch` is stable.\n // `router`, `userContext`, `mockMode`, `apiKey`, `dataContext` are less likely to need to trigger a full re-fetch IF the initial call was successful.\n }, [goal, schema, dispatch]); // Highly restricted dependencies for testing\n\n return {\n state,\n dispatch,\n handleEvent,\n };\n}\n","import React from \"react\";\nimport { UISpecNode, UIEvent, UIEventType } from \"../schema/ui\";\nimport { cn } from \"@/lib/utils\";\nimport {\n Dialog,\n DialogHeader,\n DialogTitle,\n DialogDescription,\n DialogContent,\n} from \"@/components/ui/dialog\";\nimport { Card, CardContent } from \"@/components/ui/card\";\nimport { Input } from \"@/components/ui/input\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from \"@/components/ui/select\";\nimport { Checkbox } from \"@/components/ui/checkbox\";\nimport { RadioGroup, RadioGroupItem } from \"@/components/ui/radio-group\";\nimport { Tabs, TabsList, TabsTrigger, TabsContent } from \"@/components/ui/tabs\";\nimport { Label } from \"@/components/ui/label\";\n\n// Utility to parse CSS style string into a React style object\nconst parseStyleString = (styleString: string): React.CSSProperties => {\n if (typeof styleString !== \"string\") {\n // If it's not a string (e.g., already an object or undefined), return it as is or an empty object\n return typeof styleString === \"object\" ? styleString : {};\n }\n const style: React.CSSProperties = {};\n styleString.split(\";\").forEach((declaration) => {\n const [property, value] = declaration.split(\":\");\n if (property && value) {\n const camelCasedProperty = property\n .trim()\n .replace(/-([a-z])/g, (g) => g[1].toUpperCase());\n // Revert to simple assignment, accepting the potential type mismatch flagged by linter.\n // Casting to 'any' is forbidden, and 'string' doesn't satisfy all properties.\n // @ts-expect-error - Trusting the string value is valid for the CSS property\n style[camelCasedProperty as keyof React.CSSProperties] = value.trim();\n }\n });\n return style;\n};\n\nconst isArrayOf =\n <T,>(guard: (item: unknown) => item is T) =>\n (arr: unknown): arr is T[] =>\n Array.isArray(arr) && arr.every(guard);\n\n// Shimmer components\nexport const ShimmerBlock: React.FC = () => (\n <div className=\"w-full h-8 bg-gray-200 animate-pulse rounded\" />\n);\n\nexport const ShimmerTable: React.FC<{ rows?: number }> = ({ rows = 3 }) => (\n <div className=\"w-full space-y-2\">\n <div className=\"w-full h-10 bg-gray-200 animate-pulse rounded\" />\n {Array.from({ length: rows }).map((_, i) => (\n <div key={i} className=\"w-full h-12 bg-gray-200 animate-pulse rounded\" />\n ))}\n </div>\n);\n\nexport const ShimmerCard: React.FC = () => (\n <div className=\"w-full p-4 space-y-4 border rounded-lg\">\n <div className=\"w-3/4 h-6 bg-gray-200 animate-pulse rounded\" />\n <div className=\"space-y-2\">\n <div className=\"w-full h-4 bg-gray-200 animate-pulse rounded\" />\n <div className=\"w-full h-4 bg-gray-200 animate-pulse rounded\" />\n <div className=\"w-5/6 h-4 bg-gray-200 animate-pulse rounded\" />\n </div>\n </div>\n);\n\n// Mock ShadCN components for demonstration\nconst Container: React.FC<{\n style?: React.CSSProperties;\n className?: string;\n children?: React.ReactNode;\n}> = (props) => (\n <div className={`autoui-mock-container ${props.className || \"\"}`}>\n {props.children}\n </div>\n);\n\nconst Header: React.FC<{ title: string; className?: string }> = ({\n title,\n className,\n}) => (\n <header\n className={`py-4 px-6 border-b border-gray-300 mb-4 bg-gray-50 dark:bg-gray-800 ${\n className || \"\"\n }`}\n >\n <h1 className=\"text-xl font-semibold text-gray-800 dark:text-white\">\n {title}\n </h1>\n </header>\n);\n\nconst Button: React.FC<{\n onClick?: (() => void) | undefined;\n children: React.ReactNode;\n variant?: \"default\" | \"outline\" | \"destructive\" | undefined;\n}> = ({ onClick, children, variant = \"default\" }) => (\n <button\n className={`px-4 py-2 rounded-md font-medium transition-colors ${\n variant === \"default\"\n ? \"bg-blue-600 text-white hover:bg-blue-700\"\n : variant === \"outline\"\n ? \"border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800\"\n : \"bg-red-600 text-white hover:bg-red-700\"\n }`}\n onClick={() => onClick?.()}\n >\n {children}\n </button>\n);\n\nconst Detail: React.FC<{\n data?: Record<string, React.ReactNode> | undefined;\n fields?: { key: string; label: string; type?: string }[] | undefined;\n title?: string | undefined;\n visible?: boolean | undefined;\n onBack?: (() => void) | undefined;\n}> = ({ data, fields = [], title, visible = true, onBack }) => {\n if (!visible) {\n console.log(\n `[Detail Component Internal] Detail component for node id: ${\n data?.id || title || \"Unknown Detail\"\n } is NOT RENDERING because visible is ${visible}.`\n );\n return null;\n }\n console.log(\n `[Detail Component Internal] Detail component for node id: ${\n data?.id || title || \"Unknown Detail\"\n } IS RENDERING because visible is ${visible}.`\n );\n\n return (\n <div className=\"w-full border border-gray-300 dark:border-gray-700 rounded-lg p-6 space-y-4 bg-white dark:bg-gray-900 shadow-sm\">\n <div className=\"flex justify-between items-center border-b border-gray-200 dark:border-gray-700 pb-3\">\n {title && (\n <h2 className=\"text-lg font-medium text-gray-800 dark:text-white\">\n {title}\n </h2>\n )}\n {onBack && (\n <Button variant=\"outline\" onClick={onBack}>\n Back\n </Button>\n )}\n </div>\n\n <div className=\"space-y-4\">\n {fields.map((field) => {\n try {\n if (field.type === \"heading\") {\n return (\n <h3\n key={field.key}\n className=\"text-xl font-semibold text-gray-800 dark:text-white\"\n >\n {data?.[field.key] ?? \"\"}\n </h3>\n );\n }\n\n if (field.type === \"content\") {\n return (\n <div\n key={field.key}\n className=\"text-sm text-gray-700 dark:text-gray-300\"\n >\n {data?.[field.key] ?? \"\"}\n </div>\n );\n }\n\n return (\n <div\n key={field.key}\n className=\"flex flex-col border-b border-gray-100 dark:border-gray-800 py-2\"\n >\n {field.label && (\n <span className=\"text-xs text-gray-600 dark:text-gray-400 font-medium\">\n {field.label}\n </span>\n )}\n <span className=\"text-sm text-gray-800 dark:text-gray-200\">\n {data?.[field.key] ?? \"\"}\n </span>\n </div>\n );\n } catch (e) {\n console.error(\n `[Detail Component Internal] Error rendering field: ${field?.key}`,\n e,\n \"Field data:\",\n field,\n \"Full data object:\",\n data\n );\n return (\n <div key={field?.key || \"error-field\"}>\n Error rendering field: {field?.key}\n </div>\n );\n }\n })}\n </div>\n </div>\n );\n};\n\nconst getSafeProp = <T, K extends string, D extends T>(\n props: Record<string, unknown> | null | undefined,\n key: K,\n validator: (value: unknown) => value is T,\n defaultValue: D\n): T | D => {\n if (props && typeof props === \"object\" && key in props) {\n const value = props[key];\n if (validator(value)) {\n return value;\n }\n }\n return defaultValue;\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\nconst isString = (value: unknown): value is string => typeof value === \"string\";\nconst isBoolean = (value: unknown): value is boolean =>\n typeof value === \"boolean\";\nconst isButtonVariant = (\n value: unknown\n): value is \"default\" | \"outline\" | \"destructive\" =>\n isString(value) && [\"default\", \"outline\", \"destructive\"].includes(value);\n\nconst getSafeBinding = <T, K extends string, D extends T>(\n bindings: Record<string, unknown> | null | undefined,\n key: K,\n validator: (value: unknown) => value is T,\n defaultValue: D\n): T | D => {\n if (bindings && typeof bindings === \"object\" && key in bindings) {\n const value = bindings[key];\n if (validator(value)) {\n return value;\n }\n }\n return defaultValue;\n};\n\nconst isReactNode = (value: unknown): value is React.ReactNode => {\n // This is a simplified check. A full check is complex.\n // For basic scenarios, we can check for string, number, boolean, null, undefined, or React elements.\n return (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n value === null ||\n typeof value === \"undefined\" ||\n (typeof value === \"object\" && value !== null && \"$$typeof\" in value) // Basic check for React element\n );\n};\n\nconst isRecordWithReactNodeValues = (\n value: unknown\n): value is Record<string, React.ReactNode> =>\n isObject(value) && Object.values(value).every(isReactNode);\n\nconst isSelectOptionObject = (\n item: unknown\n): item is { value: string; label: string } =>\n isObject(item) && isString(item.value) && isString(item.label);\n\nconst isTabObject = (\n item: unknown\n): item is { value: string; label: string; content?: UISpecNode } => // Allow content to be optional initially\n isObject(item) &&\n isString(item.value) &&\n isString(item.label) &&\n (item.content === undefined || isUISpecNode(item.content));\n\nconst isUISpecNode = (value: unknown): value is UISpecNode => {\n if (!isObject(value)) return false;\n return isString(value.id) && isString(value.node_type); // Basic check\n};\n\nconst isDetailFieldObject = (\n item: unknown\n): item is { key: string; label: string; type?: string } =>\n isObject(item) &&\n isString(item.key) &&\n isString(item.label) &&\n (item.type === undefined || isString(item.type));\n\n// Mock implementation - in a real application, this would dispatch events to your state engine\nconst createEventHandler = (\n node: UISpecNode,\n eventName: string,\n uiEventType: UIEventType,\n processEvent?: (event: UIEvent) => void\n) => {\n const eventConfig = node.events?.[uiEventType];\n if (!processEvent || !eventConfig) return undefined;\n\n return (eventPayload?: Record<string, unknown>) => {\n const fullEvent: UIEvent = {\n type: uiEventType,\n nodeId: node.id,\n timestamp: Date.now(),\n payload: {\n ...(eventConfig.payload || {}),\n ...(eventPayload || {}),\n },\n };\n processEvent(fullEvent);\n };\n};\n\nexport const adapterMap: Record<\n string,\n (\n node: UISpecNode,\n processEvent?: (event: UIEvent) => void\n ) => React.ReactElement\n> = {\n Container: (node, processEvent) => {\n // Extract key and style first\n const { className, style: styleProp, key, ...restProps } = node.props || {};\n // Ensure children are rendered with keys\n const children = node.children?.map((child) =>\n // Use React.cloneElement to add the key prop to the element returned by renderNode\n React.cloneElement(renderNode(child, processEvent), { key: child.id })\n );\n // Parse style string if necessary\n const style =\n typeof styleProp === \"string\"\n ? parseStyleString(styleProp)\n : (styleProp as React.CSSProperties | undefined);\n\n return (\n <div\n key={key as React.Key} // Pass key directly\n className={cn(\"autoui-container\", className as string)}\n style={style} // Use the parsed style object\n {...restProps}\n data-id={node.id}\n >\n {/* Add console log to see props during render */}\n {(() => {\n console.log(\n `[Adapter Debug] Rendering Container: id=${node.id}, props=`,\n node.props\n );\n return null;\n })()}\n {children}\n </div>\n );\n },\n\n Header: (node) => (\n <Header\n title={getSafeProp(node.props, \"title\", isString, \"Untitled\")}\n className={getSafeProp(node.props, \"className\", isString, \"\")}\n />\n ),\n\n Button: (node, processEvent) => (\n <Button\n variant={getSafeProp(node.props, \"variant\", isButtonVariant, \"default\")}\n onClick={createEventHandler(node, \"onClick\", \"CLICK\", processEvent)}\n >\n {getSafeProp(node.props, \"label\", isString, \"Button\")}\n </Button>\n ),\n\n ListView: (node, processEvent) => {\n // resolveBindings populates node.children with resolved items, each having a key.\n // We just need to render these children.\n // Extract key and style first\n const {\n className,\n style: styleProp,\n key,\n // Exclude data prop (array) from being spread onto the DOM element\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n data: _data,\n ...restProps\n } = node.props || {}; // Removed unused selectable & data\n\n // Parse style string if necessary\n const style =\n typeof styleProp === \"string\"\n ? parseStyleString(styleProp)\n : (styleProp as React.CSSProperties | undefined);\n\n // Add console log to see props during render\n console.log(\n `[Adapter Debug] Rendering ListView: id=${node.id}, props=`,\n node.props\n );\n\n // The children array from resolveBindings already contains React Elements with keys\n // if resolveBindings adds the key prop correctly.\n // If renderNode returns elements, they should retain their keys.\n // Fix: Add keys to children explicitly like in Container/Card\n const children = node.children?.map((child) =>\n React.cloneElement(renderNode(child, processEvent), { key: child.id })\n );\n\n return (\n <div\n key={key as React.Key} // Pass key directly\n className={cn(\n \"autoui-listview-container space-y-2\",\n className as string\n )}\n style={style} // Use the parsed style object\n {...restProps} // Spread remaining props (selectable, style, className, key are now excluded)\n data-id={node.id}\n >\n {children}\n </div>\n );\n },\n\n Detail: (node, processEvent) => {\n const data = getSafeProp(\n node.props,\n \"data\",\n isRecordWithReactNodeValues,\n {}\n ) as Record<string, React.ReactNode>;\n const fields = getSafeProp(\n node.props,\n \"fields\",\n isArrayOf(isDetailFieldObject),\n []\n );\n const title = getSafeProp(node.props, \"title\", isString, \"\");\n const visible = getSafeProp(node.props, \"visible\", isBoolean, true);\n\n // Add a specific log here for the Detail adapter\n console.log(\n `[Adapter Debug] Rendering Detail: id=${node.id}, props=`,\n JSON.stringify(node.props),\n `effective visible=${visible}`,\n `typeof fields=${typeof fields}`,\n `Array.isArray(fields)=${Array.isArray(fields)}`\n );\n\n return (\n <Detail\n data={data}\n fields={fields}\n title={title}\n visible={visible}\n onBack={createEventHandler(node, \"onBack\", \"CLICK\", processEvent)}\n />\n );\n },\n\n Card: (node, processEvent) => {\n // Extract key and style first\n const { className, style: styleProp, key, ...restProps } = node.props || {};\n // Ensure children are rendered with keys\n const children = node.children?.map((child) =>\n React.cloneElement(renderNode(child, processEvent), { key: child.id })\n );\n // Parse style string if necessary\n const style =\n typeof styleProp === \"string\"\n ? parseStyleString(styleProp)\n : (styleProp as React.CSSProperties | undefined);\n\n return (\n <Card\n key={key as React.Key} // Pass key directly\n className={cn(\"autoui-card\", className as string)}\n style={style} // Use parsed style object\n {...restProps} // Spread remaining props\n data-id={node.id}\n >\n {/* Using CardContent as a default wrapper, adjust if needed */}\n <CardContent className=\"p-0\">\n {\" \"}\n {/* Example: remove padding if children handle it */}\n {children}\n </CardContent>\n </Card>\n );\n },\n\n Input: (node, processEvent) => {\n const name = getSafeProp(node.props, \"name\", isString, \"inputName\");\n const label = getSafeProp(node.props, \"label\", isString, \"\");\n const value = getSafeBinding(node.bindings, \"value\", isString, \"\");\n const placeholder = getSafeProp(node.props, \"placeholder\", isString, \"\");\n const disabled = getSafeProp(node.props, \"disabled\", isBoolean, false);\n const className = getSafeProp(node.props, \"className\", isString, \"\");\n\n const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n const handler = createEventHandler(\n node,\n \"onChange\",\n \"CHANGE\",\n processEvent\n );\n if (handler) handler({ value: e.target.value });\n };\n\n const handleFocus = () => {\n const handler = createEventHandler(\n node,\n \"onFocus\",\n \"FOCUS\",\n processEvent\n );\n if (handler) handler({});\n };\n\n const handleBlur = () => {\n const handler = createEventHandler(node, \"onBlur\", \"BLUR\", processEvent);\n if (handler) handler({});\n };\n\n return (\n <div className=\"grid w-full max-w-sm items-center gap-1.5\">\n {label && <Label htmlFor={name}>{label}</Label>}\n <Input\n id={name} // Use name as id for label association\n name={name}\n placeholder={placeholder}\n disabled={disabled}\n value={value}\n onChange={handleChange}\n onFocus={handleFocus}\n onBlur={handleBlur}\n className={className}\n />\n </div>\n );\n },\n\n Select: (node, processEvent) => {\n const name = getSafeProp(node.props, \"name\", isString, \"selectName\");\n const label = getSafeProp(node.props, \"label\", isString, \"\");\n const placeholder = getSafeProp(\n node.props,\n \"placeholder\",\n isString,\n \"Select...\"\n );\n const disabled = getSafeProp(node.props, \"disabled\", isBoolean, false);\n const value = getSafeBinding(node.bindings, \"value\", isString, \"\");\n const options = getSafeBinding(\n node.bindings,\n \"options\",\n isArrayOf(isSelectOptionObject),\n []\n );\n const className = getSafeProp(node.props, \"className\", isString, \"\");\n\n const handleValueChange = (selectedValue: string) => {\n const handler = createEventHandler(\n node,\n \"onValueChange\",\n \"CHANGE\",\n processEvent\n );\n if (handler) handler({ value: selectedValue });\n };\n\n return (\n <div\n className={cn(\"grid w-full max-w-sm items-center gap-1.5\", className)}\n >\n {label && <Label htmlFor={name}>{label}</Label>}\n <Select\n name={name}\n value={value}\n onValueChange={handleValueChange}\n disabled={disabled}\n >\n <SelectTrigger id={name}>\n <SelectValue placeholder={placeholder} />\n </SelectTrigger>\n <SelectContent>\n {options.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n );\n },\n\n Textarea: (node, processEvent) => {\n // Extract key first (style is usually handled by className for Textarea, but handle just in case)\n const { key, ...propsWithoutKey } = node.props || {};\n const name = getSafeProp(propsWithoutKey, \"name\", isString, \"textareaName\");\n const label = getSafeProp(propsWithoutKey, \"label\", isString, \"\");\n const placeholder = getSafeProp(\n propsWithoutKey,\n \"placeholder\",\n isString,\n \"\"\n );\n const disabled = getSafeProp(propsWithoutKey, \"disabled\", isBoolean, false);\n const rows = getSafeProp(\n propsWithoutKey,\n \"rows\",\n (v): v is number => typeof v === \"number\",\n 3\n );\n const value = getSafeBinding(node.bindings, \"value\", isString, \"\");\n const className = getSafeProp(propsWithoutKey, \"className\", isString, \"\");\n\n const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n const handler = createEventHandler(\n node,\n \"onChange\",\n \"CHANGE\",\n processEvent\n );\n if (handler) handler({ value: e.target.value });\n };\n\n const handleFocus = () => {\n const handler = createEventHandler(\n node,\n \"onFocus\",\n \"FOCUS\",\n processEvent\n );\n if (handler) handler({});\n };\n\n const handleBlur = () => {\n const handler = createEventHandler(node, \"onBlur\", \"BLUR\", processEvent);\n if (handler) handler({});\n };\n\n return (\n <div key={key as React.Key} className=\"grid w-full gap-1.5\">\n {label && <Label htmlFor={name}>{label}</Label>}\n <Textarea\n id={name} // Use name as id for label association\n name={name}\n placeholder={placeholder}\n disabled={disabled}\n rows={rows}\n value={value}\n onChange={handleChange}\n onFocus={handleFocus}\n onBlur={handleBlur}\n className={className}\n />\n </div>\n );\n },\n\n Checkbox: (node, processEvent) => {\n // Extract key first (style is usually handled by className for Checkbox)\n const { key, ...propsWithoutKey } = node.props || {};\n const name = getSafeProp(propsWithoutKey, \"name\", isString, \"checkboxName\");\n const label = getSafeProp(propsWithoutKey, \"label\", isString, \"\");\n const checked = getSafeBinding(node.bindings, \"checked\", isBoolean, false);\n const disabled = getSafeProp(propsWithoutKey, \"disabled\", isBoolean, false);\n const className = getSafeProp(propsWithoutKey, \"className\", isString, \"\");\n\n const handleCheckedChange = (isChecked: boolean | \"indeterminate\") => {\n // Ensure we only pass boolean to our event handler\n if (typeof isChecked === \"boolean\") {\n const handler = createEventHandler(\n node,\n \"onCheckedChange\",\n \"CHANGE\",\n processEvent\n );\n if (handler) handler({ checked: isChecked });\n }\n };\n\n // Shadcn Checkbox often used with a Label\n return (\n <div\n key={key as React.Key}\n className={cn(\"flex items-center space-x-2\", className as string)}\n >\n <Checkbox\n id={name} // Use name as id for label association\n name={name}\n checked={checked}\n disabled={disabled}\n onCheckedChange={handleCheckedChange}\n />\n {/* Add the aria-label for accessibility if no visible label */}\n {label && (\n <Label htmlFor={name} className=\"cursor-pointer\">\n {label}\n </Label>\n )}\n </div>\n );\n },\n\n RadioGroup: (node, processEvent) => {\n // Extract key first (style is usually handled by className for RadioGroup)\n const { key, ...propsWithoutKey } = node.props || {};\n const name = getSafeProp(\n propsWithoutKey,\n \"name\",\n isString,\n \"radioGroupName\"\n );\n const label = getSafeProp(propsWithoutKey, \"label\", isString, \"\");\n const value = getSafeBinding(node.bindings, \"value\", isString, \"\");\n const options = getSafeBinding(\n node.bindings,\n \"options\",\n isArrayOf(isSelectOptionObject),\n []\n );\n const disabled = getSafeProp(propsWithoutKey, \"disabled\", isBoolean, false);\n const className = getSafeProp(propsWithoutKey, \"className\", isString, \"\");\n\n const handleValueChange = (selectedValue: string) => {\n const handler = createEventHandler(\n node,\n \"onValueChange\",\n \"CHANGE\",\n processEvent\n );\n if (handler) handler({ value: selectedValue });\n };\n\n return (\n <div\n key={key as React.Key}\n className={cn(\"grid gap-1.5\", className as string)}\n >\n {label && <Label className=\"mb-1\">{label}</Label>}\n <RadioGroup\n name={name}\n value={value}\n onValueChange={handleValueChange}\n disabled={disabled}\n className=\"flex flex-col space-y-1\"\n >\n {options.map((option) => (\n <div key={option.value} className=\"flex items-center space-x-2\">\n <RadioGroupItem\n value={option.value}\n id={`${name}-${option.value}`}\n />\n <Label\n htmlFor={`${name}-${option.value}`}\n className=\"cursor-pointer\"\n >\n {option.label}\n </Label>\n </div>\n ))}\n </RadioGroup>\n </div>\n );\n },\n\n Tabs: (node, processEvent) => {\n // Extract key first (style is usually handled by className for Tabs)\n const { key, ...propsWithoutKey } = node.props || {};\n // For Tabs, children are defined by the 'tabs' prop which includes content as UISpecNode\n // We need to render these UISpecNode children.\n const rawTabs = getSafeBinding(\n node.bindings,\n \"tabs\",\n isArrayOf(isTabObject),\n []\n );\n const defaultValue = getSafeProp(\n propsWithoutKey,\n \"defaultValue\",\n isString,\n rawTabs[0]?.value || \"\"\n ); // Default to first tab if available\n const className = getSafeProp(propsWithoutKey, \"className\", isString, \"\");\n\n const handleValueChange = (value: string) => {\n const handler = createEventHandler(\n node,\n \"onValueChange\",\n \"CHANGE\",\n processEvent\n );\n if (handler) handler({ value });\n };\n\n return (\n <Tabs\n key={key as React.Key}\n defaultValue={defaultValue}\n onValueChange={handleValueChange}\n className={cn(\"autoui-tabs w-full\", className)}\n data-id={node.id}\n >\n <TabsList>\n {rawTabs.map((tab) => (\n <TabsTrigger key={tab.value} value={tab.value}>\n {tab.label}\n </TabsTrigger>\n ))}\n </TabsList>\n {rawTabs.map((tab) => (\n <TabsContent key={tab.value} value={tab.value}>\n {tab.content ? renderNode(tab.content, processEvent) : null}\n </TabsContent>\n ))}\n </Tabs>\n );\n },\n\n Dialog: (node, processEvent) => {\n // Determine if the dialog should be open. Check bindings first, then props.\n // Default to false if neither is specified.\n const isOpen = getSafeBinding(\n node.bindings,\n \"visible\",\n isBoolean, // Check bindings.visible (planner output)\n getSafeProp(\n node.props,\n \"open\",\n isBoolean, // Then props.open (if binding resolution put it there)\n getSafeProp(node.props, \"visible\", isBoolean, false) // Then props.visible (if binding resolution put it there under 'visible')\n )\n );\n\n // Extract key and className first. Intentionally exclude styleProp and open (_open)\n const {\n title,\n description,\n className,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n style: _styleProp,\n key,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n open: _openProp,\n // ADD 'visible' to destructuring to prevent it from going into restProps\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n visible: _visibleProp,\n ...restProps\n } = node.props || {}; // Renamed unused styleProp to _styleProp, open to _openProp\n\n // Ensure children are rendered with keys\n const children = node.children?.map((child) =>\n React.cloneElement(renderNode(child, processEvent), { key: child.id })\n );\n\n const handleOpenChange = (open: boolean) => {\n if (!open) {\n // Only trigger onClose when dialog is closed\n const handler = createEventHandler(\n node,\n \"onClose\", // Assumed event name in UISpec\n \"CLICK\", // Use CLICK as the event type for closing dialogs\n processEvent\n );\n if (handler) {\n handler({}); // Trigger with empty payload or adjust as needed\n }\n }\n // We might need to update the state via an event if open is controlled by bindings\n // For now, assume direct control or one-way binding for visibility\n };\n\n // Add console log to see props during render\n console.log(\n `[Adapter Debug] Rendering Dialog: id=${node.id}, props=`,\n node.props,\n `isOpen=${isOpen}`\n );\n\n return (\n <Dialog\n key={key as React.Key}\n open={isOpen}\n onOpenChange={handleOpenChange}\n >\n <DialogContent\n className={cn(\"autoui-dialog-content\", className as string)}\n {...restProps} // Pass restProps to DialogContent\n data-id={node.id} // Add data-id for debugging/testing\n >\n {(title || description) && (\n <DialogHeader>\n {title && <DialogTitle>{title as string}</DialogTitle>}\n {description && (\n <DialogDescription>{description as string}</DialogDescription>\n )}\n </DialogHeader>\n )}\n {children}\n {/* Removed explicit Close button, rely on Shadcn's built-in close or trigger via handleOpenChange */}\n </DialogContent>\n </Dialog>\n );\n },\n\n Heading: (node) => {\n // Extract key and style first. Remove unused textProp, levelProp.\n const { className, style: styleProp, key, ...restProps } = node.props || {};\n const text = getSafeProp(node.props, \"text\", isString, \"Heading\");\n // Ensure level is a valid heading level (1-6), default to 2\n let level = getSafeProp(\n node.props,\n \"level\",\n (v): v is number => typeof v === \"number\" && v >= 1 && v <= 6,\n 2\n );\n if (typeof level !== \"number\" || level < 1 || level > 6) {\n level = 2; // Fallback to h2 if level is invalid\n }\n const Tag = `h${level}` as keyof JSX.IntrinsicElements;\n // Parse style string if necessary\n const style =\n typeof styleProp === \"string\"\n ? parseStyleString(styleProp)\n : (styleProp as React.CSSProperties | undefined);\n\n // Apply some default Shadcn-like heading styles based on level\n const headingStyles =\n {\n 1: \"scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl\",\n 2: \"scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0\",\n 3: \"scroll-m-20 text-2xl font-semibold tracking-tight\",\n 4: \"scroll-m-20 text-xl font-semibold tracking-tight\",\n // Add styles for h5, h6 if needed, using text-lg, text-base etc.\n }[level] || \"text-lg font-semibold\"; // Default style\n\n return (\n <Tag\n key={key as React.Key}\n className={cn(headingStyles, className as string)}\n style={style}\n {...restProps}\n >\n {text}\n </Tag>\n );\n },\n\n Text: (node) => {\n // Extract key and style first. Remove unused textProp.\n const { className, style: styleProp, key, ...restProps } = node.props || {};\n const text = getSafeProp(node.props, \"text\", isString, \"Some text\");\n // Parse style string if necessary\n const style =\n typeof styleProp === \"string\"\n ? parseStyleString(styleProp)\n : (styleProp as React.CSSProperties | undefined);\n\n // Apply default paragraph styling\n return (\n <p\n key={key as React.Key}\n className={cn(\"leading-7\", className as string)}\n style={style}\n {...restProps}\n >\n {text}\n </p>\n );\n },\n\n Badge: (node) => {\n const { className, style: styleProp, key, ...restProps } = node.props || {};\n const text = getSafeProp(node.props, \"text\", isString, \"\");\n const style =\n typeof styleProp === \"string\"\n ? parseStyleString(styleProp)\n : (styleProp as React.CSSProperties | undefined);\n\n // Simple badge styling using Tailwind\n return (\n <span\n key={key as React.Key}\n className={cn(\n \"inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-gray-100 text-gray-800\",\n className as string\n )}\n style={style}\n {...restProps}\n >\n {text}\n </span>\n );\n },\n};\n\nexport function renderNode(\n node: UISpecNode,\n processEvent?: (event: UIEvent) => void\n): React.ReactElement {\n const mappedComponent = adapterMap[node.node_type];\n if (mappedComponent) {\n return mappedComponent(node, processEvent);\n }\n console.warn(`Unknown node type: ${node.node_type}`);\n return React.createElement(\n Container,\n {},\n `Unknown node type: ${node.node_type}`\n );\n}\n","import * as React from \"react\"\nimport * as DialogPrimitive from \"@radix-ui/react-dialog\"\nimport { XIcon } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Dialog({\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Root>) {\n return <DialogPrimitive.Root data-slot=\"dialog\" {...props} />\n}\n\nfunction DialogTrigger({\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {\n return <DialogPrimitive.Trigger data-slot=\"dialog-trigger\" {...props} />\n}\n\nfunction DialogPortal({\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Portal>) {\n return <DialogPrimitive.Portal data-slot=\"dialog-portal\" {...props} />\n}\n\nfunction DialogClose({\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Close>) {\n return <DialogPrimitive.Close data-slot=\"dialog-close\" {...props} />\n}\n\nfunction DialogOverlay({\n className,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {\n return (\n <DialogPrimitive.Overlay\n data-slot=\"dialog-overlay\"\n className={cn(\n \"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction DialogContent({\n className,\n children,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Content>) {\n return (\n <DialogPortal data-slot=\"dialog-portal\">\n <DialogOverlay />\n <DialogPrimitive.Content\n data-slot=\"dialog-content\"\n className={cn(\n \"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg\",\n className\n )}\n {...props}\n >\n {children}\n <DialogPrimitive.Close className=\"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\">\n <XIcon />\n <span className=\"sr-only\">Close</span>\n </DialogPrimitive.Close>\n </DialogPrimitive.Content>\n </DialogPortal>\n )\n}\n\nfunction DialogHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"dialog-header\"\n className={cn(\"flex flex-col gap-2 text-center sm:text-left\", className)}\n {...props}\n />\n )\n}\n\nfunction DialogFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"dialog-footer\"\n className={cn(\n \"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction DialogTitle({\n className,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Title>) {\n return (\n <DialogPrimitive.Title\n data-slot=\"dialog-title\"\n className={cn(\"text-lg leading-none font-semibold\", className)}\n {...props}\n />\n )\n}\n\nfunction DialogDescription({\n className,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Description>) {\n return (\n <DialogPrimitive.Description\n data-slot=\"dialog-description\"\n className={cn(\"text-muted-foreground text-sm\", className)}\n {...props}\n />\n )\n}\n\nexport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogOverlay,\n DialogPortal,\n DialogTitle,\n DialogTrigger,\n}\n","import * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Card({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card\"\n className={cn(\n \"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-header\"\n className={cn(\n \"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardTitle({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-title\"\n className={cn(\"leading-none font-semibold\", className)}\n {...props}\n />\n )\n}\n\nfunction CardDescription({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-description\"\n className={cn(\"text-muted-foreground text-sm\", className)}\n {...props}\n />\n )\n}\n\nfunction CardAction({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-action\"\n className={cn(\n \"col-start-2 row-span-2 row-start-1 self-start justify-self-end\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardContent({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-content\"\n className={cn(\"px-6\", className)}\n {...props}\n />\n )\n}\n\nfunction CardFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-footer\"\n className={cn(\"flex items-center px-6 [.border-t]:pt-6\", className)}\n {...props}\n />\n )\n}\n\nexport {\n Card,\n CardHeader,\n CardFooter,\n CardTitle,\n CardAction,\n CardDescription,\n CardContent,\n}\n","import * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Input({ className, type, ...props }: React.ComponentProps<\"input\">) {\n return (\n <input\n type={type}\n data-slot=\"input\"\n className={cn(\n \"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm\",\n \"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]\",\n \"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Input }\n","import * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Textarea({ className, ...props }: React.ComponentProps<\"textarea\">) {\n return (\n <textarea\n data-slot=\"textarea\"\n className={cn(\n \"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Textarea }\n","import * as React from \"react\"\nimport * as SelectPrimitive from \"@radix-ui/react-select\"\nimport { CheckIcon, ChevronDownIcon, ChevronUpIcon } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Select({\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Root>) {\n return <SelectPrimitive.Root data-slot=\"select\" {...props} />\n}\n\nfunction SelectGroup({\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Group>) {\n return <SelectPrimitive.Group data-slot=\"select-group\" {...props} />\n}\n\nfunction SelectValue({\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Value>) {\n return <SelectPrimitive.Value data-slot=\"select-value\" {...props} />\n}\n\nfunction SelectTrigger({\n className,\n size = \"default\",\n children,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {\n size?: \"sm\" | \"default\"\n}) {\n return (\n <SelectPrimitive.Trigger\n data-slot=\"select-trigger\"\n data-size={size}\n className={cn(\n \"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n className\n )}\n {...props}\n >\n {children}\n <SelectPrimitive.Icon asChild>\n <ChevronDownIcon className=\"size-4 opacity-50\" />\n </SelectPrimitive.Icon>\n </SelectPrimitive.Trigger>\n )\n}\n\nfunction SelectContent({\n className,\n children,\n position = \"popper\",\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Content>) {\n return (\n <SelectPrimitive.Portal>\n <SelectPrimitive.Content\n data-slot=\"select-content\"\n className={cn(\n \"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md\",\n position === \"popper\" &&\n \"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1\",\n className\n )}\n position={position}\n {...props}\n >\n <SelectScrollUpButton />\n <SelectPrimitive.Viewport\n className={cn(\n \"p-1\",\n position === \"popper\" &&\n \"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1\"\n )}\n >\n {children}\n </SelectPrimitive.Viewport>\n <SelectScrollDownButton />\n </SelectPrimitive.Content>\n </SelectPrimitive.Portal>\n )\n}\n\nfunction SelectLabel({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Label>) {\n return (\n <SelectPrimitive.Label\n data-slot=\"select-label\"\n className={cn(\"text-muted-foreground px-2 py-1.5 text-xs\", className)}\n {...props}\n />\n )\n}\n\nfunction SelectItem({\n className,\n children,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Item>) {\n return (\n <SelectPrimitive.Item\n data-slot=\"select-item\"\n className={cn(\n \"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2\",\n className\n )}\n {...props}\n >\n <span className=\"absolute right-2 flex size-3.5 items-center justify-center\">\n <SelectPrimitive.ItemIndicator>\n <CheckIcon className=\"size-4\" />\n </SelectPrimitive.ItemIndicator>\n </span>\n <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>\n </SelectPrimitive.Item>\n )\n}\n\nfunction SelectSeparator({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Separator>) {\n return (\n <SelectPrimitive.Separator\n data-slot=\"select-separator\"\n className={cn(\"bg-border pointer-events-none -mx-1 my-1 h-px\", className)}\n {...props}\n />\n )\n}\n\nfunction SelectScrollUpButton({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {\n return (\n <SelectPrimitive.ScrollUpButton\n data-slot=\"select-scroll-up-button\"\n className={cn(\n \"flex cursor-default items-center justify-center py-1\",\n className\n )}\n {...props}\n >\n <ChevronUpIcon className=\"size-4\" />\n </SelectPrimitive.ScrollUpButton>\n )\n}\n\nfunction SelectScrollDownButton({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {\n return (\n <SelectPrimitive.ScrollDownButton\n data-slot=\"select-scroll-down-button\"\n className={cn(\n \"flex cursor-default items-center justify-center py-1\",\n className\n )}\n {...props}\n >\n <ChevronDownIcon className=\"size-4\" />\n </SelectPrimitive.ScrollDownButton>\n )\n}\n\nexport {\n Select,\n SelectContent,\n SelectGroup,\n SelectItem,\n SelectLabel,\n SelectScrollDownButton,\n SelectScrollUpButton,\n SelectSeparator,\n SelectTrigger,\n SelectValue,\n}\n","import * as React from \"react\"\nimport * as CheckboxPrimitive from \"@radix-ui/react-checkbox\"\nimport { CheckIcon } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Checkbox({\n className,\n ...props\n}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {\n return (\n <CheckboxPrimitive.Root\n data-slot=\"checkbox\"\n className={cn(\n \"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50\",\n className\n )}\n {...props}\n >\n <CheckboxPrimitive.Indicator\n data-slot=\"checkbox-indicator\"\n className=\"flex items-center justify-center text-current transition-none\"\n >\n <CheckIcon className=\"size-3.5\" />\n </CheckboxPrimitive.Indicator>\n </CheckboxPrimitive.Root>\n )\n}\n\nexport { Checkbox }\n","import * as React from \"react\"\nimport * as RadioGroupPrimitive from \"@radix-ui/react-radio-group\"\nimport { CircleIcon } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction RadioGroup({\n className,\n ...props\n}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {\n return (\n <RadioGroupPrimitive.Root\n data-slot=\"radio-group\"\n className={cn(\"grid gap-3\", className)}\n {...props}\n />\n )\n}\n\nfunction RadioGroupItem({\n className,\n ...props\n}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {\n return (\n <RadioGroupPrimitive.Item\n data-slot=\"radio-group-item\"\n className={cn(\n \"border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50\",\n className\n )}\n {...props}\n >\n <RadioGroupPrimitive.Indicator\n data-slot=\"radio-group-indicator\"\n className=\"relative flex items-center justify-center\"\n >\n <CircleIcon className=\"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2\" />\n </RadioGroupPrimitive.Indicator>\n </RadioGroupPrimitive.Item>\n )\n}\n\nexport { RadioGroup, RadioGroupItem }\n","import * as React from \"react\"\nimport * as TabsPrimitive from \"@radix-ui/react-tabs\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Tabs({\n className,\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.Root>) {\n return (\n <TabsPrimitive.Root\n data-slot=\"tabs\"\n className={cn(\"flex flex-col gap-2\", className)}\n {...props}\n />\n )\n}\n\nfunction TabsList({\n className,\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.List>) {\n return (\n <TabsPrimitive.List\n data-slot=\"tabs-list\"\n className={cn(\n \"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction TabsTrigger({\n className,\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {\n return (\n <TabsPrimitive.Trigger\n data-slot=\"tabs-trigger\"\n className={cn(\n \"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction TabsContent({\n className,\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.Content>) {\n return (\n <TabsPrimitive.Content\n data-slot=\"tabs-content\"\n className={cn(\"flex-1 outline-none\", className)}\n {...props}\n />\n )\n}\n\nexport { Tabs, TabsList, TabsTrigger, TabsContent }\n","import * as React from \"react\"\nimport * as LabelPrimitive from \"@radix-ui/react-label\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Label({\n className,\n ...props\n}: React.ComponentProps<typeof LabelPrimitive.Root>) {\n return (\n <LabelPrimitive.Root\n data-slot=\"label\"\n className={cn(\n \"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Label }\n","import React from \"react\";\nimport { UISpecNode, UIEvent } from \"../schema/ui\";\nimport {\n renderNode as renderShadcnNode,\n ShimmerBlock,\n ShimmerTable,\n ShimmerCard,\n} from \"../adapters/shadcn\";\nimport {\n createSystemEvent,\n systemEvents,\n SystemEventType,\n} from \"./system-events\";\n\n// This helps prevent infinite loops in the rendering process\nconst renderedNodesCache = new Map<\n string,\n { element: React.ReactElement; timestamp: number }\n>();\nconst MAX_CACHE_SIZE = 10;\nconst CACHE_TTL = 5000; // 5 seconds\n\n// Export for targeted cache clearing\nexport const clearRenderedNodeCacheEntry = (cacheKey: string) => {\n renderedNodesCache.delete(cacheKey);\n console.log(`[Renderer Cache] Cleared entry FOR REAL for key: ${cacheKey}`);\n};\n\n// Function to construct the cache key, can also be exported if needed elsewhere\nexport const getRendererCacheKey = (node: UISpecNode): string => {\n if (node.id === \"task-detail\") {\n // Simplified key for task-detail for more reliable cache invalidation\n const dataId = (node.props?.data as { id?: string | number })?.id;\n return `${node.id}:${node.props?.visible}:${dataId || \"no-data-selected\"}`;\n }\n\n // Default detailed key for other nodes\n let propsString = \"null\";\n try {\n propsString = JSON.stringify(node.props);\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (_e) {\n console.warn(\n `[Renderer Cache Key] Error stringifying node.props for ID ${node.id}, using 'null' for props part of key.`\n );\n }\n let bindingsString = \"null\";\n try {\n bindingsString = JSON.stringify(node.bindings);\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (_e) {\n console.warn(\n `[Renderer Cache Key] Error stringifying node.bindings for ID ${node.id}, using 'null' for bindings part of key.`\n );\n }\n return `${node.id}:${propsString}:${bindingsString}`;\n};\n\n/**\n * Renders a UI node using the appropriate adapter\n * @param node - UI specification node\n * @param adapter - Component adapter (default: \"shadcn\")\n * @param processEvent - Optional callback to handle UI events\n * @returns React element\n */\nexport async function renderNode(\n node: UISpecNode,\n adapter: \"shadcn\" = \"shadcn\",\n processEvent?: (event: UIEvent) => void\n): Promise<React.ReactElement> {\n const startTime = Date.now();\n const cacheKey = getRendererCacheKey(node);\n const cachedItem = renderedNodesCache.get(cacheKey);\n\n // Standard Cache Check - RESTORED\n if (cachedItem && startTime - cachedItem.timestamp < CACHE_TTL) {\n return cachedItem.element;\n }\n\n // if (node.id === \"task-detail\") { // Log for task-detail (if needed for other diagnostics)\n // console.log(`[Renderer renderNode] Cache MISS or expired for node: ${node.id}. Key: ${cacheKey}`);\n // }\n\n // MOVED THIS LOG UP: For task-detail, log BEFORE the RENDER_START event emission\n if (node.id === \"task-detail\") {\n let safeNodeString = \"Error stringifying node for log\";\n let propsToLog = \"{}\";\n try {\n const clonedProps = node.props ? { ...node.props } : {};\n if (clonedProps && clonedProps.data) {\n clonedProps.data = `Data present (type: ${typeof clonedProps.data}, logging suppressed)`;\n }\n if (clonedProps && Array.isArray(clonedProps.fields)) {\n clonedProps.fields = `Fields array (length: ${clonedProps.fields.length}, logging suppressed)`;\n } else if (clonedProps && clonedProps.fields) {\n clonedProps.fields = `Fields present (type: ${typeof clonedProps.fields}, logging suppressed)`;\n }\n propsToLog = JSON.stringify(clonedProps);\n\n const nodeToLog = {\n id: node.id,\n node_type: node.node_type,\n props: \"See props above\",\n bindings: node.bindings,\n events: node.events,\n children: node.children\n ? `Children array (length: ${node.children.length}, logging suppressed)`\n : null,\n };\n safeNodeString = JSON.stringify(nodeToLog);\n } catch (e: unknown) {\n if (e instanceof Error) {\n safeNodeString = `Error stringifying node for log: ${e.message}`;\n } else {\n safeNodeString = `Error stringifying node for log: Unknown error`;\n }\n if (node.props === undefined) propsToLog = \"undefined\";\n else if (node.props === null) propsToLog = \"null\";\n }\n console.log(\n `[Renderer renderNode BEFORE RENDER_START event] About to call adapter for task-detail. ID: ${\n node.id\n }, Visible: ${\n node.props?.visible\n }, Props (safe): ${propsToLog}, Bindings: ${JSON.stringify(\n node.bindings\n )}, Node (safe): ${safeNodeString}`\n );\n }\n\n await systemEvents.emit(\n createSystemEvent(SystemEventType.RENDER_START, { layout: node })\n );\n\n let result: React.ReactElement;\n\n switch (adapter) {\n case \"shadcn\":\n result = renderShadcnNode(node, processEvent);\n break;\n default:\n console.warn(`Unsupported adapter: ${adapter}, falling back to shadcn`);\n result = renderShadcnNode(node, processEvent);\n }\n\n if (node.id === \"task-detail\") {\n let elementType: string | undefined = undefined;\n if (result && typeof (result as React.ReactElement).type === \"function\") {\n elementType = ((result as React.ReactElement).type as { name: string })\n .name;\n } else if (\n result &&\n typeof (result as React.ReactElement).type === \"string\"\n ) {\n elementType = (result as React.ReactElement).type as string;\n } else if (\n result &&\n typeof (result as React.ReactElement).type === \"object\" &&\n (result as React.ReactElement).type !== null\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const componentType = (result as React.ReactElement).type as any;\n if (typeof componentType.displayName === \"string\") {\n elementType = componentType.displayName;\n }\n }\n console.log(\n `[Renderer renderNode] Adapter for task-detail returned element. Element type:`,\n elementType\n );\n }\n\n await systemEvents.emit(\n createSystemEvent(SystemEventType.RENDER_COMPLETE, {\n layout: node,\n renderTimeMs: Date.now() - startTime,\n })\n );\n\n // Store in cache - RESTORED\n renderedNodesCache.set(cacheKey, {\n element: result,\n timestamp: startTime,\n });\n\n // Clean cache if it gets too big - RESTORED\n if (renderedNodesCache.size > MAX_CACHE_SIZE) {\n // Delete oldest entry\n const oldestEntry = renderedNodesCache.entries().next().value;\n if (oldestEntry) {\n renderedNodesCache.delete(oldestEntry[0]);\n }\n }\n\n return result;\n}\n\n/**\n * Generates a shimmer placeholder for a UI node\n * @param node - UI specification node\n * @param adapter - Component adapter (default: \"shadcn\")\n * @returns React element\n */\nexport function renderShimmer(\n node?: UISpecNode,\n adapter: \"shadcn\" = \"shadcn\"\n): React.ReactElement {\n // If no node, render a default shimmer\n if (!node) {\n return <ShimmerBlock />;\n }\n\n // Generate appropriate shimmer based on node type\n switch (node.node_type) {\n case \"ListView\":\n return <ShimmerTable rows={3} />;\n case \"Detail\":\n return <ShimmerCard />;\n case \"Container\":\n return (\n <div className=\"space-y-4\">\n {node.children?.map((child, index) => (\n <div key={index}>{renderShimmer(child, adapter)}</div>\n ))}\n </div>\n );\n default:\n return <ShimmerBlock />;\n }\n}\n","import { UIEvent, UIEventType } from \"../schema/ui\";\n\nexport interface EventHookOptions {\n preventDefault?: boolean;\n stopPropagation?: boolean;\n}\n\nexport interface EventHookContext {\n originalEvent: UIEvent;\n preventDefault: () => void;\n stopPropagation: () => void;\n isDefaultPrevented: () => boolean;\n isPropagationStopped: () => boolean;\n}\n\nexport type EventHook = (context: EventHookContext) => void | Promise<void>;\n\nexport interface EventHooksMap {\n // Global hooks for all events\n all?: EventHook[];\n\n // Specific event type hooks\n [key: string]: EventHook[] | undefined;\n}\n\n/**\n * Event manager to handle registration and execution of event hooks\n */\nexport class EventManager {\n private hooks: EventHooksMap = {};\n\n /**\n * Register a hook for specific event types\n *\n * @param eventTypes - Event types to register for, or 'all' for all events\n * @param hook - Hook function to execute\n * @returns Unregister function\n */\n public register(\n eventTypes: UIEventType[] | \"all\",\n hook: EventHook\n ): () => void {\n if (eventTypes === \"all\") {\n if (!this.hooks.all) {\n this.hooks.all = [];\n }\n this.hooks.all.push(hook);\n\n return () => {\n if (this.hooks.all) {\n this.hooks.all = this.hooks.all.filter((h) => h !== hook);\n }\n };\n }\n\n eventTypes.forEach((type) => {\n if (!this.hooks[type]) {\n this.hooks[type] = [];\n }\n this.hooks[type]?.push(hook);\n });\n\n return () => {\n eventTypes.forEach((type) => {\n if (this.hooks[type]) {\n this.hooks[type] = this.hooks[type]?.filter((h) => h !== hook);\n }\n });\n };\n }\n\n /**\n * Process an event through all registered hooks\n *\n * @param event - The UI event to process\n * @returns Whether the default action should proceed\n */\n public async processEvent(event: UIEvent): Promise<boolean> {\n let defaultPrevented = false;\n let propagationStopped = false;\n\n const context: EventHookContext = {\n originalEvent: event,\n preventDefault: () => {\n defaultPrevented = true;\n },\n stopPropagation: () => {\n propagationStopped = true;\n },\n isDefaultPrevented: () => defaultPrevented,\n isPropagationStopped: () => propagationStopped,\n };\n\n // Run global hooks first\n if (this.hooks.all) {\n for (const hook of this.hooks.all) {\n await hook(context);\n if (propagationStopped) break;\n }\n }\n\n // If propagation not stopped and we have specific hooks for this event type\n if (!propagationStopped && this.hooks[event.type]) {\n for (const hook of this.hooks[event.type] || []) {\n await hook(context);\n if (propagationStopped) break;\n }\n }\n\n return !defaultPrevented;\n }\n}\n\n/**\n * Create a hook to intercept specific events\n *\n * @example\n * ```tsx\n * const unregister = useEventHook(['CLICK'], (ctx) => {\n * if (ctx.originalEvent.nodeId === 'deleteButton') {\n * // Show confirmation dialog\n * const confirmed = window.confirm('Are you sure?');\n * if (!confirmed) {\n * ctx.preventDefault();\n * }\n * }\n * });\n * ```\n */\nexport function createEventHook(\n eventTypes: UIEventType[] | \"all\",\n hook: EventHook,\n options?: EventHookOptions\n): EventHook {\n return async (context) => {\n await hook(context);\n\n if (options?.preventDefault) {\n context.preventDefault();\n }\n\n if (options?.stopPropagation) {\n context.stopPropagation();\n }\n };\n}\n","/**\n * Checks if shadcn components are available in the project\n * @returns Boolean indicating whether shadcn components are available\n */\nexport function areShadcnComponentsAvailable(): boolean {\n try {\n // Try to require one of the shadcn components\n require(\"../../components/ui/button\");\n return true;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Provides helpful guidance for missing components\n */\nexport function getMissingComponentsMessage(): string {\n return `Missing required shadcn components. Please run:\n> npm run setup-shadcn`;\n}\n","import { z } from \"zod\";\nimport { DataContext } from \"../core/bindings\";\n\n/**\n * Event types that can be triggered by UI elements\n */\nexport const uiEventType = z.enum([\n \"INIT\",\n \"CLICK\",\n \"CHANGE\",\n \"SUBMIT\",\n \"MOUSEOVER\",\n \"MOUSEOUT\",\n \"FOCUS\",\n \"BLUR\",\n]);\n\nexport type UIEventType = z.infer<typeof uiEventType>;\n\n/**\n * Event payload schema\n */\nexport const uiEvent = z.object({\n type: uiEventType,\n nodeId: z.string(),\n timestamp: z.number().nullable(),\n payload: z.record(z.unknown()).nullable(),\n});\n\nexport type UIEvent = z.infer<typeof uiEvent>;\n\n/**\n * AI response types\n */\nexport const aiResponseType = z.enum([\"AI_RESPONSE\", \"ERROR\"]);\n\nexport type AIResponseType = z.infer<typeof aiResponseType>;\n\n// --- Runtime Specific Types ---\nconst runtimeRecord = z.record(z.unknown()).nullable();\n\n// --- Interface for Runtime UISpecNode ---\nexport interface UISpecNodeInterface {\n id: string;\n node_type: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n props: Record<string, any> | null;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n bindings: Record<string, any> | null;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n events: Record<\n string,\n {\n action: string;\n target: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n payload: Record<string, any> | null;\n }\n > | null;\n children: UISpecNodeInterface[] | null;\n}\n\n// --- Runtime Schema Definition ---\nexport const uiSpecNode: z.ZodType<UISpecNodeInterface> = z.object({\n id: z.string(),\n node_type: z.string(),\n props: runtimeRecord,\n bindings: runtimeRecord,\n events: z\n .record(\n z.string(),\n z.object({\n action: z.string(),\n target: z.string(),\n payload: runtimeRecord,\n })\n )\n .nullable(),\n children: z.lazy(() => z.array(uiSpecNode)).nullable(),\n});\n\n// --- Exported Types ---\nexport type UISpecNode = z.infer<typeof uiSpecNode>;\n\n/**\n * Actions that can be dispatched to the reducer\n */\nexport const uiAction = z.discriminatedUnion(\"type\", [\n z.object({\n type: z.literal(\"UI_EVENT\"),\n event: uiEvent,\n }),\n z.object({\n type: z.literal(\"AI_RESPONSE\"),\n node: uiSpecNode,\n }),\n z.object({\n type: z.literal(\"PARTIAL_UPDATE\"),\n nodeId: z.string(),\n node: uiSpecNode,\n }),\n z.object({\n type: z.literal(\"ADD_NODE\"),\n parentId: z.string(),\n node: uiSpecNode,\n index: z.number().nullable(),\n }),\n z.object({\n type: z.literal(\"REMOVE_NODE\"),\n nodeId: z.string(),\n }),\n z.object({\n type: z.literal(\"ERROR\"),\n message: z.string(),\n }),\n z.object({\n type: z.literal(\"LOADING\"),\n isLoading: z.boolean(),\n }),\n z.object({\n type: z.literal(\"SET_DATA_CONTEXT\"),\n payload: z.record(z.string(), z.unknown()),\n }),\n]);\n\nexport type UIAction = z.infer<typeof uiAction>;\n\n/**\n * Application state for the UI engine\n */\nexport const uiState = z.object({\n layout: uiSpecNode.nullable(),\n loading: z.boolean(),\n history: z.array(uiEvent),\n error: z.string().nullable(),\n dataContext: z.record(z.string(), z.unknown()),\n});\n\nexport type UIState = z.infer<typeof uiState> & { dataContext: DataContext };\n\n/**\n * Input for the AI planner\n */\nexport const plannerInput = z.object({\n schema: z.record(z.unknown()),\n goal: z.string(),\n history: z.array(uiEvent).nullable(),\n userContext: z.record(z.unknown()).nullable().optional(),\n});\n\nexport type PlannerInput = z.infer<typeof plannerInput>;\n\n// Define a more specific type for data items\nexport type DataItem = Record<string, unknown>;\n","import { DataContext } from \"../../core/bindings\";\n\n/**\n * Drizzle schema adapter types\n */\n\n// Simplified representation of Drizzle schema\nexport interface DrizzleColumn {\n name: string;\n dataType: string;\n notNull?: boolean;\n defaultValue?: unknown;\n primaryKey?: boolean;\n unique?: boolean;\n references?: {\n table: string;\n column: string;\n };\n}\n\nexport interface DrizzleTable {\n name: string;\n schema: string;\n columns: Record<string, DrizzleColumn>;\n}\n\nexport interface DrizzleSchema {\n [tableName: string]: DrizzleTable;\n}\n\n// Database client interface\nexport interface DrizzleClientConfig {\n connectionString?: string | undefined;\n client?: unknown | undefined; // The actual Drizzle client instance\n queryFn?: ((tableName: string, query: any) => Promise<unknown[]>) | undefined;\n}\n\n// Main adapter interface\nexport interface DrizzleAdapterOptions {\n schema: DrizzleSchema;\n client?: DrizzleClientConfig | undefined;\n useMockData?: boolean | undefined;\n mockData?: Record<string, unknown[]> | undefined;\n}\n\n/**\n * Adapter for Drizzle ORM schemas\n * Handles converting Drizzle schema to AutoUI schema format\n * and optionally connects to a database\n */\nexport class DrizzleAdapter {\n private schema: DrizzleSchema;\n private client: DrizzleClientConfig | undefined;\n private useMockData: boolean;\n private mockData: Record<string, unknown[]>;\n\n constructor(options: DrizzleAdapterOptions) {\n this.schema = options.schema;\n this.client = options.client;\n this.useMockData = options.useMockData ?? !options.client;\n this.mockData = options.mockData ?? {};\n }\n\n /**\n * Convert Drizzle schema to AutoUI schema format\n */\n public getSchema(): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n Object.entries(this.schema).forEach(([tableName, table]) => {\n result[tableName] = {\n tableName: table.name,\n schema: table.schema,\n columns: this.convertColumns(table.columns),\n // Include mock data if available and mock mode is enabled\n ...(this.useMockData && this.mockData[tableName]\n ? { sampleData: this.mockData[tableName] }\n : {}),\n };\n });\n\n return result;\n }\n\n /**\n * Convert Drizzle columns to AutoUI column format\n */\n private convertColumns(\n columns: Record<string, DrizzleColumn>\n ): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n Object.entries(columns).forEach(([columnName, column]) => {\n result[columnName] = {\n type: this.mapDataType(column.dataType),\n notNull: column.notNull,\n defaultValue: column.defaultValue,\n primaryKey: column.primaryKey,\n unique: column.unique,\n references: column.references,\n };\n });\n\n return result;\n }\n\n /**\n * Map Drizzle data types to standard types\n */\n private mapDataType(drizzleType: string): string {\n const typeMap: Record<string, string> = {\n serial: \"integer\",\n integer: \"integer\",\n int: \"integer\",\n bigint: \"integer\",\n text: \"string\",\n varchar: \"string\",\n char: \"string\",\n boolean: \"boolean\",\n bool: \"boolean\",\n timestamp: \"datetime\",\n timestamptz: \"datetime\",\n date: \"date\",\n time: \"time\",\n json: \"object\",\n jsonb: \"object\",\n real: \"number\",\n float: \"number\",\n double: \"number\",\n numeric: \"number\",\n decimal: \"number\",\n };\n\n return typeMap[drizzleType.toLowerCase()] || \"string\";\n }\n\n /**\n * Execute a query against the database\n */\n public async query(tableName: string, query: any): Promise<unknown[]> {\n if (this.useMockData) {\n return this.mockData[tableName] || [];\n }\n\n if (!this.client) {\n throw new Error(\"No database client provided and mock mode is disabled\");\n }\n\n if (this.client.queryFn) {\n return this.client.queryFn(tableName, query);\n }\n\n throw new Error(\"No query function provided in client config\");\n }\n\n /**\n * Initialize the data context with schema information and optional mock data\n */\n public async initializeDataContext(): Promise<DataContext> {\n const context: DataContext = {};\n\n for (const [tableName, table] of Object.entries(this.schema)) {\n context[tableName] = {\n schema: table,\n data: this.useMockData ? this.mockData[tableName] || [] : [],\n selected: null,\n };\n }\n\n return context;\n }\n}\n","import { DataContext } from \"../../core/bindings\";\nimport { DrizzleAdapter, DrizzleAdapterOptions } from \"./drizzle\";\n\n/**\n * Generic schema adapter interface\n */\nexport interface SchemaAdapter {\n getSchema(): Record<string, unknown>;\n query(tableName: string, query: any): Promise<unknown[]>;\n initializeDataContext(): Promise<DataContext>;\n}\n\n/**\n * Schema adapter options union type\n */\nexport type SchemaAdapterOptions =\n | { type: \"drizzle\"; options: DrizzleAdapterOptions }\n | { type: \"custom\"; adapter: SchemaAdapter };\n\n/**\n * Factory function to create the appropriate schema adapter\n */\nexport function createSchemaAdapter(\n options: SchemaAdapterOptions\n): SchemaAdapter {\n switch (options.type) {\n case \"drizzle\":\n return new DrizzleAdapter(options.options);\n case \"custom\":\n return options.adapter;\n default:\n throw new Error(\n `Unsupported schema adapter type: ${(options as any).type}`\n );\n }\n}\n\nexport { DrizzleAdapter, type DrizzleAdapterOptions };\n","/**\n * AI Utilities for AutoUI React\n * Provides AI-powered UI generation functionality\n */\n\n// Temporary placeholder implementations for the exported functions\n// These will be replaced with actual implementations later\n\n/**\n * Generates a component using AI\n */\nexport const generateComponent = async (prompt: string) => {\n console.warn(\n \"generateComponent is a placeholder and will be implemented in a future version\"\n );\n return `<div>Generated Component for: ${prompt}</div>`;\n};\n\n/**\n * Generates a UI description using AI\n */\nexport const generateUIDescription = async (prompt: string) => {\n console.warn(\n \"generateUIDescription is a placeholder and will be implemented in a future version\"\n );\n return `Description for ${prompt}`;\n};\n\n/**\n * Generates a UI component using AI\n */\nexport const generateUIComponent = async (prompt: string) => {\n console.warn(\n \"generateUIComponent is a placeholder and will be implemented in a future version\"\n );\n return `<div>Generated UI Component for: ${prompt}</div>`;\n};\n"]}