Opinionated TypeScript framework for structured vibecoding - building internal web and desktop apps with batteries included
npm install @episensor/app-frameworkA comprehensive, production-ready framework for building enterprise internal tools and applications with TypeScript, React, and real-time capabilities.
- API - Complete API documentation with best practices
- Development - How to build applications with the framework
- Architecture - System design and structure
- WebSocket - Real-time communication implementation
- Desktop - Desktop application support with Tauri
- Bundling - Desktop bundling guide
- AI - AI service integration
- Patterns - Proven architectural patterns
- Testing - Testing guidelines and patterns
- Logging - Logging system documentation
- Theme - Theme system and customization
- Ports - Port configuration standards
- CORS - Dynamic CORS middleware
#### Test Suite Overview
The framework includes extensive test coverage:
- Unit Tests: 362+ tests covering all core modules
- Integration Tests: API and service integration testing
- TestServer: Built-in test server for application testing
- Mock Services: Comprehensive mocking utilities
#### Running Tests
``bashRun all tests
npm test
#### Test Infrastructure
- Jest with TypeScript support
- Built-in TestServer class for app testing
- Mock implementations for all services
- Async operation handling
- Port management utilities
๐ Quick Start
`bash
Install framework
npm install @episensor/app-frameworkCreate your app
mkdir my-app && cd my-app
npm init -y
npm install @episensor/app-framework
`$3
`typescript
import { StandardServer } from "@episensor/app-framework";const server = new StandardServer({
appName: "My App",
appVersion: "1.0.0",
port: 8080,
enableWebSocket: true,
onInitialize: async (app) => {
app.get("/health", (req, res) => res.json({ status: "ok" }));
},
});
await server.initialize();
await server.start();
`โจ Core Features
$3
- StandardServer - Simplified server setup with Express
- Request Correlation - Automatic request IDs with structured request logging
- Safer Defaults - Request body limits, trust proxy, and sane HTTP timeouts
- Port Management - Automatic port conflict resolution
- Graceful Shutdown - Clean resource cleanup
- Health Checks - Real system metrics (CPU, memory, disk) - informational only
- Startup Banner - Professional application startup display
$3
- Dual Logger System - Simple console + production file logging
- Enhanced Logger - File rotation, compression, archiving
- Category-based Logging - Organize logs by service/module
- Log Management - Statistics, cleanup, migration utilities
- Flat Structure - All logs in
/data/logs for easy backup/restore$3
- WebSocketManager - Unified Socket.IO management with namespace support
- Redis Adapter - Optional Redis adapter for scaling
- Room Management - Built-in room join/leave handlers
- Client Tracking - Track connected clients across namespaces
- Broadcast Options - Selective broadcasting with compression/volatile options
- React Hooks -
useSocketIO, useConnectionStatus
- Connection Status - Monitor connection health$3
- Session Management - Express sessions with Redis support
- Authentication Middleware - Role-based access control
- Input Validation - Zod/Joi schema validation
- File Security - Safe file operations with validation
- CORS Configuration - Cross-origin resource sharing
$3
- Settings Service - Dynamic settings with UI generation
- Environment Merging Automatic env variable merging
- File Watching Auto-reload on config file changes
- Change Events EventEmitter for config change tracking
- Common Schemas Pre-built Zod schemas for common configs
$3
- HealthCheckService Real system metrics collection
- CPU Metrics Real CPU usage with history tracking
- Memory Metrics Memory usage percentage and details
- Disk Metrics Disk space monitoring (platform-aware)
- Process Metrics Node.js process statistics
- Custom Health Checks Extensible health check framework
- Dependency Checks Monitor external service health
- Informational Only Never interrupts service operation
$3
- Queue Service - Background job processing with persistence
- AI Service - Multi-provider AI integration (OpenAI, Claude)
- Port Utilities - Port availability checking and management
- File Handler - Secure file operations with MIME validation
- Network Service - Network interface discovery
- System Monitor - System resource monitoring
$3
#### Base Components (20+)
- Forms - Input, Select, Checkbox, Radio, Switch, Textarea
- Layout - Card, Dialog, Tabs, Accordion, Separator
- Data Display - Table, Badge, Alert, Progress, Avatar
- Navigation - Button, Dropdown, Context Menu, Navigation Menu
- Feedback - Toast, Tooltip, Popover, Alert Dialog
#### Advanced Components
- SettingsFramework - Complete settings UI with validation
- LogViewer - Real-time log display with filtering, stack coalescing, ANSI stripping, auto-refresh, archives, and per-level badges
- ConnectionStatus - WebSocket connection monitoring
- AppLayout - Standard application layout with navigation
- RealtimeDataTable - Live updating data tables
- DashboardStats - Metric display cards
- UpdateNotification - Application update notifications
> UI bundle note: the UI package now bundles ESM-heavy dependencies (
react-markdown, remark-gfm, react-syntax-highlighter) for better Jest/Node compatibility, and exports the new log viewer alongside the legacy variant. Use LogViewer for the advanced experience; LogViewerLegacy remains for backwards compatibility.$3
- TestServer - Standardized test server for integration tests
- Test Utilities - Request helpers, WebSocket testing
- Mock Services - Pre-configured mocks for services
$3
- Validation - Request/response validation
- Error Handling - Centralized error management
- File Upload - Secure file upload handling
- OpenAPI - Automatic API documentation
- Health Checks - Liveness/readiness probes
- Rate Limiting - API rate limiting
๐ฆ Installation
$3
`bash
npm install @episensor/app-framework
`$3
`javascript
// Backend
import { StandardServer, createLogger } from "@episensor/app-framework";// Frontend UI components
import { Button, Card, useSocketIO, useConnectionStatus } from "@episensor/app-framework/ui";
```๐ก Usage Examples
$3
`typescript
import { StandardServer, validate, createLogger } from '@episensor/app-framework';
import { z } from 'zod';const logger = createLogger('API');
const server = new StandardServer({
appName: 'REST API',
appVersion: '1.0.0',
onInitialize: async (app) => {
// Validation middleware
const userSchema = z.object({
name: z.string(),
email: z.string().email()
});
app.post('/api/users', validate(userSchema), async (req, res) => {
// Validated request body
const user = await createUser(req.body);
res.json({ success: true, data: user });
});
}
});
``$3
`typescript
import { StandardServer, getWebSocketServer } from "@episensor/app-framework";const server = new StandardServer({
appName: "Dashboard",
appVersion: "1.0.0",
enableWebSocket: true,
onStart: async () => {
const ws = getWebSocketServer();
// Stream metrics every second
setInterval(() => {
const metrics = collectMetrics();
ws.broadcast("metrics:update", metrics);
}, 1000);
},
});
`$3
`tsx
import { useSocketIO, useConnectionStatus } from "@episensor/app-framework/ui";function Dashboard() {
const [state, actions] = useSocketIO();
const { connected } = useConnectionStatus();
const [metrics, setMetrics] = useState([]);
useEffect(() => {
if (!connected) return;
const handler = (data) => setMetrics(data);
actions.on("metrics:update", handler);
return () => actions.off("metrics:update", handler);
}, [connected, actions]);
return ;
}
`$3
`typescript
import { QueueService } from "@episensor/app-framework";const queue = new QueueService({
concurrent: 5,
persistent: true,
});
queue.registerHandler("send-email", async (job) => {
await sendEmail(job.data);
});
await queue.addJob("send-email", {
to: "user@example.com",
subject: "Welcome!",
});
`$3
`typescript
import { SettingsService } from '@episensor/app-framework';const settings = new SettingsService();
settings.registerCategory({
id: 'general',
label: 'General Settings',
settings: [{
key: 'app.theme',
label: 'Theme',
type: 'select',
options: ['light', 'dark', 'auto'],
defaultValue: 'auto'
}]
});
// React component
categories={settings.getUISchema()}
onSave={async (values) => settings.update(values)}
/>
`$3
`typescript
import {
createHealthCheckRouter,
getHealthCheckService,
} from "@episensor/app-framework";// Add health check endpoints
const healthRouter = createHealthCheckRouter({
version: "1.0.0",
customChecks: [
{
name: "database",
check: async () => ({
name: "database",
status: (await db.ping()) ? "healthy" : "unhealthy",
}),
},
],
});
app.use("/api", healthRouter);
// Get real-time metrics
const healthService = getHealthCheckService();
const metrics = await healthService.getMetrics();
console.log(
CPU: ${metrics.cpu.usage}%, Memory: ${metrics.memory.percentage}%,
);
`$3
`typescript
import { SettingsService, CommonSettingsCategories } from "@episensor/app-framework";// Initialize settings service
const settings = new SettingsService({
filePath: "./settings.json",
categories: CommonSettingsCategories,
onSettingChange: async (key, value) => {
console.log(
Setting ${key} changed to ${value});
},
});await settings.initialize();
// Get setting value
const port = await settings.get("server.port");
// Update setting
await settings.set("server.port", 8080);
`$3
`typescript
import { getWebSocketManager } from "@episensor/app-framework";// Initialize WebSocket manager
const wsManager = getWebSocketManager({
cors: { origin: "http://localhost:3000" },
adapter: "redis", // Optional Redis scaling
redisUrl: process.env.REDIS_URL,
});
await wsManager.initialize(httpServer);
// Register namespace with handlers
wsManager.registerNamespace("/dashboard", {
subscribe: (socket, topic) => {
socket.join(
topic:${topic});
socket.emit("subscribed", { topic });
},
unsubscribe: (socket, topic) => {
socket.leave(topic:${topic});
},
});// Broadcast to specific rooms
wsManager.broadcast("update", data, {
namespace: "/dashboard",
room: "topic:metrics",
compress: true,
});
// Get connection stats
const stats = wsManager.getStats();
console.log(
Connected clients: ${stats.totalClients});
`๐๏ธ Architecture
`
Framework Structure:
โโโ Core Layer
โ โโโ StandardServer # Server management
โ โโโ Logger System # Logging infrastructure
โ โโโ Port Utilities # Port management
โ โโโ File Handler # Secure file operations
โโโ Service Layer
โ โโโ WebSocket Server # Real-time communication
โ โโโ Configuration # Config management
โ โโโ Queue Service # Job processing
โ โโโ AI Service # AI integration
โ โโโ Settings Service # Settings management
โโโ Middleware Layer
โ โโโ Authentication # Auth & sessions
โ โโโ Validation # Input validation
โ โโโ Error Handling # Error management
โ โโโ Health Checks # Health monitoring
โโโ UI Layer
โโโ Base Components # Core UI elements
โโโ Advanced Components # Complex UI patterns
โโโ Hooks # React hooks
โโโ Utilities # UI helpers
`๐ง Configuration
$3
`bash
Server
NODE_ENV=production
PORT=8080
HOST=0.0.0.0Logging
LOG_LEVEL=info
LOG_DIR=./logsSession
SESSION_SECRET=your-secret-keyDatabase
DATABASE_URL=postgresql://...Redis
REDIS_HOST=localhost
REDIS_PORT=6379AI Services (optional)
OPENAI_API_KEY=sk-...
CLAUDE_API_KEY=sk-ant-...WebSocket
WS_PING_INTERVAL=25000
WS_PING_TIMEOUT=60000
`$3
`json
// data/config/app.json
{
"server": {
"port": 8080,
"cors": {
"origins": ["http://localhost:3000"]
}
},
"features": {
"enableWebSocket": true,
"enableMetrics": true
}
}
`๐ TypeScript Support
Full TypeScript support with comprehensive type definitions:
`typescript
import type {
StandardServerConfig,
Logger,
WebSocketClient,
JobStatus,
SettingType,
ApiResponse,
ValidationSchema,
} from "@episensor/app-framework";import type {
ButtonProps,
TableColumn,
SettingCategory,
WebSocketHook,
} from "@episensor/app-framework/ui";
`๐งช Testing
`typescript
import { TestServer, setupTestServer } from "@episensor/app-framework";describe("API Tests", () => {
let server: TestServer;
beforeAll(async () => {
server = await setupTestServer({
setupApp: (app) => {
app.get("/test", (req, res) => res.json({ ok: true }));
},
});
});
test("endpoint works", async () => {
const res = await server.request("/test");
expect(res.body.ok).toBe(true);
});
});
`๐ Production Deployment
$3
`dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist/ ./dist/
ENV NODE_ENV=production
HEALTHCHECK CMD curl -f http://localhost:8080/health || exit 1
CMD ["node", "dist/index.js"]
`$3
`javascript
module.exports = {
apps: [
{
name: "my-app",
script: "./dist/index.js",
instances: "max",
exec_mode: "cluster",
env: {
NODE_ENV: "production",
},
},
],
};
`๐ ๏ธ Development Tools
- Hot Reload - Automatic restart on changes
- TypeScript - Full type safety
- ESLint - Code quality enforcement
- Prettier - Code formatting
- Jest - Testing framework
- Nodemon - Development server
๐ For AI Assistants
This framework is designed to be AI-friendly. When building applications:
1. Always use StandardServer - Never use deprecated StartupOrchestrator
2. Validate all inputs - Use zod schemas for validation
3. Handle errors properly - Use try-catch and error middleware
4. Use TypeScript - Define interfaces for all data structures
5. Follow the patterns - See Development Guide
๐ Security
- Input validation on all endpoints
- Secure session management
- File upload restrictions
- Rate limiting support
- CORS configuration
- Environment variable secrets
๐ ๏ธ Development Tools
$3
Monitor and manage all your running framework apps from the macOS menu bar.
- Real-time monitoring of all processes started with
dev-server
- Grouped by app with hierarchical view of backend/frontend/websocket processes
- Resource tracking - CPU, memory, uptime for each process
- Easy management - Kill individual processes or entire apps
- Lightweight - Built in Rust for minimal overhead#### Installation
`bash
Quick install (macOS)
curl -sSL https://raw.githubusercontent.com/EPISENSOR/epi-node-process-monitor/main/install.sh | bash
`Learn more: github.com/EPISENSOR/epi-node-process-monitor
๐ License
MIT License - see LICENSE for details
๐ค Support
- Documentation: See
/docs` folder for all guides---
Built with โค๏ธ by EpiSensor