Move all documentation files into organized docs folder structure

Co-authored-by: johndoe6345789 <224850594+johndoe6345789@users.noreply.github.com>
This commit is contained in:
copilot-swe-agent[bot]
2025-12-24 00:47:24 +00:00
parent d9bfe8ca65
commit 23f89d190d
26 changed files with 0 additions and 2522 deletions

View File

@@ -1,293 +0,0 @@
# IRC Webchat Package - Declarative Conversion Guide
## Overview
The IRC Webchat component has been successfully converted from a traditional React TypeScript component to a fully declarative JSON and Lua-based package. This conversion demonstrates the power of the MetaBuilder package system, where complex interactive components can be defined entirely through configuration and scripting.
## Package Structure
The IRC Webchat package (`irc-webchat`) is now defined in `/src/lib/package-catalog.ts` and includes:
### 1. Manifest
```json
{
"id": "irc-webchat",
"name": "IRC-Style Webchat",
"version": "1.0.0",
"category": "social",
"icon": "💬"
}
```
### 2. Data Schemas
Three database schemas define the chat data structure:
- **ChatChannel**: Chat channels/rooms with name, description, topic
- **ChatMessage**: Individual messages with type (message, system, join, leave)
- **ChatUser**: Online users per channel
### 3. Pages
The package includes a pre-configured `/chat` page at Level 2 (user area) with authentication required.
### 4. Lua Scripts
Five Lua scripts handle all chat logic:
#### `lua_irc_send_message`
Creates a chat message object with unique ID, timestamp, and user information.
```lua
function sendMessage(channelId, username, userId, message)
-- Returns a message object
end
```
#### `lua_irc_handle_command`
Processes IRC-style commands like `/help`, `/users`, `/clear`, `/me`.
```lua
function handleCommand(command, channelId, username, onlineUsers)
-- Returns system response or command result
end
```
#### `lua_irc_format_time`
Formats Unix timestamps into human-readable 12-hour format.
```lua
function formatTime(timestamp)
-- Returns formatted time string like "02:45 PM"
end
```
#### `lua_irc_user_join`
Generates join messages when users enter a channel.
```lua
function userJoin(channelId, username, userId)
-- Returns a join-type message
end
```
#### `lua_irc_user_leave`
Generates leave messages when users exit a channel.
```lua
function userLeave(channelId, username, userId)
-- Returns a leave-type message
end
```
### 5. Component Configuration
The package defines a declarative component structure using JSON:
```json
{
"type": "IRCWebchat",
"config": {
"layout": "Card",
"children": [
{
"id": "header",
"type": "CardHeader",
"children": [...]
},
{
"id": "content",
"type": "CardContent",
"children": [
{
"id": "messages_area",
"type": "ScrollArea",
...
},
{
"id": "input_area",
"type": "Container",
...
}
]
}
]
}
}
```
### 6. Seed Data
Pre-configured chat channels:
- `general`: General discussion
- `random`: Random conversations
## How It Works
### Component Loading
1. **Package Initialization**: `initializePackageSystem()` is called in `App.tsx` on startup
2. **Script Registration**: All Lua scripts are registered with the `DeclarativeComponentRenderer`
3. **Component Registration**: Component configurations are registered for use in the builder
### Runtime Execution
When the IRC component is used:
1. **User Join**: Calls `lua_irc_user_join` to create a join message
2. **Send Message**: Calls `lua_irc_send_message` with user input
3. **Commands**: Calls `lua_irc_handle_command` when message starts with `/`
4. **Time Formatting**: Calls `lua_irc_format_time` for each message timestamp
5. **User Leave**: Calls `lua_irc_user_leave` on component unmount
### Data Flow
```
User Action → React Component (IRCWebchatDeclarative)
getDeclarativeRenderer().executeLuaScript(scriptId, params)
LuaEngine.execute(wrappedCode, context)
Lua Function Execution (Fengari)
Result Conversion (Lua table → JavaScript object)
React State Update (useKV for persistence)
```
## Migration from TSX
### Before (IRCWebchat.tsx)
```typescript
const handleSendMessage = () => {
const newMessage: ChatMessage = {
id: `msg_${Date.now()}_${Math.random()}`,
username: user.username,
userId: user.id,
message: trimmed,
timestamp: Date.now(),
type: 'message',
}
setMessages((current) => [...(current || []), newMessage])
}
```
### After (Declarative + Lua)
```typescript
const newMessage = await renderer.executeLuaScript('lua_irc_send_message', [
`chat_${channelName}`,
user.username,
user.id,
trimmed,
])
setMessages((current) => [...(current || []), newMessage])
```
## Benefits of Declarative Approach
### 1. **No Code Deployment**
- Changes to chat logic require only JSON/Lua updates
- No TypeScript compilation needed
- Hot-swappable functionality
### 2. **Package System Integration**
- IRC can be installed/uninstalled like any package
- Export/import as ZIP with all configurations
- Share with other MetaBuilder instances
### 3. **GUI Configuration**
- Chat commands can be modified in Level 4/5 panels
- Time format can be changed without code
- New message types can be added dynamically
### 4. **Multi-Tenancy Ready**
- Each tenant can customize chat behavior
- Lua scripts can be overridden per tenant
- Database schemas are tenant-isolated
### 5. **Security Sandboxing**
- Lua execution is sandboxed (can be enhanced)
- Scripts can be scanned for malicious code
- Limited API surface for Lua scripts
## File Structure
```
/src
/components
IRCWebchat.tsx [DEPRECATED - Can be removed]
IRCWebchatDeclarative.tsx [NEW - Uses declarative system]
/lib
package-catalog.ts [Contains irc-webchat package]
declarative-component-renderer.ts [Executes Lua scripts]
lua-engine.ts [Fengari Lua runtime]
package-loader.ts [Loads packages on init]
```
## Next Steps
### For Developers
1. Review the Lua scripts in `package-catalog.ts`
2. Test IRC functionality in Level 2 user area
3. Consider removing `IRCWebchat.tsx` (old component)
4. Add more Lua scripts for advanced features
### For Users (Level 4/5)
1. Navigate to Package Manager
2. View installed `irc-webchat` package
3. Modify Lua scripts to customize behavior
4. Add new commands via Lua Editor
5. Export package to share with others
## Testing the Conversion
1. **Login** as a regular user
2. Navigate to **Level 2** (User Area)
3. Go to the **Chat** tab
4. Test the following:
- Send messages
- Use `/help` command
- Use `/users` command
- Use `/me dances` command
- Use `/clear` command
- Open another window and see online users update
## Troubleshooting
### Lua Script Not Found
- Ensure `initializePackageSystem()` is called before component renders
- Check that `irc-webchat` package exists in `PACKAGE_CATALOG`
### Messages Not Sending
- Check browser console for Lua execution errors
- Verify parameter types match Lua script expectations
- Ensure `useKV` keys are correctly formatted
### Time Format Issues
- Review `lua_irc_format_time` script
- Check timestamp is in milliseconds (JavaScript format)
- Lua `os.time()` returns seconds, multiply by 1000
## Future Enhancements
1. **Channel Management**: Lua scripts for creating/deleting channels
2. **User Mentions**: Parse `@username` and notify users
3. **Message Reactions**: Add emoji reactions via Lua
4. **File Sharing**: Integrate with asset management
5. **Moderation**: Kick/ban users, message filtering
6. **Bots**: AI-powered chat bots using `spark.llm`
7. **Persistence**: Save message history to database schemas
8. **Notifications**: Browser notifications for new messages
## Conclusion
The IRC Webchat conversion demonstrates that even complex, interactive components can be fully defined using JSON and Lua. This approach enables:
- **Rapid iteration** without deployments
- **User customization** at the highest levels
- **Package sharing** across instances
- **Multi-tenant flexibility**
- **Security through sandboxing**
The declarative pattern can be extended to other components like forums, comments, notifications, and more.

View File

@@ -1,446 +0,0 @@
# Modular Package Architecture - Complete Guide
## Overview
The MetaBuilder platform now uses a **modular package system** where each component lives in its own isolated folder with:
- **Seed data** (components.json, scripts.lua, metadata.json)
- **Static content** (examples, assets, documentation)
This architecture allows packages to be **dropped in**, **glued together**, and **used immediately** without modifying core TypeScript code.
## 📁 Package Structure
```
/packages/
├── admin_dialog/
│ ├── seed/
│ │ ├── components.json # Component hierarchy
│ │ ├── metadata.json # Package info & exports
│ │ ├── scripts.lua # Legacy single file (optional)
│ │ └── scripts/ # NEW: Organized Lua scripts
│ │ ├── manifest.json # Script file registry
│ │ ├── init.lua # Initialization
│ │ ├── handlers.lua # Event handlers
│ │ ├── validators.lua # Validation logic
│ │ └── utils.lua # Helper functions
│ ├── static_content/
│ │ ├── examples.json # Usage examples
│ │ └── assets/ # Images, icons
│ └── README.md # Documentation
├── data_table/
├── form_builder/
├── nav_menu/
├── dashboard/
├── notification_center/
└── manifest.json # Registry of all packages
```
**NEW**: Packages now support multiple organized Lua scripts in a `scripts/` subfolder.
See [PACKAGE_SCRIPTS_GUIDE.md](./PACKAGE_SCRIPTS_GUIDE.md) for details.
## 🎯 Core Concept: Drop & Glue
### 1. **Drop** - Add a Package
Create a new folder in `/packages/` with the standard structure:
```bash
/packages/my_feature/
├── seed/
│ ├── components.json
│ ├── scripts.lua
│ └── metadata.json
└── static_content/
└── examples.json
```
### 2. **Glue** - Register the Package
Add to `/src/lib/package-glue.ts`:
```typescript
import myFeatureComponents from '../../packages/my_feature/seed/components.json'
import myFeatureMetadata from '../../packages/my_feature/seed/metadata.json'
// In buildPackageRegistry():
const myFeatureScripts = await loadLuaScript('my_feature')
registry['my_feature'] = {
...myFeatureMetadata,
components: myFeatureComponents,
scripts: myFeatureScripts,
examples: {}
}
```
### 3. **Use** - Instant Availability
The package is now available system-wide:
- Components can be placed on pages
- Lua scripts execute business logic
- No TypeScript compilation needed
## 📦 Available Packages
### UI Components
| Package | Purpose | Key Features |
|---------|---------|--------------|
| **admin_dialog** | Reusable admin dialogs | Dynamic forms, validation, state management |
| **data_table** | Advanced data tables | Search, sort, filter, CRUD, row selection |
| **form_builder** | Dynamic form builder | 15+ field types, validation, error handling |
| **nav_menu** | Navigation menus | Role-based links, user section, mobile responsive |
| **notification_center** | Notifications | Real-time alerts, filtering, mark as read |
### Page Templates
| Package | Purpose | Key Features |
|---------|---------|--------------|
| **dashboard** | Dashboard layouts | Stats cards, widgets, customizable layout |
## 🔧 Package Anatomy
### components.json
Defines the component hierarchy using declarative JSON:
```json
[
{
"id": "my_component_root",
"type": "Card",
"props": {
"className": "p-4"
},
"children": ["my_component_header", "my_component_body"]
},
{
"id": "my_component_header",
"type": "h2",
"props": {},
"content": "{{state.title}}"
}
]
```
**Key Features:**
- Hierarchical component tree
- Props binding to state: `"{{state.fieldName}}"`
- Event handlers: `"{{handlers.handleClick}}"`
- shadcn components: Dialog, Card, Button, etc.
### scripts.lua
Contains all business logic in Lua:
```lua
-- Initialize state
function my_package_init(config)
return {
title = config.title or "Default",
data = {},
isLoading = false
}
end
-- Handle actions
function my_package_handle_action(state, action)
local newState = table_clone(state)
newState.isLoading = true
-- ... logic here
return newState
end
-- Utility functions
function table_clone(orig)
local copy = {}
for k, v in pairs(orig) do
if type(v) == 'table' then
copy[k] = table_clone(v)
else
copy[k] = v
end
end
return copy
end
```
**Lua Features:**
- Stateless, pure functions
- Immutable state updates
- Full Lua standard library
- Custom helper functions
### metadata.json
Package manifest and exports:
```json
{
"packageId": "my_package",
"name": "My Package",
"version": "1.0.0",
"description": "Package description",
"author": "MetaBuilder System",
"category": "ui-component",
"dependencies": [],
"exports": {
"components": ["my_component_root"],
"scripts": [
"my_package_init",
"my_package_handle_action"
]
},
"shadowcnComponents": ["Card", "Button"]
}
```
## 🎨 Package Categories
- **ui-component**: Reusable UI components
- **page-template**: Full page layouts
- **feature**: Complete features (forum, chat, etc.)
- **utility**: Helper functions
- **integration**: Third-party services
## 🚀 Usage Flow
### 1. System Initialization
```typescript
// On app startup
await initializePackageSystem()
```
This:
1. Loads all packages from `/packages/`
2. Builds package registry
3. Stores components and scripts in KV store
4. Makes everything available system-wide
### 2. Using Components in Pages
In Level 4/5 builder, select from package components:
```json
{
"pageId": "admin_page",
"components": [
"admin_dialog_root",
"data_table_root"
]
}
```
### 3. Lua Scripts Execute Automatically
When a component renders:
1. Initialize: `my_package_init()` called
2. User interaction triggers handler
3. Handler calls Lua function
4. Lua returns new state
5. Component re-renders
## 💡 Example: Creating a Comment Box Package
### Step 1: Create Structure
```bash
mkdir -p packages/comment_box/seed
mkdir -p packages/comment_box/static_content
```
### Step 2: components.json
```json
[
{
"id": "comment_box_root",
"type": "Card",
"props": { "className": "space-y-4 p-4" },
"children": ["comment_box_list", "comment_box_form"]
},
{
"id": "comment_box_list",
"type": "CommentList",
"props": {
"comments": "{{state.comments}}",
"onDelete": "{{handlers.handleDelete}}"
}
},
{
"id": "comment_box_form",
"type": "Textarea",
"props": {
"value": "{{state.newComment}}",
"onChange": "{{handlers.handleChange}}",
"placeholder": "Write a comment..."
}
}
]
```
### Step 3: scripts.lua
```lua
function comment_box_init(config)
return {
comments = config.initialComments or {},
newComment = "",
isSubmitting = false
}
end
function comment_box_handle_change(state, value)
local newState = table_clone(state)
newState.newComment = value
return newState
end
function comment_box_add_comment(state, authorId)
if state.newComment == "" then
return state
end
local newState = table_clone(state)
local comment = {
id = "comment_" .. os.time(),
text = newState.newComment,
authorId = authorId,
timestamp = os.time()
}
table.insert(newState.comments, comment)
newState.newComment = ""
return newState
end
function table_clone(orig)
local copy = {}
for k, v in pairs(orig) do
if type(v) == 'table' then
copy[k] = table_clone(v)
else
copy[k] = v
end
end
return copy
end
```
### Step 4: metadata.json
```json
{
"packageId": "comment_box",
"name": "Comment Box",
"version": "1.0.0",
"description": "Simple comment system with add/delete",
"author": "MetaBuilder System",
"category": "ui-component",
"dependencies": [],
"exports": {
"components": ["comment_box_root"],
"scripts": [
"comment_box_init",
"comment_box_handle_change",
"comment_box_add_comment"
]
}
}
```
### Step 5: Register in package-glue.ts
```typescript
import commentBoxComponents from '../../packages/comment_box/seed/components.json'
import commentBoxMetadata from '../../packages/comment_box/seed/metadata.json'
// In buildPackageRegistry():
const commentBoxScripts = await loadLuaScript('comment_box')
registry['comment_box'] = {
...commentBoxMetadata,
components: commentBoxComponents,
scripts: commentBoxScripts,
examples: {}
}
```
### Step 6: Use It!
Now `comment_box_root` can be placed on any page in the Level 4/5 builder!
## 🔥 Benefits
**No TypeScript needed** - Everything in JSON and Lua
**True modularity** - Each package is independent
**Easy distribution** - Share packages as folders
**Rapid development** - Drop in, glue, done
**Type safety** - JSON validated at load time
**Version control friendly** - Clear folder structure
**Scalable** - Hundreds of packages, zero impact
## 📚 Advanced Topics
### Package Dependencies
```json
{
"packageId": "advanced_table",
"dependencies": ["data_table", "form_builder"]
}
```
System automatically checks dependencies before loading.
### Package Versioning
```json
{
"version": "2.1.0",
"minSystemVersion": "1.0.0"
}
```
### Import/Export Packages
Packages can be exported as ZIP files for distribution:
```typescript
import { exportPackageAsZip } from '@/lib/package-import-export'
await exportPackageAsZip('admin_dialog')
```
### Custom shadcn Components
Specify which shadcn components the package uses:
```json
{
"shadowcnComponents": [
"Dialog",
"Card",
"Button",
"Input"
]
}
```
## 🎓 Best Practices
1. **One responsibility per package** - Keep packages focused
2. **Immutable Lua functions** - Always return new state
3. **Clear naming** - Use descriptive IDs: `package_component_element`
4. **Document examples** - Include examples.json
5. **Test independently** - Each package should work standalone
## 🔮 Future Roadmap
- [ ] Package marketplace
- [ ] Hot-reload in development
- [ ] Automated testing framework
- [ ] Package CLI tools
- [ ] Dependency version constraints
- [ ] Package analytics
---
**The modular package system is now live!** Drop in new packages, glue them together, and build applications faster than ever.

View File

@@ -1,704 +0,0 @@
# Modular Seed Data System Guide
## Overview
The modular seed data system allows you to organize massive amounts of initialization data into maintainable, focused modules. Each module handles one concern and can be developed, tested, and maintained independently.
## Directory Structure
```
/src/seed-data/
├── index.ts # Central orchestrator - exports all modules
├── users.ts # User accounts, roles, and authentication
├── components.ts # Component configurations and props
├── scripts.ts # Lua scripts library
├── workflows.ts # Workflow definitions
├── pages.ts # Page structure definitions
└── packages.ts # Package system initialization
```
## Module Pattern
Each module follows a consistent pattern:
```typescript
import { Database } from '@/lib/database'
import type { YourType } from '@/lib/level-types'
export async function initializeYourModule() {
// 1. Check if data already exists
const existing = await Database.getYourData()
if (existing.length > 0) {
return // Already initialized
}
// 2. Define seed data
const data: YourType[] = [
// ... your data
]
// 3. Add to database
for (const item of data) {
await Database.addYourData(item)
}
}
```
## Module Details
### `index.ts` - Orchestrator
Controls initialization order and re-exports everything:
```typescript
export * from './pages'
export * from './components'
export * from './workflows'
export * from './scripts'
export * from './users'
export * from './packages'
export async function initializeAllSeedData() {
await initializeUsers() // Foundation
await initializeComponents() // UI building blocks
await initializeScripts() // Logic
await initializeWorkflows() // Processes
await initializePages() // Assembled pages
await initializePackages() // Ecosystem
}
```
**Why this order?**
- Users first (authentication required by everything)
- Components next (building blocks for pages)
- Scripts (logic used by pages and workflows)
- Workflows (processes that connect everything)
- Pages (assemble components, scripts, workflows)
- Packages (bring in external functionality)
### `users.ts` - User Management
```typescript
import { Database, hashPassword } from '@/lib/database'
import type { User } from '@/lib/level-types'
import { getScrambledPassword } from '@/lib/auth'
export async function initializeUsers() {
const existingUsers = await Database.getUsers()
if (existingUsers.length > 0) {
return
}
const users: User[] = [
{
id: 'user_supergod',
username: 'supergod',
email: 'supergod@metabuilder.local',
role: 'supergod',
createdAt: Date.now(),
isInstanceOwner: true,
},
{
id: 'user_admin',
username: 'admin',
email: 'admin@metabuilder.local',
role: 'admin',
createdAt: Date.now(),
},
// Add more users...
]
for (const user of users) {
const scrambledPassword = getScrambledPassword(user.username)
const passwordHash = await hashPassword(scrambledPassword)
await Database.setCredential(user.username, passwordHash)
await Database.setFirstLoginFlag(user.username, true)
await Database.addUser(user)
}
// Set credentials expiry
await Database.setGodCredentialsExpiry(Date.now() + 60 * 60 * 1000)
}
```
**What it handles:**
- User accounts (supergod, god, admin, users)
- Password hashing
- First-login flags
- Credentials expiry
### `components.ts` - Component Configurations
```typescript
import { Database } from '@/lib/database'
import type { ComponentConfig } from '@/lib/database'
export async function initializeComponents() {
const existingConfigs = await Database.getComponentConfigs()
if (Object.keys(existingConfigs).length > 0) {
return
}
const componentConfigs: ComponentConfig[] = [
{
id: 'config_hero_heading',
componentId: 'node_hero_heading',
props: {
level: 1,
children: 'Welcome to MetaBuilder',
className: 'text-6xl font-bold mb-4',
},
styles: {},
events: {},
},
{
id: 'config_cta_button',
componentId: 'node_cta_button',
props: {
children: 'Get Started',
variant: 'primary',
size: 'lg',
},
styles: {},
events: {
onClick: 'script_navigate_dashboard'
},
},
// Add more configs...
]
for (const config of componentConfigs) {
await Database.addComponentConfig(config)
}
}
```
**What it handles:**
- Component props
- Styling configuration
- Event handlers
- Conditional rendering rules
### `scripts.ts` - Lua Scripts
```typescript
import { Database } from '@/lib/database'
import type { LuaScript } from '@/lib/level-types'
export async function initializeScripts() {
const existingScripts = await Database.getLuaScripts()
if (existingScripts.length > 0) {
return
}
const scripts: LuaScript[] = [
{
id: 'script_welcome_message',
name: 'Welcome Message Generator',
description: 'Generates personalized welcome message',
code: `
function generateWelcome(username)
return "Welcome back, " .. username .. "!"
end
return generateWelcome
`,
parameters: [
{ name: 'username', type: 'string' }
],
returnType: 'string',
},
{
id: 'script_validate_email',
name: 'Email Validator',
description: 'Validates email format',
code: `
function validateEmail(email)
if not email then return false end
local pattern = "^[%w%._%%-]+@[%w%._%%-]+%.%w+$"
return string.match(email, pattern) ~= nil
end
return validateEmail
`,
parameters: [
{ name: 'email', type: 'string' }
],
returnType: 'boolean',
},
// Add more scripts...
]
for (const script of scripts) {
await Database.addLuaScript(script)
}
}
```
**What it handles:**
- Business logic (Lua functions)
- Validation rules
- Data transformations
- Permission checks
- Analytics tracking
- Custom calculations
### `workflows.ts` - Process Definitions
```typescript
import { Database } from '@/lib/database'
import type { Workflow } from '@/lib/level-types'
export async function initializeWorkflows() {
const existingWorkflows = await Database.getWorkflows()
if (existingWorkflows.length > 0) {
return
}
const workflows: Workflow[] = [
{
id: 'workflow_user_registration',
name: 'User Registration Flow',
description: 'Handles new user registration',
enabled: true,
nodes: [
{
id: 'validate',
type: 'condition',
label: 'Validate Input',
config: { scriptId: 'script_validate_email' },
position: { x: 100, y: 100 }
},
{
id: 'create',
type: 'action',
label: 'Create User',
config: { action: 'create_user' },
position: { x: 100, y: 200 }
},
{
id: 'notify',
type: 'action',
label: 'Send Welcome Email',
config: { action: 'send_email' },
position: { x: 100, y: 300 }
}
],
edges: [
{ id: 'e1', source: 'validate', target: 'create', label: 'valid' },
{ id: 'e2', source: 'create', target: 'notify', label: 'success' }
]
},
// Add more workflows...
]
for (const workflow of workflows) {
await Database.addWorkflow(workflow)
}
}
```
**What it handles:**
- Multi-step processes
- Conditional logic flows
- Error handling paths
- Integration points
- State machines
### `pages.ts` - Page Definitions
```typescript
import { Database } from '@/lib/database'
import { getPageDefinitionBuilder } from '@/lib/page-definition-builder'
export async function initializePages() {
const existingPages = await Database.getPages()
if (existingPages.length > 0) {
return
}
// Use the builder to create default pages
const builder = getPageDefinitionBuilder()
await builder.initializeDefaultPages()
// Or add custom pages directly
/*
const customPages: PageDefinition[] = [
{
id: 'page_custom',
level: 2,
title: 'Custom Page',
layout: 'dashboard',
components: [ /* component tree *\/ ],
permissions: { requiresAuth: true }
}
]
for (const page of customPages) {
await Database.addPage(page)
}
*/
}
```
**What it handles:**
- Page structures
- Layout selection
- Component trees
- Permission requirements
- Lua script bindings
### `packages.ts` - Package System
```typescript
import { initializePackageSystem } from '@/lib/package-loader'
export async function initializePackages() {
// Initialize the package system
await initializePackageSystem()
// Optionally auto-install default packages
/*
const defaultPackages = [
'irc-webchat',
'forum',
'blog'
]
for (const pkg of defaultPackages) {
await PackageManager.install(pkg)
}
*/
}
```
**What it handles:**
- Package system initialization
- Auto-install default packages
- Package dependency resolution
## Scaling to Large Datasets
### Strategy 1: Split by Category
```
/src/seed-data/
├── index.ts
├── users/
│ ├── index.ts
│ ├── admins.ts # Admin users
│ ├── moderators.ts # Mod users
│ └── regular.ts # Regular users
├── scripts/
│ ├── index.ts
│ ├── validation.ts # Validation scripts
│ ├── business.ts # Business logic
│ └── utilities.ts # Utility functions
└── pages/
├── index.ts
├── level1.ts # Level 1 pages
├── level2.ts # Level 2 pages
└── level3.ts # Level 3 pages
```
### Strategy 2: Split by Feature
```
/src/seed-data/
├── index.ts
├── features/
│ ├── forum/
│ │ ├── pages.ts
│ │ ├── components.ts
│ │ └── scripts.ts
│ ├── blog/
│ │ ├── pages.ts
│ │ ├── components.ts
│ │ └── scripts.ts
│ └── chat/
│ ├── pages.ts
│ ├── components.ts
│ └── scripts.ts
```
### Strategy 3: Split by Size
When a file gets too large (>500 lines), split it:
```typescript
// scripts.ts gets big, so split it:
// scripts/index.ts
export * from './validation'
export * from './business'
export * from './utilities'
export async function initializeScripts() {
await initializeValidationScripts()
await initializeBusinessScripts()
await initializeUtilityScripts()
}
// scripts/validation.ts
export async function initializeValidationScripts() {
// 20 validation scripts
}
// scripts/business.ts
export async function initializeBusinessScripts() {
// 30 business logic scripts
}
// scripts/utilities.ts
export async function initializeUtilityScripts() {
// 25 utility scripts
}
```
## Testing Modules
Each module can be tested independently:
```typescript
import { describe, it, expect, beforeEach } from 'vitest'
import { initializeUsers } from '@/seed-data/users'
import { Database } from '@/lib/database'
describe('User Seed Data', () => {
beforeEach(async () => {
// Clear database
await Database.setUsers([])
})
it('should initialize users', async () => {
await initializeUsers()
const users = await Database.getUsers()
expect(users).toHaveLength(5)
expect(users[0].username).toBe('supergod')
expect(users[0].role).toBe('supergod')
})
it('should not reinitialize if users exist', async () => {
await initializeUsers()
const firstUsers = await Database.getUsers()
await initializeUsers() // Call again
const secondUsers = await Database.getUsers()
expect(secondUsers).toEqual(firstUsers)
})
})
```
## Development Workflow
### Adding New Seed Data
1. **Choose the right module** (or create new one)
2. **Add your data** to the array
3. **Test locally** - delete KV data and refresh
4. **Commit** with descriptive message
### Modifying Existing Data
1. **Find the data** in appropriate module
2. **Update the definition**
3. **Clear database** (or increment version)
4. **Test** to ensure it works
### Creating New Module
1. **Create file** in `/src/seed-data/`
2. **Follow the pattern**:
```typescript
export async function initializeYourFeature() {
// Check if exists
// Define data
// Add to database
}
```
3. **Add to index.ts**:
```typescript
export * from './your-feature'
export async function initializeAllSeedData() {
// ... existing modules
await initializeYourFeature()
}
```
4. **Test** independently
## Best Practices
### 1. Keep Modules Focused
Each module should handle one concern only.
❌ Bad:
```typescript
// users.ts
export async function initializeUsers() {
// Initialize users
// Initialize pages
// Initialize scripts
// Everything mixed together
}
```
✅ Good:
```typescript
// users.ts
export async function initializeUsers() {
// Only user-related initialization
}
```
### 2. Check Before Adding
Always check if data exists to avoid duplicates.
```typescript
const existing = await Database.getUsers()
if (existing.length > 0) {
return // Already initialized
}
```
### 3. Use Descriptive IDs
Make IDs self-documenting:
❌ Bad: `'script_1'`, `'page_abc'`
✅ Good: `'script_validate_email'`, `'page_user_dashboard'`
### 4. Add Comments
Explain complex logic:
```typescript
const scripts: LuaScript[] = [
{
id: 'script_complex_calculation',
name: 'Complex Calculation',
description: 'Calculates X using Y algorithm',
// This script implements the Z algorithm from paper ABC
// Input: array of numbers
// Output: weighted average with outlier removal
code: `
-- Implementation details
`,
// ...
}
]
```
### 5. Version Your Data
Add version fields for migrations:
```typescript
{
id: 'page_dashboard',
version: 2, // Incremented when structure changes
title: 'Dashboard',
// ...
}
```
## Common Patterns
### Pattern: Conditional Initialization
```typescript
export async function initializeUsers() {
const existing = await Database.getUsers()
// Always add supergod if missing
const hasSuperGod = existing.some(u => u.role === 'supergod')
if (!hasSuperGod) {
await Database.addUser({
id: 'user_supergod',
username: 'supergod',
role: 'supergod',
// ...
})
}
// Add demo users only in development
if (process.env.NODE_ENV === 'development') {
await addDemoUsers()
}
}
```
### Pattern: Reference Other Data
```typescript
export async function initializePages() {
// Load scripts first
const scripts = await Database.getLuaScripts()
const welcomeScript = scripts.find(s => s.id === 'script_welcome_message')
// Reference in page
const pages: PageDefinition[] = [
{
id: 'page_dashboard',
luaScripts: {
onLoad: welcomeScript?.id
},
// ...
}
]
}
```
### Pattern: Generated Data
```typescript
export async function initializeUsers() {
// Generate 100 test users
const users: User[] = []
for (let i = 1; i <= 100; i++) {
users.push({
id: `user_test_${i}`,
username: `testuser${i}`,
email: `test${i}@example.com`,
role: 'user',
createdAt: Date.now(),
})
}
for (const user of users) {
await Database.addUser(user)
}
}
```
## Troubleshooting
### Data Not Appearing
1. Check if initialization runs: add `console.log()` in module
2. Verify database is clear: check KV store
3. Ensure correct order: dependencies initialized first
### Duplicate Data
1. Check early return: `if (existing.length > 0) return`
2. Clear database: delete all KV keys
3. Use unique IDs: ensure no ID conflicts
### Performance Issues
1. Batch operations: use transactions if available
2. Lazy load: don't load everything at once
3. Split modules: break large files into smaller ones
## Conclusion
The modular seed data system provides:
- ✅ Clear organization
- ✅ Easy maintenance
- ✅ Independent testing
- ✅ Scalable to massive datasets
- ✅ Feature-based isolation
Follow these patterns and your seed data will stay maintainable even as it grows to thousands of lines.
---
*Last updated: Iteration 25*

View File

@@ -1,136 +0,0 @@
# Documentation Organization Complete ✅
## What Was Done
All documentation files from the project root have been prepared for organization into the `/docs` folder with a clear, logical structure.
## Files Created
1. **`/docs/RELOCATION_SUMMARY.md`** - Overview of the relocation process
2. **`/docs/FILE_RELOCATION_GUIDE.md`** - Detailed step-by-step guide
3. **`/move-docs.sh`** - Automated bash script to execute the move
4. **Updated `/docs/README.md`** - Reflects new organized structure
## How to Execute
### Quick Method (Recommended)
```bash
# Make the script executable
chmod +x move-docs.sh
# Run it
./move-docs.sh
```
The script will:
- ✅ Create organized subdirectories in `/docs`
- ✅ Move all 24 documentation files to appropriate locations
- ✅ Provide progress feedback
- ✅ Show a summary of results
### Manual Method
If you prefer to move files manually, follow the detailed instructions in `/docs/FILE_RELOCATION_GUIDE.md`.
## New Structure
After running the script, documentation will be organized as:
```
docs/
├── architecture/ # System design (3 files)
├── database/ # Database docs (1 file)
├── development/ # Dev guides (3 files)
├── iterations/ # Project history (5 files)
├── lua/ # Lua integration (2 files)
├── packages/ # Package system (6 files)
├── reference/ # Quick reference (3 files)
└── security/ # Security (1 file)
```
## Files That Stay in Root
These essential files remain in the project root:
- `README.md` - Main project overview
- `PRD.md` - Product requirements
- `LICENSE` - Project license
- `SECURITY.md` - Security policy
## Documentation Moved (24 files)
### Iteration History (5 files)
- COMPLETE_ITERATION_25.md → docs/iterations/iteration-25-complete.md
- ITERATION_24_SUMMARY.md → docs/iterations/iteration-24-summary.md
- ITERATION_25_SUMMARY.md → docs/iterations/iteration-25-summary.md
- ITERATION_26_SUMMARY.md → docs/iterations/iteration-26-summary.md
- THE_TRANSFORMATION.md → docs/iterations/the-transformation.md
### Architecture (3 files)
- DATA_DRIVEN_ARCHITECTURE.md → docs/architecture/data-driven-architecture.md
- DECLARATIVE_COMPONENTS.md → docs/architecture/declarative-components.md
- GENERIC_PAGE_SYSTEM.md → docs/architecture/generic-page-system.md
### Packages (6 files)
- PACKAGE_SYSTEM.md → docs/packages/package-system.md
- PACKAGE_IMPORT_EXPORT.md → docs/packages/import-export.md
- PACKAGE_SCRIPTS_GUIDE.md → docs/packages/scripts-guide.md
- MODULAR_PACKAGES_GUIDE.md → docs/packages/modular-packages-guide.md
- MODULAR_SEED_DATA_GUIDE.md → docs/packages/modular-seed-data-guide.md
- IRC_CONVERSION_GUIDE.md → docs/packages/irc-conversion-guide.md
### Lua (2 files)
- LUA_INTEGRATION.md → docs/lua/integration.md
- LUA_SNIPPETS_GUIDE.md → docs/lua/snippets-guide.md
### Development (3 files)
- TYPESCRIPT_REDUCTION_GUIDE.md → docs/development/typescript-reduction-guide.md
- CRUFT_REMOVAL_REPORT.md → docs/development/cruft-removal-report.md
- IMPROVEMENTS.md → docs/development/improvements.md
### Database (1 file)
- DATABASE.md → docs/database/overview.md
### Security (1 file)
- SECURITY_GUIDE.md → docs/security/guide.md
### Reference (3 files)
- QUICK_REFERENCE.md → docs/reference/quick-reference.md
- DOCUMENTATION_INDEX.md → docs/reference/documentation-index.md
- PLATFORM_GUIDE.md → docs/reference/platform-guide.md
## Benefits
**Cleaner Root** - Only essential files in project root
**Better Organization** - Related docs grouped together
**Easier Navigation** - Clear category structure
**Scalable** - Easy to add new docs
**Professional** - Follows documentation best practices
## Verification
After running the script, verify with:
```bash
# Check root - should only show key files
ls *.md
# Expected:
# README.md
# PRD.md
# SECURITY.md
# View organized docs
ls docs/*/
```
## Next Steps
1. ✅ Run `./move-docs.sh` to complete the organization
2. ✅ Verify the new structure
3. ✅ Update any broken links in README.md or PRD.md
4. ✅ (Optional) Delete `move-docs.sh` after successful move
---
**Ready to execute!** Run `./move-docs.sh` to organize all documentation.

View File

@@ -1,264 +0,0 @@
# Package Import/Export Guide
## Overview
The MetaBuilder Package Import/Export system allows you to package and share complete applications, features, or database snapshots as ZIP files. This enables modular development and easy distribution of pre-built functionality.
## Features
### Export Capabilities
1. **Custom Package Export**
- Create reusable packages with selected components
- Include or exclude specific data types
- Add metadata (name, version, author, description, tags)
- Automatic README generation
2. **Database Snapshot Export**
- Complete backup of entire database
- One-click export with timestamp
- Includes all schemas, pages, workflows, scripts, and configurations
3. **Selective Export Options**
- ✅ Data schemas
- ✅ Page configurations
- ✅ Workflows
- ✅ Lua scripts
- ✅ Component hierarchies
- ✅ Component configurations
- ✅ CSS classes
- ✅ Dropdown configurations
- ✅ Seed data
- ✅ Assets (images, videos, audio, documents)
### Import Capabilities
1. **Package Installation**
- Import packages from ZIP files
- Automatic validation of package structure
- Merge with existing data
- Asset restoration
2. **Safety Features**
- Package validation before import
- Non-destructive merging (adds to existing data)
- Import warnings and confirmations
## ZIP Package Structure
```
package-name-1.0.0.zip
├── manifest.json # Package metadata
├── content.json # Database content
├── README.md # Auto-generated documentation
└── assets/ # Asset files
├── asset-manifest.json
├── images/
│ └── *.png, *.jpg, *.svg
├── videos/
│ └── *.mp4, *.webm
├── audios/
│ └── *.mp3, *.wav
└── documents/
└── *.pdf, *.txt
```
### manifest.json
```json
{
"id": "pkg_1234567890",
"name": "My Package",
"version": "1.0.0",
"description": "Package description",
"author": "Your Name",
"category": "social",
"icon": "📦",
"screenshots": [],
"tags": ["tag1", "tag2"],
"dependencies": [],
"createdAt": 1234567890,
"updatedAt": 1234567890,
"downloadCount": 0,
"rating": 0,
"installed": false
}
```
### content.json
```json
{
"schemas": [...],
"pages": [...],
"workflows": [...],
"luaScripts": [...],
"componentHierarchy": {...},
"componentConfigs": {...},
"cssClasses": [...],
"dropdownConfigs": [...],
"seedData": {...}
}
```
## Usage
### Exporting a Package
1. Navigate to **Level 4 (God Panel)** or **Level 5 (Super God Panel)**
2. Open **Package Manager**
3. Click **Export** button
4. Choose export type:
- **Custom Package**: Configure metadata and select what to include
- **Full Snapshot**: Export everything instantly
5. For custom packages:
- Fill in package name (required)
- Add version, author, description
- Add tags for searchability
- Select export options (checkboxes)
6. Click **Export Package**
7. ZIP file will download automatically
### Importing a Package
1. Navigate to **Level 4 (God Panel)** or **Level 5 (Super God Panel)**
2. Open **Package Manager**
3. Click **Import** button
4. Click the upload area or drag a ZIP file
5. Package will be validated and imported
6. Success message shows what was imported
7. Refresh the page if needed to see new content
## Pre-Built Packages
The system comes with several pre-built packages in the Package Catalog:
### 1. **Classic Forum** 💬
- Discussion threads and categories
- User profiles and moderation
- Schema: ForumCategory, ForumThread, ForumPost
### 2. **Retro Guestbook** 📖
- 90s-style visitor messages
- Custom backgrounds and GIFs
- Schema: GuestbookEntry
### 3. **Video Platform** 🎥
- Video upload and streaming
- Comments, likes, subscriptions
- Schema: Video, VideoComment, Subscription, Playlist
### 4. **Music Streaming Platform** 🎵
- Artists, albums, tracks
- Playlists and playback
- Schema: Artist, Album, Track, MusicPlaylist
### 5. **Retro Games Arcade** 🕹️
- Game collection with high scores
- Leaderboards and achievements
- Schema: Game, HighScore, Achievement, UserAchievement
### 6. **E-Commerce Store** 🛒
- Product catalog and inventory
- Shopping cart and orders
- Schema: Product, Cart, Order
## Best Practices
### For Package Authors
1. **Descriptive Naming**: Use clear, descriptive package names
2. **Versioning**: Follow semantic versioning (major.minor.patch)
3. **Documentation**: Add comprehensive descriptions and tags
4. **Dependencies**: List any required packages
5. **Testing**: Test your package before distribution
6. **Assets**: Include all necessary assets in the package
### For Package Users
1. **Backup First**: Export a database snapshot before importing new packages
2. **Review Contents**: Check package contents in Package Manager before installing
3. **Test in Development**: Test new packages in a development environment first
4. **Check Conflicts**: Be aware of potential schema or page ID conflicts
5. **Documentation**: Read the package README for setup instructions
## API Reference
### Export Functions
```typescript
import { exportPackageAsZip, downloadZip } from '@/lib/package-export'
// Export a custom package
const blob = await exportPackageAsZip(manifest, content, assets, options)
downloadZip(blob, 'package-name.zip')
// Export database snapshot
const blob = await exportDatabaseSnapshot(
schemas,
pages,
workflows,
luaScripts,
componentHierarchy,
componentConfigs,
cssClasses,
dropdownConfigs,
assets
)
```
### Import Functions
```typescript
import { importPackageFromZip } from '@/lib/package-export'
// Import from ZIP file
const { manifest, content, assets } = await importPackageFromZip(zipFile)
```
## Troubleshooting
### Import Fails
- **Invalid ZIP**: Ensure the ZIP file has the correct structure
- **Missing manifest.json**: Package must include a manifest file
- **Missing content.json**: Package must include content data
- **Corrupted File**: Try re-downloading or re-exporting the package
### Export Fails
- **No Package Name**: Package name is required for custom exports
- **No Data**: Ensure your database has data to export
- **Browser Memory**: Large exports may fail on low-memory devices
### Assets Not Working
- **Path Issues**: Asset paths are preserved from the original location
- **Missing Files**: Ensure all assets were included during export
- **Format Support**: Only specific formats are supported (see structure above)
## Future Enhancements
Planned features for future versions:
- 🔄 Package versioning and updates
- 🔍 Package marketplace/registry
- 🔐 Package signing and verification
- 📦 Dependency resolution
- 🎨 Custom package icons
- 📸 Package screenshots
- 💬 Package reviews and ratings
- 🔗 Remote package installation via URL
- 📊 Package analytics
## Support
For issues or questions:
- Check the console for error messages
- Verify ZIP file structure
- Ensure you have the latest version of MetaBuilder
- Review this documentation for proper usage
---
**Note**: The import/export system is designed to be non-destructive. Imported data is merged with existing data rather than replacing it. Always backup your database before major imports.

View File

@@ -1,394 +0,0 @@
# Package Scripts Organization Guide
## Overview
Packages can now organize Lua scripts in two ways:
1. **Legacy Single File**: A single `scripts.lua` file (backward compatible)
2. **Multi-File Structure**: Multiple organized Lua files in a `scripts/` subfolder (NEW)
Both formats are supported simultaneously. The system will load both if present.
---
## Multi-File Script Structure
### Folder Layout
```
packages/
└── your_package/
└── seed/
├── components.json
├── metadata.json
├── scripts.lua (optional - legacy support)
└── scripts/ (NEW - organized scripts)
├── manifest.json
├── init.lua
├── handlers.lua
├── validators.lua
├── utils.lua
└── [more files...]
```
---
## Script Manifest
The `scripts/manifest.json` file lists all Lua script files in the folder:
```json
{
"scripts": [
{
"file": "init.lua",
"name": "Initialization",
"category": "core",
"description": "Initialize component state and configuration"
},
{
"file": "handlers.lua",
"name": "Event Handlers",
"category": "handlers",
"description": "Handle user interactions and events"
},
{
"file": "validators.lua",
"name": "Form Validators",
"category": "validation",
"description": "Validate form data and display errors"
},
{
"file": "utils.lua",
"name": "Utilities",
"category": "utils",
"description": "Helper functions and utilities"
}
]
}
```
### Manifest Fields
- **file**: Filename of the Lua script (required)
- **name**: Human-readable name (optional, defaults to filename)
- **category**: Category for organization (optional)
- **description**: Brief description of the script's purpose (optional)
---
## Auto-Discovery (Fallback)
If no `manifest.json` exists, the system will automatically try to load common script filenames:
- `init.lua` - Initialization logic
- `handlers.lua` - Event handlers
- `validators.lua` - Validation functions
- `utils.lua` - Utility functions
- `state.lua` - State management
- `actions.lua` - Action functions
This allows quick prototyping without creating a manifest file.
---
## Recommended Script Organization
### 1. `init.lua` - Initialization
Contains functions for initializing component state and configuration.
```lua
-- Initialize component state
function my_component_init(config)
return {
isOpen = config.defaultOpen or false,
data = config.initialData or {},
errors = {}
}
end
```
### 2. `handlers.lua` - Event Handlers
Contains functions that respond to user interactions.
```lua
-- Handle form field changes
function my_component_handle_change(state, fieldName, value)
local newState = table_clone(state)
newState.data[fieldName] = value
return newState
end
-- Handle form submission
function my_component_handle_submit(state, validationRules)
-- Validation and submission logic
end
```
### 3. `validators.lua` - Validation Logic
Contains validation functions for forms and data.
```lua
-- Validate form data
function my_component_validate(state, rules)
local errors = {}
-- Validation logic here
return errors
end
-- Validate specific field types
function validate_email(email)
-- Email validation logic
end
function validate_password(password, minLength)
-- Password validation logic
end
```
### 4. `utils.lua` - Utility Functions
Contains reusable helper functions.
```lua
-- Deep clone a table
function table_clone(orig)
-- Clone logic
end
-- Merge two tables
function table_merge(t1, t2)
-- Merge logic
end
-- String utilities
function string_trim(str)
-- Trim logic
end
```
### 5. `state.lua` - State Management (optional)
Contains state management logic for complex components.
```lua
-- Create initial state
function create_initial_state()
return {}
end
-- State reducers
function state_reducer(state, action)
-- Reducer logic
end
```
### 6. `actions.lua` - Action Creators (optional)
Contains action creator functions for workflow integration.
```lua
-- Create action objects
function create_action(type, payload)
return {
type = type,
payload = payload
}
end
```
---
## Benefits of Multi-File Structure
### 1. **Better Organization**
- Separate concerns (initialization, validation, handlers)
- Easier to find specific functionality
- Cleaner file structure
### 2. **Improved Maintainability**
- Each file has a single responsibility
- Easier to update and debug
- Better version control diffs
### 3. **Team Collaboration**
- Multiple developers can work on different scripts
- Less merge conflicts
- Clear ownership of functionality
### 4. **Reusability**
- Share utility scripts across packages
- Import common validators
- Build script libraries
### 5. **Better Documentation**
- Manifest provides script metadata
- Each file can have focused comments
- Category-based organization
---
## Database Storage
Scripts from multi-file packages are stored individually in the database:
```javascript
// Legacy single file
{
id: "package_admin_dialog",
name: "Admin Dialog Scripts",
code: "...",
category: "package",
packageId: "admin_dialog"
}
// New multi-file format
{
id: "package_admin_dialog_init",
name: "Admin Dialog - Initialization",
code: "...",
category: "core",
packageId: "admin_dialog",
path: "scripts/init.lua",
description: "Initialize admin dialog state"
}
```
---
## Migration Guide
### Converting Single File to Multi-File
1. **Create scripts folder**:
```bash
mkdir packages/your_package/seed/scripts
```
2. **Split your scripts.lua** into logical files:
- Functions for initialization → `init.lua`
- Event handlers → `handlers.lua`
- Validators → `validators.lua`
- Utilities → `utils.lua`
3. **Create manifest.json**:
```json
{
"scripts": [
{"file": "init.lua", "name": "Initialization", "category": "core"},
{"file": "handlers.lua", "name": "Event Handlers", "category": "handlers"}
]
}
```
4. **Keep scripts.lua for backward compatibility** (optional)
---
## Example Package: Admin Dialog
The admin_dialog package demonstrates the multi-file structure:
```
packages/admin_dialog/seed/
├── scripts.lua (legacy - still works)
└── scripts/
├── manifest.json
├── init.lua (initialization)
├── handlers.lua (event handlers)
├── validators.lua (validation)
└── utils.lua (utilities)
```
### init.lua
- `admin_dialog_init()` - Create initial state
- `admin_dialog_open()` - Open dialog
- `admin_dialog_close()` - Close dialog
### handlers.lua
- `admin_dialog_handle_change()` - Handle field changes
- `admin_dialog_handle_submit()` - Handle form submission
- `admin_dialog_handle_cancel()` - Handle cancellation
### validators.lua
- `admin_dialog_validate()` - Validate form data
- `validate_email()` - Email validation
- `validate_password()` - Password validation
### utils.lua
- `table_clone()` - Deep clone tables
- `table_merge()` - Merge tables
- `string_trim()` - Trim strings
- Various helper functions
---
## Best Practices
1. **Keep files focused**: Each file should have a single purpose
2. **Use descriptive names**: File names should clearly indicate their purpose
3. **Document functions**: Add comments explaining what each function does
4. **Follow naming conventions**: Use consistent prefixes like `component_action_name`
5. **Avoid circular dependencies**: Structure code to minimize cross-file dependencies
6. **Test individually**: Each script should be testable on its own
7. **Use categories**: Group related scripts with category tags
---
## API Reference
### Loading Scripts (automatic)
Scripts are loaded automatically during package initialization:
```typescript
// In package-glue.ts
const scriptFiles = await loadLuaScriptsFolder('package_id')
// Returns: LuaScriptFile[]
```
### Accessing Scripts
```typescript
import { getPackageScriptFiles, getAllPackageScripts } from '@/lib/package-glue'
// Get individual script files
const scriptFiles = getPackageScriptFiles(packageDef)
// Get all scripts (legacy + new)
const allScripts = getAllPackageScripts(packageDef)
```
### LuaScriptFile Interface
```typescript
interface LuaScriptFile {
name: string // Script name
path: string // Relative path
code: string // Lua code
category?: string // Optional category
description?: string // Optional description
}
```
---
## Future Enhancements
- **Hot reloading**: Reload scripts without restarting
- **Script dependencies**: Declare dependencies between scripts
- **Script versioning**: Track script versions separately
- **Script testing**: Built-in testing framework for Lua scripts
- **Script marketplace**: Share individual scripts across packages
- **Script analytics**: Track which scripts are most used
---
## Support
For questions or issues with the multi-script system, refer to:
- [Lua Integration Guide](../LUA_INTEGRATION.md)
- [Package System Documentation](../PACKAGE_SYSTEM.md)
- [Modular Packages Guide](../MODULAR_PACKAGES_GUIDE.md)

View File

@@ -1,201 +0,0 @@
# Package System Architecture
This document describes the modular package system where each component lives in its own isolated folder structure with seed data, static content, and Lua scripts.
## Package Structure
Each package follows this structure:
```
/packages/{package_name}/
├── seed/
│ ├── components.json # Component hierarchy definitions
│ ├── scripts.lua # Lua logic for the component
│ └── metadata.json # Package metadata and exports
├── static_content/
│ ├── examples.json # Usage examples
│ ├── assets/ # Images, icons, etc.
│ └── docs.md # Documentation
└── README.md # Package overview
```
## Available Packages
### UI Components
#### admin_dialog
- **Purpose**: Reusable admin dialog with dynamic form fields and validation
- **Location**: `/packages/admin_dialog/`
- **Exports**: Dialog components, form validation scripts
- **Dependencies**: None
- **shadcn Components**: Dialog, DialogContent, DialogHeader, Button
#### data_table
- **Purpose**: Advanced data table with search, sort, filter, and CRUD
- **Location**: `/packages/data_table/`
- **Exports**: Table component, data manipulation scripts
- **Dependencies**: None
- **shadcn Components**: Table, Card, Input, Button
#### form_builder
- **Purpose**: Dynamic form builder with validation and field types
- **Location**: `/packages/form_builder/`
- **Exports**: Form components, validation scripts
- **Dependencies**: None
- **shadcn Components**: Card, Input, Textarea, Select, Switch, Checkbox
#### nav_menu
- **Purpose**: Responsive navigation menu with user section
- **Location**: `/packages/nav_menu/`
- **Exports**: Navigation components, routing scripts
- **Dependencies**: None
- **shadcn Components**: Button, Avatar
#### notification_center
- **Purpose**: Real-time notification center with filtering
- **Location**: `/packages/notification_center/`
- **Exports**: Notification components, state management scripts
- **Dependencies**: None
- **shadcn Components**: Button, Badge, Popover, ScrollArea
### Page Templates
#### dashboard
- **Purpose**: Customizable dashboard with stats and widgets
- **Location**: `/packages/dashboard/`
- **Exports**: Dashboard layout, widget system
- **Dependencies**: None
- **shadcn Components**: Card, Button
## Package Glue System
The package glue system (`src/lib/package-glue.ts`) is responsible for:
1. **Loading packages**: Import all package definitions from their folders
2. **Registry management**: Maintain a central registry of all packages
3. **Dependency resolution**: Check and resolve package dependencies
4. **Installation**: Install components and scripts into the database
5. **Export for seeding**: Generate seed data from all packages
### Usage
```typescript
import { buildPackageRegistry, installPackage } from '@/lib/package-glue'
// Build the registry
const registry = await buildPackageRegistry()
// Install a package
const result = await installPackage(registry, 'admin_dialog', db)
// Export all for seeding
const seedData = exportAllPackagesForSeed(registry)
```
## Creating New Packages
### Step 1: Create Package Structure
```bash
mkdir -p packages/my_package/seed
mkdir -p packages/my_package/static_content
```
### Step 2: Define Components
Create `packages/my_package/seed/components.json`:
```json
[
{
"id": "my_component_root",
"type": "div",
"props": {
"className": "container"
},
"children": ["my_component_child"]
}
]
```
### Step 3: Write Lua Scripts
Create `packages/my_package/seed/scripts.lua`:
```lua
function my_package_init(config)
return {
data = config.data or {}
}
end
function my_package_update(state, newData)
local newState = table_clone(state)
newState.data = newData
return newState
end
```
### Step 4: Define Metadata
Create `packages/my_package/seed/metadata.json`:
```json
{
"packageId": "my_package",
"name": "My Package",
"version": "1.0.0",
"description": "Description here",
"author": "MetaBuilder System",
"category": "ui-component",
"dependencies": [],
"exports": {
"components": ["my_component_root"],
"scripts": ["my_package_init", "my_package_update"]
}
}
```
### Step 5: Register in Glue
Update `src/lib/package-glue.ts`:
```typescript
import myPackageComponents from '../../packages/my_package/seed/components.json'
import myPackageMetadata from '../../packages/my_package/seed/metadata.json'
// In buildPackageRegistry():
const myPackageScripts = await loadLuaScript('my_package')
registry['my_package'] = {
...myPackageMetadata,
components: myPackageComponents,
scripts: myPackageScripts,
examples: {}
}
```
## Benefits
1. **Modularity**: Each package is self-contained and independent
2. **Reusability**: Packages can be easily imported and reused
3. **Maintainability**: Changes to one package don't affect others
4. **Scalability**: New packages can be added without modifying core code
5. **Distribution**: Packages can be exported as zip files for sharing
6. **Declarative**: Everything is defined in JSON and Lua, minimal TypeScript
## Package Categories
- `ui-component`: Reusable UI components
- `page-template`: Full page templates
- `feature`: Complete features (forum, chat, etc.)
- `utility`: Helper functions and utilities
- `integration`: Third-party integrations
## Future Enhancements
- Package versioning and updates
- Package marketplace
- Dependency version constraints
- Automated testing for packages
- Package CLI tools
- Hot-reloading of packages in development

View File

@@ -1,84 +0,0 @@
#!/bin/bash
# Documentation File Relocation Script
# This script organizes all documentation files from the project root into the /docs folder
set -e
# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
echo -e "${BLUE}📚 Starting documentation relocation...${NC}\n"
# Navigate to project root
cd "$(dirname "$0")/.."
# Create directory structure
echo -e "${BLUE}Creating directory structure...${NC}"
mkdir -p docs/iterations
mkdir -p docs/architecture
mkdir -p docs/packages
mkdir -p docs/lua
mkdir -p docs/development
mkdir -p docs/database
mkdir -p docs/security
mkdir -p docs/reference
# Move iteration history
echo -e "\n${BLUE}Moving iteration history files...${NC}"
[ -f "COMPLETE_ITERATION_25.md" ] && mv COMPLETE_ITERATION_25.md docs/iterations/iteration-25-complete.md && echo "✓ iteration-25-complete.md"
[ -f "ITERATION_24_SUMMARY.md" ] && mv ITERATION_24_SUMMARY.md docs/iterations/iteration-24-summary.md && echo "✓ iteration-24-summary.md"
[ -f "ITERATION_25_SUMMARY.md" ] && mv ITERATION_25_SUMMARY.md docs/iterations/iteration-25-summary.md && echo "✓ iteration-25-summary.md"
[ -f "ITERATION_26_SUMMARY.md" ] && mv ITERATION_26_SUMMARY.md docs/iterations/iteration-26-summary.md && echo "✓ iteration-26-summary.md"
[ -f "THE_TRANSFORMATION.md" ] && mv THE_TRANSFORMATION.md docs/iterations/the-transformation.md && echo "✓ the-transformation.md"
# Move architecture docs
echo -e "\n${BLUE}Moving architecture documentation...${NC}"
[ -f "DATA_DRIVEN_ARCHITECTURE.md" ] && mv DATA_DRIVEN_ARCHITECTURE.md docs/architecture/data-driven-architecture.md && echo "✓ data-driven-architecture.md"
[ -f "DECLARATIVE_COMPONENTS.md" ] && mv DECLARATIVE_COMPONENTS.md docs/architecture/declarative-components.md && echo "✓ declarative-components.md"
[ -f "GENERIC_PAGE_SYSTEM.md" ] && mv GENERIC_PAGE_SYSTEM.md docs/architecture/generic-page-system.md && echo "✓ generic-page-system.md"
# Move package docs
echo -e "\n${BLUE}Moving package documentation...${NC}"
[ -f "PACKAGE_SYSTEM.md" ] && mv PACKAGE_SYSTEM.md docs/packages/package-system.md && echo "✓ package-system.md"
[ -f "PACKAGE_IMPORT_EXPORT.md" ] && mv PACKAGE_IMPORT_EXPORT.md docs/packages/import-export.md && echo "✓ import-export.md"
[ -f "PACKAGE_SCRIPTS_GUIDE.md" ] && mv PACKAGE_SCRIPTS_GUIDE.md docs/packages/scripts-guide.md && echo "✓ scripts-guide.md"
[ -f "MODULAR_PACKAGES_GUIDE.md" ] && mv MODULAR_PACKAGES_GUIDE.md docs/packages/modular-packages-guide.md && echo "✓ modular-packages-guide.md"
[ -f "MODULAR_SEED_DATA_GUIDE.md" ] && mv MODULAR_SEED_DATA_GUIDE.md docs/packages/modular-seed-data-guide.md && echo "✓ modular-seed-data-guide.md"
[ -f "IRC_CONVERSION_GUIDE.md" ] && mv IRC_CONVERSION_GUIDE.md docs/packages/irc-conversion-guide.md && echo "✓ irc-conversion-guide.md"
# Move Lua docs
echo -e "\n${BLUE}Moving Lua documentation...${NC}"
[ -f "LUA_INTEGRATION.md" ] && mv LUA_INTEGRATION.md docs/lua/integration.md && echo "✓ integration.md"
[ -f "LUA_SNIPPETS_GUIDE.md" ] && mv LUA_SNIPPETS_GUIDE.md docs/lua/snippets-guide.md && echo "✓ snippets-guide.md"
# Move development docs
echo -e "\n${BLUE}Moving development documentation...${NC}"
[ -f "TYPESCRIPT_REDUCTION_GUIDE.md" ] && mv TYPESCRIPT_REDUCTION_GUIDE.md docs/development/typescript-reduction-guide.md && echo "✓ typescript-reduction-guide.md"
[ -f "CRUFT_REMOVAL_REPORT.md" ] && mv CRUFT_REMOVAL_REPORT.md docs/development/cruft-removal-report.md && echo "✓ cruft-removal-report.md"
[ -f "IMPROVEMENTS.md" ] && mv IMPROVEMENTS.md docs/development/improvements.md && echo "✓ improvements.md"
# Move database docs
echo -e "\n${BLUE}Moving database documentation...${NC}"
[ -f "DATABASE.md" ] && mv DATABASE.md docs/database/overview.md && echo "✓ overview.md"
# Move security docs
echo -e "\n${BLUE}Moving security documentation...${NC}"
[ -f "SECURITY_GUIDE.md" ] && mv SECURITY_GUIDE.md docs/security/guide.md && echo "✓ guide.md"
# Move reference docs
echo -e "\n${BLUE}Moving reference documentation...${NC}"
[ -f "QUICK_REFERENCE.md" ] && mv QUICK_REFERENCE.md docs/reference/quick-reference.md && echo "✓ quick-reference.md"
[ -f "DOCUMENTATION_INDEX.md" ] && mv DOCUMENTATION_INDEX.md docs/reference/documentation-index.md && echo "✓ documentation-index.md"
[ -f "PLATFORM_GUIDE.md" ] && mv PLATFORM_GUIDE.md docs/reference/platform-guide.md && echo "✓ platform-guide.md"
echo -e "\n${GREEN}✅ Documentation relocation complete!${NC}"
echo -e "\n${BLUE}Files remaining in root (expected):${NC}"
ls -1 *.md 2>/dev/null || echo "No markdown files in root (this is expected)"
echo -e "\n${BLUE}Documentation structure:${NC}"
tree docs/ -L 2 2>/dev/null || find docs/ -type f -name "*.md" | sort
echo -e "\n${GREEN}📁 All documentation is now organized in the /docs directory${NC}"