diff --git a/LUA_SNIPPETS_GUIDE.md b/LUA_SNIPPETS_GUIDE.md
new file mode 100644
index 000000000..94507e97c
--- /dev/null
+++ b/LUA_SNIPPETS_GUIDE.md
@@ -0,0 +1,182 @@
+# Lua Snippet Library - Quick Reference
+
+The MetaBuilder Lua Snippet Library provides 30+ pre-built code templates to accelerate your development workflow.
+
+## Categories
+
+### Data Validation
+- **Email Validation** - Validate email format using pattern matching
+- **Password Strength Validator** - Check password meets security requirements
+- **Phone Number Validation** - Validate US phone number format
+- **Required Fields Validator** - Check multiple required fields are present
+
+### Data Transformation
+- **Snake Case to Camel Case** - Convert snake_case strings to camelCase
+- **Flatten Nested Object** - Convert nested table to flat key-value pairs
+- **Normalize User Data** - Clean and normalize user input data
+
+### Array Operations
+- **Filter Array** - Filter array elements by condition
+- **Map Array** - Transform each array element
+- **Reduce Array to Sum** - Calculate sum of numeric array values
+- **Group Array by Property** - Group array items by a property value
+- **Sort Array** - Sort array by property value
+
+### String Processing
+- **Create URL Slug** - Convert text to URL-friendly slug
+- **Truncate Text** - Truncate long text with ellipsis
+- **Extract Hashtags** - Find all hashtags in text
+- **Word Counter** - Count words and characters in text
+
+### Math & Calculations
+- **Calculate Percentage** - Calculate percentage and format result
+- **Calculate Discount** - Calculate price after discount
+- **Compound Interest Calculator** - Calculate compound interest over time
+- **Statistical Analysis** - Calculate mean, median, mode, std dev
+
+### Conditionals & Logic
+- **Role-Based Access Check** - Check if user has required role
+- **Time-Based Logic** - Execute logic based on time of day
+- **Feature Flag Checker** - Check if feature is enabled for user
+
+### Error Handling
+- **Try-Catch Pattern** - Safe execution with error handling
+- **Validation Error Accumulator** - Collect all validation errors at once
+
+### User Management
+- **Build User Profile** - Create complete user profile from data
+- **Log User Activity** - Create activity log entry
+
+### Date & Time
+- **Format Date** - Format timestamp in various ways
+- **Calculate Date Difference** - Calculate difference between two dates
+
+### Utilities
+- **Safe JSON Parse** - Parse JSON string with error handling
+- **Generate Unique ID** - Create unique identifier
+- **Rate Limit Checker** - Check if action exceeds rate limit
+- **Simple Cache Manager** - Cache data with expiration
+
+## Usage
+
+### In the Lua Editor
+1. Click the **"Snippet Library"** button in the Lua code section
+2. Browse categories or use the search bar
+3. Click a snippet card to preview details
+4. Click **"Insert"** to add the code at your cursor position
+5. Customize the code for your needs
+
+### Standalone View
+1. Navigate to the **"Snippet Library"** tab in Level 4
+2. Search or filter by category
+3. Click any snippet to view full details
+4. Click **"Copy"** to copy to clipboard
+
+## Context API
+
+All snippets use the MetaBuilder context API:
+
+```lua
+-- Access input data
+local data = context.data or {}
+
+-- Access current user
+local user = context.user or {}
+
+-- Log messages
+log("Processing started...")
+
+-- Return results
+return { success = true, result = processedData }
+```
+
+## Common Patterns
+
+### Validation Pattern
+```lua
+local data = context.data or {}
+
+if not data.field then
+ return { valid = false, error = "Field is required" }
+end
+
+if not validateCondition(data.field) then
+ return { valid = false, error = "Validation failed" }
+end
+
+return { valid = true, data = data }
+```
+
+### Transformation Pattern
+```lua
+local input = context.data or {}
+
+local output = {
+ field1 = transform(input.field1),
+ field2 = normalize(input.field2),
+ metadata = {
+ processedAt = os.time(),
+ version = "1.0"
+ }
+}
+
+return output
+```
+
+### Error Handling Pattern
+```lua
+local function riskyOperation()
+ -- operation that might fail
+end
+
+local success, result = pcall(riskyOperation)
+
+if success then
+ return { success = true, result = result }
+else
+ log("Error: " .. tostring(result))
+ return { success = false, error = tostring(result) }
+end
+```
+
+## Tips
+
+- **Search by functionality** - Use keywords like "validate", "calculate", "transform"
+- **Check tags** - Tags help identify snippet capabilities quickly
+- **Review parameters** - Each snippet documents required input parameters
+- **Customize freely** - Snippets are starting points, modify as needed
+- **Combine patterns** - Mix multiple snippets for complex logic
+- **Test thoroughly** - Use the test runner to verify behavior with sample data
+
+## Adding Custom Snippets
+
+While the library comes with 30+ pre-built snippets, you can:
+1. Copy existing snippets as templates
+2. Modify to fit your use case
+3. Save as new Lua scripts in your project
+4. Reference from workflows
+
+## Best Practices
+
+✅ **Do:**
+- Use descriptive variable names
+- Add comments for complex logic
+- Validate input data before processing
+- Return structured results
+- Log important steps
+- Handle edge cases
+
+❌ **Avoid:**
+- Infinite loops (workflows have execution limits)
+- Blocking operations
+- Modifying global state
+- Assuming data exists without checks
+- Returning undefined or null values
+
+## Support
+
+For questions about snippets or to request new patterns:
+- Check the snippet description and parameter docs
+- Test with sample data in the Lua editor
+- Review execution logs for debugging
+- Consult the Lua language documentation
diff --git a/PRD.md b/PRD.md
index 48f7cffe4..70aefd504 100644
--- a/PRD.md
+++ b/PRD.md
@@ -55,11 +55,18 @@ This is a 4-tier meta-application builder: a public website layer, authenticated
- **Success criteria**: Nodes connect smoothly; execution order clear; can branch/merge; error handling; logs show execution path; integrates with Lua
### Lua Lambda System (Level 4)
-- **Functionality**: Real Lua interpreter (fengari-web) with full language support, Monaco editor with syntax highlighting and autocomplete, parameter handling, context API access, and comprehensive execution feedback
-- **Purpose**: Provide safe, sandboxed scripting for custom transformations, validations, and business logic with real Lua execution beyond declarative capabilities, enhanced by professional code editing experience
+- **Functionality**: Real Lua interpreter (fengari-web) with full language support, Monaco editor with syntax highlighting and autocomplete, parameter handling, context API access, comprehensive execution feedback, and extensive snippet library with 30+ pre-built templates
+- **Purpose**: Provide safe, sandboxed scripting for custom transformations, validations, and business logic with real Lua execution beyond declarative capabilities, enhanced by professional code editing experience and reusable code patterns
- **Trigger**: User adds "Lua Action" node in workflow or creates Lua script in scripts tab
-- **Progression**: Open Monaco-based Lua editor → Define parameters → Write Lua code with syntax highlighting and autocomplete → Access context.data/user/kv via intelligent suggestions → Test with sample inputs → View execution logs → Return structured results → Integrate into workflows
-- **Success criteria**: Monaco editor integrated with Lua language support; autocomplete provides context API suggestions (context.data, context.user, context.kv, log, print); syntax highlighting active; real Lua execution via fengari; parameter type validation; execution logs captured; return values parsed; syntax/runtime errors shown with line numbers; can transform JSON data; fullscreen editing mode available; integrates with workflow nodes
+- **Progression**: Open Monaco-based Lua editor → Define parameters → Browse snippet library by category → Search and preview snippets → Insert template code → Customize with syntax highlighting and autocomplete → Access context.data/user/kv via intelligent suggestions → Test with sample inputs → View execution logs → Return structured results → Integrate into workflows
+- **Success criteria**: Monaco editor integrated with Lua language support; autocomplete provides context API suggestions (context.data, context.user, context.kv, log, print); syntax highlighting active; real Lua execution via fengari; parameter type validation; execution logs captured; return values parsed; syntax/runtime errors shown with line numbers; can transform JSON data; fullscreen editing mode available; snippet library accessible with 30+ templates across 12 categories; snippets insertable at cursor position; integrates with workflow nodes
+
+### Lua Snippet Library (Level 4)
+- **Functionality**: Comprehensive library of 30+ pre-built Lua code templates organized into 12 categories (Data Validation, Data Transformation, Array Operations, String Processing, Math & Calculations, Conditionals & Logic, User Management, Error Handling, API & Networking, Date & Time, File Operations, Utilities)
+- **Purpose**: Accelerate development by providing tested, reusable patterns for common operations; reduce errors; teach best practices
+- **Trigger**: User clicks "Snippet Library" button in Lua editor or opens "Snippet Library" tab in Level 4
+- **Progression**: Open snippet library → Browse by category or search by keyword/tag → Preview snippet details and parameters → View full code in syntax-highlighted display → Copy to clipboard or insert into editor → Customize for specific use case
+- **Success criteria**: 30+ snippets covering common patterns; organized into logical categories; searchable by name, description, and tags; preview shows code, description, and required parameters; one-click copy or insert; snippets include validation, transformation, calculations, conditionals, string operations, array operations, date handling, error handling, and utilities; modal detail view for full inspection
## Edge Case Handling
- **Invalid User Credentials**: Show clear error message; rate limit after 5 attempts; support password reset flow
@@ -107,13 +114,14 @@ Animations should feel responsive and purposeful - immediate visual feedback for
- **Components**:
- Sidebar with collapsible sections for component catalog
- Resizable panels for canvas/inspector layout
- - Card for component previews in catalog
- - Dialog for login form and settings
- - Tabs for switching between visual/code views
- - ScrollArea for component lists and property panels
+ - Card for component previews in catalog and snippet library
+ - Dialog for login form, settings, and snippet detail view
+ - Sheet for slide-out snippet library panel
+ - Tabs for switching between visual/code views and snippet categories
+ - ScrollArea for component lists, property panels, and snippet browsing
- Input, Select, Switch, Slider for property editors
- Button throughout for actions
- - Badge for component type indicators
+ - Badge for component type indicators and snippet tags
- Separator for visual hierarchy
- Tooltip for help text on hover
- Sonner for notifications
@@ -126,13 +134,16 @@ Animations should feel responsive and purposeful - immediate visual feedback for
- Canvas ruler and grid overlay
- Component outline overlay on hover
- Fullscreen mode for Monaco editor instances
+ - Snippet library with category filtering and search
+ - Snippet card grid with tag display and copy/insert actions
+ - Snippet detail modal with parameter documentation and code highlighting
- **States**:
- Canvas: neutral state shows dotted grid, hover shows drop zones, dragging shows blue outlines
- Components: default has subtle border, hover shows blue glow, selected shows thick accent border with resize handles
- Drop zones: hidden by default, appear on drag with dashed accent border and background tint
- Property inputs: follow standard focus states with accent color
- **Icon Selection**:
- - Phosphor icons: Layout for layouts, PaintBrush for styling, Code for code editor, Lock/LockOpen for auth, FloppyDisk for save, Eye for preview, ArrowsOutSimple for fullscreen, Plus for add, Trash for delete, Copy for duplicate, CaretRight/Down for tree expand
+ - Phosphor icons: Layout for layouts, PaintBrush for styling, Code for code editor, Lock/LockOpen for auth, FloppyDisk for save, Eye for preview, ArrowsOutSimple for fullscreen, Plus for add, Trash for delete, Copy for duplicate/copy, CaretRight/Down for tree expand, BookOpen for snippet library, MagnifyingGlass for search, Tag for snippet tags, Check for copied confirmation, ArrowRight for insert action
- **Spacing**:
- Sidebars: p-4 for sections, gap-2 for component grid
- Canvas: p-8 for outer padding, min-h-screen for scrollability
diff --git a/src/components/Level4.tsx b/src/components/Level4.tsx
index fd6d86fd5..6ca1f6ba3 100644
--- a/src/components/Level4.tsx
+++ b/src/components/Level4.tsx
@@ -3,11 +3,12 @@ import { useKV } from '@github/spark/hooks'
import { Button } from '@/components/ui/button'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Badge } from '@/components/ui/badge'
-import { SignOut, Database, Lightning, Code, Eye, House, Download, Upload } from '@phosphor-icons/react'
+import { SignOut, Database, Lightning, Code, Eye, House, Download, Upload, BookOpen } from '@phosphor-icons/react'
import { toast } from 'sonner'
import { SchemaEditorLevel4 } from './SchemaEditorLevel4'
import { WorkflowEditor } from './WorkflowEditor'
import { LuaEditor } from './LuaEditor'
+import { LuaSnippetLibrary } from './LuaSnippetLibrary'
import type { User as UserType, AppConfiguration } from '@/lib/level-types'
import type { ModelSchema } from '@/lib/schema-types'
@@ -120,7 +121,7 @@ export function Level4({ user, onLogout, onNavigate, onPreview }: Level4Props) {
-
+
Data Schemas
@@ -136,6 +137,10 @@ export function Level4({ user, onLogout, onNavigate, onPreview }: Level4Props) {
Lua Scripts
{appConfig.luaScripts.length}
+
+
+ Snippet Library
+
@@ -165,6 +170,10 @@ export function Level4({ user, onLogout, onNavigate, onPreview }: Level4Props) {
}
/>
+
+
+
+