LocalPing: self-hosted uptime monitor with static public status site
No files matched your search
@@ -0,0 +1,15 @@
|
||||
# Server Configuration
|
||||
API_PORT=8000
|
||||
NODE_ENV=production
|
||||
SESSION_SECRET=change_me_to_a_random_string
|
||||
|
||||
# Notification Settings
|
||||
NOTIFICATION_ENABLED=false
|
||||
NOTIFICATION_METHOD=dbus
|
||||
|
||||
# Monitoring
|
||||
PING_INTERVAL=60
|
||||
ALERT_COOLDOWN=300
|
||||
|
||||
# API Authentication
|
||||
ADMIN_API_KEY=localping-admin-key-12345
|
||||
@@ -0,0 +1,2 @@
|
||||
# Auto detect text files and perform LF normalization
|
||||
* text=auto
|
||||
@@ -0,0 +1,5 @@
|
||||
node_modules/
|
||||
.env
|
||||
data/
|
||||
logs/
|
||||
*.log
|
||||
@@ -0,0 +1,166 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
LocalPing is a self-hosted uptime monitoring system for homelabs. It monitors services using ICMP, TCP, UDP, HTTP/HTTPS protocols with real-time dashboards and historical tracking. Data is stored in PostgreSQL via Prisma ORM.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
# Development
|
||||
npm run dev # Start with nodemon (auto-reload)
|
||||
npm start # Start production server
|
||||
|
||||
# Database (Prisma)
|
||||
npm run prisma:generate # Generate Prisma client after schema changes
|
||||
npm run prisma:push # Push schema changes to database
|
||||
npm run prisma:studio # Open Prisma Studio GUI
|
||||
|
||||
# Testing
|
||||
npm test # Run all tests
|
||||
npm run test:watch # Run tests in watch mode
|
||||
npm run test:coverage # Run tests with coverage
|
||||
npm run test:backup # Run backup service tests only
|
||||
|
||||
# Production (PM2)
|
||||
npm run pm2:start # Start with PM2
|
||||
npm run pm2:stop # Stop all PM2 processes
|
||||
npm run pm2:restart # Restart all PM2 processes
|
||||
npm run pm2:logs # View PM2 logs
|
||||
|
||||
# Other
|
||||
npm run gui # Launch Electron GUI
|
||||
npm run web # Start in web-only mode
|
||||
npm run verify:ping # Verify ping data integrity
|
||||
```
|
||||
|
||||
### ICMP Capabilities (Linux)
|
||||
```bash
|
||||
sudo setcap cap_net_raw=ep $(which node)
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
### Entry Point & Server
|
||||
- `src/app.js` - Express server with WebSocket support, session management, route loading, and graceful shutdown handling
|
||||
|
||||
### Database Layer (Prisma)
|
||||
- `prisma/schema.prisma` - Database schema definition with 12 models
|
||||
- `src/config/prisma.js` - Prisma client singleton and connection management
|
||||
- `src/services/cacheService.js` - In-memory caching layer for database queries
|
||||
|
||||
### Core Services
|
||||
- `src/services/monitorService.js` - Central monitoring orchestrator. Manages ping intervals, status tracking (in-memory Map), alert cooldowns, and retry logic
|
||||
- `src/services/pingService.js` - Ping execution layer. Delegates to worker pool for multi-threaded pings
|
||||
- `src/services/workers/workerPool.js` - Thread pool manager (size: 2-8 based on CPU cores)
|
||||
- `src/services/workers/pingWorker.js` - Worker thread for executing individual pings
|
||||
|
||||
### Notification & Events
|
||||
- `src/services/notificationService.js` - Discord webhook notifications for monitor status changes and incidents
|
||||
- `src/services/eventDetectionService.js` - Rule-based event detection and auto-incident creation
|
||||
|
||||
### Routes
|
||||
- `src/routes/api.js` - REST API endpoints (`/api/*`) - requires API key auth
|
||||
- `src/routes/admin.js` - Admin panel routes (`/admin/*`) - requires session auth
|
||||
- `src/routes/public.js` - Public status page routes (`/`)
|
||||
- `src/routes/setup.js` - First-time setup wizard (`/setup`)
|
||||
|
||||
### Middleware
|
||||
- `src/middleware/auth.js` - API key validation, rate limiting, input validation
|
||||
- `src/middleware/setupCheck.js` - Redirects to setup wizard if not configured
|
||||
|
||||
### Views
|
||||
- `src/views/*.ejs` - EJS templates for admin panel, public dashboard, and setup wizard
|
||||
|
||||
## Database Schema (Prisma)
|
||||
|
||||
Models defined in `prisma/schema.prisma`:
|
||||
- `Target` - Monitor configurations (host, protocol, interval, etc.)
|
||||
- `PingResult` - Individual ping results with timestamps
|
||||
- `Statistic` - Daily aggregated statistics per target (unique on targetId + date)
|
||||
- `Alert` - Status change alerts
|
||||
- `Incident` - Manual/auto-created incidents
|
||||
- `EventRule` - Event detection rules for auto-incidents
|
||||
- `Action` - Target-specific actions
|
||||
- `Favicon` - Cached favicons for apps
|
||||
- `NotificationSettings` - Discord webhook configuration (singleton)
|
||||
- `AdminSettings` - Session duration, data retention, debug logging (singleton)
|
||||
- `PublicUISettings` - Public dashboard customization (singleton)
|
||||
- `Post` - Blog posts
|
||||
|
||||
## Key Patterns
|
||||
|
||||
### Monitor Status Flow
|
||||
1. `monitorService.startMonitoring()` loads enabled targets
|
||||
2. Each target gets an interval timer calling `pingTarget()`
|
||||
3. `pingService.ping()` delegates to worker pool
|
||||
4. Results stored via `prisma.pingResult.create()`
|
||||
5. Status changes trigger `notificationService` and `eventDetectionService`
|
||||
|
||||
### Database Query Pattern (Prisma)
|
||||
```javascript
|
||||
const { getPrisma } = require('../config/prisma');
|
||||
const prisma = getPrisma();
|
||||
|
||||
// Find all enabled targets
|
||||
const targets = await prisma.target.findMany({ where: { enabled: true } });
|
||||
|
||||
// Find by ID
|
||||
const target = await prisma.target.findUnique({ where: { id: targetId } });
|
||||
|
||||
// Create
|
||||
await prisma.pingResult.create({ data: { targetId, success: true, responseTime: 50 } });
|
||||
|
||||
// Update
|
||||
await prisma.target.update({ where: { id }, data: { name: 'New Name' } });
|
||||
|
||||
// Delete
|
||||
await prisma.target.delete({ where: { id } });
|
||||
|
||||
// Raw SQL (for complex queries)
|
||||
const result = await prisma.$queryRaw`SELECT * FROM targets WHERE enabled = true`;
|
||||
```
|
||||
|
||||
### Non-Blocking Design
|
||||
- Initial pings run in background (`setImmediate`, `Promise.allSettled`)
|
||||
- Database writes deferred with `setImmediate`
|
||||
- Worker pool prevents ping operations from blocking main thread
|
||||
|
||||
## Environment Variables
|
||||
|
||||
```env
|
||||
DATABASE_URL="postgresql://localping:localping@localhost:5432/localping"
|
||||
API_PORT=8000 # Server port
|
||||
SESSION_SECRET=... # Express session secret
|
||||
PING_INTERVAL=60 # Default ping interval (seconds)
|
||||
ALERT_COOLDOWN=300 # Alert cooldown (seconds)
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
Tests are in `__tests__/` directory using Jest:
|
||||
- `__tests__/services/backupService.test.js` - Export/import functionality
|
||||
- `__tests__/services/pingService.test.js` - Ping service tests
|
||||
|
||||
Run single test file:
|
||||
```bash
|
||||
npx jest __tests__/services/backupService.test.js
|
||||
```
|
||||
|
||||
## Migration Note
|
||||
|
||||
This codebase was migrated from a custom MongoDB-style PostgreSQL wrapper (`pg` package with `db.collection()` API) to Prisma ORM. Some route files may still contain legacy patterns that need to be updated to use the Prisma client.
|
||||
|
||||
Legacy pattern (to be replaced):
|
||||
```javascript
|
||||
const db = getDB();
|
||||
await db.collection('targets').find({}).toArray();
|
||||
```
|
||||
|
||||
New Prisma pattern:
|
||||
```javascript
|
||||
const prisma = getPrisma();
|
||||
await prisma.target.findMany();
|
||||
```
|
||||
@@ -0,0 +1,23 @@
|
||||
# LocalPing
|
||||
|
||||
Self-hosted uptime monitor for homelabs: ICMP/TCP/UDP/HTTP(S) checks, incident log, news posts, admin panel, and a fast static public status site.
|
||||
|
||||
## Install
|
||||
```bash
|
||||
git clone https://github.com/YOUR-ORG/localping.git && cd localping
|
||||
sudo ./install.sh # Ubuntu 22.04+: Node, Postgres, systemd service
|
||||
```
|
||||
Then open `http://<host>:8000/setup` to create the admin account.
|
||||
|
||||
## Public site
|
||||
The public frontend is plain HTML/CSS/JS in `src/site` (no build step, ~10 KB). It reads a slim JSON API (`/api/site/summary`, `/api/site/news`) and supports:
|
||||
- service **tiers** (featured / normal / background), per-service **explainers** (ⓘ) and a **public link** switch, edited in *Admin → Site*
|
||||
- custom **name, accent colour and app icon** (also used for the PWA manifest), in *Admin → Site*
|
||||
- `SITE_DIR=/path/to/theme` to serve your own theme; `SITE_HOSTS=status.example.com` to limit it to certain hostnames
|
||||
- `SITE_NAME`, `SITE_URL` env vars for RSS
|
||||
|
||||
Edit the About page and footer in `src/site`.
|
||||
|
||||
## Dev
|
||||
`npm install && npx prisma db push && npm run dev`. Tests: `npm test`.
|
||||
License: MIT.
|
||||
@@ -0,0 +1,710 @@
|
||||
// Mock uuid before requiring backupService
|
||||
jest.mock('uuid', () => ({
|
||||
v4: () => {
|
||||
return 'test-' + Math.random().toString(36).substr(2, 9) + '-' + Date.now();
|
||||
}
|
||||
}));
|
||||
|
||||
const backupService = require('../../src/services/backupService');
|
||||
const { getDB } = require('../../src/config/db');
|
||||
|
||||
// Simple UUID generator for tests
|
||||
function generateId() {
|
||||
return 'test-' + Math.random().toString(36).substr(2, 9) + '-' + Date.now();
|
||||
}
|
||||
|
||||
// Mock the database with shared state
|
||||
const mockCollections = {
|
||||
targets: [],
|
||||
incidents: [],
|
||||
posts: [],
|
||||
pingResults: [],
|
||||
statistics: [],
|
||||
actions: [],
|
||||
alerts: [],
|
||||
adminSettings: [],
|
||||
publicUISettings: [],
|
||||
favicons: []
|
||||
};
|
||||
|
||||
jest.mock('../../src/config/db', () => {
|
||||
|
||||
const createMockCollection = (name) => {
|
||||
return {
|
||||
find: (query = {}) => ({
|
||||
toArray: async () => {
|
||||
let results = mockCollections[name] || [];
|
||||
// Simple query matching
|
||||
if (Object.keys(query).length > 0) {
|
||||
results = results.filter(item => {
|
||||
return Object.keys(query).every(key => {
|
||||
if (query[key] && typeof query[key] === 'object' && '$in' in query[key]) {
|
||||
return query[key].$in.includes(item[key]);
|
||||
}
|
||||
return item[key] === query[key];
|
||||
});
|
||||
});
|
||||
}
|
||||
return results;
|
||||
}
|
||||
}),
|
||||
findOne: async (query = {}) => {
|
||||
const items = mockCollections[name] || [];
|
||||
if (Object.keys(query).length === 0) {
|
||||
return items[0] || null;
|
||||
}
|
||||
return items.find(item => {
|
||||
return Object.keys(query).every(key => item[key] === query[key]);
|
||||
}) || null;
|
||||
},
|
||||
insertOne: async (doc) => {
|
||||
if (!mockCollections[name]) {
|
||||
mockCollections[name] = [];
|
||||
}
|
||||
if (!doc._id) {
|
||||
// Generate a simple ID for testing
|
||||
doc._id = 'test-' + Math.random().toString(36).substr(2, 9) + '-' + Date.now();
|
||||
}
|
||||
mockCollections[name].push(doc);
|
||||
return { insertedId: doc._id };
|
||||
},
|
||||
updateOne: async (query, update) => {
|
||||
const items = mockCollections[name] || [];
|
||||
const index = items.findIndex(item => {
|
||||
return Object.keys(query).every(key => item[key] === query[key]);
|
||||
});
|
||||
if (index !== -1 && update.$set) {
|
||||
items[index] = { ...items[index], ...update.$set };
|
||||
return { modifiedCount: 1 };
|
||||
}
|
||||
return { modifiedCount: 0 };
|
||||
},
|
||||
deleteOne: async (query) => {
|
||||
const items = mockCollections[name] || [];
|
||||
const index = items.findIndex(item => {
|
||||
return Object.keys(query).every(key => item[key] === query[key]);
|
||||
});
|
||||
if (index !== -1) {
|
||||
items.splice(index, 1);
|
||||
return { deletedCount: 1 };
|
||||
}
|
||||
return { deletedCount: 0 };
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
getDB: () => ({
|
||||
collection: (name) => createMockCollection(name),
|
||||
query: async (sql, params) => {
|
||||
// Simple mock for SQL queries used in positions endpoint
|
||||
if (sql.includes('SELECT _id FROM targets WHERE _id IN')) {
|
||||
const targetIds = params;
|
||||
const targets = mockCollections.targets.filter(t => targetIds.includes(t._id));
|
||||
return { rows: targets.map(t => ({ _id: t._id })) };
|
||||
}
|
||||
return { rows: [] };
|
||||
}
|
||||
})
|
||||
};
|
||||
});
|
||||
|
||||
describe('BackupService', () => {
|
||||
let mockDB;
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
mockDB = getDB();
|
||||
// Clear all collections
|
||||
Object.keys(mockCollections).forEach(key => {
|
||||
mockCollections[key] = [];
|
||||
});
|
||||
});
|
||||
|
||||
describe('exportData', () => {
|
||||
it('should export full data when full option is true', async () => {
|
||||
// Setup test data
|
||||
const targetId = generateId();
|
||||
await mockDB.collection('targets').insertOne({
|
||||
_id: targetId,
|
||||
name: 'Test Target',
|
||||
host: 'example.com',
|
||||
protocol: 'HTTP',
|
||||
port: 80,
|
||||
auth: JSON.stringify({ username: 'test', password: 'pass' }),
|
||||
quickCommands: JSON.stringify(['cmd1', 'cmd2'])
|
||||
});
|
||||
|
||||
const result = await backupService.exportData({ full: true });
|
||||
|
||||
expect(result).toHaveProperty('version');
|
||||
expect(result).toHaveProperty('exportDate');
|
||||
expect(result).toHaveProperty('data');
|
||||
expect(result.data).toHaveProperty('targets');
|
||||
expect(result.data.targets).toHaveLength(1);
|
||||
expect(result.data.targets[0].name).toBe('Test Target');
|
||||
// Should parse JSON fields
|
||||
expect(typeof result.data.targets[0].auth).toBe('object');
|
||||
expect(Array.isArray(result.data.targets[0].quickCommands)).toBe(true);
|
||||
});
|
||||
|
||||
it('should export only monitors when monitors option is true', async () => {
|
||||
const targetId = generateId();
|
||||
await mockDB.collection('targets').insertOne({
|
||||
_id: targetId,
|
||||
name: 'Test Target',
|
||||
host: 'example.com'
|
||||
});
|
||||
|
||||
const result = await backupService.exportData({ monitors: true });
|
||||
|
||||
expect(result.data).toHaveProperty('targets');
|
||||
expect(result.data.targets).toHaveLength(1);
|
||||
expect(result.data).not.toHaveProperty('incidents');
|
||||
expect(result.data).not.toHaveProperty('posts');
|
||||
});
|
||||
|
||||
it('should export incidents when incidents option is true', async () => {
|
||||
const incidentId = generateId();
|
||||
await mockDB.collection('incidents').insertOne({
|
||||
_id: incidentId,
|
||||
title: 'Test Incident',
|
||||
status: 'investigating'
|
||||
});
|
||||
|
||||
const result = await backupService.exportData({ incidents: true });
|
||||
|
||||
expect(result.data).toHaveProperty('incidents');
|
||||
expect(result.data.incidents).toHaveLength(1);
|
||||
expect(result.data.incidents[0].title).toBe('Test Incident');
|
||||
});
|
||||
|
||||
it('should export posts when posts option is true', async () => {
|
||||
const postId = generateId();
|
||||
await mockDB.collection('posts').insertOne({
|
||||
_id: postId,
|
||||
title: 'Test Post',
|
||||
content: 'Test Content'
|
||||
});
|
||||
|
||||
const result = await backupService.exportData({ posts: true });
|
||||
|
||||
expect(result.data).toHaveProperty('posts');
|
||||
expect(result.data.posts).toHaveLength(1);
|
||||
expect(result.data.posts[0].title).toBe('Test Post');
|
||||
});
|
||||
|
||||
it('should export data points when dataPoints option is true', async () => {
|
||||
const pingId = generateId();
|
||||
const statId = generateId();
|
||||
await mockDB.collection('pingResults').insertOne({
|
||||
_id: pingId,
|
||||
targetId: generateId(),
|
||||
success: true,
|
||||
responseTime: 100
|
||||
});
|
||||
await mockDB.collection('statistics').insertOne({
|
||||
_id: statId,
|
||||
targetId: generateId(),
|
||||
date: new Date(),
|
||||
totalPings: 100
|
||||
});
|
||||
|
||||
const result = await backupService.exportData({ dataPoints: true });
|
||||
|
||||
expect(result.data).toHaveProperty('pingResults');
|
||||
expect(result.data).toHaveProperty('statistics');
|
||||
expect(result.data).toHaveProperty('ping_results'); // Legacy format
|
||||
expect(result.data).toHaveProperty('daily_stats'); // Legacy format
|
||||
expect(result.data.pingResults).toHaveLength(1);
|
||||
expect(result.data.statistics).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should export settings when settings option is true', async () => {
|
||||
await mockDB.collection('adminSettings').insertOne({
|
||||
_id: 'settings',
|
||||
sessionDurationDays: 30
|
||||
});
|
||||
await mockDB.collection('publicUISettings').insertOne({
|
||||
_id: 'settings',
|
||||
title: 'Test Title'
|
||||
});
|
||||
|
||||
const result = await backupService.exportData({ settings: true });
|
||||
|
||||
expect(result.data).toHaveProperty('adminSettings');
|
||||
expect(result.data).toHaveProperty('publicUISettings');
|
||||
expect(result.data.adminSettings.sessionDurationDays).toBe(30);
|
||||
expect(result.data.publicUISettings.title).toBe('Test Title');
|
||||
});
|
||||
|
||||
it('should parse JSON fields in targets correctly', async () => {
|
||||
const targetId = generateId();
|
||||
await mockDB.collection('targets').insertOne({
|
||||
_id: targetId,
|
||||
name: 'Test Target',
|
||||
auth: JSON.stringify({ username: 'user', password: 'pass' }),
|
||||
quickCommands: JSON.stringify(['cmd1', 'cmd2'])
|
||||
});
|
||||
|
||||
const result = await backupService.exportData({ monitors: true });
|
||||
|
||||
expect(typeof result.data.targets[0].auth).toBe('object');
|
||||
expect(result.data.targets[0].auth.username).toBe('user');
|
||||
expect(Array.isArray(result.data.targets[0].quickCommands)).toBe(true);
|
||||
expect(result.data.targets[0].quickCommands[0]).toBe('cmd1');
|
||||
});
|
||||
|
||||
it('should handle invalid JSON in auth field gracefully', async () => {
|
||||
const targetId = generateId();
|
||||
await mockDB.collection('targets').insertOne({
|
||||
_id: targetId,
|
||||
name: 'Test Target',
|
||||
auth: 'invalid json {'
|
||||
});
|
||||
|
||||
const result = await backupService.exportData({ monitors: true });
|
||||
|
||||
expect(result.data.targets[0].auth).toBeNull();
|
||||
});
|
||||
|
||||
it('should return empty arrays when collections are empty', async () => {
|
||||
const result = await backupService.exportData({ monitors: true });
|
||||
|
||||
expect(result.data.targets).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('importData', () => {
|
||||
it('should import targets successfully', async () => {
|
||||
const targetId = generateId();
|
||||
const importData = {
|
||||
data: {
|
||||
targets: [{
|
||||
_id: targetId,
|
||||
name: 'Imported Target',
|
||||
host: 'example.com',
|
||||
protocol: 'HTTP',
|
||||
port: 80,
|
||||
auth: { username: 'user', password: 'pass' },
|
||||
quickCommands: ['cmd1']
|
||||
}]
|
||||
}
|
||||
};
|
||||
|
||||
const result = await backupService.importData(importData);
|
||||
|
||||
expect(result.imported).toHaveProperty('targets');
|
||||
expect(result.imported.targets.imported).toBe(1);
|
||||
|
||||
// Verify target was imported
|
||||
const imported = await mockDB.collection('targets').findOne({ _id: targetId });
|
||||
expect(imported).toBeTruthy();
|
||||
expect(imported.name).toBe('Imported Target');
|
||||
// Auth should be stringified
|
||||
expect(typeof imported.auth).toBe('string');
|
||||
});
|
||||
|
||||
it('should skip existing targets when overwrite is false', async () => {
|
||||
const targetId = generateId();
|
||||
await mockDB.collection('targets').insertOne({
|
||||
_id: targetId,
|
||||
name: 'Existing Target',
|
||||
host: 'old.com'
|
||||
});
|
||||
|
||||
const importData = {
|
||||
data: {
|
||||
targets: [{
|
||||
_id: targetId,
|
||||
name: 'Existing Target',
|
||||
host: 'new.com'
|
||||
}]
|
||||
}
|
||||
};
|
||||
|
||||
const result = await backupService.importData(importData, { overwrite: false });
|
||||
|
||||
expect(result.imported.targets.skipped).toBe(1);
|
||||
|
||||
// Verify target was not updated
|
||||
const existing = await mockDB.collection('targets').findOne({ _id: targetId });
|
||||
expect(existing.host).toBe('old.com');
|
||||
});
|
||||
|
||||
it('should update existing targets when overwrite is true', async () => {
|
||||
const targetId = generateId();
|
||||
await mockDB.collection('targets').insertOne({
|
||||
_id: targetId,
|
||||
name: 'Existing Target',
|
||||
host: 'old.com'
|
||||
});
|
||||
|
||||
const importData = {
|
||||
data: {
|
||||
targets: [{
|
||||
_id: targetId,
|
||||
name: 'Existing Target',
|
||||
host: 'new.com'
|
||||
}]
|
||||
}
|
||||
};
|
||||
|
||||
const result = await backupService.importData(importData, { overwrite: true });
|
||||
|
||||
expect(result.imported.targets.updated).toBe(1);
|
||||
|
||||
// Verify target was updated
|
||||
const updated = await mockDB.collection('targets').findOne({ _id: targetId });
|
||||
expect(updated.host).toBe('new.com');
|
||||
});
|
||||
|
||||
it('should handle targets with same name but different ID', async () => {
|
||||
const existingId = generateId();
|
||||
const newId = generateId();
|
||||
await mockDB.collection('targets').insertOne({
|
||||
_id: existingId,
|
||||
name: 'Same Name',
|
||||
host: 'old.com'
|
||||
});
|
||||
|
||||
const importData = {
|
||||
data: {
|
||||
targets: [{
|
||||
_id: newId,
|
||||
name: 'Same Name',
|
||||
host: 'new.com'
|
||||
}]
|
||||
}
|
||||
};
|
||||
|
||||
const result = await backupService.importData(importData, { overwrite: true });
|
||||
|
||||
// Should update existing target with same name
|
||||
expect(result.imported.targets.updated).toBe(1);
|
||||
|
||||
const updated = await mockDB.collection('targets').findOne({ _id: existingId });
|
||||
expect(updated.host).toBe('new.com');
|
||||
});
|
||||
|
||||
it('should import incidents successfully', async () => {
|
||||
const incidentId = generateId();
|
||||
const importData = {
|
||||
data: {
|
||||
incidents: [{
|
||||
_id: incidentId,
|
||||
title: 'Imported Incident',
|
||||
status: 'investigating'
|
||||
}]
|
||||
}
|
||||
};
|
||||
|
||||
const result = await backupService.importData(importData);
|
||||
|
||||
expect(result.imported).toHaveProperty('incidents');
|
||||
expect(result.imported.incidents.imported).toBe(1);
|
||||
|
||||
const imported = await mockDB.collection('incidents').findOne({ _id: incidentId });
|
||||
expect(imported).toBeTruthy();
|
||||
expect(imported.title).toBe('Imported Incident');
|
||||
});
|
||||
|
||||
it('should import posts successfully', async () => {
|
||||
const postId = generateId();
|
||||
const importData = {
|
||||
data: {
|
||||
posts: [{
|
||||
_id: postId,
|
||||
title: 'Imported Post',
|
||||
content: 'Content'
|
||||
}]
|
||||
}
|
||||
};
|
||||
|
||||
const result = await backupService.importData(importData);
|
||||
|
||||
expect(result.imported).toHaveProperty('posts');
|
||||
expect(result.imported.posts.imported).toBe(1);
|
||||
});
|
||||
|
||||
it('should import pingResults successfully', async () => {
|
||||
const pingId = generateId();
|
||||
const targetId = generateId();
|
||||
const importData = {
|
||||
data: {
|
||||
pingResults: [{
|
||||
_id: pingId,
|
||||
targetId: targetId,
|
||||
success: true,
|
||||
responseTime: 100
|
||||
}]
|
||||
}
|
||||
};
|
||||
|
||||
const result = await backupService.importData(importData);
|
||||
|
||||
expect(result.imported).toHaveProperty('pingResults');
|
||||
expect(result.imported.pingResults.imported).toBe(1);
|
||||
});
|
||||
|
||||
it('should import statistics successfully', async () => {
|
||||
const statId = generateId();
|
||||
const targetId = generateId();
|
||||
const importData = {
|
||||
data: {
|
||||
statistics: [{
|
||||
_id: statId,
|
||||
targetId: targetId,
|
||||
date: new Date(),
|
||||
totalPings: 100
|
||||
}]
|
||||
}
|
||||
};
|
||||
|
||||
const result = await backupService.importData(importData);
|
||||
|
||||
expect(result.imported).toHaveProperty('statistics');
|
||||
expect(result.imported.statistics.imported).toBe(1);
|
||||
});
|
||||
|
||||
it('should import legacy ping_results format', async () => {
|
||||
const targetId = generateId();
|
||||
const importData = {
|
||||
data: {
|
||||
ping_results: [{
|
||||
targetId: targetId,
|
||||
success: 1,
|
||||
responseTime: 100,
|
||||
timestamp: new Date()
|
||||
}]
|
||||
}
|
||||
};
|
||||
|
||||
const result = await backupService.importData(importData);
|
||||
|
||||
expect(result.imported).toHaveProperty('ping_results');
|
||||
expect(result.imported.ping_results.imported).toBe(1);
|
||||
});
|
||||
|
||||
it('should import legacy daily_stats format', async () => {
|
||||
const targetId = generateId();
|
||||
const importData = {
|
||||
data: {
|
||||
daily_stats: [{
|
||||
targetId: targetId,
|
||||
date: new Date(),
|
||||
totalPings: 100,
|
||||
successfulPings: 95,
|
||||
avgResponseTime: 50
|
||||
}]
|
||||
}
|
||||
};
|
||||
|
||||
const result = await backupService.importData(importData);
|
||||
|
||||
expect(result.imported).toHaveProperty('daily_stats');
|
||||
expect(result.imported.daily_stats.imported).toBe(1);
|
||||
});
|
||||
|
||||
it('should import settings successfully', async () => {
|
||||
const importData = {
|
||||
data: {
|
||||
adminSettings: {
|
||||
_id: 'settings',
|
||||
sessionDurationDays: 60
|
||||
},
|
||||
publicUISettings: {
|
||||
_id: 'settings',
|
||||
title: 'New Title'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const result = await backupService.importData(importData);
|
||||
|
||||
expect(result.imported).toHaveProperty('adminSettings');
|
||||
expect(result.imported).toHaveProperty('publicUISettings');
|
||||
expect(result.imported.adminSettings.imported).toBe(1);
|
||||
expect(result.imported.publicUISettings.imported).toBe(1);
|
||||
});
|
||||
|
||||
it('should update settings when overwrite is true', async () => {
|
||||
await mockDB.collection('adminSettings').insertOne({
|
||||
_id: 'settings',
|
||||
sessionDurationDays: 30
|
||||
});
|
||||
|
||||
const importData = {
|
||||
data: {
|
||||
adminSettings: {
|
||||
_id: 'settings',
|
||||
sessionDurationDays: 60
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const result = await backupService.importData(importData, { overwrite: true });
|
||||
|
||||
expect(result.imported.adminSettings.updated).toBe(1);
|
||||
|
||||
const updated = await mockDB.collection('adminSettings').findOne({ _id: 'settings' });
|
||||
expect(updated.sessionDurationDays).toBe(60);
|
||||
});
|
||||
|
||||
it('should import favicons successfully', async () => {
|
||||
const faviconId = generateId();
|
||||
const importData = {
|
||||
data: {
|
||||
favicons: [{
|
||||
_id: faviconId,
|
||||
appUrl: 'https://example.com',
|
||||
favicon: 'data:image/png;base64,...'
|
||||
}]
|
||||
}
|
||||
};
|
||||
|
||||
const result = await backupService.importData(importData);
|
||||
|
||||
expect(result.imported).toHaveProperty('favicons');
|
||||
expect(result.imported.favicons.imported).toBe(1);
|
||||
});
|
||||
|
||||
it('should stringify object auth field when importing', async () => {
|
||||
const targetId = generateId();
|
||||
const importData = {
|
||||
data: {
|
||||
targets: [{
|
||||
_id: targetId,
|
||||
name: 'Test',
|
||||
auth: { username: 'user', password: 'pass' }
|
||||
}]
|
||||
}
|
||||
};
|
||||
|
||||
await backupService.importData(importData);
|
||||
|
||||
const imported = await mockDB.collection('targets').findOne({ _id: targetId });
|
||||
expect(typeof imported.auth).toBe('string');
|
||||
const parsed = JSON.parse(imported.auth);
|
||||
expect(parsed.username).toBe('user');
|
||||
});
|
||||
|
||||
it('should stringify array quickCommands when importing', async () => {
|
||||
const targetId = generateId();
|
||||
const importData = {
|
||||
data: {
|
||||
targets: [{
|
||||
_id: targetId,
|
||||
name: 'Test',
|
||||
quickCommands: ['cmd1', 'cmd2']
|
||||
}]
|
||||
}
|
||||
};
|
||||
|
||||
await backupService.importData(importData);
|
||||
|
||||
const imported = await mockDB.collection('targets').findOne({ _id: targetId });
|
||||
expect(typeof imported.quickCommands).toBe('string');
|
||||
const parsed = JSON.parse(imported.quickCommands);
|
||||
expect(Array.isArray(parsed)).toBe(true);
|
||||
expect(parsed[0]).toBe('cmd1');
|
||||
});
|
||||
|
||||
it('should throw error for invalid import data format', async () => {
|
||||
const importData = { invalid: 'format' };
|
||||
|
||||
await expect(backupService.importData(importData)).rejects.toThrow('Invalid import data format');
|
||||
});
|
||||
|
||||
it('should handle errors gracefully and continue with other imports', async () => {
|
||||
const targetId = generateId();
|
||||
const importData = {
|
||||
data: {
|
||||
targets: [{
|
||||
_id: targetId,
|
||||
name: 'Valid Target'
|
||||
}],
|
||||
incidents: [{
|
||||
// Missing required _id - this will cause an error when trying to insert
|
||||
title: 'Invalid Incident'
|
||||
}]
|
||||
}
|
||||
};
|
||||
|
||||
const result = await backupService.importData(importData);
|
||||
|
||||
// Targets should still be imported
|
||||
expect(result.imported.targets.imported).toBe(1);
|
||||
// Incidents import should either succeed (if _id is auto-generated) or have errors
|
||||
// The mock will auto-generate _id, so it might succeed. Let's check that targets were imported
|
||||
expect(result.imported.targets).toBeDefined();
|
||||
// If incidents failed, there should be errors, otherwise it should be imported
|
||||
if (result.errors.length > 0) {
|
||||
expect(result.errors.some(e => e.type === 'incidents')).toBe(true);
|
||||
} else {
|
||||
// If no errors, incidents should have been imported (with auto-generated _id)
|
||||
expect(result.imported.incidents).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('should skip duplicate pingResults', async () => {
|
||||
const pingId = generateId();
|
||||
const targetId = generateId();
|
||||
|
||||
await mockDB.collection('pingResults').insertOne({
|
||||
_id: pingId,
|
||||
targetId: targetId,
|
||||
success: true
|
||||
});
|
||||
|
||||
const importData = {
|
||||
data: {
|
||||
pingResults: [{
|
||||
_id: pingId,
|
||||
targetId: targetId,
|
||||
success: true
|
||||
}]
|
||||
}
|
||||
};
|
||||
|
||||
const result = await backupService.importData(importData);
|
||||
|
||||
expect(result.imported.pingResults.imported).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle round-trip export/import correctly', async () => {
|
||||
// Create test data
|
||||
const targetId = generateId();
|
||||
await mockDB.collection('targets').insertOne({
|
||||
_id: targetId,
|
||||
name: 'Round Trip Test',
|
||||
host: 'example.com',
|
||||
protocol: 'HTTP',
|
||||
port: 80,
|
||||
auth: JSON.stringify({ username: 'user', password: 'pass' }),
|
||||
quickCommands: JSON.stringify(['cmd1'])
|
||||
});
|
||||
|
||||
// Export
|
||||
const exported = await backupService.exportData({ monitors: true });
|
||||
|
||||
// Clear database
|
||||
await mockDB.collection('targets').deleteOne({ _id: targetId });
|
||||
|
||||
// Import
|
||||
const importResult = await backupService.importData(exported);
|
||||
|
||||
expect(importResult.imported.targets.imported).toBe(1);
|
||||
|
||||
// Verify data integrity
|
||||
const imported = await mockDB.collection('targets').findOne({ _id: targetId });
|
||||
expect(imported.name).toBe('Round Trip Test');
|
||||
expect(imported.host).toBe('example.com');
|
||||
// Auth should be stringified after import
|
||||
expect(typeof imported.auth).toBe('string');
|
||||
const parsedAuth = JSON.parse(imported.auth);
|
||||
expect(parsedAuth.username).toBe('user');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
jest.useFakeTimers();
|
||||
|
||||
jest.mock('../../src/services/pingService', () => ({
|
||||
ping: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock('../../src/services/notificationService', () => ({
|
||||
getMonitorDownDelayMinutes: jest.fn().mockResolvedValue(1),
|
||||
}));
|
||||
|
||||
jest.mock('../../src/config/prisma', () => ({
|
||||
getPrisma: () => ({
|
||||
adminSettings: { findUnique: jest.fn().mockResolvedValue({ debugLogging: false }) },
|
||||
pingResult: { create: jest.fn().mockResolvedValue({}) },
|
||||
statistic: {
|
||||
findUnique: jest.fn().mockResolvedValue(null),
|
||||
create: jest.fn().mockResolvedValue({}),
|
||||
update: jest.fn().mockResolvedValue({}),
|
||||
aggregate: jest.fn().mockResolvedValue({ _sum: { totalPings: 0, successfulPings: 0 } }),
|
||||
},
|
||||
alert: { create: jest.fn().mockResolvedValue({}) },
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('../../src/services/eventDetectionService', () => ({
|
||||
evaluateRules: jest.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
const pingService = require('../../src/services/pingService');
|
||||
const monitorService = require('../../src/services/monitorService');
|
||||
|
||||
const target = {
|
||||
id: 'monitor-delay-test',
|
||||
_id: 'monitor-delay-test',
|
||||
name: 'Delay test',
|
||||
host: 'example.test',
|
||||
protocol: 'HTTPS',
|
||||
interval: 60,
|
||||
retries: 0,
|
||||
};
|
||||
|
||||
function settle() {
|
||||
return Promise.resolve().then(() => Promise.resolve());
|
||||
}
|
||||
|
||||
describe('MonitorService sustained outage notifications', () => {
|
||||
beforeEach(() => {
|
||||
monitorService.stopAllMonitoring();
|
||||
monitorService.setNotificationDelayMinutes(1);
|
||||
monitorService.handleTargetDown = jest.fn().mockResolvedValue({});
|
||||
monitorService.handleTargetUp = jest.fn().mockResolvedValue({});
|
||||
pingService.ping.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
monitorService.stopAllMonitoring();
|
||||
});
|
||||
|
||||
it('does not notify for an outage that recovers before the delay', async () => {
|
||||
pingService.ping.mockResolvedValueOnce({ success: false, responseTime: null })
|
||||
.mockResolvedValueOnce({ success: true, responseTime: 12 });
|
||||
|
||||
await monitorService.pingTarget(target);
|
||||
await settle();
|
||||
jest.advanceTimersByTime(59 * 1000);
|
||||
await monitorService.pingTarget(target);
|
||||
jest.runOnlyPendingTimers();
|
||||
await settle();
|
||||
|
||||
expect(monitorService.handleTargetDown).not.toHaveBeenCalled();
|
||||
// Recovery is still recorded internally; only the external notification
|
||||
// is suppressed because the outage did not reach the configured delay.
|
||||
expect(monitorService.handleTargetUp).toHaveBeenCalledTimes(1);
|
||||
expect(monitorService.handleTargetUp).toHaveBeenCalledWith(
|
||||
target,
|
||||
12,
|
||||
expect.any(Number),
|
||||
false,
|
||||
);
|
||||
expect(monitorService.getNotificationState(target.id).notificationSent).toBe(false);
|
||||
});
|
||||
|
||||
it('sends one down notification after the configured delay and then one recovery notification', async () => {
|
||||
pingService.ping.mockResolvedValueOnce({ success: false, responseTime: null })
|
||||
.mockResolvedValueOnce({ success: true, responseTime: 18 });
|
||||
|
||||
await monitorService.pingTarget(target);
|
||||
await settle();
|
||||
expect(monitorService.handleTargetDown).not.toHaveBeenCalled();
|
||||
|
||||
jest.advanceTimersByTime(60 * 1000);
|
||||
await settle();
|
||||
expect(monitorService.handleTargetDown).toHaveBeenCalledTimes(1);
|
||||
|
||||
await monitorService.pingTarget(target);
|
||||
jest.runOnlyPendingTimers();
|
||||
await settle();
|
||||
expect(monitorService.handleTargetUp).toHaveBeenCalledTimes(1);
|
||||
expect(monitorService.handleTargetUp).toHaveBeenCalledWith(
|
||||
target,
|
||||
18,
|
||||
expect.any(Number),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the in-memory delay when the settings lookup fails', async () => {
|
||||
const notificationService = require('../../src/services/notificationService');
|
||||
notificationService.getMonitorDownDelayMinutes.mockRejectedValueOnce(new Error('database unavailable'));
|
||||
monitorService.setNotificationDelayMinutes(1);
|
||||
pingService.ping.mockResolvedValueOnce({ success: false, responseTime: null });
|
||||
|
||||
await monitorService.pingTarget(target);
|
||||
await settle();
|
||||
jest.advanceTimersByTime(60 * 1000);
|
||||
await settle();
|
||||
|
||||
expect(monitorService.handleTargetDown).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('reschedules an active outage when the global delay changes', async () => {
|
||||
const notificationService = require('../../src/services/notificationService');
|
||||
notificationService.getMonitorDownDelayMinutes.mockResolvedValue(1);
|
||||
monitorService.setNotificationDelayMinutes(5);
|
||||
pingService.ping.mockResolvedValueOnce({ success: false, responseTime: null });
|
||||
|
||||
monitorService.startTargetMonitor({ ...target, interval: 3600 });
|
||||
await monitorService.pingTarget(target, monitorService.monitorGeneration.get(target.id));
|
||||
await settle();
|
||||
|
||||
jest.advanceTimersByTime(30 * 1000);
|
||||
monitorService.setNotificationDelayMinutes(1);
|
||||
await settle();
|
||||
jest.advanceTimersByTime(30 * 1000);
|
||||
await settle();
|
||||
|
||||
expect(monitorService.handleTargetDown).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not let an older settings lookup replace a newer delay', async () => {
|
||||
const notificationService = require('../../src/services/notificationService');
|
||||
let resolveDelay;
|
||||
notificationService.getMonitorDownDelayMinutes.mockReturnValueOnce(new Promise(resolve => {
|
||||
resolveDelay = resolve;
|
||||
}));
|
||||
monitorService.setNotificationDelayMinutes(5);
|
||||
pingService.ping.mockResolvedValueOnce({ success: false, responseTime: null });
|
||||
|
||||
await monitorService.pingTarget(target);
|
||||
await settle();
|
||||
monitorService.setNotificationDelayMinutes(1);
|
||||
resolveDelay(5);
|
||||
await settle();
|
||||
|
||||
expect(monitorService.notificationDelayMinutes).toBe(1);
|
||||
});
|
||||
|
||||
it('ignores a ping result from a monitor generation that was restarted', async () => {
|
||||
let resolvePing;
|
||||
pingService.ping.mockReturnValueOnce(new Promise(resolve => { resolvePing = resolve; }));
|
||||
|
||||
monitorService.startTargetMonitor(target);
|
||||
const oldGeneration = monitorService.monitorGeneration.get(target.id);
|
||||
const oldPing = monitorService.pingTarget(target, oldGeneration);
|
||||
monitorService.startTargetMonitor(target);
|
||||
|
||||
resolvePing({ success: false, responseTime: null });
|
||||
await oldPing;
|
||||
await settle();
|
||||
|
||||
expect(monitorService.getTargetStatus(target.id)).toBe('unknown');
|
||||
expect(monitorService.getNotificationState(target.id).downSince).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,230 @@
|
||||
const pingService = require('../../src/services/pingService');
|
||||
const axios = require('axios');
|
||||
const tcpPing = require('tcp-ping');
|
||||
|
||||
jest.mock('axios');
|
||||
jest.mock('tcp-ping');
|
||||
jest.mock('child_process');
|
||||
|
||||
describe('PingService', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('ping method - protocol validation', () => {
|
||||
it('should return error for unknown protocol', async () => {
|
||||
const target = {
|
||||
host: 'example.com',
|
||||
protocol: 'UNKNOWN',
|
||||
port: 80,
|
||||
};
|
||||
|
||||
const result = await pingService.ping(target);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('Unknown protocol');
|
||||
});
|
||||
|
||||
it('should handle case-insensitive protocol', async () => {
|
||||
const target = {
|
||||
host: 'example.com',
|
||||
protocol: 'tcp',
|
||||
port: 80,
|
||||
};
|
||||
|
||||
tcpPing.probe.mockImplementation((host, port, callback) => {
|
||||
callback(null, true);
|
||||
});
|
||||
|
||||
const result = await pingService.ping(target);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.protocol).toBe('TCP');
|
||||
});
|
||||
});
|
||||
|
||||
describe('pingTCP method', () => {
|
||||
it('should successfully ping TCP host', async () => {
|
||||
tcpPing.probe.mockImplementation((host, port, callback) => {
|
||||
callback(null, true);
|
||||
});
|
||||
|
||||
const result = await pingService.pingTCP('example.com', 80, Date.now());
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.protocol).toBe('TCP');
|
||||
expect(result.responseTime).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it('should handle TCP connection failure', async () => {
|
||||
tcpPing.probe.mockImplementation((host, port, callback) => {
|
||||
callback(new Error('Connection refused'), false);
|
||||
});
|
||||
|
||||
const result = await pingService.pingTCP('example.com', 80, Date.now());
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('Connection refused');
|
||||
expect(result.protocol).toBe('TCP');
|
||||
});
|
||||
|
||||
it('should use default port 80 for TCP', async () => {
|
||||
tcpPing.probe.mockImplementation((host, port, callback) => {
|
||||
callback(null, true);
|
||||
});
|
||||
|
||||
const result = await pingService.pingTCP('example.com', 80, Date.now());
|
||||
|
||||
expect(tcpPing.probe).toHaveBeenCalledWith('example.com', 80, expect.any(Function));
|
||||
});
|
||||
});
|
||||
|
||||
describe('pingUDP method', () => {
|
||||
it('should successfully send UDP ping', async () => {
|
||||
const result = await pingService.pingUDP('example.com', 53, Date.now());
|
||||
|
||||
// UDP is expected to timeout or fail without a listening server
|
||||
expect(result.protocol).toBe('UDP');
|
||||
expect(result.responseTime).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it('should handle UDP timeout', async () => {
|
||||
const result = await pingService.pingUDP('example.com', 53, Date.now());
|
||||
|
||||
// Without a real server, UDP will timeout
|
||||
expect(result).toHaveProperty('responseTime');
|
||||
expect(result).toHaveProperty('protocol', 'UDP');
|
||||
});
|
||||
|
||||
it('should use default port 53 for UDP', async () => {
|
||||
const result = await pingService.pingUDP('example.com', 53, Date.now());
|
||||
|
||||
expect(result).toHaveProperty('protocol', 'UDP');
|
||||
});
|
||||
});
|
||||
|
||||
describe('pingHTTP method', () => {
|
||||
it('should successfully ping HTTP endpoint', async () => {
|
||||
axios.mockResolvedValue({ status: 200 });
|
||||
|
||||
const result = await pingService.pingHTTP('http://example.com/', Date.now());
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.protocol).toBe('HTTP');
|
||||
expect(result.responseTime).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it('should handle HTTP timeout', async () => {
|
||||
axios.mockRejectedValue(new Error('Request timeout'));
|
||||
|
||||
const result = await pingService.pingHTTP('http://example.com/', Date.now());
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('Request timeout');
|
||||
});
|
||||
|
||||
it('should use port 443 for HTTPS by default', async () => {
|
||||
axios.mockResolvedValue({ status: 200 });
|
||||
|
||||
const result = await pingService.pingHTTP('https://example.com/', Date.now());
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.protocol).toBe('HTTPS');
|
||||
});
|
||||
|
||||
it('should use custom port in HTTP URL', async () => {
|
||||
axios.mockResolvedValue({ status: 200 });
|
||||
|
||||
const result = await pingService.pingHTTP('http://example.com:8080/', Date.now());
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ping routing', () => {
|
||||
it('should route TCP protocol correctly', async () => {
|
||||
tcpPing.probe.mockImplementation((host, port, callback) => {
|
||||
callback(null, true);
|
||||
});
|
||||
|
||||
const target = {
|
||||
host: 'example.com',
|
||||
protocol: 'TCP',
|
||||
port: 80,
|
||||
};
|
||||
|
||||
const result = await pingService.ping(target);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.protocol).toBe('TCP');
|
||||
});
|
||||
|
||||
it('should route HTTP protocol correctly', async () => {
|
||||
axios.mockResolvedValue({ status: 200 });
|
||||
|
||||
const target = {
|
||||
host: 'example.com',
|
||||
protocol: 'HTTP',
|
||||
port: 80,
|
||||
path: '/',
|
||||
};
|
||||
|
||||
const result = await pingService.ping(target);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.protocol).toBe('HTTP');
|
||||
});
|
||||
|
||||
it('should route HTTPS protocol correctly', async () => {
|
||||
axios.mockResolvedValue({ status: 200 });
|
||||
|
||||
const target = {
|
||||
host: 'example.com',
|
||||
protocol: 'HTTPS',
|
||||
port: 443,
|
||||
path: '/',
|
||||
};
|
||||
|
||||
const result = await pingService.ping(target);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.protocol).toBe('HTTPS');
|
||||
});
|
||||
});
|
||||
|
||||
describe('response structure', () => {
|
||||
it('should always include success, responseTime, and protocol', async () => {
|
||||
tcpPing.probe.mockImplementation((host, port, callback) => {
|
||||
callback(null, true);
|
||||
});
|
||||
|
||||
const result = await pingService.pingTCP('example.com', 80, Date.now());
|
||||
|
||||
expect(result).toHaveProperty('success');
|
||||
expect(result).toHaveProperty('responseTime');
|
||||
expect(result).toHaveProperty('protocol');
|
||||
});
|
||||
|
||||
it('should include error message when ping fails', async () => {
|
||||
tcpPing.probe.mockImplementation((host, port, callback) => {
|
||||
callback(new Error('Network error'), false);
|
||||
});
|
||||
|
||||
const result = await pingService.pingTCP('example.com', 80, Date.now());
|
||||
|
||||
expect(result).toHaveProperty('error');
|
||||
expect(typeof result.error).toBe('string');
|
||||
});
|
||||
|
||||
it('should measure response time accurately', async () => {
|
||||
tcpPing.probe.mockImplementation((host, port, callback) => {
|
||||
setTimeout(() => callback(null, true), 10);
|
||||
});
|
||||
|
||||
const startTime = Date.now();
|
||||
const result = await pingService.pingTCP('example.com', 80, startTime);
|
||||
|
||||
expect(result.responseTime).toBeGreaterThanOrEqual(10);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
module.exports = {
|
||||
apps: [
|
||||
{
|
||||
name: 'localping',
|
||||
script: './src/app.js',
|
||||
args: '--mode all',
|
||||
instances: 1,
|
||||
exec_mode: 'fork',
|
||||
env: {
|
||||
NODE_ENV: 'production',
|
||||
API_PORT: 8000,
|
||||
ADMIN_PORT: 8000,
|
||||
PUBLIC_PORT: 8000,
|
||||
},
|
||||
error_file: './logs/error.log',
|
||||
out_file: './logs/out.log',
|
||||
log_date_format: 'YYYY-MM-DD HH:mm:ss Z',
|
||||
merge_logs: true,
|
||||
autorestart: true,
|
||||
ignore_watch: [
|
||||
'logs',
|
||||
'node_modules',
|
||||
'data',
|
||||
'prisma',
|
||||
'scripts',
|
||||
'.git',
|
||||
],
|
||||
max_memory_restart: '512M',
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,420 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
echo "🚀 LocalPing Installation Script"
|
||||
echo "=================================="
|
||||
|
||||
# Check for the privileges required to install packages and manage systemd.
|
||||
if [[ $EUID -ne 0 ]]; then
|
||||
echo "❌ This script must be run as root"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Parse arguments
|
||||
REPO_URL="${1:-https://github.com/YOUR-ORG/localping.git}"
|
||||
BRANCH="${2:-main}"
|
||||
INSTALL_DIR="${3:-/opt/localping}"
|
||||
SKIP_UPDATE="${4:-false}"
|
||||
|
||||
echo "📋 Installation Configuration:"
|
||||
echo " Repository: $REPO_URL"
|
||||
echo " Branch: $BRANCH"
|
||||
echo " Install Path: $INSTALL_DIR"
|
||||
echo ""
|
||||
|
||||
# Detect if already installed
|
||||
IS_UPDATE=false
|
||||
if [ -d "$INSTALL_DIR" ]; then
|
||||
if [ -f "$INSTALL_DIR/.env" ] && [ -f "$INSTALL_DIR/package.json" ]; then
|
||||
echo "✓ Existing LocalPing installation detected at $INSTALL_DIR"
|
||||
echo ""
|
||||
echo "What will be updated:"
|
||||
echo " • Source code (latest version from $BRANCH branch)"
|
||||
echo " • Dependencies (npm packages)"
|
||||
echo " • Systemd service configuration"
|
||||
echo ""
|
||||
echo "What will be preserved:"
|
||||
echo " • PostgreSQL database"
|
||||
echo " • Configuration (.env file)"
|
||||
echo " • Admin credentials"
|
||||
echo ""
|
||||
|
||||
# Only ask for confirmation if running in interactive terminal and not skipping confirmation
|
||||
if [ "$SKIP_UPDATE" != "true" ] && [ -t 0 ]; then
|
||||
read -p "Continue with update? (y/n) " -n 1 -r
|
||||
echo
|
||||
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
|
||||
echo "❌ Update cancelled."
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
IS_UPDATE=true
|
||||
else
|
||||
echo "⚠️ Directory exists at $INSTALL_DIR but is not a valid LocalPing installation"
|
||||
echo "❌ Please remove the directory or use a different path"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "📦 Installing system dependencies..."
|
||||
apt-get update -qq 2>/dev/null || apt-get update
|
||||
|
||||
# Install minimal dependencies
|
||||
apt-get install -y -qq \
|
||||
curl \
|
||||
git \
|
||||
build-essential \
|
||||
python3 \
|
||||
libnotify-bin \
|
||||
2>/dev/null || apt-get install -y \
|
||||
curl \
|
||||
git \
|
||||
build-essential \
|
||||
python3 \
|
||||
libnotify-bin
|
||||
|
||||
# Install Node.js if not present
|
||||
if ! command -v node &> /dev/null; then
|
||||
echo "📦 Installing Node.js v20..."
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash - 2>/dev/null
|
||||
apt-get install -y -qq nodejs 2>/dev/null || apt-get install -y nodejs
|
||||
fi
|
||||
|
||||
# Install git if not present (shouldn't happen but just in case)
|
||||
if ! command -v git &> /dev/null; then
|
||||
echo "📦 Installing git..."
|
||||
apt-get install -y -qq git 2>/dev/null || apt-get install -y git
|
||||
fi
|
||||
|
||||
echo "✅ System dependencies installed"
|
||||
|
||||
# Clone or update repository
|
||||
if [ "$IS_UPDATE" = false ]; then
|
||||
echo "📥 Cloning LocalPing repository..."
|
||||
mkdir -p "$(dirname "$INSTALL_DIR")"
|
||||
git clone --branch "$BRANCH" "$REPO_URL" "$INSTALL_DIR"
|
||||
else
|
||||
echo "🔄 Updating LocalPing repository..."
|
||||
cd "$INSTALL_DIR"
|
||||
# Fetch the requested branch and make the working tree exactly match it.
|
||||
# `checkout -B` only changes tracked files, so the installation's .env,
|
||||
# data, and logs remain untouched.
|
||||
git fetch --prune origin "$BRANCH"
|
||||
git checkout -B "$BRANCH" "origin/$BRANCH"
|
||||
fi
|
||||
|
||||
cd "$INSTALL_DIR"
|
||||
|
||||
# Validate required files exist
|
||||
if [ ! -f ".env.example" ]; then
|
||||
echo "❌ .env.example not found at $INSTALL_DIR"
|
||||
echo "The repository may be corrupted. Please try again."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "📥 Installing npm dependencies..."
|
||||
npm install --silent 2>/dev/null || npm install
|
||||
|
||||
echo "📁 Creating data directory..."
|
||||
mkdir -p "$INSTALL_DIR/data"
|
||||
|
||||
echo "🗄️ Setting up PostgreSQL..."
|
||||
# Install PostgreSQL if not present
|
||||
if ! command -v psql &> /dev/null; then
|
||||
echo "📦 Installing PostgreSQL..."
|
||||
apt-get install -y -qq postgresql postgresql-contrib 2>/dev/null || apt-get install -y postgresql postgresql-contrib
|
||||
systemctl enable postgresql
|
||||
systemctl start postgresql
|
||||
echo "✅ PostgreSQL installed"
|
||||
else
|
||||
echo "✓ PostgreSQL already installed"
|
||||
# Ensure PostgreSQL is running
|
||||
systemctl start postgresql 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# Wait for PostgreSQL to be ready
|
||||
sleep 2
|
||||
|
||||
# Reuse database settings from an existing installation. This prevents an
|
||||
# update from generating a new password that does not match the existing
|
||||
# PostgreSQL role.
|
||||
EXISTING_DATABASE_URL=""
|
||||
if [ -f ".env" ]; then
|
||||
# .env is the installation's own configuration file and is needed here so
|
||||
# Prisma and the service use the same credentials as the database setup.
|
||||
set -a
|
||||
# shellcheck disable=SC1091
|
||||
. ./.env
|
||||
set +a
|
||||
EXISTING_DATABASE_URL="${DATABASE_URL:-}"
|
||||
fi
|
||||
|
||||
DB_HOST="${DB_HOST:-localhost}"
|
||||
DB_PORT="${DB_PORT:-5432}"
|
||||
DB_NAME="${DB_NAME:-localping}"
|
||||
DB_USER="${DB_USER:-localping}"
|
||||
GENERATED_DB_PASSWORD=false
|
||||
if [ -z "${DB_PASSWORD:-}" ]; then
|
||||
DB_PASSWORD=$(openssl rand -base64 24 | tr -d "=+/" | cut -c1-24)
|
||||
GENERATED_DB_PASSWORD=true
|
||||
fi
|
||||
|
||||
case "$DB_NAME" in
|
||||
""|*[!A-Za-z0-9_]* ) echo "❌ DB_NAME may only contain letters, numbers, and underscores"; exit 1 ;;
|
||||
esac
|
||||
case "$DB_USER" in
|
||||
""|*[!A-Za-z0-9_]* ) echo "❌ DB_USER may only contain letters, numbers, and underscores"; exit 1 ;;
|
||||
esac
|
||||
|
||||
run_as_postgres() {
|
||||
if ! command -v runuser >/dev/null 2>&1; then
|
||||
echo "❌ runuser is required to configure PostgreSQL as the postgres user"
|
||||
exit 1
|
||||
fi
|
||||
runuser -u postgres -- "$@"
|
||||
}
|
||||
|
||||
# Create database and user if they don't exist
|
||||
echo "🔧 Configuring PostgreSQL database..."
|
||||
if ! run_as_postgres psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='$DB_USER'" | grep -q '^1$'; then
|
||||
run_as_postgres psql -v ON_ERROR_STOP=1 -v db_password="$DB_PASSWORD" -c "CREATE USER \"$DB_USER\" WITH PASSWORD :'db_password';"
|
||||
elif [ "$GENERATED_DB_PASSWORD" = true ] && [ -z "$EXISTING_DATABASE_URL" ]; then
|
||||
# A partially completed installation may have a role but no saved
|
||||
# connection URL. Make the generated credentials usable before saving them.
|
||||
run_as_postgres psql -v ON_ERROR_STOP=1 -v db_password="$DB_PASSWORD" -c "ALTER ROLE \"$DB_USER\" WITH PASSWORD :'db_password';"
|
||||
fi
|
||||
|
||||
if ! run_as_postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname='$DB_NAME'" | grep -q '^1$'; then
|
||||
run_as_postgres psql -v ON_ERROR_STOP=1 -c "CREATE DATABASE \"$DB_NAME\" OWNER \"$DB_USER\";"
|
||||
fi
|
||||
run_as_postgres psql -v ON_ERROR_STOP=1 -c "GRANT ALL PRIVILEGES ON DATABASE \"$DB_NAME\" TO \"$DB_USER\";"
|
||||
|
||||
# Configure PostgreSQL for local-only access (security)
|
||||
PG_MAJOR_VERSION=$(run_as_postgres psql -tAc "SHOW server_version;" | xargs | cut -d. -f1)
|
||||
PG_HBA_FILE="/etc/postgresql/$PG_MAJOR_VERSION/main/pg_hba.conf"
|
||||
|
||||
if [ -f "$PG_HBA_FILE" ]; then
|
||||
# Ensure local connections use md5 (password) authentication
|
||||
if ! grep -q "^local.*$DB_NAME.*$DB_USER.*md5" "$PG_HBA_FILE"; then
|
||||
# Add local connection rule if it doesn't exist
|
||||
printf 'local %s %s md5\n' "$DB_NAME" "$DB_USER" >> "$PG_HBA_FILE"
|
||||
fi
|
||||
# Ensure host connections are restricted to localhost only
|
||||
if ! grep -q "^host.*$DB_NAME.*$DB_USER.*127.0.0.1/32.*md5" "$PG_HBA_FILE"; then
|
||||
printf 'host %s %s 127.0.0.1/32 md5\n' "$DB_NAME" "$DB_USER" >> "$PG_HBA_FILE"
|
||||
fi
|
||||
# Reload PostgreSQL configuration
|
||||
systemctl reload postgresql 2>/dev/null || run_as_postgres pg_ctl reload -D "/var/lib/postgresql/$PG_MAJOR_VERSION/main" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
echo "✅ PostgreSQL database configured"
|
||||
|
||||
echo "🔧 Setting up environment file..."
|
||||
if [ ! -f ".env" ]; then
|
||||
# Generate secure random strings
|
||||
SESSION_SECRET=$(openssl rand -base64 32)
|
||||
ADMIN_API_KEY=$(openssl rand -hex 16)
|
||||
|
||||
cat > .env << EOF
|
||||
# Server Configuration
|
||||
API_PORT=8000
|
||||
NODE_ENV=production
|
||||
SESSION_SECRET=$SESSION_SECRET
|
||||
|
||||
# Database Configuration
|
||||
DB_HOST=localhost
|
||||
DB_PORT=5432
|
||||
DB_NAME=$DB_NAME
|
||||
DB_USER=$DB_USER
|
||||
DB_PASSWORD=$DB_PASSWORD
|
||||
DATABASE_URL=postgresql://$DB_USER:$DB_PASSWORD@$DB_HOST:$DB_PORT/$DB_NAME
|
||||
|
||||
# Notification Settings
|
||||
NOTIFICATION_ENABLED=true
|
||||
NOTIFICATION_METHOD=dbus
|
||||
|
||||
# Monitoring
|
||||
PING_INTERVAL=60
|
||||
ALERT_COOLDOWN=300
|
||||
|
||||
# API Authentication
|
||||
ADMIN_API_KEY=$ADMIN_API_KEY
|
||||
|
||||
# Admin Credentials (set during first-time setup)
|
||||
# ADMIN_PASSWORD=
|
||||
# ADMIN_USERNAME=
|
||||
EOF
|
||||
echo "✅ .env file created with secure values"
|
||||
else
|
||||
if [ "$IS_UPDATE" = true ]; then
|
||||
echo "✓ Preserving existing .env file"
|
||||
# Add database settings required by Prisma to older installations
|
||||
# without replacing any existing application configuration.
|
||||
if ! grep -q "^DB_HOST=" .env; then
|
||||
{
|
||||
echo ""
|
||||
echo "# Database Configuration"
|
||||
echo "DB_HOST=$DB_HOST"
|
||||
echo "DB_PORT=$DB_PORT"
|
||||
echo "DB_NAME=$DB_NAME"
|
||||
echo "DB_USER=$DB_USER"
|
||||
echo "DB_PASSWORD=$DB_PASSWORD"
|
||||
} >> .env
|
||||
echo "✅ Added database configuration to .env"
|
||||
else
|
||||
grep -q "^DB_PORT=" .env || echo "DB_PORT=$DB_PORT" >> .env
|
||||
grep -q "^DB_NAME=" .env || echo "DB_NAME=$DB_NAME" >> .env
|
||||
grep -q "^DB_USER=" .env || echo "DB_USER=$DB_USER" >> .env
|
||||
grep -q "^DB_PASSWORD=" .env || echo "DB_PASSWORD=$DB_PASSWORD" >> .env
|
||||
fi
|
||||
if [ -z "$EXISTING_DATABASE_URL" ] && ! grep -q "^DATABASE_URL=" .env; then
|
||||
echo "DATABASE_URL=postgresql://$DB_USER:$DB_PASSWORD@$DB_HOST:$DB_PORT/$DB_NAME" >> .env
|
||||
echo "✅ Added DATABASE_URL for Prisma to .env"
|
||||
fi
|
||||
else
|
||||
echo "⚠️ .env already exists, skipping creation"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "🔄 Syncing database schema with Prisma..."
|
||||
npx prisma generate
|
||||
npx prisma db push --skip-generate
|
||||
|
||||
echo "🔐 Setting ICMP capabilities for Node.js..."
|
||||
NODE_PATH=$(which node)
|
||||
setcap cap_net_raw=ep "$NODE_PATH" 2>/dev/null || true
|
||||
|
||||
# Run the service as the invoking user when available; root is the fallback.
|
||||
SERVICE_USER="${SUDO_USER:-root}"
|
||||
SERVICE_NAME="localping"
|
||||
|
||||
echo "🛠️ Creating systemd service..."
|
||||
|
||||
# Get Node.js path
|
||||
NODE_BIN=$(which node)
|
||||
|
||||
# Create systemd service file to run Node.js directly (production-optimized)
|
||||
cat > "/etc/systemd/system/${SERVICE_NAME}.service" << SYSTEMD_EOF
|
||||
[Unit]
|
||||
Description=LocalPing - System Uptime Monitor
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=$SERVICE_USER
|
||||
WorkingDirectory=$INSTALL_DIR
|
||||
Environment="PATH=/usr/local/bin:/usr/bin:/bin"
|
||||
Environment="NODE_ENV=production"
|
||||
EnvironmentFile=-$INSTALL_DIR/.env
|
||||
|
||||
# Start Node.js app directly
|
||||
ExecStart=$NODE_BIN $INSTALL_DIR/src/app.js
|
||||
|
||||
# Restart automatically on failure
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
|
||||
# Grant ICMP permissions for ping functionality
|
||||
AmbientCapabilities=CAP_NET_RAW
|
||||
CapabilityBoundingSet=CAP_NET_RAW
|
||||
|
||||
# Security settings
|
||||
ProtectHome=true
|
||||
NoNewPrivileges=true
|
||||
PrivateDevices=yes
|
||||
ProtectKernelTunables=yes
|
||||
ProtectKernelModules=yes
|
||||
ProtectControlGroups=yes
|
||||
|
||||
# Process management
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
SyslogIdentifier=$SERVICE_NAME
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
SYSTEMD_EOF
|
||||
|
||||
# Set permissions
|
||||
chown root:root "/etc/systemd/system/${SERVICE_NAME}.service"
|
||||
chmod 644 "/etc/systemd/system/${SERVICE_NAME}.service"
|
||||
|
||||
# Reload systemd
|
||||
systemctl daemon-reload
|
||||
|
||||
# Enable and start/restart the service
|
||||
echo "🚀 Starting LocalPing service..."
|
||||
systemctl enable "$SERVICE_NAME"
|
||||
systemctl restart "$SERVICE_NAME"
|
||||
|
||||
# Wait for service to start
|
||||
sleep 3
|
||||
|
||||
if ! systemctl is-active --quiet "$SERVICE_NAME"; then
|
||||
echo "❌ LocalPing failed to start after the update"
|
||||
systemctl status "$SERVICE_NAME" --no-pager 2>&1 | head -n 40 || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✅ Systemd service configured"
|
||||
echo ""
|
||||
|
||||
# Show status
|
||||
echo "📊 Service Status:"
|
||||
systemctl status "$SERVICE_NAME" --no-pager 2>&1 | head -n 20 || true
|
||||
|
||||
echo ""
|
||||
if [ "$IS_UPDATE" = true ]; then
|
||||
echo "✅ Update complete!"
|
||||
echo ""
|
||||
echo "What was updated:"
|
||||
echo " ✓ Source code to latest version"
|
||||
echo " ✓ Dependencies (npm packages)"
|
||||
echo " ✓ Systemd service configuration"
|
||||
echo ""
|
||||
echo "What was preserved:"
|
||||
echo " ✓ PostgreSQL database"
|
||||
echo " ✓ Configuration (.env file)"
|
||||
echo " ✓ Admin credentials and monitors"
|
||||
else
|
||||
echo "✅ Installation complete!"
|
||||
echo ""
|
||||
fi
|
||||
|
||||
# Get the IPv4 address
|
||||
IP_ADDR=$(hostname -I | awk '{print $1}')
|
||||
if [ -z "$IP_ADDR" ]; then
|
||||
IP_ADDR="localhost"
|
||||
fi
|
||||
|
||||
echo "📊 Access LocalPing:"
|
||||
echo " Public Page: http://$IP_ADDR:8000"
|
||||
echo " API: http://$IP_ADDR:8000/api"
|
||||
echo ""
|
||||
|
||||
if [ "$IS_UPDATE" = false ]; then
|
||||
echo "🔧 First Time Setup:"
|
||||
echo " 1. Visit http://$IP_ADDR:8000/setup to complete configuration"
|
||||
echo " 2. Create admin credentials and configure gateway IP"
|
||||
echo " 3. You'll be redirected to login at http://$IP_ADDR:8000/admin/login"
|
||||
echo " 4. Login to access the admin panel"
|
||||
echo ""
|
||||
else
|
||||
echo "🔄 Service has been restarted with the latest code"
|
||||
echo " Login at http://$IP_ADDR:8000/admin/login"
|
||||
echo ""
|
||||
fi
|
||||
echo ""
|
||||
echo "📖 Useful Commands:"
|
||||
echo " View logs: journalctl -u $SERVICE_NAME -f"
|
||||
echo " Service status: systemctl status $SERVICE_NAME"
|
||||
echo " Start service: systemctl start $SERVICE_NAME"
|
||||
echo " Stop service: systemctl stop $SERVICE_NAME"
|
||||
echo " Restart service: systemctl restart $SERVICE_NAME"
|
||||
echo " Install directory: $INSTALL_DIR"
|
||||
echo ""
|
||||
echo "ℹ️ The service will auto-start on system boot."
|
||||
echo "ℹ️ Environment file located at: $INSTALL_DIR/.env"
|
||||
echo ""
|
||||
@@ -0,0 +1,19 @@
|
||||
module.exports = {
|
||||
testEnvironment: 'node',
|
||||
testMatch: ['**/__tests__/**/*.test.js', '**/*.test.js'],
|
||||
collectCoverageFrom: [
|
||||
'src/**/*.js',
|
||||
'!src/app.js',
|
||||
'!src/cli/**',
|
||||
'!src/electron/**',
|
||||
'!src/public/**',
|
||||
],
|
||||
coveragePathIgnorePatterns: [
|
||||
'/node_modules/',
|
||||
'/tests/',
|
||||
],
|
||||
transformIgnorePatterns: [
|
||||
'node_modules/(?!(default-gateway)/)',
|
||||
],
|
||||
testTimeout: 10000,
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"name": "localping",
|
||||
"version": "0.1.0",
|
||||
"description": "A local system uptime monitor - Quick-fix your homelab remotely",
|
||||
"main": "src/app.js",
|
||||
"scripts": {
|
||||
"start": "node src/app.js",
|
||||
"dev": "nodemon src/app.js",
|
||||
"gui": "electron src/electron/main.js",
|
||||
"web": "node src/app.js --mode web",
|
||||
"pm2:start": "pm2 start ecosystem.config.js",
|
||||
"pm2:stop": "pm2 stop all",
|
||||
"pm2:logs": "pm2 logs",
|
||||
"pm2:restart": "pm2 restart all",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"test:coverage": "jest --coverage",
|
||||
"test:backup": "jest __tests__/services/backupService.test.js",
|
||||
"test:backup:watch": "jest __tests__/services/backupService.test.js --watch",
|
||||
"verify:ping": "node scripts/verify-ping-data.js",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:push": "prisma db push",
|
||||
"prisma:studio": "prisma studio",
|
||||
"postinstall": "prisma generate"
|
||||
},
|
||||
"keywords": [
|
||||
"uptime",
|
||||
"monitoring",
|
||||
"homelab",
|
||||
"ping",
|
||||
"dashboard"
|
||||
],
|
||||
"author": "Your Name",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=16.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@prisma/client": "^6.8.2",
|
||||
"axios": "^1.13.2",
|
||||
"better-sqlite3": "^12.4.5",
|
||||
"chalk": "^5.6.2",
|
||||
"cors": "^2.8.5",
|
||||
"default-gateway": "^7.2.2",
|
||||
"dotenv": "^17.2.3",
|
||||
"ejs": "^3.1.10",
|
||||
"electron-is-dev": "^3.0.1",
|
||||
"express": "^5.1.0",
|
||||
"express-session": "^1.17.3",
|
||||
"express-ws": "^5.0.2",
|
||||
"inquirer": "^13.0.1",
|
||||
"isomorphic-form-data": "^2.0.0",
|
||||
"nodemon": "^3.1.11",
|
||||
"pg": "^8.13.1",
|
||||
"pm2": "^6.0.13",
|
||||
"shell-escape": "^0.2.0",
|
||||
"tcp-ping": "^0.1.1",
|
||||
"uuid": "^13.0.0",
|
||||
"yargs": "^18.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/preset-env": "^7.28.5",
|
||||
"@babel/preset-typescript": "^7.28.5",
|
||||
"jest": "^29.7.0",
|
||||
"prisma": "^6.8.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
// Prisma Schema for LocalPing
|
||||
// Run `npx prisma generate` after changes
|
||||
// Run `npx prisma db push` to sync with database
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
model Target {
|
||||
id String @id @default(uuid()) @map("_id")
|
||||
name String @unique
|
||||
host String
|
||||
protocol String
|
||||
port Int?
|
||||
path String?
|
||||
enabled Boolean @default(true)
|
||||
publicVisible Boolean @default(true)
|
||||
publicShowDetails Boolean @default(false)
|
||||
publicShowStatus Boolean @default(true)
|
||||
publicShowAppLink Boolean @default(true)
|
||||
interval Int @default(60)
|
||||
retries Int @default(0)
|
||||
retryInterval Int @default(5)
|
||||
timeout Int @default(30)
|
||||
httpMethod String @default("GET")
|
||||
statusCodes String @default("200-299")
|
||||
maxRedirects Int @default(5)
|
||||
ignoreSsl Boolean @default(false)
|
||||
upsideDown Boolean @default(false)
|
||||
important Boolean @default(false)
|
||||
auth Json?
|
||||
appUrl String?
|
||||
appIcon String?
|
||||
position Int @default(0)
|
||||
group String?
|
||||
quickCommands Json?
|
||||
description String?
|
||||
tier String @default("normal") // featured | normal | background
|
||||
linkPublic Boolean @default(true)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
pingResults PingResult[]
|
||||
alerts Alert[]
|
||||
statistics Statistic[]
|
||||
actions Action[]
|
||||
|
||||
@@map("targets")
|
||||
}
|
||||
|
||||
model PingResult {
|
||||
id String @id @default(uuid()) @map("_id")
|
||||
targetId String
|
||||
success Boolean
|
||||
responseTime Int?
|
||||
timestamp DateTime @default(now())
|
||||
statusCode Int?
|
||||
error String?
|
||||
protocol String?
|
||||
|
||||
target Target @relation(fields: [targetId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([targetId])
|
||||
@@index([timestamp])
|
||||
@@index([targetId, timestamp])
|
||||
@@map("pingResults")
|
||||
}
|
||||
|
||||
model Alert {
|
||||
id String @id @default(uuid()) @map("_id")
|
||||
targetId String
|
||||
type String
|
||||
timestamp DateTime @default(now())
|
||||
message String?
|
||||
|
||||
target Target @relation(fields: [targetId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([targetId])
|
||||
@@index([timestamp])
|
||||
@@map("alerts")
|
||||
}
|
||||
|
||||
model Statistic {
|
||||
id String @id @default(uuid()) @map("_id")
|
||||
targetId String
|
||||
date DateTime @db.Date
|
||||
totalPings Int @default(0)
|
||||
successfulPings Int @default(0)
|
||||
failedPings Int @default(0)
|
||||
uptime Float @default(0)
|
||||
lastResponseTime Int @default(0)
|
||||
avgResponseTime Float @default(0)
|
||||
minResponseTime Int?
|
||||
maxResponseTime Int?
|
||||
|
||||
target Target @relation(fields: [targetId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([targetId, date])
|
||||
@@index([targetId])
|
||||
@@index([date])
|
||||
@@map("statistics")
|
||||
}
|
||||
|
||||
model Incident {
|
||||
id String @id @default(uuid()) @map("_id")
|
||||
title String
|
||||
description String?
|
||||
severity String @default("major")
|
||||
status String @default("investigating")
|
||||
affectedServices Json?
|
||||
updates Json?
|
||||
resolvedAt DateTime?
|
||||
isScheduled Boolean @default(false)
|
||||
scheduledStart DateTime?
|
||||
scheduledEnd DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([status])
|
||||
@@index([isScheduled, scheduledStart])
|
||||
@@map("incidents")
|
||||
}
|
||||
|
||||
model EventRule {
|
||||
id String @id @default(uuid()) @map("_id")
|
||||
name String
|
||||
eventType String
|
||||
enabled Boolean @default(true)
|
||||
conditions Json
|
||||
incidentTitle String
|
||||
incidentDescription String
|
||||
incidentSeverity String @default("major")
|
||||
incidentStatus String @default("investigating")
|
||||
autoResolve Boolean @default(false)
|
||||
autoResolveMessage String?
|
||||
cooldownMinutes Int @default(0)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([enabled])
|
||||
@@map("eventRules")
|
||||
}
|
||||
|
||||
model Action {
|
||||
id String @id @default(uuid()) @map("_id")
|
||||
targetId String
|
||||
name String
|
||||
type String
|
||||
command String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
target Target @relation(fields: [targetId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([targetId, name])
|
||||
@@index([targetId])
|
||||
@@map("actions")
|
||||
}
|
||||
|
||||
model Favicon {
|
||||
id String @id @default(uuid()) @map("_id")
|
||||
appUrl String @unique
|
||||
favicon String?
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@map("favicons")
|
||||
}
|
||||
|
||||
model SiteBrand {
|
||||
id String @id @default("brand") @map("_id")
|
||||
name String?
|
||||
accent String?
|
||||
tagline String?
|
||||
iconData Bytes?
|
||||
iconType String?
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@map("siteBrand")
|
||||
}
|
||||
|
||||
model PublicUISettings {
|
||||
id String @id @default("settings") @map("_id")
|
||||
title String @default("Homelab")
|
||||
subtitle String @default("System Status & Application Dashboard")
|
||||
customCSS String?
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@map("publicUISettings")
|
||||
}
|
||||
|
||||
model AdminSettings {
|
||||
id String @id @default("settings") @map("_id")
|
||||
sessionDurationDays Int @default(30)
|
||||
dataRetentionDays Int @default(30)
|
||||
debugLogging Boolean @default(false)
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@map("adminSettings")
|
||||
}
|
||||
|
||||
model NotificationSettings {
|
||||
id String @id @default("settings") @map("_id")
|
||||
enabled Boolean @default(false)
|
||||
discord Json?
|
||||
events Json?
|
||||
monitorDownDelayMinutes Int @default(5)
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@map("notificationSettings")
|
||||
}
|
||||
|
||||
model Post {
|
||||
id String @id @default(uuid()) @map("_id")
|
||||
title String
|
||||
content String
|
||||
published Boolean @default(true)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([published])
|
||||
@@index([createdAt])
|
||||
@@map("posts")
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
# CDN Library Download Scripts
|
||||
|
||||
These scripts download all external CDN libraries locally to make the project self-sustainable and work offline.
|
||||
|
||||
## Usage
|
||||
|
||||
### Option 1: Bash Script (Linux/macOS)
|
||||
|
||||
```bash
|
||||
./scripts/download-cdn-libs.sh
|
||||
```
|
||||
|
||||
### Option 2: Node.js Script (Cross-platform)
|
||||
|
||||
```bash
|
||||
node scripts/download-cdn-libs.js
|
||||
```
|
||||
|
||||
## What Gets Downloaded
|
||||
|
||||
The scripts will download the following libraries to `src/public/vendor/`:
|
||||
|
||||
1. **Tailwind CSS** → `vendor/tailwindcss.js`
|
||||
2. **Chart.js** → `vendor/chart.js`
|
||||
3. **Axios** → `vendor/axios.min.js`
|
||||
4. **Marked** (Markdown parser) → `vendor/marked.min.js`
|
||||
5. **Font Awesome** → `vendor/font-awesome/all.min.css` + webfonts
|
||||
|
||||
## After Running
|
||||
|
||||
All view files have already been updated to use local paths instead of CDN URLs. The libraries will be served from `/vendor/` when the application runs.
|
||||
|
||||
## Notes
|
||||
|
||||
- Make sure you have an internet connection when running these scripts
|
||||
- The scripts will create the necessary directory structure automatically
|
||||
- Font Awesome CSS paths are automatically updated to point to local webfonts
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Create PostgreSQL user and database for localping
|
||||
|
||||
echo "🔧 Creating PostgreSQL user and database..."
|
||||
|
||||
# Check if PostgreSQL is running
|
||||
if ! pg_isready > /dev/null 2>&1; then
|
||||
echo "❌ PostgreSQL is not running. Start it with: sudo systemctl start postgresql"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Create user if it doesn't exist
|
||||
echo "👤 Creating user 'localping'..."
|
||||
sudo -u postgres psql -c "SELECT 1 FROM pg_roles WHERE rolname='localping';" | grep -q 1 || \
|
||||
sudo -u postgres psql -c "CREATE USER localping WITH PASSWORD 'localping';"
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
echo "✅ User 'localping' created or already exists"
|
||||
else
|
||||
echo "⚠️ User creation may have failed (might already exist)"
|
||||
fi
|
||||
|
||||
# Create database if it doesn't exist
|
||||
echo "🗄️ Creating database 'localping'..."
|
||||
sudo -u postgres psql -c "SELECT 1 FROM pg_database WHERE datname='localping';" | grep -q 1 || \
|
||||
sudo -u postgres psql -c "CREATE DATABASE localping OWNER localping;"
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
echo "✅ Database 'localping' created or already exists"
|
||||
else
|
||||
echo "⚠️ Database creation may have failed (might already exist)"
|
||||
fi
|
||||
|
||||
# Grant privileges
|
||||
echo "🔐 Granting privileges..."
|
||||
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE localping TO localping;"
|
||||
|
||||
echo ""
|
||||
echo "✅ Setup complete! The app should now be able to connect."
|
||||
echo ""
|
||||
echo "💡 If you want to use a different password, update your .env file:"
|
||||
echo " DB_PASSWORD=your_password_here"
|
||||
echo ""
|
||||
echo " Then run this script again with the new password in the CREATE USER command."
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Script to download all CDN libraries locally for offline use
|
||||
* This makes the project self-sustainable without internet connection
|
||||
*/
|
||||
|
||||
const https = require('https');
|
||||
const http = require('http');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { URL } = require('url');
|
||||
|
||||
const PROJECT_ROOT = path.join(__dirname, '..');
|
||||
const VENDOR_DIR = path.join(PROJECT_ROOT, 'src', 'public', 'vendor');
|
||||
const FONTAWESOME_DIR = path.join(VENDOR_DIR, 'font-awesome');
|
||||
|
||||
// Colors for console output
|
||||
const colors = {
|
||||
green: '\x1b[32m',
|
||||
yellow: '\x1b[33m',
|
||||
reset: '\x1b[0m'
|
||||
};
|
||||
|
||||
function log(message, color = 'reset') {
|
||||
console.log(`${colors[color]}${message}${colors.reset}`);
|
||||
}
|
||||
|
||||
// Create directories
|
||||
function ensureDir(dir) {
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
// Download file function
|
||||
function downloadFile(url, outputPath, maxRedirects = 5) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (maxRedirects <= 0) {
|
||||
reject(new Error('Too many redirects'));
|
||||
return;
|
||||
}
|
||||
|
||||
const parsedUrl = new URL(url);
|
||||
const protocol = parsedUrl.protocol === 'https:' ? https : http;
|
||||
|
||||
const file = fs.createWriteStream(outputPath);
|
||||
|
||||
const request = protocol.get(url, (response) => {
|
||||
if (response.statusCode === 301 || response.statusCode === 302 || response.statusCode === 307 || response.statusCode === 308) {
|
||||
file.close();
|
||||
if (fs.existsSync(outputPath)) {
|
||||
fs.unlinkSync(outputPath);
|
||||
}
|
||||
|
||||
// Handle redirects - resolve relative URLs
|
||||
let redirectUrl = response.headers.location;
|
||||
if (!redirectUrl) {
|
||||
reject(new Error(`Redirect without location header from ${url}`));
|
||||
return;
|
||||
}
|
||||
|
||||
// Resolve relative URLs
|
||||
if (redirectUrl.startsWith('/')) {
|
||||
redirectUrl = `${parsedUrl.protocol}//${parsedUrl.host}${redirectUrl}`;
|
||||
} else if (!redirectUrl.startsWith('http://') && !redirectUrl.startsWith('https://')) {
|
||||
redirectUrl = new URL(redirectUrl, url).href;
|
||||
}
|
||||
|
||||
return downloadFile(redirectUrl, outputPath, maxRedirects - 1)
|
||||
.then(resolve)
|
||||
.catch(reject);
|
||||
}
|
||||
|
||||
if (response.statusCode !== 200) {
|
||||
file.close();
|
||||
if (fs.existsSync(outputPath)) {
|
||||
fs.unlinkSync(outputPath);
|
||||
}
|
||||
reject(new Error(`Failed to download ${url}: ${response.statusCode}`));
|
||||
return;
|
||||
}
|
||||
|
||||
response.pipe(file);
|
||||
|
||||
file.on('finish', () => {
|
||||
file.close();
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
request.on('error', (err) => {
|
||||
file.close();
|
||||
if (fs.existsSync(outputPath)) {
|
||||
fs.unlinkSync(outputPath);
|
||||
}
|
||||
reject(err);
|
||||
});
|
||||
|
||||
file.on('error', (err) => {
|
||||
file.close();
|
||||
if (fs.existsSync(outputPath)) {
|
||||
fs.unlinkSync(outputPath);
|
||||
}
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
log('Starting CDN library download...', 'green');
|
||||
|
||||
// Create directories
|
||||
ensureDir(VENDOR_DIR);
|
||||
ensureDir(FONTAWESOME_DIR);
|
||||
ensureDir(path.join(FONTAWESOME_DIR, 'webfonts'));
|
||||
|
||||
const downloads = [
|
||||
{
|
||||
name: 'Tailwind CSS',
|
||||
url: 'https://cdn.tailwindcss.com',
|
||||
output: path.join(VENDOR_DIR, 'tailwindcss.js')
|
||||
},
|
||||
{
|
||||
name: 'Chart.js',
|
||||
url: 'https://cdn.jsdelivr.net/npm/chart.js',
|
||||
output: path.join(VENDOR_DIR, 'chart.js')
|
||||
},
|
||||
{
|
||||
name: 'Axios',
|
||||
url: 'https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js',
|
||||
output: path.join(VENDOR_DIR, 'axios.min.js')
|
||||
},
|
||||
{
|
||||
name: 'Marked',
|
||||
url: 'https://cdn.jsdelivr.net/npm/marked/marked.min.js',
|
||||
output: path.join(VENDOR_DIR, 'marked.min.js')
|
||||
},
|
||||
{
|
||||
name: 'Font Awesome CSS',
|
||||
url: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css',
|
||||
output: path.join(FONTAWESOME_DIR, 'all.min.css')
|
||||
}
|
||||
];
|
||||
|
||||
// Download main libraries
|
||||
for (let i = 0; i < downloads.length; i++) {
|
||||
const item = downloads[i];
|
||||
log(`[${i + 1}/${downloads.length}] Downloading ${item.name}...`, 'green');
|
||||
log(` URL: ${item.url}`, 'yellow');
|
||||
|
||||
try {
|
||||
await downloadFile(item.url, item.output);
|
||||
log(` ✓ Saved to: ${item.output}`, 'green');
|
||||
} catch (error) {
|
||||
log(` ✗ Failed: ${error.message}`, 'yellow');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Download Font Awesome fonts
|
||||
log('\nDownloading Font Awesome webfonts...', 'yellow');
|
||||
const fontFiles = [
|
||||
'fa-solid-900.woff2',
|
||||
'fa-regular-400.woff2',
|
||||
'fa-brands-400.woff2',
|
||||
'fa-v4compatibility.woff2'
|
||||
];
|
||||
|
||||
for (const font of fontFiles) {
|
||||
const url = `https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/webfonts/${font}`;
|
||||
const output = path.join(FONTAWESOME_DIR, 'webfonts', font);
|
||||
|
||||
log(` Downloading ${font}...`, 'yellow');
|
||||
try {
|
||||
await downloadFile(url, output);
|
||||
log(` ✓ Saved: ${font}`, 'green');
|
||||
} catch (error) {
|
||||
log(` ✗ Failed to download ${font}: ${error.message}`, 'yellow');
|
||||
}
|
||||
}
|
||||
|
||||
// Update Font Awesome CSS to use local paths
|
||||
log('\nUpdating Font Awesome CSS paths...', 'yellow');
|
||||
const cssPath = path.join(FONTAWESOME_DIR, 'all.min.css');
|
||||
let cssContent = fs.readFileSync(cssPath, 'utf8');
|
||||
|
||||
// Replace relative paths with absolute paths
|
||||
cssContent = cssContent.replace(/url\(\.\.\/webfonts\//g, 'url(/vendor/font-awesome/webfonts/');
|
||||
cssContent = cssContent.replace(/url\(webfonts\//g, 'url(/vendor/font-awesome/webfonts/');
|
||||
|
||||
fs.writeFileSync(cssPath, cssContent);
|
||||
log(' ✓ Updated CSS paths', 'green');
|
||||
|
||||
log('\n✓ All libraries downloaded successfully!', 'green');
|
||||
log(`Files saved to: ${VENDOR_DIR}`, 'green');
|
||||
log('\nNext step: Update view files to use local paths instead of CDN URLs', 'yellow');
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error('Error:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Script to download all CDN libraries locally for offline use
|
||||
# This makes the project self-sustainable without internet connection
|
||||
|
||||
set -e
|
||||
|
||||
# Colors for output
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# Base directories
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||
VENDOR_DIR="$PROJECT_ROOT/src/public/vendor"
|
||||
FONTAWESOME_DIR="$VENDOR_DIR/font-awesome"
|
||||
|
||||
echo -e "${GREEN}Starting CDN library download...${NC}"
|
||||
|
||||
# Create vendor directory
|
||||
mkdir -p "$VENDOR_DIR"
|
||||
mkdir -p "$FONTAWESOME_DIR"
|
||||
|
||||
# Function to download file
|
||||
download_file() {
|
||||
local url=$1
|
||||
local output=$2
|
||||
echo -e "${YELLOW}Downloading: $url${NC}"
|
||||
curl -L -f -s "$url" -o "$output" || {
|
||||
echo "Failed to download $url"
|
||||
return 1
|
||||
}
|
||||
echo -e "${GREEN}✓ Saved to: $output${NC}"
|
||||
}
|
||||
|
||||
# 1. Download Tailwind CSS (standalone build)
|
||||
echo -e "\n${GREEN}[1/5] Downloading Tailwind CSS...${NC}"
|
||||
download_file "https://cdn.tailwindcss.com" "$VENDOR_DIR/tailwindcss.js"
|
||||
|
||||
# 2. Download Chart.js
|
||||
echo -e "\n${GREEN}[2/5] Downloading Chart.js...${NC}"
|
||||
download_file "https://cdn.jsdelivr.net/npm/chart.js" "$VENDOR_DIR/chart.js"
|
||||
|
||||
# 3. Download Axios
|
||||
echo -e "\n${GREEN}[3/5] Downloading Axios...${NC}"
|
||||
download_file "https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js" "$VENDOR_DIR/axios.min.js"
|
||||
|
||||
# 4. Download Marked (Markdown parser)
|
||||
echo -e "\n${GREEN}[4/5] Downloading Marked...${NC}"
|
||||
download_file "https://cdn.jsdelivr.net/npm/marked/marked.min.js" "$VENDOR_DIR/marked.min.js"
|
||||
|
||||
# 5. Download Font Awesome CSS and fonts
|
||||
echo -e "\n${GREEN}[5/5] Downloading Font Awesome...${NC}"
|
||||
download_file "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" "$FONTAWESOME_DIR/all.min.css"
|
||||
|
||||
# Download Font Awesome fonts (webfonts)
|
||||
echo -e "${YELLOW}Downloading Font Awesome webfonts...${NC}"
|
||||
mkdir -p "$FONTAWESOME_DIR/webfonts"
|
||||
|
||||
# Get the font file URLs from the CSS
|
||||
FONT_FILES=(
|
||||
"fa-solid-900.woff2"
|
||||
"fa-regular-400.woff2"
|
||||
"fa-brands-400.woff2"
|
||||
"fa-v4compatibility.woff2"
|
||||
)
|
||||
|
||||
for font in "${FONT_FILES[@]}"; do
|
||||
download_file "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/webfonts/$font" "$FONTAWESOME_DIR/webfonts/$font"
|
||||
done
|
||||
|
||||
# Update Font Awesome CSS to use local paths
|
||||
echo -e "${YELLOW}Updating Font Awesome CSS paths...${NC}"
|
||||
sed -i "s|url(../webfonts/|url(/vendor/font-awesome/webfonts/|g" "$FONTAWESOME_DIR/all.min.css"
|
||||
sed -i "s|url(webfonts/|url(/vendor/font-awesome/webfonts/|g" "$FONTAWESOME_DIR/all.min.css"
|
||||
|
||||
echo -e "\n${GREEN}✓ All libraries downloaded successfully!${NC}"
|
||||
echo -e "${GREEN}Files saved to: $VENDOR_DIR${NC}"
|
||||
echo -e "\n${YELLOW}Next step: Update view files to use local paths instead of CDN URLs${NC}"
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Initialize PostgreSQL database cluster for Arch Linux
|
||||
|
||||
echo "🗄️ Initializing PostgreSQL database cluster..."
|
||||
|
||||
# Check if PostgreSQL is installed
|
||||
if ! command -v psql &> /dev/null; then
|
||||
echo "❌ PostgreSQL is not installed. Please install it first:"
|
||||
echo " sudo pacman -S postgresql"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if data directory exists and is empty
|
||||
DATA_DIR="/var/lib/postgres/data"
|
||||
|
||||
if [ -d "$DATA_DIR" ] && [ "$(ls -A $DATA_DIR 2>/dev/null)" ]; then
|
||||
echo "✓ PostgreSQL data directory already exists and is not empty"
|
||||
echo " If you want to reinitialize, remove it first: sudo rm -rf $DATA_DIR"
|
||||
else
|
||||
echo "📦 Initializing PostgreSQL data directory..."
|
||||
sudo -u postgres initdb --locale=C.UTF-8 --encoding=UTF8 -D "$DATA_DIR"
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
echo "✅ PostgreSQL database cluster initialized"
|
||||
else
|
||||
echo "❌ Failed to initialize PostgreSQL"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Start PostgreSQL service
|
||||
echo "🚀 Starting PostgreSQL service..."
|
||||
sudo systemctl start postgresql
|
||||
sudo systemctl enable postgresql
|
||||
|
||||
# Wait for PostgreSQL to be ready
|
||||
echo "⏳ Waiting for PostgreSQL to be ready..."
|
||||
sleep 2
|
||||
|
||||
# Check if PostgreSQL is running
|
||||
if pg_isready > /dev/null 2>&1; then
|
||||
echo "✅ PostgreSQL is running"
|
||||
else
|
||||
echo "❌ PostgreSQL failed to start. Check logs with: sudo journalctl -u postgresql"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Create database and user if they don't exist
|
||||
DB_NAME="localping"
|
||||
DB_USER="localping"
|
||||
|
||||
echo "🔧 Creating database and user..."
|
||||
|
||||
# Generate secure password if .env doesn't exist or DB_PASSWORD is not set
|
||||
if [ ! -f .env ] || ! grep -q "DB_PASSWORD" .env; then
|
||||
DB_PASSWORD=$(openssl rand -base64 24 | tr -d "=+/" | cut -c1-24)
|
||||
echo "📝 Generated database password: $DB_PASSWORD"
|
||||
echo " Add this to your .env file: DB_PASSWORD=$DB_PASSWORD"
|
||||
else
|
||||
# Extract password from .env file
|
||||
DB_PASSWORD=$(grep "DB_PASSWORD" .env | cut -d '=' -f2 | tr -d '"' | tr -d "'")
|
||||
if [ -z "$DB_PASSWORD" ]; then
|
||||
DB_PASSWORD=$(openssl rand -base64 24 | tr -d "=+/" | cut -c1-24)
|
||||
echo "📝 Generated database password: $DB_PASSWORD"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Create user if it doesn't exist
|
||||
sudo -u postgres psql -c "SELECT 1 FROM pg_roles WHERE rolname='$DB_USER'" | grep -q 1 || \
|
||||
sudo -u postgres psql -c "CREATE USER $DB_USER WITH PASSWORD '$DB_PASSWORD';"
|
||||
|
||||
# Create database if it doesn't exist
|
||||
sudo -u postgres psql -c "SELECT 1 FROM pg_database WHERE datname='$DB_NAME'" | grep -q 1 || \
|
||||
sudo -u postgres psql -c "CREATE DATABASE $DB_NAME OWNER $DB_USER;"
|
||||
|
||||
# Grant privileges
|
||||
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;"
|
||||
|
||||
echo "✅ PostgreSQL setup complete!"
|
||||
echo ""
|
||||
echo "📋 Database connection info:"
|
||||
echo " Host: localhost"
|
||||
echo " Port: 5432"
|
||||
echo " Database: $DB_NAME"
|
||||
echo " User: $DB_USER"
|
||||
echo " Password: $DB_PASSWORD"
|
||||
echo ""
|
||||
echo "💡 Make sure your .env file contains:"
|
||||
echo " DB_HOST=localhost"
|
||||
echo " DB_PORT=5432"
|
||||
echo " DB_NAME=$DB_NAME"
|
||||
echo " DB_USER=$DB_USER"
|
||||
echo " DB_PASSWORD=$DB_PASSWORD"
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Run all unit tests and report results
|
||||
# This script should be run after making changes to ensure everything still works
|
||||
|
||||
echo "=========================================="
|
||||
echo "Running All Unit Tests"
|
||||
echo "=========================================="
|
||||
echo ""
|
||||
|
||||
# Run all tests
|
||||
npm test
|
||||
|
||||
# Check exit code
|
||||
if [ $? -eq 0 ]; then
|
||||
echo ""
|
||||
echo "=========================================="
|
||||
echo "✓ All tests passed!"
|
||||
echo "=========================================="
|
||||
exit 0
|
||||
else
|
||||
echo ""
|
||||
echo "=========================================="
|
||||
echo "✗ Some tests failed. Please fix errors above."
|
||||
echo "=========================================="
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Test script for backup/import functionality
|
||||
# This script runs the backup service tests and reports any errors
|
||||
|
||||
echo "=========================================="
|
||||
echo "Running Backup Service Tests"
|
||||
echo "=========================================="
|
||||
echo ""
|
||||
|
||||
# Run the tests
|
||||
npm test -- __tests__/services/backupService.test.js
|
||||
|
||||
# Check exit code
|
||||
if [ $? -eq 0 ]; then
|
||||
echo ""
|
||||
echo "=========================================="
|
||||
echo "✓ All backup service tests passed!"
|
||||
echo "=========================================="
|
||||
exit 0
|
||||
else
|
||||
echo ""
|
||||
echo "=========================================="
|
||||
echo "✗ Some tests failed. Please fix errors above."
|
||||
echo "=========================================="
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Verification script to check if ping data is being saved to the database
|
||||
* Run this script to verify that ping results and statistics are being stored correctly
|
||||
*/
|
||||
|
||||
require('dotenv').config();
|
||||
const { connectDB, getDB } = require('../src/config/db');
|
||||
const chalk = require('../src/utils/colors');
|
||||
|
||||
async function verifyPingData() {
|
||||
try {
|
||||
console.log(chalk.cyan('Connecting to database...'));
|
||||
await connectDB();
|
||||
const db = getDB();
|
||||
|
||||
console.log(chalk.cyan('\n=== Verifying Ping Data ===\n'));
|
||||
|
||||
// Check targets
|
||||
const targets = await db.collection('targets').find({ enabled: true }).toArray();
|
||||
console.log(chalk.yellow(`Found ${targets.length} enabled target(s)\n`));
|
||||
|
||||
if (targets.length === 0) {
|
||||
console.log(chalk.red('✗ No enabled targets found. Please create and enable at least one target.'));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Check ping results for each target
|
||||
for (const target of targets) {
|
||||
console.log(chalk.cyan(`\n--- Target: ${target.name} (${target._id}) ---`));
|
||||
|
||||
// Get recent ping results (last 24 hours)
|
||||
const oneDayAgo = new Date();
|
||||
oneDayAgo.setHours(oneDayAgo.getHours() - 24);
|
||||
|
||||
const recentPings = await db.collection('pingResults').find({
|
||||
targetId: target._id,
|
||||
timestamp: { $gte: oneDayAgo }
|
||||
}).toArray();
|
||||
|
||||
console.log(` Recent ping results (last 24h): ${recentPings.length}`);
|
||||
|
||||
if (recentPings.length > 0) {
|
||||
const latest = recentPings[recentPings.length - 1];
|
||||
const latestTime = new Date(latest.timestamp);
|
||||
const minutesAgo = Math.floor((Date.now() - latestTime.getTime()) / 1000 / 60);
|
||||
console.log(chalk.green(` ✓ Latest ping: ${minutesAgo} minutes ago`));
|
||||
console.log(` Success: ${latest.success}, Response Time: ${latest.responseTime || 'N/A'}ms`);
|
||||
} else {
|
||||
console.log(chalk.red(` ✗ No ping results found in last 24 hours`));
|
||||
}
|
||||
|
||||
// Get total ping results
|
||||
const totalPings = await db.collection('pingResults').find({
|
||||
targetId: target._id
|
||||
}).toArray();
|
||||
console.log(` Total ping results: ${totalPings.length}`);
|
||||
|
||||
// Check statistics
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
const todayStats = await db.collection('statistics').findOne({
|
||||
targetId: target._id,
|
||||
date: today
|
||||
});
|
||||
|
||||
if (todayStats) {
|
||||
console.log(chalk.green(` ✓ Today's statistics:`));
|
||||
console.log(` Total Pings: ${todayStats.totalPings}`);
|
||||
console.log(` Successful: ${todayStats.successfulPings}`);
|
||||
console.log(` Failed: ${todayStats.failedPings}`);
|
||||
console.log(` Avg Response Time: ${Math.round(todayStats.avgResponseTime || 0)}ms`);
|
||||
console.log(` Uptime: ${todayStats.uptime?.toFixed(2) || 0}%`);
|
||||
} else {
|
||||
console.log(chalk.yellow(` ⚠ No statistics found for today`));
|
||||
}
|
||||
}
|
||||
|
||||
// Overall summary
|
||||
const allPings = await db.collection('pingResults').find({}).toArray();
|
||||
const allStats = await db.collection('statistics').find({}).toArray();
|
||||
|
||||
console.log(chalk.cyan('\n=== Summary ==='));
|
||||
console.log(`Total ping results in database: ${allPings.length}`);
|
||||
console.log(`Total statistics records: ${allStats.length}`);
|
||||
|
||||
if (allPings.length === 0) {
|
||||
console.log(chalk.red('\n✗ WARNING: No ping results found in database!'));
|
||||
console.log(chalk.yellow(' This could mean:'));
|
||||
console.log(chalk.yellow(' 1. Monitoring is not running'));
|
||||
console.log(chalk.yellow(' 2. Targets are not enabled'));
|
||||
console.log(chalk.yellow(' 3. Database writes are failing (check logs)'));
|
||||
process.exit(1);
|
||||
} else {
|
||||
console.log(chalk.green('\n✓ Ping data is being saved to the database'));
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error(chalk.red('\n✗ Error verifying ping data:'), error.message);
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Run verification
|
||||
verifyPingData().then(() => {
|
||||
process.exit(0);
|
||||
}).catch(err => {
|
||||
console.error(chalk.red('Fatal error:'), err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
require('dotenv').config();
|
||||
const express = require('express');
|
||||
const expressWs = require('express-ws');
|
||||
const session = require('express-session');
|
||||
const cors = require('cors');
|
||||
const path = require('path');
|
||||
const yargs = require('yargs/yargs');
|
||||
const { hideBin } = require('yargs/helpers');
|
||||
const chalk = require('./utils/colors');
|
||||
|
||||
const { connectDB, disconnectDB, getPrisma } = require('./config/prisma');
|
||||
const SQLiteSessionStore = require('./config/sessionStore');
|
||||
const monitorService = require('./services/monitorService');
|
||||
const gatewayService = require('./services/gatewayService');
|
||||
// sqliteService removed - using PostgreSQL via db.js now
|
||||
const dataRetentionService = require('./services/dataRetentionService');
|
||||
const { apiKeyAuth, createRateLimiter, validateTargetInput } = require('./middleware/auth');
|
||||
const { setupCheckMiddleware, isSetupComplete } = require('./middleware/setupCheck');
|
||||
|
||||
// Parse command line arguments
|
||||
const argv = yargs(hideBin(process.argv))
|
||||
.option('mode', {
|
||||
describe: 'Application mode',
|
||||
choices: ['api', 'admin', 'public', 'all'],
|
||||
default: 'all',
|
||||
})
|
||||
.parse();
|
||||
|
||||
const app = express();
|
||||
app.set('trust proxy', true);
|
||||
expressWs(app);
|
||||
|
||||
// Middleware
|
||||
const compression = require('compression');
|
||||
app.use(compression());
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
app.use(cors());
|
||||
|
||||
// Initialize persistent session store
|
||||
const sessionStore = new SQLiteSessionStore();
|
||||
|
||||
// Helper function to get session duration from database (defaults to 30 days)
|
||||
const getSessionDuration = async () => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const settings = await prisma.adminSettings.findUnique({ where: { id: 'settings' } });
|
||||
const days = settings?.sessionDurationDays || 30;
|
||||
return days * 24 * 60 * 60 * 1000; // Convert days to milliseconds
|
||||
} catch (error) {
|
||||
// If DB not ready, return default
|
||||
return 30 * 24 * 60 * 60 * 1000; // 30 days default
|
||||
}
|
||||
};
|
||||
|
||||
// Session middleware for admin authentication
|
||||
// Note: maxAge will be updated dynamically in login route based on settings
|
||||
const sessionMiddleware = session({
|
||||
store: sessionStore,
|
||||
secret: process.env.SESSION_SECRET || 'localping-dev-secret',
|
||||
resave: false,
|
||||
saveUninitialized: false, // Don't save uninitialized sessions
|
||||
cookie: {
|
||||
secure: false, // Allow HTTP cookies for development - can be set via SECURE_COOKIES env var
|
||||
httpOnly: true,
|
||||
sameSite: 'lax', // Use 'lax' instead of 'strict' to allow cross-site requests with cookies
|
||||
maxAge: 30 * 24 * 60 * 60 * 1000 // Default 30 days, will be updated on login
|
||||
}
|
||||
});
|
||||
|
||||
app.use(sessionMiddleware);
|
||||
|
||||
// Rate limiting middleware (skip for localhost development)
|
||||
const apiRateLimiter = (req, res, next) => {
|
||||
const isLocalhost = req.ip === '127.0.0.1' || req.ip === '::1' || req.ip === '::ffff:127.0.0.1';
|
||||
if (isLocalhost && process.env.NODE_ENV !== 'production') {
|
||||
// Skip rate limiting for localhost in development
|
||||
return next();
|
||||
}
|
||||
// Apply rate limiter for production or remote IPs
|
||||
createRateLimiter(15 * 60 * 1000, 100)(req, res, next);
|
||||
};
|
||||
app.use('/api/', apiRateLimiter);
|
||||
|
||||
// Set view engine
|
||||
app.set('view engine', 'ejs');
|
||||
app.set('views', path.join(__dirname, 'views'));
|
||||
|
||||
// Static files
|
||||
app.use(express.static(path.join(__dirname, "public"), { maxAge: "7d" }));
|
||||
|
||||
// Serve favicon.ico (browser default)
|
||||
app.get('/favicon.ico', (req, res) => {
|
||||
res.sendFile(path.join(__dirname, 'public', 'favicon.ico'));
|
||||
});
|
||||
|
||||
// Health check endpoint (must be before setup check middleware)
|
||||
app.get('/health', (req, res) => {
|
||||
res.json({
|
||||
status: 'ok',
|
||||
timestamp: new Date(),
|
||||
uptime: process.uptime(),
|
||||
mode: argv.mode,
|
||||
});
|
||||
});
|
||||
|
||||
// Setup routes - must be registered BEFORE setup check middleware
|
||||
const setupRoutes = require('./routes/setup');
|
||||
app.use('/setup', setupRoutes);
|
||||
console.log(chalk.cyan('✓ Setup routes loaded'));
|
||||
|
||||
// Setup check middleware - redirect to setup if not configured
|
||||
// This checks after setup routes are registered
|
||||
app.use(setupCheckMiddleware);
|
||||
|
||||
// Initialize database
|
||||
let prisma = null;
|
||||
|
||||
const startServer = async () => {
|
||||
try {
|
||||
// Connect to PostgreSQL database via Prisma
|
||||
prisma = await connectDB();
|
||||
|
||||
// Detect gateway
|
||||
await gatewayService.detectAllGateways();
|
||||
|
||||
// Set up periodic cleanup of old data (handled by dataRetentionService)
|
||||
|
||||
// Set up periodic data retention processing
|
||||
// Run once on startup, then every 6 hours
|
||||
(async () => {
|
||||
try {
|
||||
await dataRetentionService.processRetentionForAllTargets();
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error processing initial data retention:'), error.message);
|
||||
}
|
||||
})();
|
||||
|
||||
setInterval(async () => {
|
||||
try {
|
||||
await dataRetentionService.processRetentionForAllTargets();
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error processing data retention:'), error.message);
|
||||
}
|
||||
}, 6 * 60 * 60 * 1000); // Run every 6 hours
|
||||
|
||||
// Set up periodic processing of scheduled incidents
|
||||
const IncidentService = require('./services/incidentService');
|
||||
const incidentService = new IncidentService(prisma);
|
||||
setInterval(async () => {
|
||||
try {
|
||||
await incidentService.processScheduledIncidents();
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error processing scheduled incidents:'), error.message);
|
||||
}
|
||||
}, 60 * 1000); // Check every minute
|
||||
|
||||
// Check if setup is needed
|
||||
if (!isSetupComplete()) {
|
||||
console.log(chalk.yellow('\n⚠️ LocalPing setup incomplete!'));
|
||||
console.log(chalk.yellow(' Visit http://localhost:8000/setup to complete setup\n'));
|
||||
}
|
||||
|
||||
// Static public site (src/site, or SITE_DIR to override with your own theme).
|
||||
// SITE_HOSTS (comma-separated) limits it to specific Host headers; unset = all hosts.
|
||||
if (argv.mode === 'public' || argv.mode === 'all') {
|
||||
const siteDir = process.env.SITE_DIR || path.join(__dirname, 'site');
|
||||
if (require('fs').existsSync(path.join(siteDir, 'index.html'))) {
|
||||
const hosts = (process.env.SITE_HOSTS || '').split(',').map((h) => h.trim().toLowerCase()).filter(Boolean);
|
||||
const onlyHosts = (mw) => (req, res, next) => (!hosts.length || hosts.includes(req.hostname.toLowerCase())) ? mw(req, res, next) : next();
|
||||
const spa = (req, res) => res.sendFile(path.join(siteDir, 'index.html'), { headers: { 'Cache-Control': 'no-cache' } });
|
||||
app.use('/', onlyHosts(require('./routes/site')));
|
||||
app.use('/s', onlyHosts(express.static(siteDir, { maxAge: '1h' })));
|
||||
app.use(onlyHosts(express.static(siteDir, { maxAge: '1h', index: false })));
|
||||
['/', '/status', '/news', '/tools', '/about'].forEach((r) => app.get(r, onlyHosts(spa)));
|
||||
console.log(chalk.cyan('✓ Static site loaded from ' + siteDir + (hosts.length ? ' for ' + hosts.join(',') : '')));
|
||||
}
|
||||
}
|
||||
|
||||
// Public routes - load FIRST so they don't get caught by authenticated API routes
|
||||
if (argv.mode === 'public' || argv.mode === 'all') {
|
||||
const publicRoutes = require('./routes/public');
|
||||
app.use('/', publicRoutes);
|
||||
console.log(chalk.cyan('✓ Public routes loaded'));
|
||||
}
|
||||
|
||||
// Admin routes - must be before authenticated API routes
|
||||
if (argv.mode === 'admin' || argv.mode === 'all') {
|
||||
const adminRoutes = require('./routes/admin');
|
||||
app.use('/admin', adminRoutes);
|
||||
console.log(chalk.cyan('✓ Admin routes loaded'));
|
||||
}
|
||||
|
||||
// Authenticated API routes - load LAST so public routes are matched first
|
||||
if (argv.mode === 'api' || argv.mode === 'all') {
|
||||
const apiRoutes = require('./routes/api');
|
||||
// Apply API key authentication to API routes
|
||||
app.use('/api', apiKeyAuth, apiRoutes);
|
||||
console.log(chalk.cyan('✓ API routes loaded with authentication'));
|
||||
}
|
||||
|
||||
// Start monitoring (non-blocking - runs in background)
|
||||
monitorService.startMonitoring();
|
||||
|
||||
// Listen on port (starts immediately, doesn't wait for monitoring)
|
||||
const port = process.env.API_PORT || 3000;
|
||||
app.listen(port, () => {
|
||||
console.log(chalk.green(`✓ Server running on http://localhost:${port}`));
|
||||
console.log(chalk.cyan(` Mode: ${argv.mode}`));
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Failed to start server:'), error.message);
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
// Graceful shutdown
|
||||
const shutdown = async (signal) => {
|
||||
console.log(chalk.yellow(`\n✓ Received ${signal}, shutting down gracefully...`));
|
||||
|
||||
try {
|
||||
monitorService.stopAllMonitoring();
|
||||
const pingService = require('./services/pingService');
|
||||
await pingService.shutdown();
|
||||
await disconnectDB();
|
||||
console.log(chalk.green('✓ Server shut down successfully'));
|
||||
process.exit(0);
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error during shutdown:'), error.message);
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
||||
process.on('SIGINT', () => shutdown('SIGINT'));
|
||||
|
||||
// Start server
|
||||
startServer();
|
||||
|
||||
module.exports = app;
|
||||
@@ -0,0 +1,228 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
require('dotenv').config();
|
||||
const chalk = require('../utils/colors');
|
||||
const yargs = require('yargs/yargs');
|
||||
const { hideBin } = require('yargs/helpers');
|
||||
const inquirer = require('inquirer');
|
||||
const { connectDB, getDB, closeDB } = require('../config/db');
|
||||
const pingService = require('../services/pingService');
|
||||
const gatewayService = require('../services/gatewayService');
|
||||
|
||||
const argv = yargs(hideBin(process.argv))
|
||||
.command('status', 'Show system status')
|
||||
.command('test <host>', 'Test ping a host')
|
||||
.command('config', 'Configure targets')
|
||||
.command('list', 'List all targets')
|
||||
.command('notify', 'Send test notification')
|
||||
.command('gateway', 'Show detected gateway')
|
||||
.command('monitor', 'Start interactive monitor (for terminal)')
|
||||
.help()
|
||||
.alias('h', 'help')
|
||||
.version()
|
||||
.alias('v', 'version')
|
||||
.parse();
|
||||
|
||||
const command = argv._[0];
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
switch (command) {
|
||||
case 'status':
|
||||
await showStatus();
|
||||
break;
|
||||
case 'test':
|
||||
await testHost(argv.host);
|
||||
break;
|
||||
case 'config':
|
||||
await configureTargets();
|
||||
break;
|
||||
case 'list':
|
||||
await listTargets();
|
||||
break;
|
||||
case 'notify':
|
||||
await sendTestNotification();
|
||||
break;
|
||||
case 'gateway':
|
||||
await showGateway();
|
||||
break;
|
||||
case 'monitor':
|
||||
await interactiveMonitor();
|
||||
break;
|
||||
default:
|
||||
showHelp();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error:'), error.message);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
await closeDB();
|
||||
}
|
||||
}
|
||||
|
||||
async function showStatus() {
|
||||
const db = await connectDB();
|
||||
|
||||
const targets = await db.collection('targets').find({}).toArray();
|
||||
const upTargets = targets.filter((t) => t.enabled).length;
|
||||
|
||||
console.log(chalk.cyan('\n📊 LocalPing Status\n'));
|
||||
console.log(`Total Targets: ${chalk.bold(targets.length)}`);
|
||||
console.log(`Enabled Targets: ${chalk.bold(upTargets)}`);
|
||||
console.log();
|
||||
|
||||
if (targets.length === 0) {
|
||||
console.log(chalk.yellow('No targets configured. Use "localping config" to add targets.'));
|
||||
} else {
|
||||
console.log(chalk.cyan('\nRecent Alerts:'));
|
||||
const alerts = await db.collection('alerts').find({}).sort({ timestamp: -1 }).limit(5).toArray();
|
||||
|
||||
if (alerts.length === 0) {
|
||||
console.log(chalk.green('✓ No alerts'));
|
||||
} else {
|
||||
alerts.forEach((alert) => {
|
||||
const icon = alert.type === 'down' ? '✗' : '✓';
|
||||
const color = alert.type === 'down' ? chalk.red : chalk.green;
|
||||
console.log(color(`${icon} ${alert.message}`));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
console.log();
|
||||
}
|
||||
|
||||
async function testHost(host) {
|
||||
console.log(chalk.cyan(`\n🔍 Testing ${host}...\n`));
|
||||
|
||||
const tests = [
|
||||
{ protocol: 'ICMP', host },
|
||||
{ protocol: 'TCP', host, port: 80 },
|
||||
{ protocol: 'UDP', host, port: 53 },
|
||||
{ protocol: 'HTTP', host, port: 80, path: '/' },
|
||||
{ protocol: 'HTTPS', host, port: 443, path: '/' },
|
||||
];
|
||||
|
||||
for (const test of tests) {
|
||||
const result = await pingService.ping(test);
|
||||
const status = result.success ? chalk.green('✓ UP') : chalk.red('✗ DOWN');
|
||||
const time = result.responseTime ? ` (${result.responseTime}ms)` : '';
|
||||
console.log(`${test.protocol.padEnd(8)} ${status}${time}`);
|
||||
}
|
||||
|
||||
console.log();
|
||||
}
|
||||
|
||||
async function configureTargets() {
|
||||
const db = await connectDB();
|
||||
|
||||
const answers = await inquirer.prompt([
|
||||
{
|
||||
type: 'list',
|
||||
name: 'action',
|
||||
message: 'What would you like to do?',
|
||||
choices: [
|
||||
{ name: 'Add target', value: 'add' },
|
||||
{ name: 'Edit target', value: 'edit' },
|
||||
{ name: 'Delete target', value: 'delete' },
|
||||
{ name: 'Back', value: 'back' },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
if (answers.action === 'add') {
|
||||
const target = await inquirer.prompt([
|
||||
{ type: 'input', name: 'name', message: 'Target name:' },
|
||||
{ type: 'input', name: 'host', message: 'Host/IP:' },
|
||||
{
|
||||
type: 'list',
|
||||
name: 'protocol',
|
||||
message: 'Protocol:',
|
||||
choices: ['ICMP', 'TCP', 'UDP', 'HTTP', 'HTTPS'],
|
||||
},
|
||||
{ type: 'input', name: 'port', message: 'Port (optional):', default: '' },
|
||||
{ type: 'input', name: 'interval', message: 'Ping interval (seconds):', default: '60' },
|
||||
]);
|
||||
|
||||
await db.collection('targets').insertOne({
|
||||
...target,
|
||||
port: target.port ? parseInt(target.port) : null,
|
||||
interval: parseInt(target.interval),
|
||||
enabled: true,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
|
||||
console.log(chalk.green('✓ Target added successfully!'));
|
||||
}
|
||||
}
|
||||
|
||||
async function listTargets() {
|
||||
const db = await connectDB();
|
||||
|
||||
const targets = await db.collection('targets').find({}).toArray();
|
||||
|
||||
console.log(chalk.cyan('\n📋 Configured Targets\n'));
|
||||
|
||||
if (targets.length === 0) {
|
||||
console.log(chalk.yellow('No targets configured.'));
|
||||
} else {
|
||||
targets.forEach((target, i) => {
|
||||
console.log(`${i + 1}. ${target.name}`);
|
||||
console.log(` Host: ${target.host}${target.port ? ':' + target.port : ''}`);
|
||||
console.log(` Protocol: ${target.protocol}`);
|
||||
console.log(` Interval: ${target.interval}s`);
|
||||
console.log(` Status: ${target.enabled ? chalk.green('Enabled') : chalk.yellow('Disabled')}\n`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function sendTestNotification() {
|
||||
console.log(chalk.cyan('\n📢 Browser notifications are available in the public UI\n'));
|
||||
console.log(chalk.yellow('Desktop notifications have been removed for containerized environments.'));
|
||||
console.log(chalk.green('Visit the public dashboard to enable browser notifications.'));
|
||||
console.log();
|
||||
}
|
||||
|
||||
async function showGateway() {
|
||||
await gatewayService.detectAllGateways();
|
||||
|
||||
console.log(chalk.cyan('\n🌐 Gateway Information\n'));
|
||||
|
||||
const gateways = gatewayService.getAllGateways();
|
||||
|
||||
if (gateways.length === 0) {
|
||||
console.log(chalk.yellow('No gateway detected.'));
|
||||
} else {
|
||||
gateways.forEach((gw) => {
|
||||
console.log(`IPv${gw.version}: ${gw.ip} (${gw.interface})`);
|
||||
});
|
||||
}
|
||||
|
||||
console.log();
|
||||
}
|
||||
|
||||
async function interactiveMonitor() {
|
||||
const db = await connectDB();
|
||||
|
||||
console.log(chalk.cyan('\n📡 LocalPing Interactive Monitor\n'));
|
||||
console.log(chalk.gray('Press Ctrl+C to exit\n'));
|
||||
|
||||
// Placeholder for terminal UI implementation
|
||||
console.log(chalk.yellow('⚠ Terminal UI not yet implemented.'));
|
||||
console.log('Use the web admin panel instead: http://\n');
|
||||
}
|
||||
|
||||
function showHelp() {
|
||||
console.log(chalk.cyan('\nLocalPing CLI - Local System Uptime Monitor\n'));
|
||||
console.log('Commands:');
|
||||
console.log(' localping status - Show system status');
|
||||
console.log(' localping test - Test ping a host');
|
||||
console.log(' localping config - Configure targets');
|
||||
console.log(' localping list - List all targets');
|
||||
console.log(' localping notify - Send test notification');
|
||||
console.log(' localping gateway - Show detected gateway');
|
||||
console.log(' localping monitor - Start interactive monitor');
|
||||
console.log();
|
||||
}
|
||||
|
||||
// Run CLI
|
||||
main();
|
||||
@@ -0,0 +1,880 @@
|
||||
require('dotenv').config();
|
||||
const { Pool } = require('pg');
|
||||
const chalk = require('../utils/colors');
|
||||
const cacheService = require('../services/cacheService');
|
||||
|
||||
let pool = null;
|
||||
|
||||
const connectDB = async (retries = 5, delay = 2000) => {
|
||||
// Get database connection details from environment or use defaults
|
||||
const dbConfig = {
|
||||
host: process.env.DB_HOST || 'localhost',
|
||||
port: process.env.DB_PORT || 5432,
|
||||
database: process.env.DB_NAME || 'localping',
|
||||
user: process.env.DB_USER || 'localping',
|
||||
password: process.env.DB_PASSWORD || 'localping',
|
||||
max: 20, // Maximum number of clients in the pool
|
||||
idleTimeoutMillis: 30000,
|
||||
connectionTimeoutMillis: 2000,
|
||||
};
|
||||
|
||||
for (let attempt = 1; attempt <= retries; attempt++) {
|
||||
try {
|
||||
// Close existing pool if it exists
|
||||
if (pool) {
|
||||
try {
|
||||
await pool.end();
|
||||
} catch (e) {
|
||||
// Ignore errors when closing
|
||||
}
|
||||
pool = null;
|
||||
}
|
||||
|
||||
pool = new Pool(dbConfig);
|
||||
|
||||
// Test connection
|
||||
const client = await pool.connect();
|
||||
await client.query('SELECT NOW()');
|
||||
client.release();
|
||||
|
||||
// Initialize tables
|
||||
await initializeTables();
|
||||
|
||||
console.log(chalk.green('✓ PostgreSQL database connected'));
|
||||
|
||||
// Return a minimal object compatible with the rest of the code
|
||||
return {
|
||||
collection: (name) => createCollectionWrapper(name),
|
||||
admin: () => ({
|
||||
ping: async () => {
|
||||
try {
|
||||
const client = await pool.connect();
|
||||
await client.query('SELECT 1');
|
||||
client.release();
|
||||
return true;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
} catch (error) {
|
||||
if (attempt === retries) {
|
||||
console.error(chalk.red('✗ PostgreSQL connection failed after'), retries, 'attempts:', error.message);
|
||||
console.error(chalk.yellow(' Please check:'));
|
||||
console.error(chalk.yellow(' - PostgreSQL is running: systemctl status postgresql'));
|
||||
console.error(chalk.yellow(' - Database credentials in .env file'));
|
||||
console.error(chalk.yellow(' - Connection settings:'), `host=${dbConfig.host}, port=${dbConfig.port}, database=${dbConfig.database}, user=${dbConfig.user}`);
|
||||
process.exit(1);
|
||||
} else {
|
||||
const waitTime = delay * Math.pow(2, attempt - 1); // Exponential backoff
|
||||
console.error(chalk.yellow(`⚠ PostgreSQL connection failed (attempt ${attempt}/${retries}):`), error.message);
|
||||
console.error(chalk.yellow(` Retrying in ${waitTime / 1000} seconds...`));
|
||||
await new Promise(resolve => setTimeout(resolve, waitTime));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const executeQuery = async (text, params) => {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
const result = await client.query(text, params);
|
||||
return result;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
};
|
||||
|
||||
const initializeTables = async () => {
|
||||
try {
|
||||
// Targets table
|
||||
await executeQuery(`
|
||||
CREATE TABLE IF NOT EXISTS targets (
|
||||
_id TEXT PRIMARY KEY,
|
||||
name TEXT UNIQUE NOT NULL,
|
||||
host TEXT NOT NULL,
|
||||
protocol TEXT NOT NULL,
|
||||
port INTEGER,
|
||||
path TEXT,
|
||||
enabled BOOLEAN DEFAULT true,
|
||||
"publicVisible" BOOLEAN DEFAULT true,
|
||||
"publicShowDetails" BOOLEAN DEFAULT false,
|
||||
"publicShowStatus" BOOLEAN DEFAULT true,
|
||||
"publicShowAppLink" BOOLEAN DEFAULT true,
|
||||
interval INTEGER DEFAULT 60,
|
||||
retries INTEGER DEFAULT 0,
|
||||
"retryInterval" INTEGER DEFAULT 5,
|
||||
timeout INTEGER DEFAULT 30,
|
||||
"httpMethod" TEXT DEFAULT 'GET',
|
||||
"statusCodes" TEXT DEFAULT '200-299',
|
||||
"maxRedirects" INTEGER DEFAULT 5,
|
||||
"ignoreSsl" BOOLEAN DEFAULT false,
|
||||
"upsideDown" BOOLEAN DEFAULT false,
|
||||
auth TEXT,
|
||||
"appUrl" TEXT,
|
||||
"appIcon" TEXT,
|
||||
position INTEGER DEFAULT 0,
|
||||
"group" TEXT,
|
||||
"quickCommands" TEXT,
|
||||
"createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
// Migration: Add publicVisible column if it doesn't exist
|
||||
try {
|
||||
await executeQuery(`ALTER TABLE targets ADD COLUMN IF NOT EXISTS "publicVisible" BOOLEAN DEFAULT true`);
|
||||
} catch (error) {
|
||||
// Column already exists, ignore
|
||||
}
|
||||
|
||||
// Migration: Add publicShowDetails column if it doesn't exist
|
||||
try {
|
||||
await executeQuery(`ALTER TABLE targets ADD COLUMN IF NOT EXISTS "publicShowDetails" BOOLEAN DEFAULT false`);
|
||||
} catch (error) {
|
||||
// Column already exists, ignore
|
||||
}
|
||||
|
||||
// Migration: Add publicShowStatus column if it doesn't exist
|
||||
try {
|
||||
await executeQuery(`ALTER TABLE targets ADD COLUMN IF NOT EXISTS "publicShowStatus" BOOLEAN DEFAULT true`);
|
||||
} catch (error) {
|
||||
// Column already exists, ignore
|
||||
}
|
||||
|
||||
// Migration: Add publicShowAppLink column if it doesn't exist
|
||||
try {
|
||||
await executeQuery(`ALTER TABLE targets ADD COLUMN IF NOT EXISTS "publicShowAppLink" BOOLEAN DEFAULT true`);
|
||||
} catch (error) {
|
||||
// Column already exists, ignore
|
||||
}
|
||||
|
||||
// Ping results table
|
||||
await executeQuery(`
|
||||
CREATE TABLE IF NOT EXISTS "pingResults" (
|
||||
_id TEXT PRIMARY KEY,
|
||||
"targetId" TEXT NOT NULL,
|
||||
success BOOLEAN NOT NULL,
|
||||
"responseTime" INTEGER,
|
||||
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
"statusCode" INTEGER,
|
||||
error TEXT,
|
||||
protocol TEXT,
|
||||
FOREIGN KEY("targetId") REFERENCES targets(_id)
|
||||
)
|
||||
`);
|
||||
|
||||
// Alerts table
|
||||
await executeQuery(`
|
||||
CREATE TABLE IF NOT EXISTS alerts (
|
||||
_id TEXT PRIMARY KEY,
|
||||
"targetId" TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
message TEXT,
|
||||
FOREIGN KEY("targetId") REFERENCES targets(_id)
|
||||
)
|
||||
`);
|
||||
|
||||
// Statistics table
|
||||
await executeQuery(`
|
||||
CREATE TABLE IF NOT EXISTS statistics (
|
||||
_id TEXT PRIMARY KEY,
|
||||
"targetId" TEXT NOT NULL,
|
||||
date DATE NOT NULL,
|
||||
"totalPings" INTEGER DEFAULT 0,
|
||||
"successfulPings" INTEGER DEFAULT 0,
|
||||
"failedPings" INTEGER DEFAULT 0,
|
||||
uptime REAL DEFAULT 0,
|
||||
"lastResponseTime" INTEGER DEFAULT 0,
|
||||
"avgResponseTime" REAL DEFAULT 0,
|
||||
"minResponseTime" INTEGER,
|
||||
"maxResponseTime" INTEGER,
|
||||
FOREIGN KEY("targetId") REFERENCES targets(_id),
|
||||
UNIQUE("targetId", date)
|
||||
)
|
||||
`);
|
||||
|
||||
// Incidents table
|
||||
await executeQuery(`
|
||||
CREATE TABLE IF NOT EXISTS incidents (
|
||||
_id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
description TEXT,
|
||||
severity TEXT DEFAULT 'major',
|
||||
status TEXT DEFAULT 'investigating',
|
||||
"affectedServices" TEXT,
|
||||
updates TEXT,
|
||||
"resolvedAt" TIMESTAMP,
|
||||
"createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
// Migration: Add affectedServices column if it doesn't exist
|
||||
try {
|
||||
await executeQuery(`ALTER TABLE incidents ADD COLUMN IF NOT EXISTS "affectedServices" TEXT`);
|
||||
} catch (error) {
|
||||
// Column already exists, ignore
|
||||
}
|
||||
|
||||
// Migration: Add updates column if it doesn't exist
|
||||
try {
|
||||
await executeQuery(`ALTER TABLE incidents ADD COLUMN IF NOT EXISTS updates TEXT`);
|
||||
} catch (error) {
|
||||
// Column already exists, ignore
|
||||
}
|
||||
|
||||
// Migration: Add resolvedAt column if it doesn't exist
|
||||
try {
|
||||
await executeQuery(`ALTER TABLE incidents ADD COLUMN IF NOT EXISTS "resolvedAt" TIMESTAMP`);
|
||||
} catch (error) {
|
||||
// Column already exists, ignore
|
||||
}
|
||||
|
||||
// Event Rules table
|
||||
await executeQuery(`
|
||||
CREATE TABLE IF NOT EXISTS "eventRules" (
|
||||
_id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
"eventType" TEXT NOT NULL,
|
||||
enabled BOOLEAN DEFAULT true,
|
||||
conditions TEXT NOT NULL,
|
||||
"incidentTitle" TEXT NOT NULL,
|
||||
"incidentDescription" TEXT NOT NULL,
|
||||
"incidentSeverity" TEXT DEFAULT 'major',
|
||||
"incidentStatus" TEXT DEFAULT 'investigating',
|
||||
"autoResolve" BOOLEAN DEFAULT false,
|
||||
"autoResolveMessage" TEXT,
|
||||
"cooldownMinutes" INTEGER DEFAULT 0,
|
||||
"createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
// Actions table
|
||||
await executeQuery(`
|
||||
CREATE TABLE IF NOT EXISTS actions (
|
||||
_id TEXT PRIMARY KEY,
|
||||
"targetId" TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
command TEXT,
|
||||
"createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY("targetId") REFERENCES targets(_id),
|
||||
UNIQUE("targetId", name)
|
||||
)
|
||||
`);
|
||||
|
||||
// Favicons table
|
||||
await executeQuery(`
|
||||
CREATE TABLE IF NOT EXISTS favicons (
|
||||
_id TEXT PRIMARY KEY,
|
||||
"appUrl" TEXT NOT NULL UNIQUE,
|
||||
favicon TEXT,
|
||||
"updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
// Public UI Settings table
|
||||
await executeQuery(`
|
||||
CREATE TABLE IF NOT EXISTS "publicUISettings" (
|
||||
_id TEXT PRIMARY KEY DEFAULT 'settings',
|
||||
title TEXT DEFAULT 'Homelab',
|
||||
subtitle TEXT DEFAULT 'System Status & Application Dashboard',
|
||||
"customCSS" TEXT,
|
||||
"updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
// Initialize default settings if not exists
|
||||
await executeQuery(`
|
||||
INSERT INTO "publicUISettings" (_id, title, subtitle, "customCSS")
|
||||
VALUES ('settings', 'Homelab', 'System Status & Application Dashboard', NULL)
|
||||
ON CONFLICT (_id) DO NOTHING
|
||||
`);
|
||||
|
||||
// Posts table (for blog/changelog)
|
||||
await executeQuery(`
|
||||
CREATE TABLE IF NOT EXISTS posts (
|
||||
_id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
published BOOLEAN DEFAULT true,
|
||||
"createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
// Admin Settings table
|
||||
await executeQuery(`
|
||||
CREATE TABLE IF NOT EXISTS "adminSettings" (
|
||||
_id TEXT PRIMARY KEY DEFAULT 'settings',
|
||||
"sessionDurationDays" INTEGER DEFAULT 30,
|
||||
"dataRetentionDays" INTEGER DEFAULT 30,
|
||||
"updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
// Migration: Add dataRetentionDays column if it doesn't exist
|
||||
try {
|
||||
await executeQuery(`ALTER TABLE "adminSettings" ADD COLUMN IF NOT EXISTS "dataRetentionDays" INTEGER DEFAULT 30`);
|
||||
} catch (error) {
|
||||
// Column already exists, ignore
|
||||
}
|
||||
|
||||
// Migration: Add debugLogging column if it doesn't exist
|
||||
try {
|
||||
await executeQuery(`ALTER TABLE "adminSettings" ADD COLUMN IF NOT EXISTS "debugLogging" BOOLEAN DEFAULT false`);
|
||||
} catch (error) {
|
||||
// Column already exists, ignore
|
||||
}
|
||||
|
||||
// Initialize default admin settings if not exists
|
||||
await executeQuery(`
|
||||
INSERT INTO "adminSettings" (_id, "sessionDurationDays", "dataRetentionDays")
|
||||
VALUES ('settings', 30, 30)
|
||||
ON CONFLICT (_id) DO NOTHING
|
||||
`);
|
||||
|
||||
// Notification Settings table
|
||||
await executeQuery(`
|
||||
CREATE TABLE IF NOT EXISTS "notificationSettings" (
|
||||
_id TEXT PRIMARY KEY DEFAULT 'settings',
|
||||
enabled BOOLEAN DEFAULT false,
|
||||
discord TEXT,
|
||||
events TEXT,
|
||||
"monitorDownDelayMinutes" INTEGER DEFAULT 5,
|
||||
"updatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
// Migration: add the sustained-outage notification delay to existing installs.
|
||||
try {
|
||||
await executeQuery(`ALTER TABLE "notificationSettings" ADD COLUMN IF NOT EXISTS "monitorDownDelayMinutes" INTEGER DEFAULT 5`);
|
||||
} catch (error) {
|
||||
// Column already exists, ignore.
|
||||
}
|
||||
|
||||
// Create indices
|
||||
await executeQuery(`CREATE INDEX IF NOT EXISTS idx_targets_enabled ON targets(enabled)`);
|
||||
await executeQuery(`CREATE INDEX IF NOT EXISTS idx_pingResults_targetId ON "pingResults"("targetId")`);
|
||||
await executeQuery(`CREATE INDEX IF NOT EXISTS idx_pingResults_timestamp ON "pingResults"(timestamp)`);
|
||||
await executeQuery(`CREATE INDEX IF NOT EXISTS idx_alerts_targetId ON alerts("targetId")`);
|
||||
await executeQuery(`CREATE INDEX IF NOT EXISTS idx_alerts_timestamp ON alerts(timestamp)`);
|
||||
await executeQuery(`CREATE INDEX IF NOT EXISTS idx_statistics_targetId ON statistics("targetId")`);
|
||||
await executeQuery(`CREATE INDEX IF NOT EXISTS idx_statistics_date ON statistics(date)`);
|
||||
await executeQuery(`CREATE INDEX IF NOT EXISTS idx_incidents_status ON incidents(status)`);
|
||||
await executeQuery(`CREATE INDEX IF NOT EXISTS idx_eventRules_enabled ON "eventRules"(enabled)`);
|
||||
await executeQuery(`CREATE INDEX IF NOT EXISTS idx_actions_targetId ON actions("targetId")`);
|
||||
await executeQuery(`CREATE INDEX IF NOT EXISTS idx_posts_published ON posts(published)`);
|
||||
await executeQuery(`CREATE INDEX IF NOT EXISTS idx_posts_createdAt ON posts("createdAt")`);
|
||||
|
||||
console.log(chalk.green('✓ PostgreSQL tables initialized'));
|
||||
} catch (error) {
|
||||
console.error(chalk.yellow('⚠ Warning initializing tables:'), error.message);
|
||||
}
|
||||
};
|
||||
|
||||
// Get TTL for different collections
|
||||
const getTTL = (collectionName) => {
|
||||
const ttlMap = {
|
||||
'adminSettings': 300000, // 5 minutes - rarely changes
|
||||
'publicUISettings': 300000, // 5 minutes - rarely changes
|
||||
'targets': 30000, // 30 seconds - may change more often
|
||||
'statistics': 120000, // 2 minutes - updated periodically
|
||||
'favicons': 600000, // 10 minutes - very rarely changes
|
||||
'posts': 60000, // 1 minute - may change occasionally
|
||||
'incidents': 60000, // 1 minute - may change occasionally
|
||||
};
|
||||
return ttlMap[collectionName] || 60000; // Default 1 minute
|
||||
};
|
||||
|
||||
const createCollectionWrapper = (name) => {
|
||||
return {
|
||||
find: (queryObj = {}) => {
|
||||
// Store options for chaining
|
||||
let sortOption = null;
|
||||
let limitOption = null;
|
||||
|
||||
const chainable = {
|
||||
sort: (sortObj) => {
|
||||
sortOption = sortObj;
|
||||
return chainable;
|
||||
},
|
||||
limit: (num) => {
|
||||
limitOption = num;
|
||||
return chainable;
|
||||
},
|
||||
toArray: async () => {
|
||||
try {
|
||||
// Check cache first
|
||||
const cacheKey = cacheService.generateKey(name, queryObj, { sort: sortOption, limit: limitOption });
|
||||
const cached = cacheService.get(cacheKey);
|
||||
if (cached !== null) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const keys = Object.keys(queryObj).filter(k => typeof queryObj[k] !== 'function');
|
||||
let sql = `SELECT * FROM "${name}"`;
|
||||
const params = [];
|
||||
let paramIndex = 1;
|
||||
|
||||
if (keys.length > 0) {
|
||||
const whereClauses = keys.map(k => {
|
||||
const val = queryObj[k];
|
||||
// Handle MongoDB-style operators
|
||||
if (typeof val === 'object' && val !== null && !(val instanceof Date)) {
|
||||
if ('$gte' in val) {
|
||||
const gteVal = val.$gte;
|
||||
if (gteVal instanceof Date) {
|
||||
params.push(gteVal.toISOString().split('T')[0]);
|
||||
} else {
|
||||
params.push(gteVal);
|
||||
}
|
||||
const idx = paramIndex++;
|
||||
return `"${k}" >= $${idx}`;
|
||||
} else if ('$lte' in val) {
|
||||
const lteVal = val.$lte;
|
||||
if (lteVal instanceof Date) {
|
||||
params.push(lteVal.toISOString().split('T')[0]);
|
||||
} else {
|
||||
params.push(lteVal);
|
||||
}
|
||||
const idx = paramIndex++;
|
||||
return `"${k}" <= $${idx}`;
|
||||
} else if ('$gt' in val) {
|
||||
const gtVal = val.$gt;
|
||||
if (gtVal instanceof Date) {
|
||||
params.push(gtVal.toISOString().split('T')[0]);
|
||||
} else {
|
||||
params.push(gtVal);
|
||||
}
|
||||
const idx = paramIndex++;
|
||||
return `"${k}" > $${idx}`;
|
||||
} else if ('$lt' in val) {
|
||||
const ltVal = val.$lt;
|
||||
if (ltVal instanceof Date) {
|
||||
params.push(ltVal.toISOString().split('T')[0]);
|
||||
} else {
|
||||
params.push(ltVal);
|
||||
}
|
||||
const idx = paramIndex++;
|
||||
return `"${k}" < $${idx}`;
|
||||
} else {
|
||||
// Fallback to JSON stringify for other objects
|
||||
params.push(JSON.stringify(val));
|
||||
const idx = paramIndex++;
|
||||
return `"${k}" = $${idx}`;
|
||||
}
|
||||
}
|
||||
// Handle different types
|
||||
if (typeof val === 'boolean') {
|
||||
params.push(val);
|
||||
} else if (val instanceof Date) {
|
||||
// Convert Date to ISO date string (YYYY-MM-DD)
|
||||
params.push(val.toISOString().split('T')[0]);
|
||||
} else {
|
||||
params.push(val);
|
||||
}
|
||||
const idx = paramIndex++;
|
||||
return `"${k}" = $${idx}`;
|
||||
});
|
||||
sql += ' WHERE ' + whereClauses.join(' AND ');
|
||||
}
|
||||
|
||||
// Add sorting
|
||||
if (sortOption) {
|
||||
const sortKey = Object.keys(sortOption)[0];
|
||||
const sortDir = sortOption[sortKey] === 1 ? 'ASC' : 'DESC';
|
||||
sql += ` ORDER BY "${sortKey}" ${sortDir}`;
|
||||
}
|
||||
|
||||
// Add limit
|
||||
if (limitOption) {
|
||||
sql += ` LIMIT ${limitOption}`;
|
||||
}
|
||||
|
||||
const result = await executeQuery(sql, params);
|
||||
|
||||
// Convert boolean integers back to booleans for compatibility
|
||||
const results = result.rows.map(row => {
|
||||
const converted = {};
|
||||
for (const [key, value] of Object.entries(row)) {
|
||||
// PostgreSQL returns booleans as booleans, but keep for consistency
|
||||
converted[key] = value;
|
||||
}
|
||||
return converted;
|
||||
});
|
||||
|
||||
// Cache the results
|
||||
cacheService.set(cacheKey, results, getTTL(name));
|
||||
|
||||
return results;
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Error finding ${name}:`), error.message);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return chainable;
|
||||
},
|
||||
findOne: async (queryObj = {}) => {
|
||||
try {
|
||||
// Check cache first
|
||||
const cacheKey = cacheService.generateKey(name, queryObj, { findOne: true });
|
||||
const cached = cacheService.get(cacheKey);
|
||||
if (cached !== null) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const keys = Object.keys(queryObj).filter(k => typeof queryObj[k] !== 'function');
|
||||
let sql = `SELECT * FROM "${name}"`;
|
||||
const params = [];
|
||||
let paramIndex = 1;
|
||||
|
||||
if (keys.length > 0) {
|
||||
const whereClauses = keys.map(k => {
|
||||
const val = queryObj[k];
|
||||
// Handle different types
|
||||
if (typeof val === 'boolean') {
|
||||
params.push(val);
|
||||
} else if (val instanceof Date) {
|
||||
// Convert Date to ISO date string (YYYY-MM-DD) for DATE columns
|
||||
if (name === 'statistics' && k === 'date') {
|
||||
params.push(val.toISOString().split('T')[0]);
|
||||
} else {
|
||||
params.push(val.toISOString().split('T')[0]);
|
||||
}
|
||||
} else if (typeof val === 'object' && val !== null) {
|
||||
params.push(JSON.stringify(val));
|
||||
} else {
|
||||
params.push(val);
|
||||
}
|
||||
const idx = paramIndex++;
|
||||
return `"${k}" = $${idx}`;
|
||||
});
|
||||
sql += ' WHERE ' + whereClauses.join(' AND ');
|
||||
}
|
||||
|
||||
sql += ' LIMIT 1';
|
||||
const result = await executeQuery(sql, params);
|
||||
const row = result.rows[0] || null;
|
||||
|
||||
// Cache the result
|
||||
cacheService.set(cacheKey, row, getTTL(name));
|
||||
|
||||
return row;
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Error finding one ${name}:`), error.message);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
insertOne: async (doc) => {
|
||||
try {
|
||||
const id = doc._id || require('uuid').v4();
|
||||
const docWithId = { _id: id, ...doc };
|
||||
const fields = Object.keys(docWithId);
|
||||
const placeholders = fields.map((_, i) => `$${i + 1}`).join(', ');
|
||||
const quotedFields = fields.map(f => `"${f}"`).join(', ');
|
||||
const values = fields.map(f => {
|
||||
const val = docWithId[f];
|
||||
// PostgreSQL handles booleans natively
|
||||
if (typeof val === 'boolean') {
|
||||
return val;
|
||||
}
|
||||
// Convert Date to ISO timestamp string (YYYY-MM-DD HH:MM:SS) or date string for DATE columns
|
||||
if (val instanceof Date) {
|
||||
// For statistics table date column, use date format
|
||||
if (name === 'statistics' && f === 'date') {
|
||||
return val.toISOString().split('T')[0];
|
||||
}
|
||||
return val.toISOString().replace('T', ' ').substring(0, 19);
|
||||
}
|
||||
// Convert arrays and objects to JSON strings
|
||||
if (typeof val === 'object' && val !== null) {
|
||||
return JSON.stringify(val);
|
||||
}
|
||||
return val;
|
||||
});
|
||||
|
||||
// Use INSERT with ON CONFLICT for tables with unique constraints
|
||||
let sql = `INSERT INTO "${name}" (${quotedFields}) VALUES (${placeholders})`;
|
||||
|
||||
// Handle unique constraints with ON CONFLICT for specific tables
|
||||
if (name === 'statistics') {
|
||||
// Statistics has UNIQUE(targetId, date) - use ON CONFLICT to increment values atomically
|
||||
// In ON CONFLICT, reference existing row columns directly (no qualifier needed)
|
||||
// and new row columns with excluded.
|
||||
const updateClauses = [];
|
||||
// Increment counters
|
||||
if (fields.includes('totalPings')) {
|
||||
updateClauses.push(`"totalPings" = statistics."totalPings" + excluded."totalPings"`);
|
||||
}
|
||||
if (fields.includes('successfulPings')) {
|
||||
updateClauses.push(`"successfulPings" = statistics."successfulPings" + excluded."successfulPings"`);
|
||||
}
|
||||
if (fields.includes('failedPings')) {
|
||||
updateClauses.push(`"failedPings" = statistics."failedPings" + excluded."failedPings"`);
|
||||
}
|
||||
// Update latest values
|
||||
if (fields.includes('lastResponseTime')) {
|
||||
updateClauses.push(`"lastResponseTime" = excluded."lastResponseTime"`);
|
||||
}
|
||||
// Recalculate average: weighted average of existing and new
|
||||
if (fields.includes('avgResponseTime')) {
|
||||
updateClauses.push(`"avgResponseTime" = CASE
|
||||
WHEN statistics."totalPings" + excluded."totalPings" > 0
|
||||
THEN (statistics."avgResponseTime" * statistics."totalPings" + excluded."avgResponseTime" * excluded."totalPings") / (statistics."totalPings" + excluded."totalPings")
|
||||
ELSE excluded."avgResponseTime"
|
||||
END`);
|
||||
}
|
||||
// Recalculate uptime percentage
|
||||
if (fields.includes('uptime')) {
|
||||
updateClauses.push(`"uptime" = CASE
|
||||
WHEN statistics."totalPings" + excluded."totalPings" > 0
|
||||
THEN (CAST(statistics."successfulPings" + excluded."successfulPings" AS REAL) / CAST(statistics."totalPings" + excluded."totalPings" AS REAL)) * 100
|
||||
ELSE excluded."uptime"
|
||||
END`);
|
||||
}
|
||||
// Update min/max response times
|
||||
if (fields.includes('minResponseTime')) {
|
||||
updateClauses.push(`"minResponseTime" = CASE
|
||||
WHEN statistics."minResponseTime" IS NULL THEN excluded."minResponseTime"
|
||||
WHEN excluded."minResponseTime" IS NULL THEN statistics."minResponseTime"
|
||||
WHEN statistics."minResponseTime" < excluded."minResponseTime" THEN statistics."minResponseTime"
|
||||
ELSE excluded."minResponseTime"
|
||||
END`);
|
||||
}
|
||||
if (fields.includes('maxResponseTime')) {
|
||||
updateClauses.push(`"maxResponseTime" = CASE
|
||||
WHEN statistics."maxResponseTime" IS NULL THEN excluded."maxResponseTime"
|
||||
WHEN excluded."maxResponseTime" IS NULL THEN statistics."maxResponseTime"
|
||||
WHEN statistics."maxResponseTime" > excluded."maxResponseTime" THEN statistics."maxResponseTime"
|
||||
ELSE excluded."maxResponseTime"
|
||||
END`);
|
||||
}
|
||||
if (updateClauses.length > 0) {
|
||||
sql = `INSERT INTO "${name}" (${quotedFields}) VALUES (${placeholders}) ON CONFLICT("targetId", date) DO UPDATE SET ${updateClauses.join(', ')}`;
|
||||
}
|
||||
} else if (name === 'actions') {
|
||||
// Actions has UNIQUE(targetId, name) - use ON CONFLICT to update instead
|
||||
const updateFields = fields.filter(f => f !== '_id' && f !== 'targetId' && f !== 'name');
|
||||
const updateClauses = updateFields.map(f => `"${f}" = excluded."${f}"`).join(', ');
|
||||
sql = `INSERT INTO "${name}" (${quotedFields}) VALUES (${placeholders}) ON CONFLICT("targetId", name) DO UPDATE SET ${updateClauses}`;
|
||||
} else if (name === 'favicons') {
|
||||
// Favicons has UNIQUE(appUrl) - use ON CONFLICT to update instead
|
||||
const updateFields = fields.filter(f => f !== '_id' && f !== 'appUrl');
|
||||
const updateClauses = updateFields.map(f => `"${f}" = excluded."${f}"`).join(', ');
|
||||
sql = `INSERT INTO "${name}" (${quotedFields}) VALUES (${placeholders}) ON CONFLICT("appUrl") DO UPDATE SET ${updateClauses}`;
|
||||
} else if (name === 'targets') {
|
||||
// Targets has UNIQUE(name) - use ON CONFLICT to update instead
|
||||
const updateFields = fields.filter(f => f !== '_id' && f !== 'name');
|
||||
const updateClauses = updateFields.map(f => `"${f}" = excluded."${f}"`).join(', ');
|
||||
sql = `INSERT INTO "${name}" (${quotedFields}) VALUES (${placeholders}) ON CONFLICT(name) DO UPDATE SET ${updateClauses}`;
|
||||
}
|
||||
|
||||
await executeQuery(sql, values);
|
||||
|
||||
// Invalidate cache for this collection
|
||||
cacheService.invalidateCollection(name);
|
||||
|
||||
return { insertedId: id };
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Error inserting into ${name}:`), error.message);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
updateOne: async (queryObj, update) => {
|
||||
try {
|
||||
const { $set } = update;
|
||||
const setClauses = Object.keys($set).map((k, i) => `"${k}" = $${i + 1}`).join(', ');
|
||||
const setValues = Object.values($set).map((v, idx) => {
|
||||
if (typeof v === 'boolean') {
|
||||
return v;
|
||||
}
|
||||
if (v instanceof Date) {
|
||||
// For statistics table date column, use date format (YYYY-MM-DD)
|
||||
const key = Object.keys($set)[idx];
|
||||
if (name === 'statistics' && key === 'date') {
|
||||
return v.toISOString().split('T')[0];
|
||||
}
|
||||
return v.toISOString().replace('T', ' ').substring(0, 19);
|
||||
}
|
||||
if (typeof v === 'object' && v !== null) {
|
||||
return JSON.stringify(v);
|
||||
}
|
||||
return v;
|
||||
});
|
||||
|
||||
const queryKeys = Object.keys(queryObj);
|
||||
const whereClauses = queryKeys.map((k, i) => `"${k}" = $${setValues.length + i + 1}`).join(' AND ');
|
||||
const whereValues = Object.values(queryObj).map((v, idx) => {
|
||||
if (typeof v === 'boolean') {
|
||||
return v;
|
||||
}
|
||||
if (v instanceof Date) {
|
||||
// For statistics table date column, use date format (YYYY-MM-DD)
|
||||
const key = Object.keys(queryObj)[idx];
|
||||
if (name === 'statistics' && key === 'date') {
|
||||
return v.toISOString().split('T')[0];
|
||||
}
|
||||
return v.toISOString().replace('T', ' ').substring(0, 19);
|
||||
}
|
||||
if (typeof v === 'object' && v !== null) {
|
||||
return JSON.stringify(v);
|
||||
}
|
||||
return v;
|
||||
});
|
||||
|
||||
const sql = `UPDATE "${name}" SET ${setClauses} WHERE ${whereClauses}`;
|
||||
const result = await executeQuery(sql, [...setValues, ...whereValues]);
|
||||
|
||||
// Invalidate cache for this collection
|
||||
cacheService.invalidateCollection(name);
|
||||
|
||||
return { modifiedCount: result.rowCount || 0 };
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Error updating ${name}:`), error.message);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
deleteOne: async (queryObj) => {
|
||||
try {
|
||||
const keys = Object.keys(queryObj);
|
||||
const whereClauses = keys.map((k, i) => `"${k}" = $${i + 1}`).join(' AND ');
|
||||
const values = Object.values(queryObj).map(v => {
|
||||
if (typeof v === 'boolean') {
|
||||
return v;
|
||||
}
|
||||
if (v instanceof Date) {
|
||||
return v.toISOString().replace('T', ' ').substring(0, 19);
|
||||
}
|
||||
return v;
|
||||
});
|
||||
|
||||
const sql = `DELETE FROM "${name}" WHERE ${whereClauses}`;
|
||||
const result = await executeQuery(sql, values);
|
||||
|
||||
// Invalidate cache for this collection
|
||||
cacheService.invalidateCollection(name);
|
||||
|
||||
return { deletedCount: result.rowCount || 0 };
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Error deleting from ${name}:`), error.message);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
deleteMany: async (queryObj = {}) => {
|
||||
try {
|
||||
const keys = Object.keys(queryObj).filter(k => typeof queryObj[k] !== 'function');
|
||||
let sql = `DELETE FROM "${name}"`;
|
||||
const params = [];
|
||||
let paramIndex = 1;
|
||||
|
||||
if (keys.length > 0) {
|
||||
const whereClauses = keys.map(k => {
|
||||
const val = queryObj[k];
|
||||
if (typeof val === 'boolean') {
|
||||
params.push(val);
|
||||
} else if (val instanceof Date) {
|
||||
params.push(val.toISOString().split('T')[0]);
|
||||
} else {
|
||||
params.push(val);
|
||||
}
|
||||
const idx = paramIndex++;
|
||||
return `"${k}" = $${idx}`;
|
||||
});
|
||||
sql += ' WHERE ' + whereClauses.join(' AND ');
|
||||
}
|
||||
|
||||
const result = await executeQuery(sql, params);
|
||||
|
||||
// Invalidate cache for this collection
|
||||
cacheService.invalidateCollection(name);
|
||||
|
||||
return { deletedCount: result.rowCount || 0 };
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Error deleting from ${name}:`), error.message);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
countDocuments: async (queryObj = {}) => {
|
||||
try {
|
||||
// Check cache first
|
||||
const cacheKey = cacheService.generateKey(name, queryObj, { count: true });
|
||||
const cached = cacheService.get(cacheKey);
|
||||
if (cached !== null) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const keys = Object.keys(queryObj).filter(k => typeof queryObj[k] !== 'function');
|
||||
let sql = `SELECT COUNT(*) as count FROM "${name}"`;
|
||||
const params = [];
|
||||
let paramIndex = 1;
|
||||
|
||||
if (keys.length > 0) {
|
||||
const whereClauses = keys.map(k => {
|
||||
const val = queryObj[k];
|
||||
params.push(typeof val === 'boolean' ? val : val);
|
||||
const idx = paramIndex++;
|
||||
return `"${k}" = $${idx}`;
|
||||
});
|
||||
sql += ' WHERE ' + whereClauses.join(' AND ');
|
||||
}
|
||||
|
||||
const result = await executeQuery(sql, params);
|
||||
const count = result.rows[0] ? parseInt(result.rows[0].count) : 0;
|
||||
|
||||
// Cache the count
|
||||
cacheService.set(cacheKey, count, getTTL(name));
|
||||
|
||||
return count;
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Error counting ${name}:`), error.message);
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
createIndex: async () => true
|
||||
};
|
||||
};
|
||||
|
||||
const getDB = () => {
|
||||
if (!pool) {
|
||||
throw new Error('Database not connected. Call connectDB() first.');
|
||||
}
|
||||
return {
|
||||
collection: (name) => createCollectionWrapper(name),
|
||||
admin: () => ({
|
||||
ping: async () => {
|
||||
try {
|
||||
const client = await pool.connect();
|
||||
await client.query('SELECT 1');
|
||||
client.release();
|
||||
return true;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}),
|
||||
// Direct query method for complex SQL queries
|
||||
query: async (text, params) => {
|
||||
return await executeQuery(text, params);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const closeDB = async () => {
|
||||
if (pool) {
|
||||
await pool.end();
|
||||
console.log(chalk.green('✓ PostgreSQL connection closed'));
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
connectDB,
|
||||
getDB,
|
||||
closeDB,
|
||||
};
|
||||
@@ -0,0 +1,91 @@
|
||||
const { PrismaClient } = require('@prisma/client');
|
||||
const chalk = require('../utils/colors');
|
||||
|
||||
// Singleton pattern for Prisma client
|
||||
let prisma = null;
|
||||
|
||||
/**
|
||||
* Get or create the Prisma client instance
|
||||
*/
|
||||
const getPrisma = () => {
|
||||
if (!prisma) {
|
||||
prisma = new PrismaClient({
|
||||
log: process.env.NODE_ENV === 'development'
|
||||
? ['warn', 'error']
|
||||
: ['error'],
|
||||
});
|
||||
}
|
||||
return prisma;
|
||||
};
|
||||
|
||||
/**
|
||||
* Keep existing installations compatible with additive schema changes. The
|
||||
* application is commonly upgraded in place, so relying only on a fresh
|
||||
* `prisma db push` would leave the notification settings endpoint unusable on
|
||||
* older databases.
|
||||
*/
|
||||
const ensureRuntimeSchema = async (client) => {
|
||||
try {
|
||||
await client.$executeRawUnsafe(
|
||||
'ALTER TABLE "notificationSettings" ADD COLUMN IF NOT EXISTS "monitorDownDelayMinutes" INTEGER NOT NULL DEFAULT 5',
|
||||
);
|
||||
// The public uptime list aggregates recent ping results by monitor and
|
||||
// time bucket. Keep the two predicates together in one index so that
|
||||
// loading the compact graphs does not scan the complete ping history.
|
||||
await client.$executeRawUnsafe(
|
||||
'CREATE INDEX IF NOT EXISTS idx_pingResults_targetId_timestamp ON "pingResults"("targetId", timestamp)',
|
||||
);
|
||||
} catch (error) {
|
||||
// A first-run database may not have been pushed yet. Prisma's normal
|
||||
// schema deployment remains responsible for creating missing tables.
|
||||
console.warn(chalk.yellow('⚠ Could not apply notification delay migration:'), error.message);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Connect to the database
|
||||
*/
|
||||
const connectDB = async () => {
|
||||
try {
|
||||
const client = getPrisma();
|
||||
await client.$connect();
|
||||
await ensureRuntimeSchema(client);
|
||||
console.log(chalk.green('✓ PostgreSQL database connected via Prisma'));
|
||||
return client;
|
||||
} catch (error) {
|
||||
console.error(chalk.red('✗ PostgreSQL connection failed:'), error.message);
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Disconnect from the database
|
||||
*/
|
||||
const disconnectDB = async () => {
|
||||
if (prisma) {
|
||||
await prisma.$disconnect();
|
||||
console.log(chalk.green('✓ PostgreSQL connection closed'));
|
||||
prisma = null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Execute raw SQL query
|
||||
* @param {string} sql - SQL query with $1, $2, etc. placeholders
|
||||
* @param {Array} params - Query parameters
|
||||
*/
|
||||
const executeRawQuery = async (sql, params = []) => {
|
||||
const client = getPrisma();
|
||||
// Convert $1, $2 style to Prisma.sql template
|
||||
// For now, use $queryRawUnsafe but be careful with SQL injection
|
||||
const result = await client.$queryRawUnsafe(sql, ...params);
|
||||
return { rows: result };
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
getPrisma,
|
||||
connectDB,
|
||||
disconnectDB,
|
||||
executeRawQuery,
|
||||
ensureRuntimeSchema,
|
||||
};
|
||||
@@ -0,0 +1,136 @@
|
||||
const Database = require('better-sqlite3');
|
||||
const session = require('express-session');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
let db = null;
|
||||
|
||||
class SQLiteSessionStore extends session.Store {
|
||||
constructor(options = {}) {
|
||||
super(options);
|
||||
const dbDir = path.join(process.cwd(), 'data');
|
||||
const dbPath = path.join(dbDir, 'localping.db');
|
||||
|
||||
// Ensure data directory exists
|
||||
if (!fs.existsSync(dbDir)) {
|
||||
fs.mkdirSync(dbDir, { recursive: true });
|
||||
}
|
||||
|
||||
db = new Database(dbPath);
|
||||
db.pragma('foreign_keys = ON');
|
||||
|
||||
// Create sessions table if it doesn't exist
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
sid TEXT PRIMARY KEY,
|
||||
sess TEXT NOT NULL,
|
||||
expire INTEGER NOT NULL
|
||||
)
|
||||
`);
|
||||
|
||||
// Create index on expire for cleanup
|
||||
db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_expire ON sessions(expire)
|
||||
`);
|
||||
|
||||
// Clean up expired sessions periodically (every hour)
|
||||
setInterval(() => {
|
||||
this.cleanup();
|
||||
}, 60 * 60 * 1000);
|
||||
}
|
||||
|
||||
get(sid, callback) {
|
||||
try {
|
||||
const stmt = db.prepare('SELECT sess FROM sessions WHERE sid = ? AND expire > ?');
|
||||
const row = stmt.get(sid, Date.now());
|
||||
|
||||
if (row) {
|
||||
callback(null, JSON.parse(row.sess));
|
||||
} else {
|
||||
callback(null, null);
|
||||
}
|
||||
} catch (error) {
|
||||
callback(error);
|
||||
}
|
||||
}
|
||||
|
||||
set(sid, sess, callback) {
|
||||
try {
|
||||
const expire = sess.cookie && sess.cookie.expires
|
||||
? sess.cookie.expires.getTime()
|
||||
: Date.now() + (24 * 60 * 60 * 1000); // Default 24 hours
|
||||
|
||||
const stmt = db.prepare('INSERT OR REPLACE INTO sessions (sid, sess, expire) VALUES (?, ?, ?)');
|
||||
stmt.run(sid, JSON.stringify(sess), expire);
|
||||
callback(null);
|
||||
} catch (error) {
|
||||
callback(error);
|
||||
}
|
||||
}
|
||||
|
||||
destroy(sid, callback) {
|
||||
try {
|
||||
const stmt = db.prepare('DELETE FROM sessions WHERE sid = ?');
|
||||
stmt.run(sid);
|
||||
callback(null);
|
||||
} catch (error) {
|
||||
callback(error);
|
||||
}
|
||||
}
|
||||
|
||||
all(callback) {
|
||||
try {
|
||||
const stmt = db.prepare('SELECT sess FROM sessions WHERE expire > ?');
|
||||
const rows = stmt.all(Date.now());
|
||||
const sessions = rows.map(row => JSON.parse(row.sess));
|
||||
callback(null, sessions);
|
||||
} catch (error) {
|
||||
callback(error);
|
||||
}
|
||||
}
|
||||
|
||||
length(callback) {
|
||||
try {
|
||||
const stmt = db.prepare('SELECT COUNT(*) as count FROM sessions WHERE expire > ?');
|
||||
const row = stmt.get(Date.now());
|
||||
callback(null, row ? row.count : 0);
|
||||
} catch (error) {
|
||||
callback(error);
|
||||
}
|
||||
}
|
||||
|
||||
clear(callback) {
|
||||
try {
|
||||
db.exec('DELETE FROM sessions');
|
||||
callback(null);
|
||||
} catch (error) {
|
||||
callback(error);
|
||||
}
|
||||
}
|
||||
|
||||
touch(sid, sess, callback) {
|
||||
try {
|
||||
const expire = sess.cookie && sess.cookie.expires
|
||||
? sess.cookie.expires.getTime()
|
||||
: Date.now() + (24 * 60 * 60 * 1000);
|
||||
|
||||
const stmt = db.prepare('UPDATE sessions SET sess = ?, expire = ? WHERE sid = ?');
|
||||
stmt.run(JSON.stringify(sess), expire, sid);
|
||||
callback(null);
|
||||
} catch (error) {
|
||||
callback(error);
|
||||
}
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
try {
|
||||
const stmt = db.prepare('DELETE FROM sessions WHERE expire < ?');
|
||||
stmt.run(Date.now());
|
||||
} catch (error) {
|
||||
console.error('Error cleaning up sessions:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SQLiteSessionStore;
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
const { app, BrowserWindow, Menu, ipcMain } = require('electron');
|
||||
const path = require('path');
|
||||
const isDev = require('electron-is-dev');
|
||||
|
||||
let mainWindow;
|
||||
|
||||
function createWindow() {
|
||||
mainWindow = new BrowserWindow({
|
||||
width: 1400,
|
||||
height: 900,
|
||||
minWidth: 800,
|
||||
minHeight: 600,
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.js'),
|
||||
contextIsolation: true,
|
||||
enableRemoteModule: false,
|
||||
nodeIntegration: false,
|
||||
},
|
||||
});
|
||||
|
||||
const startURL = isDev
|
||||
? 'http://localhost:3001/admin'
|
||||
: `file://${path.join(__dirname, '../views/admin/index.ejs')}`;
|
||||
|
||||
mainWindow.loadURL(startURL);
|
||||
|
||||
if (isDev) {
|
||||
mainWindow.webContents.openDevTools();
|
||||
}
|
||||
|
||||
mainWindow.on('closed', () => {
|
||||
mainWindow = null;
|
||||
});
|
||||
}
|
||||
|
||||
// Create application menu
|
||||
function createMenu() {
|
||||
const template = [
|
||||
{
|
||||
label: 'File',
|
||||
submenu: [
|
||||
{
|
||||
label: 'Exit',
|
||||
accelerator: 'CmdOrCtrl+Q',
|
||||
click: () => {
|
||||
app.quit();
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'View',
|
||||
submenu: [
|
||||
{
|
||||
label: 'Reload',
|
||||
accelerator: 'CmdOrCtrl+R',
|
||||
click: () => {
|
||||
mainWindow.webContents.reload();
|
||||
},
|
||||
},
|
||||
{
|
||||
label: 'Dev Tools',
|
||||
accelerator: 'CmdOrCtrl+Shift+I',
|
||||
click: () => {
|
||||
mainWindow.webContents.toggleDevTools();
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const menu = Menu.buildFromTemplate(template);
|
||||
Menu.setApplicationMenu(menu);
|
||||
}
|
||||
|
||||
app.on('ready', () => {
|
||||
createWindow();
|
||||
createMenu();
|
||||
});
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
app.on('activate', () => {
|
||||
if (mainWindow === null) {
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
|
||||
// IPC handlers
|
||||
ipcMain.handle('get-status', async (event) => {
|
||||
// Implementation for getting status from API
|
||||
return { status: 'ok' };
|
||||
});
|
||||
|
||||
module.exports = mainWindow;
|
||||
@@ -0,0 +1,5 @@
|
||||
const { contextBridge, ipcMain } = require('electron');
|
||||
|
||||
contextBridge.exposeInMainWorld('api', {
|
||||
getStatus: () => ipcMain.invoke('get-status'),
|
||||
});
|
||||
@@ -0,0 +1,191 @@
|
||||
const chalk = require('../utils/colors');
|
||||
|
||||
/**
|
||||
* API Key Authentication Middleware
|
||||
* Checks for valid API key in Authorization header or X-API-Key header
|
||||
*/
|
||||
function apiKeyAuth(req, res, next) {
|
||||
const apiKey = process.env.ADMIN_API_KEY;
|
||||
|
||||
// If no API key is configured, skip authentication (unsafe - only for local dev)
|
||||
if (!apiKey) {
|
||||
console.warn(chalk.yellow('⚠ No ADMIN_API_KEY configured - authentication disabled'));
|
||||
return next();
|
||||
}
|
||||
|
||||
// Check for API key in headers
|
||||
const authHeader = req.headers.authorization || '';
|
||||
const xApiKey = req.headers['x-api-key'] || '';
|
||||
|
||||
// Support both "Bearer <token>" and direct key
|
||||
const providedKey = authHeader.replace('Bearer ', '') || xApiKey;
|
||||
|
||||
if (!providedKey || providedKey !== apiKey) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
error: 'Unauthorized: Invalid or missing API key',
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin Page Authentication Middleware
|
||||
* Checks for admin password in session or cookie
|
||||
*/
|
||||
function adminPageAuth(req, res, next) {
|
||||
const adminPassword = process.env.ADMIN_PASSWORD;
|
||||
|
||||
// If no admin password is configured, skip authentication (shouldn't happen after setup)
|
||||
if (!adminPassword || !adminPassword.trim()) {
|
||||
console.warn(chalk.yellow('⚠ No ADMIN_PASSWORD configured - admin page authentication disabled'));
|
||||
return next();
|
||||
}
|
||||
|
||||
// Allow login page and login POST endpoint without authentication
|
||||
if (req.path === '/login' || (req.method === 'POST' && req.path === '/login')) {
|
||||
return next();
|
||||
}
|
||||
|
||||
// Check if user has valid admin session
|
||||
// Session expiration is handled automatically by the session store and cookie maxAge
|
||||
if (req.session && req.session.adminAuthenticated) {
|
||||
return next();
|
||||
}
|
||||
|
||||
// Not authenticated - redirect to login
|
||||
if (req.headers.accept && req.headers.accept.includes('application/json')) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
error: 'Unauthorized: Admin authentication required',
|
||||
});
|
||||
}
|
||||
|
||||
// For page requests, redirect to login
|
||||
res.redirect('/admin/login');
|
||||
}
|
||||
|
||||
/**
|
||||
* Rate Limiting Middleware
|
||||
* Prevents brute force attacks on API endpoints
|
||||
*/
|
||||
function createRateLimiter(windowMs = 15 * 60 * 1000, maxRequests = 100) {
|
||||
const requests = new Map();
|
||||
|
||||
return (req, res, next) => {
|
||||
const ip = req.ip || req.connection.remoteAddress;
|
||||
const now = Date.now();
|
||||
|
||||
// Clean old entries
|
||||
if (!requests.has(ip)) {
|
||||
requests.set(ip, []);
|
||||
}
|
||||
|
||||
const userRequests = requests.get(ip);
|
||||
|
||||
// Remove requests outside the window
|
||||
const recentRequests = userRequests.filter((time) => now - time < windowMs);
|
||||
requests.set(ip, recentRequests);
|
||||
|
||||
// Check if over limit
|
||||
if (recentRequests.length >= maxRequests) {
|
||||
return res.status(429).json({
|
||||
success: false,
|
||||
error: 'Too many requests, please try again later',
|
||||
});
|
||||
}
|
||||
|
||||
// Record this request
|
||||
recentRequests.push(now);
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Input Validation Middleware
|
||||
* Validates that required fields are present and valid
|
||||
* For PUT requests, allows partial updates (only validates provided fields)
|
||||
*/
|
||||
function validateTargetInput(req, res, next) {
|
||||
const { name, host, protocol, port, interval } = req.body;
|
||||
const isUpdate = req.method === 'PUT';
|
||||
|
||||
const errors = [];
|
||||
|
||||
// For PUT requests, only validate fields that are provided
|
||||
// For POST requests, validate all required fields
|
||||
if (!isUpdate) {
|
||||
// Validate name (required for POST)
|
||||
if (!name || typeof name !== 'string' || name.trim().length === 0) {
|
||||
errors.push('Target name is required and must be a non-empty string');
|
||||
}
|
||||
|
||||
// Validate host (required for POST)
|
||||
if (!host || typeof host !== 'string' || host.trim().length === 0) {
|
||||
errors.push('Host is required and must be a non-empty string');
|
||||
}
|
||||
|
||||
// Validate protocol (required for POST)
|
||||
const validProtocols = ['ICMP', 'TCP', 'UDP', 'HTTP', 'HTTPS'];
|
||||
if (!protocol || !validProtocols.includes(protocol.toUpperCase())) {
|
||||
errors.push(`Protocol must be one of: ${validProtocols.join(', ')}`);
|
||||
}
|
||||
} else {
|
||||
// For PUT requests, only validate provided fields
|
||||
// Validate name if provided
|
||||
if (name !== undefined) {
|
||||
if (typeof name !== 'string' || name.trim().length === 0) {
|
||||
errors.push('Target name must be a non-empty string');
|
||||
}
|
||||
}
|
||||
|
||||
// Validate host if provided
|
||||
if (host !== undefined) {
|
||||
if (typeof host !== 'string' || host.trim().length === 0) {
|
||||
errors.push('Host must be a non-empty string');
|
||||
}
|
||||
}
|
||||
|
||||
// Validate protocol if provided
|
||||
if (protocol !== undefined) {
|
||||
const validProtocols = ['ICMP', 'TCP', 'UDP', 'HTTP', 'HTTPS'];
|
||||
if (!validProtocols.includes(protocol.toUpperCase())) {
|
||||
errors.push(`Protocol must be one of: ${validProtocols.join(', ')}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Validate port if provided (null means no custom port, which is valid)
|
||||
if (port !== undefined && port !== null) {
|
||||
const portNum = parseInt(port, 10);
|
||||
if (isNaN(portNum) || portNum < 1 || portNum > 65535) {
|
||||
errors.push('Port must be a number between 1 and 65535');
|
||||
}
|
||||
}
|
||||
|
||||
// Validate interval if provided (null means use default, which is valid)
|
||||
if (interval !== undefined && interval !== null) {
|
||||
const intervalNum = parseInt(interval, 10);
|
||||
if (isNaN(intervalNum) || intervalNum < 5 || intervalNum > 3600) {
|
||||
errors.push('Interval must be a number between 5 and 3600 seconds');
|
||||
}
|
||||
}
|
||||
|
||||
// If there are errors, return them
|
||||
if (errors.length > 0) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
errors: errors,
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
apiKeyAuth,
|
||||
adminPageAuth,
|
||||
createRateLimiter,
|
||||
validateTargetInput,
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Setup Check Middleware
|
||||
* Checks if LocalPing has been configured (admin password set)
|
||||
* Redirects to setup wizard if not configured
|
||||
*/
|
||||
|
||||
function isSetupComplete() {
|
||||
const adminPassword = process.env.ADMIN_PASSWORD;
|
||||
return !!(adminPassword && adminPassword.trim());
|
||||
}
|
||||
|
||||
function setupCheckMiddleware(req, res, next) {
|
||||
// Allow access to setup routes without checking
|
||||
if (req.path.startsWith('/setup')) {
|
||||
return next();
|
||||
}
|
||||
|
||||
// Allow static assets
|
||||
if (req.path.startsWith('/public') || req.path.startsWith('/vendor') || req.path.startsWith('/js') || req.path.startsWith('/css') || req.path.match(/\.(css|js|png|jpg|gif|svg|ico|woff|woff2|ttf|eot)$/)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
// Check if setup is complete
|
||||
if (!isSetupComplete()) {
|
||||
// Allow public API access for status pages, but redirect web UI
|
||||
if (req.path.startsWith('/api/') && req.headers.accept !== 'text/html') {
|
||||
return next();
|
||||
}
|
||||
|
||||
// Redirect web UI to setup
|
||||
if (req.headers.accept && req.headers.accept.includes('text/html')) {
|
||||
return res.redirect('/setup');
|
||||
}
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
setupCheckMiddleware,
|
||||
isSetupComplete,
|
||||
};
|
||||
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 18 KiB |
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<browserconfig><msapplication><tile><square70x70logo src="/ms-icon-70x70.png"/><square150x150logo src="/ms-icon-150x150.png"/><square310x310logo src="/ms-icon-310x310.png"/><TileColor>#ffffff</TileColor></tile></msapplication></browserconfig>
|
||||
|
After Width: | Height: | Size: 709 B |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,934 @@
|
||||
let pingChart = null;
|
||||
let selectedTargetId = null;
|
||||
let allTargets = [];
|
||||
|
||||
// Session-based authentication - no API key needed for admin panel
|
||||
// API calls use secure session cookies automatically
|
||||
axios.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
// If 401, redirect to login
|
||||
if (error.response?.status === 401) {
|
||||
window.location.href = '/admin/login';
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
// Load on page load
|
||||
loadDashboard();
|
||||
|
||||
// Auto-refresh every 15 seconds
|
||||
setInterval(loadDashboard, 15000);
|
||||
|
||||
async function loadDashboard() {
|
||||
try {
|
||||
const res = await axios.get('/admin/api/dashboard');
|
||||
const { dashboard } = res.data;
|
||||
|
||||
allTargets = dashboard.targets;
|
||||
|
||||
// Update stats
|
||||
const upCount = dashboard.targets.filter((t) => t.currentStatus === 'up').length;
|
||||
const downCount = dashboard.targets.length - upCount;
|
||||
|
||||
document.getElementById('total-targets').textContent = dashboard.targets.length;
|
||||
document.getElementById('targets-up').textContent = upCount;
|
||||
document.getElementById('targets-down').textContent = downCount;
|
||||
document.getElementById('active-monitors').textContent = dashboard.targets.filter((t) => t.enabled).length;
|
||||
|
||||
// Display monitors list
|
||||
displayMonitorsList(dashboard.targets);
|
||||
|
||||
// Update selected monitor if one is selected (but NOT if form is open)
|
||||
const formPanel = document.getElementById('form-panel');
|
||||
if (selectedTargetId && !formPanel.classList.contains('hidden')) {
|
||||
// Form is open, don't switch to details view
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedTargetId) {
|
||||
const selectedTarget = dashboard.targets.find(t => t._id === selectedTargetId);
|
||||
if (selectedTarget) {
|
||||
displayMonitorDetail(selectedTarget);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading dashboard:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function displayMonitorsList(targets) {
|
||||
const list = document.getElementById('services-list');
|
||||
const searchTerm = document.getElementById('search-input')?.value.toLowerCase() || '';
|
||||
|
||||
const filtered = targets.filter(target =>
|
||||
target.name.toLowerCase().includes(searchTerm) ||
|
||||
target.host.toLowerCase().includes(searchTerm)
|
||||
);
|
||||
|
||||
if (filtered.length === 0) {
|
||||
list.innerHTML = '<div class="px-4 py-8 text-center text-slate-400">No monitors found</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
list.innerHTML = filtered.map(target => {
|
||||
const isSelected = selectedTargetId === target._id;
|
||||
const statusColor = target.currentStatus === 'up' ? 'bg-green-500' : 'bg-red-500';
|
||||
|
||||
return `
|
||||
<div
|
||||
onclick="selectMonitor('${target._id}')"
|
||||
class="px-4 py-3 cursor-pointer hover:bg-slate-700/50 transition ${isSelected ? 'service-item-selected' : ''}"
|
||||
>
|
||||
<div class="flex items-start justify-between mb-2">
|
||||
<div class="flex items-center gap-2 flex-1">
|
||||
<div class="w-2 h-2 rounded-full ${statusColor} flex-shrink-0"></div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<h3 class="font-semibold text-sm truncate">${target.name}</h3>
|
||||
<p class="text-slate-400 text-xs">${target.host}:${target.port || 'default'}</p>
|
||||
</div>
|
||||
</div>
|
||||
<span class="text-xs font-medium px-2 py-1 rounded ${target.currentStatus === 'up' ? 'bg-green-900 text-green-200' : 'bg-red-900 text-red-200'} flex-shrink-0">
|
||||
${target.currentStatus === 'up' ? '✓' : '✗'}
|
||||
</span>
|
||||
</div>
|
||||
<div class="uptime-bar uptime-bar-${target._id}" style="width: 100%; max-width: 200px;">
|
||||
Loading...
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
// Load uptime data for all monitors
|
||||
filtered.forEach(target => {
|
||||
loadAndDisplayMiniUptime(target._id);
|
||||
});
|
||||
}
|
||||
|
||||
async function loadAndDisplayMiniUptime(targetId) {
|
||||
try {
|
||||
const res = await axios.get(`/api/targets/${targetId}/statistics?days=1`);
|
||||
const stats = res.data.statistics || [];
|
||||
|
||||
let html = '';
|
||||
stats.forEach(stat => {
|
||||
const isUp = stat.successfulPings > 0;
|
||||
html += `<div class="uptime-segment ${isUp ? 'up' : 'down'}" style="width: 4px; height: 12px;" title="${isUp ? 'Up' : 'Down'}"></div>`;
|
||||
});
|
||||
|
||||
const el = document.querySelector(`.uptime-bar-${targetId}`);
|
||||
if (el) {
|
||||
el.innerHTML = html;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading uptime bars:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function selectMonitor(targetId) {
|
||||
selectedTargetId = targetId;
|
||||
const selectedTarget = allTargets.find(t => t._id === targetId);
|
||||
if (selectedTarget) {
|
||||
displayMonitorDetail(selectedTarget);
|
||||
// Compact the sidebar when a monitor is selected
|
||||
const sidebarTop = document.getElementById('sidebar-top-section');
|
||||
sidebarTop.classList.remove('sidebar-top-expanded');
|
||||
sidebarTop.classList.add('sidebar-top-compact');
|
||||
}
|
||||
}
|
||||
|
||||
async function displayMonitorDetail(target) {
|
||||
// Show details panel
|
||||
document.getElementById('no-selection').classList.add('hidden');
|
||||
document.getElementById('details-panel').classList.remove('hidden');
|
||||
|
||||
// Update header immediately
|
||||
document.getElementById('detail-name').textContent = target.name;
|
||||
document.getElementById('detail-host').textContent = `${target.host}:${target.port || 'default'} • ${target.protocol}`;
|
||||
document.getElementById('detail-interval').textContent = `Check every ${target.interval || 60} seconds`;
|
||||
|
||||
// Update status badge
|
||||
const statusBadge = document.getElementById('detail-status');
|
||||
if (target.currentStatus === 'up') {
|
||||
statusBadge.textContent = '✓ Up';
|
||||
statusBadge.className = 'px-4 py-2 rounded-lg font-medium text-lg bg-green-900 text-green-200';
|
||||
} else {
|
||||
statusBadge.textContent = '✗ Down';
|
||||
statusBadge.className = 'px-4 py-2 rounded-lg font-medium text-lg bg-red-900 text-red-200';
|
||||
}
|
||||
|
||||
// Set loading state for chart
|
||||
document.getElementById('detail-uptime-24h').textContent = 'Loading...';
|
||||
document.getElementById('detail-uptime-30d').textContent = 'Loading...';
|
||||
document.getElementById('detail-current-ping').textContent = 'Loading...';
|
||||
document.getElementById('detail-avg-ping').textContent = 'Loading...';
|
||||
|
||||
// Load uptime data
|
||||
try {
|
||||
const res24h = await axios.get(`/api/targets/${target._id}/uptime?days=1`);
|
||||
const res30d = await axios.get(`/api/targets/${target._id}/uptime?days=30`);
|
||||
const resStats = await axios.get(`/api/targets/${target._id}/statistics?days=1`);
|
||||
|
||||
const uptime24h = res24h.data.uptime;
|
||||
const uptime30d = res30d.data.uptime;
|
||||
const stats = resStats.data.statistics || [];
|
||||
|
||||
// Get the most recent avg response time
|
||||
const latestStat = stats.length > 0 ? stats[stats.length - 1] : null;
|
||||
const currentPing = latestStat?.lastResponseTime || 0;
|
||||
const avgPing = latestStat?.avgResponseTime || 0;
|
||||
|
||||
// Update uptime stats
|
||||
document.getElementById('detail-uptime-24h').textContent = `${uptime24h.toFixed(2)}%`;
|
||||
document.getElementById('detail-uptime-30d').textContent = `${uptime30d.toFixed(2)}%`;
|
||||
document.getElementById('detail-current-ping').textContent = currentPing.toFixed(2) + ' ms';
|
||||
document.getElementById('detail-avg-ping').textContent = avgPing.toFixed(2) + ' ms';
|
||||
|
||||
// Generate uptime visualization
|
||||
await generateUptimeVisualization(target._id);
|
||||
|
||||
// Load and display ping chart
|
||||
await loadPingChart(target._id);
|
||||
} catch (error) {
|
||||
console.error('Error loading monitor details:', error);
|
||||
document.getElementById('detail-uptime-24h').textContent = '-- %';
|
||||
document.getElementById('detail-uptime-30d').textContent = '-- %';
|
||||
document.getElementById('detail-current-ping').textContent = '-- ms';
|
||||
document.getElementById('detail-avg-ping').textContent = '-- ms';
|
||||
}
|
||||
}
|
||||
|
||||
async function generateUptimeVisualization(targetId) {
|
||||
try {
|
||||
const res = await axios.get(`/api/targets/${targetId}/statistics?days=30`);
|
||||
const stats = res.data.statistics || [];
|
||||
|
||||
const viz = document.getElementById('uptime-visualization');
|
||||
viz.innerHTML = '';
|
||||
|
||||
// Create segments based on real statistics data
|
||||
stats.forEach(stat => {
|
||||
const segment = document.createElement('div');
|
||||
segment.className = 'uptime-segment';
|
||||
|
||||
const isUp = stat.successfulPings > 0;
|
||||
if (!isUp) {
|
||||
segment.classList.add('down');
|
||||
} else {
|
||||
segment.classList.add('up');
|
||||
}
|
||||
|
||||
segment.title = `${new Date(stat.date).toLocaleDateString()}: ${isUp ? 'Up' : 'Down'}`;
|
||||
viz.appendChild(segment);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error generating uptime visualization:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPingChart(targetId, days = 1) {
|
||||
try {
|
||||
// Update button styling
|
||||
document.querySelectorAll('.period-btn').forEach(btn => {
|
||||
btn.classList.remove('bg-cyan-600', 'text-white');
|
||||
btn.classList.add('bg-slate-700', 'hover:bg-slate-600');
|
||||
});
|
||||
|
||||
// Find and highlight the clicked button
|
||||
const clickedBtn = document.querySelector(`.period-btn[data-period="${days <= 0.05 ? '1h' : days === 1 ? '24h' : days === 7 ? '7d' : '30d'}"]`);
|
||||
if (clickedBtn) {
|
||||
clickedBtn.classList.remove('bg-slate-700', 'hover:bg-slate-600');
|
||||
clickedBtn.classList.add('bg-cyan-600', 'text-white');
|
||||
}
|
||||
|
||||
const res = await axios.get(`/api/targets/${targetId}/statistics?days=${days}`);
|
||||
const stats = res.data.statistics || [];
|
||||
|
||||
const labels = [];
|
||||
const data = [];
|
||||
|
||||
stats.forEach(stat => {
|
||||
const date = new Date(stat.date);
|
||||
const label = days <= 0.05
|
||||
? date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
|
||||
: days <= 1
|
||||
? date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
|
||||
: date.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
|
||||
labels.push(label);
|
||||
data.push(stat.avgResponseTime || 0);
|
||||
});
|
||||
|
||||
const ctx = document.getElementById('ping-chart').getContext('2d');
|
||||
|
||||
if (pingChart) {
|
||||
pingChart.destroy();
|
||||
}
|
||||
|
||||
pingChart = new Chart(ctx, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
label: 'Response Time (ms)',
|
||||
data,
|
||||
borderColor: '#10b981',
|
||||
backgroundColor: 'rgba(16, 185, 129, 0.1)',
|
||||
fill: true,
|
||||
tension: 0.4,
|
||||
pointRadius: 2,
|
||||
pointBackgroundColor: '#10b981',
|
||||
pointBorderColor: '#fff',
|
||||
pointHoverRadius: 5,
|
||||
borderWidth: 2,
|
||||
},
|
||||
],
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
labels: { color: '#cbd5e1' },
|
||||
},
|
||||
},
|
||||
scales: {
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
grid: { color: '#475569' },
|
||||
ticks: { color: '#cbd5e1' },
|
||||
},
|
||||
x: {
|
||||
grid: { color: '#475569' },
|
||||
ticks: { color: '#cbd5e1', maxRotation: 45, minRotation: 0 },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error loading ping chart:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Form panel functions
|
||||
function showAddTargetForm() {
|
||||
const formPanel = document.getElementById('form-panel');
|
||||
const detailsPanel = document.getElementById('details-panel');
|
||||
const noSelection = document.getElementById('no-selection');
|
||||
const form = document.getElementById('target-form');
|
||||
const title = document.getElementById('form-title');
|
||||
|
||||
title.textContent = 'Add Monitor';
|
||||
form.reset();
|
||||
delete form.dataset.targetId;
|
||||
|
||||
// Reset protocol-specific sections
|
||||
updateProtocolSettings();
|
||||
resetAuthenticationMethod();
|
||||
|
||||
// Show form panel, hide details
|
||||
formPanel.classList.remove('hidden');
|
||||
detailsPanel.classList.add('hidden');
|
||||
noSelection.classList.add('hidden');
|
||||
}
|
||||
|
||||
function cancelEditForm() {
|
||||
const formPanel = document.getElementById('form-panel');
|
||||
const detailsPanel = document.getElementById('details-panel');
|
||||
const noSelection = document.getElementById('no-selection');
|
||||
const sidebarTop = document.getElementById('sidebar-top-section');
|
||||
|
||||
// If a monitor is selected, show details. Otherwise show no-selection
|
||||
if (selectedTargetId) {
|
||||
formPanel.classList.add('hidden');
|
||||
detailsPanel.classList.remove('hidden');
|
||||
// Keep sidebar compact when a monitor is selected
|
||||
sidebarTop.classList.remove('sidebar-top-expanded');
|
||||
sidebarTop.classList.add('sidebar-top-compact');
|
||||
} else {
|
||||
formPanel.classList.add('hidden');
|
||||
noSelection.classList.remove('hidden');
|
||||
// Expand sidebar when no monitor is selected
|
||||
sidebarTop.classList.remove('sidebar-top-compact');
|
||||
sidebarTop.classList.add('sidebar-top-expanded');
|
||||
}
|
||||
}
|
||||
|
||||
function showEditForm() {
|
||||
const formPanel = document.getElementById('form-panel');
|
||||
const detailsPanel = document.getElementById('details-panel');
|
||||
const form = document.getElementById('target-form');
|
||||
|
||||
// First load the target data
|
||||
editTarget();
|
||||
|
||||
// Then show the form panel
|
||||
setTimeout(() => {
|
||||
formPanel.classList.remove('hidden');
|
||||
detailsPanel.classList.add('hidden');
|
||||
}, 10);
|
||||
}
|
||||
|
||||
function updateProtocolSettings() {
|
||||
const protocol = document.getElementById('target-protocol').value;
|
||||
const httpSection = document.getElementById('http-options-section');
|
||||
const authSection = document.getElementById('auth-section');
|
||||
|
||||
// Show HTTP options for HTTP/HTTPS protocols
|
||||
if (protocol === 'HTTP' || protocol === 'HTTPS') {
|
||||
httpSection.classList.remove('hidden');
|
||||
authSection.classList.remove('hidden');
|
||||
} else {
|
||||
httpSection.classList.add('hidden');
|
||||
authSection.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
function resetAuthenticationMethod() {
|
||||
const authMethod = document.getElementById('target-auth-method');
|
||||
const basicFields = document.getElementById('basic-auth-fields');
|
||||
const bearerFields = document.getElementById('bearer-auth-fields');
|
||||
|
||||
authMethod.value = 'none';
|
||||
basicFields.classList.add('hidden');
|
||||
bearerFields.classList.add('hidden');
|
||||
}
|
||||
|
||||
// Listen for auth method changes
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const authMethod = document.getElementById('target-auth-method');
|
||||
if (authMethod) {
|
||||
authMethod.addEventListener('change', (e) => {
|
||||
const basicFields = document.getElementById('basic-auth-fields');
|
||||
const bearerFields = document.getElementById('bearer-auth-fields');
|
||||
|
||||
basicFields.classList.add('hidden');
|
||||
bearerFields.classList.add('hidden');
|
||||
|
||||
if (e.target.value === 'basic') {
|
||||
basicFields.classList.remove('hidden');
|
||||
} else if (e.target.value === 'bearer') {
|
||||
bearerFields.classList.remove('hidden');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
async function addTarget(event) {
|
||||
event.preventDefault();
|
||||
|
||||
const form = document.getElementById('target-form');
|
||||
const isEdit = form.dataset.targetId;
|
||||
|
||||
const target = {
|
||||
name: document.getElementById('target-name').value,
|
||||
host: document.getElementById('target-host').value,
|
||||
protocol: document.getElementById('target-protocol').value,
|
||||
port: document.getElementById('target-port').value ? parseInt(document.getElementById('target-port').value) : null,
|
||||
interval: document.getElementById('target-interval').value ? parseInt(document.getElementById('target-interval').value) : 60,
|
||||
enabled: document.getElementById('target-enabled').checked,
|
||||
appUrl: document.getElementById('target-app-url').value || null,
|
||||
appIcon: document.getElementById('target-app-icon').value || null,
|
||||
retries: parseInt(document.getElementById('target-retries').value) || 0,
|
||||
retryInterval: parseInt(document.getElementById('target-retry-interval').value) || 5,
|
||||
timeout: parseInt(document.getElementById('target-timeout').value) || 30,
|
||||
httpMethod: document.getElementById('target-http-method').value || 'GET',
|
||||
statusCodes: document.getElementById('target-status-codes').value || '200-299',
|
||||
maxRedirects: parseInt(document.getElementById('target-max-redirects').value) || 5,
|
||||
ignoreSsl: document.getElementById('target-ignore-ssl').checked,
|
||||
upsideDown: document.getElementById('target-upside-down').checked,
|
||||
position: parseInt(document.getElementById('target-position').value) || 0,
|
||||
group: document.getElementById('target-group').value || null,
|
||||
quickCommands: document.getElementById('target-quick-commands').value
|
||||
? document.getElementById('target-quick-commands').value.split(',').map(cmd => cmd.trim()).filter(cmd => cmd)
|
||||
: [],
|
||||
};
|
||||
|
||||
// Add authentication if set
|
||||
const authMethod = document.getElementById('target-auth-method').value;
|
||||
if (authMethod === 'basic') {
|
||||
target.auth = {
|
||||
type: 'basic',
|
||||
username: document.getElementById('target-auth-username').value,
|
||||
password: document.getElementById('target-auth-password').value,
|
||||
};
|
||||
} else if (authMethod === 'bearer') {
|
||||
target.auth = {
|
||||
type: 'bearer',
|
||||
token: document.getElementById('target-auth-token').value,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
let savedTargetId;
|
||||
if (isEdit) {
|
||||
await axios.put(`/api/targets/${form.dataset.targetId}`, target);
|
||||
savedTargetId = form.dataset.targetId;
|
||||
} else {
|
||||
const res = await axios.post('/api/targets', target);
|
||||
savedTargetId = res.data.target._id;
|
||||
}
|
||||
|
||||
// Close form and return to details
|
||||
const formPanel = document.getElementById('form-panel');
|
||||
const detailsPanel = document.getElementById('details-panel');
|
||||
formPanel.classList.add('hidden');
|
||||
|
||||
form.reset();
|
||||
document.getElementById('target-enabled').checked = true;
|
||||
|
||||
// Reload dashboard and show the saved monitor details
|
||||
await loadDashboard();
|
||||
|
||||
// If we just saved a new monitor, select the first one
|
||||
if (!isEdit && allTargets.length > 0) {
|
||||
selectMonitor(allTargets[0]._id);
|
||||
} else if (isEdit) {
|
||||
// If editing, refresh the details view
|
||||
displayMonitorDetail(allTargets.find(t => t._id === form.dataset.targetId));
|
||||
}
|
||||
|
||||
// Test the monitor immediately after saving
|
||||
selectedTargetId = savedTargetId;
|
||||
setTimeout(() => {
|
||||
testTarget();
|
||||
}, 500);
|
||||
} catch (error) {
|
||||
alert('Error saving target: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function editTarget() {
|
||||
if (!selectedTargetId) return;
|
||||
|
||||
try {
|
||||
const res = await axios.get(`/api/targets/${selectedTargetId}`);
|
||||
const target = res.data.target;
|
||||
|
||||
// General section
|
||||
document.getElementById('target-name').value = target.name;
|
||||
document.getElementById('target-host').value = target.host;
|
||||
document.getElementById('target-protocol').value = target.protocol;
|
||||
document.getElementById('target-port').value = target.port || '';
|
||||
document.getElementById('target-interval').value = target.interval || 60;
|
||||
|
||||
// Application section
|
||||
document.getElementById('target-app-url').value = target.appUrl || '';
|
||||
document.getElementById('target-app-icon').value = target.appIcon || '';
|
||||
|
||||
// Retries section
|
||||
document.getElementById('target-retries').value = target.retries || 0;
|
||||
document.getElementById('target-retry-interval').value = target.retryInterval || 5;
|
||||
|
||||
// HTTP Options section
|
||||
document.getElementById('target-http-method').value = target.httpMethod || 'GET';
|
||||
document.getElementById('target-timeout').value = target.timeout || 30;
|
||||
document.getElementById('target-status-codes').value = target.statusCodes || '200-299';
|
||||
document.getElementById('target-max-redirects').value = target.maxRedirects || 5;
|
||||
|
||||
// Authentication section
|
||||
if (target.auth) {
|
||||
if (target.auth.type === 'basic') {
|
||||
document.getElementById('target-auth-method').value = 'basic';
|
||||
document.getElementById('target-auth-username').value = target.auth.username || '';
|
||||
document.getElementById('target-auth-password').value = target.auth.password || '';
|
||||
} else if (target.auth.type === 'bearer') {
|
||||
document.getElementById('target-auth-method').value = 'bearer';
|
||||
document.getElementById('target-auth-token').value = target.auth.token || '';
|
||||
}
|
||||
} else {
|
||||
document.getElementById('target-auth-method').value = 'none';
|
||||
}
|
||||
|
||||
// Advanced section
|
||||
document.getElementById('target-ignore-ssl').checked = target.ignoreSsl || false;
|
||||
document.getElementById('target-upside-down').checked = target.upsideDown || false;
|
||||
document.getElementById('target-enabled').checked = target.enabled !== false;
|
||||
|
||||
// Public UI settings
|
||||
document.getElementById('target-position').value = target.position || 0;
|
||||
document.getElementById('target-group').value = target.group || '';
|
||||
const quickCommandsInput = document.getElementById('target-quick-commands');
|
||||
if (quickCommandsInput) {
|
||||
quickCommandsInput.value = (target.quickCommands || []).join(', ');
|
||||
}
|
||||
|
||||
const form = document.getElementById('target-form');
|
||||
const title = document.getElementById('form-title');
|
||||
|
||||
title.textContent = 'Edit Monitor';
|
||||
form.dataset.targetId = selectedTargetId;
|
||||
|
||||
// Update protocol settings to show HTTP/auth options if needed
|
||||
updateProtocolSettings();
|
||||
} catch (error) {
|
||||
alert('Error loading target: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteTarget() {
|
||||
if (!selectedTargetId) return;
|
||||
if (!confirm('Are you sure you want to delete this monitor?')) return;
|
||||
|
||||
try {
|
||||
await axios.delete(`/api/targets/${selectedTargetId}`);
|
||||
selectedTargetId = null;
|
||||
document.getElementById('no-selection').classList.remove('hidden');
|
||||
document.getElementById('details-panel').classList.add('hidden');
|
||||
loadDashboard();
|
||||
} catch (error) {
|
||||
alert('Error deleting target: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function testTarget() {
|
||||
if (!selectedTargetId) return;
|
||||
|
||||
try {
|
||||
const res = await axios.post(`/api/targets/${selectedTargetId}/test`);
|
||||
const result = res.data.result;
|
||||
|
||||
showTestNotification(result);
|
||||
} catch (error) {
|
||||
showTestNotification(null, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
function showTestNotification(result, errorMessage) {
|
||||
const notificationId = 'test-notification-' + Date.now();
|
||||
const isSuccess = result && result.success;
|
||||
const targetName = allTargets.find(t => t._id === selectedTargetId)?.name || 'Target';
|
||||
|
||||
let container = document.getElementById('notificationContainer');
|
||||
if (!container) {
|
||||
container = document.createElement('div');
|
||||
container.id = 'notificationContainer';
|
||||
container.style.cssText = 'position: fixed; top: 20px; right: 20px; z-index: 1000; display: flex; flex-direction: column; gap: 10px; max-width: 400px; pointer-events: none;';
|
||||
document.body.appendChild(container);
|
||||
}
|
||||
|
||||
const notification = document.createElement('div');
|
||||
notification.id = notificationId;
|
||||
notification.className = `notification ${isSuccess ? 'success' : 'error'}`;
|
||||
|
||||
if (isSuccess) {
|
||||
notification.innerHTML = `
|
||||
<button class="notification-close" onclick="document.getElementById('${notificationId}').remove()">×</button>
|
||||
<div class="notification-title">✓ ${targetName} is UP</div>
|
||||
<div class="notification-stat">
|
||||
<span>Response Time:</span>
|
||||
<span><strong>${(result.responseTime || 0).toFixed(2)} ms</strong></span>
|
||||
</div>
|
||||
<div class="notification-stat">
|
||||
<span>Protocol:</span>
|
||||
<span><strong>${result.protocol || 'N/A'}</strong></span>
|
||||
</div>
|
||||
<div class="notification-stat">
|
||||
<span>Timestamp:</span>
|
||||
<span><strong>${new Date().toLocaleTimeString()}</strong></span>
|
||||
</div>
|
||||
`;
|
||||
} else {
|
||||
notification.innerHTML = `
|
||||
<button class="notification-close" onclick="document.getElementById('${notificationId}').remove()">×</button>
|
||||
<div class="notification-title">✗ ${targetName} is DOWN</div>
|
||||
<div class="notification-stat">
|
||||
<span>Error:</span>
|
||||
<span><strong>${errorMessage || result?.error || 'Connection failed'}</strong></span>
|
||||
</div>
|
||||
<div class="notification-stat">
|
||||
<span>Timestamp:</span>
|
||||
<span><strong>${new Date().toLocaleTimeString()}</strong></span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
container.appendChild(notification);
|
||||
|
||||
// Auto-remove after 5 seconds
|
||||
setTimeout(() => {
|
||||
const el = document.getElementById(notificationId);
|
||||
if (el) {
|
||||
el.style.animation = 'slideOut 0.3s ease-in forwards';
|
||||
setTimeout(() => el.remove(), 300);
|
||||
}
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
// Search functionality
|
||||
document.getElementById('search-input')?.addEventListener('input', () => {
|
||||
displayMonitorsList(allTargets);
|
||||
});
|
||||
|
||||
// Public UI Settings functions
|
||||
function showPublicUISettings() {
|
||||
const modal = document.getElementById('public-settings-modal');
|
||||
const settingsList = document.getElementById('public-settings-list');
|
||||
|
||||
if (allTargets.length === 0) {
|
||||
settingsList.innerHTML = '<div class="text-slate-400 text-sm text-center py-4">No monitors available</div>';
|
||||
modal.classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
settingsList.innerHTML = allTargets.map(target => {
|
||||
const isEnabled = target.enabled !== false;
|
||||
return `
|
||||
<label class="flex items-center gap-3 p-3 bg-slate-700/30 rounded cursor-pointer hover:bg-slate-700/50 transition">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="public-ui-setting w-4 h-4 cursor-pointer"
|
||||
data-target-id="${target._id}"
|
||||
${isEnabled ? 'checked' : ''}
|
||||
>
|
||||
<div class="flex-1">
|
||||
<div class="text-sm font-medium text-white">${target.name}</div>
|
||||
<div class="text-xs text-slate-400">${target.host}:${target.port || 'default'}</div>
|
||||
</div>
|
||||
<span class="text-xs px-2 py-1 rounded ${isEnabled ? 'bg-green-900 text-green-200' : 'bg-slate-600 text-slate-300'}">
|
||||
${isEnabled ? 'Visible' : 'Hidden'}
|
||||
</span>
|
||||
</label>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
modal.classList.remove('hidden');
|
||||
}
|
||||
|
||||
async function savePublicSettings() {
|
||||
const checkboxes = document.querySelectorAll('.public-ui-setting');
|
||||
const updates = [];
|
||||
|
||||
for (const checkbox of checkboxes) {
|
||||
const targetId = checkbox.dataset.targetId;
|
||||
const isEnabled = checkbox.checked;
|
||||
updates.push({ targetId, enabled: isEnabled });
|
||||
}
|
||||
|
||||
try {
|
||||
// Update each target's enabled status
|
||||
for (const update of updates) {
|
||||
await axios.put(`/api/targets/${update.targetId}`, {
|
||||
enabled: update.enabled
|
||||
});
|
||||
}
|
||||
|
||||
document.getElementById('public-settings-modal').classList.add('hidden');
|
||||
|
||||
// Show success notification
|
||||
showSuccessNotification('Public UI settings saved successfully!');
|
||||
|
||||
// Reload dashboard
|
||||
await loadDashboard();
|
||||
} catch (error) {
|
||||
alert('Error saving settings: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
function showSuccessNotification(message) {
|
||||
const notificationId = 'success-notification-' + Date.now();
|
||||
|
||||
let container = document.getElementById('notificationContainer');
|
||||
if (!container) {
|
||||
container = document.createElement('div');
|
||||
container.id = 'notificationContainer';
|
||||
container.style.cssText = 'position: fixed; top: 20px; right: 20px; z-index: 1000; display: flex; flex-direction: column; gap: 10px; max-width: 400px; pointer-events: none;';
|
||||
document.body.appendChild(container);
|
||||
}
|
||||
|
||||
const notification = document.createElement('div');
|
||||
notification.id = notificationId;
|
||||
notification.className = 'notification success';
|
||||
notification.innerHTML = `
|
||||
<button class="notification-close" onclick="document.getElementById('${notificationId}').remove()">×</button>
|
||||
<div class="notification-title">✓ ${message}</div>
|
||||
`;
|
||||
|
||||
container.appendChild(notification);
|
||||
|
||||
setTimeout(() => {
|
||||
const el = document.getElementById(notificationId);
|
||||
if (el) {
|
||||
el.style.animation = 'slideOut 0.3s ease-in forwards';
|
||||
setTimeout(() => el.remove(), 300);
|
||||
}
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// ============ INCIDENT MANAGEMENT FUNCTIONS ============
|
||||
|
||||
function showIncidentsPanel() {
|
||||
// Hide details and form panels
|
||||
document.getElementById('details-panel').classList.add('hidden');
|
||||
document.getElementById('form-panel').classList.add('hidden');
|
||||
document.getElementById('no-selection').classList.add('hidden');
|
||||
|
||||
// Show incidents panel
|
||||
document.getElementById('incidents-panel').classList.remove('hidden');
|
||||
|
||||
loadIncidentsPanel();
|
||||
}
|
||||
|
||||
function hideIncidentsPanel() {
|
||||
const incidentsPanel = document.getElementById('incidents-panel');
|
||||
const noSelection = document.getElementById('no-selection');
|
||||
const sidebarTop = document.getElementById('sidebar-top-section');
|
||||
|
||||
incidentsPanel.classList.add('hidden');
|
||||
|
||||
// If a monitor is selected, show details with compact sidebar. Otherwise show no-selection with expanded sidebar
|
||||
if (selectedTargetId) {
|
||||
noSelection.classList.add('hidden');
|
||||
const selectedTarget = allTargets.find(t => t._id === selectedTargetId);
|
||||
if (selectedTarget) {
|
||||
displayMonitorDetail(selectedTarget);
|
||||
sidebarTop.classList.remove('sidebar-top-expanded');
|
||||
sidebarTop.classList.add('sidebar-top-compact');
|
||||
}
|
||||
} else {
|
||||
noSelection.classList.remove('hidden');
|
||||
sidebarTop.classList.remove('sidebar-top-compact');
|
||||
sidebarTop.classList.add('sidebar-top-expanded');
|
||||
}
|
||||
}
|
||||
|
||||
function loadIncidentsPanel() {
|
||||
loadIncidents();
|
||||
}
|
||||
|
||||
async function loadIncidents() {
|
||||
try {
|
||||
const res = await axios.get('/admin/api/incidents');
|
||||
const incidents = res.data.incidents || [];
|
||||
|
||||
const list = document.getElementById('incidents-list-panel');
|
||||
|
||||
if (incidents.length === 0) {
|
||||
list.innerHTML = '<div class="text-slate-400 text-sm text-center py-8">No incidents reported</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
list.innerHTML = incidents.map(incident => {
|
||||
const severityColor = {
|
||||
minor: 'bg-yellow-900 text-yellow-200',
|
||||
major: 'bg-orange-900 text-orange-200',
|
||||
critical: 'bg-red-900 text-red-200'
|
||||
}[incident.severity] || 'bg-slate-700';
|
||||
|
||||
const statusColor = {
|
||||
investigating: 'bg-blue-900 text-blue-200',
|
||||
identified: 'bg-cyan-900 text-cyan-200',
|
||||
monitoring: 'bg-purple-900 text-purple-200',
|
||||
resolved: 'bg-green-900 text-green-200'
|
||||
}[incident.status] || 'bg-slate-700';
|
||||
|
||||
return `
|
||||
<div class="bg-slate-700/30 rounded p-4 border border-slate-600">
|
||||
<div class="flex justify-between items-start mb-3">
|
||||
<div class="flex-1">
|
||||
<h3 class="font-semibold text-white text-sm">${incident.title}</h3>
|
||||
<p class="text-slate-400 text-xs mt-1">${new Date(incident.createdAt).toLocaleString()}</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<span class="text-xs px-2 py-1 rounded ${severityColor}">
|
||||
${incident.severity.toUpperCase()}
|
||||
</span>
|
||||
<span class="text-xs px-2 py-1 rounded ${statusColor}">
|
||||
${incident.status.toUpperCase()}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-slate-300 text-xs mb-3">${incident.description}</p>
|
||||
<div class="flex gap-2">
|
||||
<button onclick="editIncident('${incident._id}')" class="flex-1 bg-slate-600 hover:bg-slate-500 px-2 py-1 rounded text-xs">
|
||||
Edit
|
||||
</button>
|
||||
<button onclick="deleteIncident('${incident._id}')" class="flex-1 bg-red-900 hover:bg-red-800 px-2 py-1 rounded text-xs">
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
} catch (error) {
|
||||
console.error('Error loading incidents:', error);
|
||||
const list = document.getElementById('incidents-list-panel');
|
||||
if (list) {
|
||||
list.innerHTML = `<div class="text-red-400 text-sm">Error loading incidents</div>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showCreateIncidentModal() {
|
||||
document.getElementById('incident-form').reset();
|
||||
document.getElementById('incident-form-modal').classList.remove('hidden');
|
||||
delete document.getElementById('incident-form').dataset.incidentId;
|
||||
}
|
||||
|
||||
async function editIncident(incidentId) {
|
||||
try {
|
||||
const res = await axios.get(`/admin/api/incidents/${incidentId}`);
|
||||
const incident = res.data.incident;
|
||||
|
||||
document.getElementById('incident-title').value = incident.title;
|
||||
document.getElementById('incident-description').value = incident.description;
|
||||
document.getElementById('incident-severity').value = incident.severity;
|
||||
document.getElementById('incident-status').value = incident.status;
|
||||
|
||||
document.getElementById('incident-form').dataset.incidentId = incidentId;
|
||||
document.getElementById('incident-form-modal').classList.remove('hidden');
|
||||
} catch (error) {
|
||||
alert('Error loading incident: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveIncident(event) {
|
||||
event.preventDefault();
|
||||
|
||||
const title = document.getElementById('incident-title').value;
|
||||
const description = document.getElementById('incident-description').value;
|
||||
const severity = document.getElementById('incident-severity').value;
|
||||
const status = document.getElementById('incident-status').value;
|
||||
const incidentId = document.getElementById('incident-form').dataset.incidentId;
|
||||
|
||||
try {
|
||||
if (incidentId) {
|
||||
// Update existing incident
|
||||
await axios.put(`/admin/api/incidents/${incidentId}`, {
|
||||
title,
|
||||
description,
|
||||
severity,
|
||||
status
|
||||
});
|
||||
showSuccessNotification('Incident updated successfully!');
|
||||
} else {
|
||||
// Create new incident
|
||||
await axios.post('/admin/api/incidents', {
|
||||
title,
|
||||
description,
|
||||
severity,
|
||||
status
|
||||
});
|
||||
showSuccessNotification('Incident reported successfully!');
|
||||
}
|
||||
|
||||
document.getElementById('incident-form-modal').classList.add('hidden');
|
||||
loadIncidents();
|
||||
} catch (error) {
|
||||
alert('Error saving incident: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteIncident(incidentId) {
|
||||
if (!confirm('Are you sure you want to delete this incident?')) return;
|
||||
|
||||
try {
|
||||
await axios.delete(`/admin/api/incidents/${incidentId}`);
|
||||
showSuccessNotification('Incident deleted successfully!');
|
||||
loadIncidents();
|
||||
} catch (error) {
|
||||
alert('Error deleting incident: ' + error.message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
/**
|
||||
* Browser Notification System for LocalPing
|
||||
* Handles desktop and in-app notifications for status changes
|
||||
*/
|
||||
|
||||
class NotificationManager {
|
||||
constructor() {
|
||||
this.notificationPermission = Notification.permission;
|
||||
this.targetStates = new Map(); // Track previous states and delayed notification state
|
||||
this.inPageNotifications = [];
|
||||
this.maxInPageNotifications = 5;
|
||||
|
||||
// Request notification permission if not already granted
|
||||
if (this.notificationPermission === 'default') {
|
||||
this.requestPermission();
|
||||
}
|
||||
|
||||
// Initialize notification container
|
||||
this.initializeContainer();
|
||||
}
|
||||
|
||||
/**
|
||||
* Request notification permission from user
|
||||
*/
|
||||
async requestPermission() {
|
||||
try {
|
||||
const permission = await Notification.requestPermission();
|
||||
this.notificationPermission = permission;
|
||||
|
||||
if (permission === 'granted') {
|
||||
console.log('✓ Browser notifications enabled');
|
||||
} else if (permission === 'denied') {
|
||||
console.log('✗ Browser notifications disabled by user');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error requesting notification permission:', err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize notification container in DOM
|
||||
*/
|
||||
initializeContainer() {
|
||||
if (!document.getElementById('notification-container')) {
|
||||
const container = document.createElement('div');
|
||||
container.id = 'notification-container';
|
||||
container.style.cssText = `
|
||||
position: fixed;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
z-index: 9999;
|
||||
max-width: 400px;
|
||||
pointer-events: none;
|
||||
`;
|
||||
document.body.appendChild(container);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show browser notification
|
||||
*/
|
||||
showBrowserNotification(title, options = {}) {
|
||||
if (this.notificationPermission !== 'granted') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const notification = new Notification(title, {
|
||||
icon: '/android-icon-192x192.png',
|
||||
badge: '/favicon-32x32.png',
|
||||
...options,
|
||||
});
|
||||
|
||||
// Auto-close after 5 seconds
|
||||
setTimeout(() => notification.close(), 5000);
|
||||
|
||||
// Handle click
|
||||
notification.onclick = () => {
|
||||
window.focus();
|
||||
notification.close();
|
||||
};
|
||||
|
||||
return notification;
|
||||
} catch (err) {
|
||||
console.error('Error showing browser notification:', err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show in-page toast notification
|
||||
*/
|
||||
showToastNotification(message, type = 'info', duration = 4000) {
|
||||
const container = document.getElementById('notification-container');
|
||||
if (!container) {
|
||||
this.initializeContainer();
|
||||
return this.showToastNotification(message, type, duration);
|
||||
}
|
||||
|
||||
const notification = document.createElement('div');
|
||||
notification.className = `notification notification-${type}`;
|
||||
notification.innerHTML = message;
|
||||
|
||||
const colors = {
|
||||
success: '#10b981',
|
||||
error: '#ef4444',
|
||||
warning: '#f59e0b',
|
||||
info: '#3b82f6',
|
||||
};
|
||||
|
||||
notification.style.cssText = `
|
||||
background-color: ${colors[type] || colors.info};
|
||||
color: white;
|
||||
padding: 16px;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 10px;
|
||||
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
|
||||
animation: slideIn 0.3s ease-out;
|
||||
pointer-events: auto;
|
||||
cursor: pointer;
|
||||
`;
|
||||
|
||||
// Add animation
|
||||
if (!document.querySelector('style[data-notification-styles]')) {
|
||||
const style = document.createElement('style');
|
||||
style.setAttribute('data-notification-styles', 'true');
|
||||
style.textContent = `
|
||||
@keyframes slideIn {
|
||||
from {
|
||||
transform: translateX(400px);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@keyframes slideOut {
|
||||
from {
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
}
|
||||
to {
|
||||
transform: translateX(400px);
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
container.appendChild(notification);
|
||||
|
||||
// Click to dismiss
|
||||
notification.addEventListener('click', () => {
|
||||
notification.style.animation = 'slideOut 0.3s ease-out';
|
||||
setTimeout(() => notification.remove(), 300);
|
||||
});
|
||||
|
||||
// A zero duration means the toast should remain until the user dismisses
|
||||
// it (used for sustained outage notifications).
|
||||
if (duration > 0) {
|
||||
setTimeout(() => {
|
||||
if (notification.parentElement) {
|
||||
notification.style.animation = 'slideOut 0.3s ease-out';
|
||||
setTimeout(() => notification.remove(), 300);
|
||||
}
|
||||
}, duration);
|
||||
}
|
||||
|
||||
// Track notifications
|
||||
this.inPageNotifications.push(notification);
|
||||
if (this.inPageNotifications.length > this.maxInPageNotifications) {
|
||||
const old = this.inPageNotifications.shift();
|
||||
old.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update target status and send notifications if changed
|
||||
*/
|
||||
updateTargetStatus(targetId, targetName, newStatus, metadata = {}) {
|
||||
const previous = this.targetStates.get(targetId);
|
||||
const previousStatus = previous?.status || previous;
|
||||
const hadDownNotification = previous?.downNotified === true;
|
||||
|
||||
// No change
|
||||
if (previousStatus === newStatus && !(newStatus === 'down' && metadata.notificationEligible && !previous?.downNotified)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Keep the status immediately visible, but gate monitor toasts/browser
|
||||
// notifications on the server's sustained-outage eligibility signal.
|
||||
const state = typeof previous === 'object' && previous ? previous : { status: previousStatus };
|
||||
state.status = newStatus;
|
||||
if (newStatus === 'up') state.downNotified = false;
|
||||
this.targetStates.set(targetId, state);
|
||||
|
||||
// Only send notifications if transitioning from a known state
|
||||
if (previousStatus === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (newStatus === 'up' && previousStatus === 'down' && hadDownNotification) {
|
||||
this.notifyTargetUp(targetName);
|
||||
state.downNotified = false;
|
||||
} else if (newStatus === 'down' && metadata.notificationEligible && !state.downNotified) {
|
||||
state.downNotified = true;
|
||||
this.notifyTargetDown(targetName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify when target comes online
|
||||
*/
|
||||
notifyTargetUp(targetName) {
|
||||
const message = `✓ ${targetName} is back online`;
|
||||
|
||||
// Browser notification
|
||||
this.showBrowserNotification('Target Online', {
|
||||
body: message,
|
||||
tag: `target-${targetName}`,
|
||||
requireInteraction: false,
|
||||
});
|
||||
|
||||
// In-page notification
|
||||
this.showToastNotification(message, 'success');
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify when target goes offline
|
||||
*/
|
||||
notifyTargetDown(targetName) {
|
||||
const message = `✗ ${targetName} is offline`;
|
||||
|
||||
// Browser notification
|
||||
this.showBrowserNotification('Target Offline', {
|
||||
body: message,
|
||||
tag: `target-${targetName}`,
|
||||
requireInteraction: true,
|
||||
});
|
||||
|
||||
// In-page notification
|
||||
this.showToastNotification(message, 'error', 0); // Don't auto-dismiss for errors
|
||||
}
|
||||
|
||||
/**
|
||||
* Get notification preference from localStorage
|
||||
*/
|
||||
getPreference(key, defaultValue = true) {
|
||||
const stored = localStorage.getItem(`notification-${key}`);
|
||||
return stored !== null ? stored === 'true' : defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set notification preference
|
||||
*/
|
||||
setPreference(key, value) {
|
||||
localStorage.setItem(`notification-${key}`, value ? 'true' : 'false');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if notifications are enabled
|
||||
*/
|
||||
isEnabled() {
|
||||
return this.getPreference('enabled', true) && this.notificationPermission === 'granted';
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle notifications
|
||||
*/
|
||||
async toggleNotifications(enabled) {
|
||||
this.setPreference('enabled', enabled);
|
||||
if (enabled && this.notificationPermission === 'default') {
|
||||
await this.requestPermission();
|
||||
}
|
||||
return this.isEnabled();
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify about new incident
|
||||
*/
|
||||
notifyIncident(incident) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
const severityEmojis = {
|
||||
'minor': '⚠️',
|
||||
'major': '🔶',
|
||||
'critical': '🔴'
|
||||
};
|
||||
|
||||
const emoji = severityEmojis[incident.severity] || '📢';
|
||||
const message = `${emoji} ${incident.title}`;
|
||||
|
||||
// Browser notification
|
||||
this.showBrowserNotification('New Incident', {
|
||||
body: `${incident.severity.toUpperCase()}: ${incident.description}`,
|
||||
tag: `incident-${incident._id}`,
|
||||
requireInteraction: incident.severity === 'critical',
|
||||
});
|
||||
|
||||
// In-page notification
|
||||
this.showToastNotification(message, incident.severity === 'critical' ? 'error' : incident.severity === 'major' ? 'warning' : 'info', incident.severity === 'critical' ? 0 : 5000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify about incident update
|
||||
*/
|
||||
notifyIncidentUpdate(incident) {
|
||||
if (!this.isEnabled()) return;
|
||||
|
||||
const statusMessages = {
|
||||
'investigating': '🔍 Investigating',
|
||||
'identified': '⚠️ Issue Identified',
|
||||
'monitoring': '👁️ Monitoring',
|
||||
'resolved': '✅ Resolved'
|
||||
};
|
||||
|
||||
const message = `${statusMessages[incident.status] || '📢'} ${incident.title}`;
|
||||
|
||||
// Browser notification
|
||||
this.showBrowserNotification('Incident Update', {
|
||||
body: `${incident.status.toUpperCase()}: ${incident.description}`,
|
||||
tag: `incident-update-${incident._id}`,
|
||||
requireInteraction: false,
|
||||
});
|
||||
|
||||
// In-page notification
|
||||
const type = incident.status === 'resolved' ? 'success' : 'info';
|
||||
this.showToastNotification(message, type);
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize and export
|
||||
const notificationManager = new NotificationManager();
|
||||
|
||||
// Make available globally
|
||||
if (typeof window !== 'undefined') {
|
||||
window.notificationManager = notificationManager;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "App",
|
||||
"icons": [
|
||||
{
|
||||
"src": "\/android-icon-192x192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image\/png",
|
||||
"purpose": "any maskable"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 2.5 KiB |
@@ -0,0 +1,3 @@
|
||||
/*! Axios v1.13.2 Copyright (c) 2025 Matt Zabriskie and contributors */
|
||||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).axios=t()}(this,(function(){"use strict";function e(e){var r,n;function o(r,n){try{var a=e[r](n),u=a.value,s=u instanceof t;Promise.resolve(s?u.v:u).then((function(t){if(s){var n="return"===r?"return":"next";if(!u.k||t.done)return o(n,t);t=e[n](t).value}i(a.done?"return":"normal",t)}),(function(e){o("throw",e)}))}catch(e){i("throw",e)}}function i(e,t){switch(e){case"return":r.resolve({value:t,done:!0});break;case"throw":r.reject(t);break;default:r.resolve({value:t,done:!1})}(r=r.next)?o(r.key,r.arg):n=null}this._invoke=function(e,t){return new Promise((function(i,a){var u={key:e,arg:t,resolve:i,reject:a,next:null};n?n=n.next=u:(r=n=u,o(e,t))}))},"function"!=typeof e.return&&(this.return=void 0)}function t(e,t){this.v=e,this.k=t}function r(e){var r={},n=!1;function o(r,o){return n=!0,o=new Promise((function(t){t(e[r](o))})),{done:!1,value:new t(o,1)}}return r["undefined"!=typeof Symbol&&Symbol.iterator||"@@iterator"]=function(){return this},r.next=function(e){return n?(n=!1,e):o("next",e)},"function"==typeof e.throw&&(r.throw=function(e){if(n)throw n=!1,e;return o("throw",e)}),"function"==typeof e.return&&(r.return=function(e){return n?(n=!1,e):o("return",e)}),r}function n(e){var t,r,n,i=2;for("undefined"!=typeof Symbol&&(r=Symbol.asyncIterator,n=Symbol.iterator);i--;){if(r&&null!=(t=e[r]))return t.call(e);if(n&&null!=(t=e[n]))return new o(t.call(e));r="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function o(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then((function(e){return{value:e,done:t}}))}return o=function(e){this.s=e,this.n=e.next},o.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var r=this.s.return;return void 0===r?Promise.resolve({value:e,done:!0}):t(r.apply(this.s,arguments))},throw:function(e){var r=this.s.return;return void 0===r?Promise.reject(e):t(r.apply(this.s,arguments))}},new o(e)}function i(e){return new t(e,0)}function a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function u(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?a(Object(r),!0).forEach((function(t){m(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):a(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function s(){s=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag";function f(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{f({},"")}catch(e){f=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof m?t:m,a=Object.create(i.prototype),u=new P(n||[]);return o(a,"_invoke",{value:k(e,r,u)}),a}function p(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var d="suspendedStart",h="executing",v="completed",y={};function m(){}function b(){}function g(){}var w={};f(w,a,(function(){return this}));var E=Object.getPrototypeOf,O=E&&E(E(L([])));O&&O!==r&&n.call(O,a)&&(w=O);var S=g.prototype=m.prototype=Object.create(w);function x(e){["next","throw","return"].forEach((function(t){f(e,t,(function(e){return this._invoke(t,e)}))}))}function R(e,t){function r(o,i,a,u){var s=p(e[o],e,i);if("throw"!==s.type){var c=s.arg,f=c.value;return f&&"object"==typeof f&&n.call(f,"__await")?t.resolve(f.__await).then((function(e){r("next",e,a,u)}),(function(e){r("throw",e,a,u)})):t.resolve(f).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,u)}))}u(s.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function k(t,r,n){var o=d;return function(i,a){if(o===h)throw new Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var u=n.delegate;if(u){var s=T(u,n);if(s){if(s===y)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===d)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=p(t,r,n);if("normal"===c.type){if(o=n.done?v:"suspendedYield",c.arg===y)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=v,n.method="throw",n.arg=c.arg)}}}function T(t,r){var n=r.method,o=t.iterator[n];if(o==Line truncated
|
||||
//# sourceMappingURL=axios.min.js.map
|
||||
@@ -0,0 +1,14 @@
|
||||
/*!
|
||||
* Chart.js v4.5.1
|
||||
* https://www.chartjs.org
|
||||
* (c) 2025 Chart.js Contributors
|
||||
* Released under the MIT License
|
||||
*/
|
||||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Chart=e()}(this,(function(){"use strict";var t=Object.freeze({__proto__:null,get Colors(){return Jo},get Decimation(){return ta},get Filler(){return ba},get Legend(){return Ma},get SubTitle(){return Pa},get Title(){return ka},get Tooltip(){return Na}});function e(){}const i=(()=>{let t=0;return()=>t++})();function s(t){return null==t}function n(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.slice(0,7)&&"Array]"===e.slice(-6)}function o(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}function a(t){return("number"==typeof t||t instanceof Number)&&isFinite(+t)}function r(t,e){return a(t)?t:e}function l(t,e){return void 0===t?e:t}const h=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100:+t/e,c=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function d(t,e,i){if(t&&"function"==typeof t.call)return t.apply(i,e)}function u(t,e,i,s){let a,r,l;if(n(t))if(r=t.length,s)for(a=r-1;a>=0;a--)e.call(i,t[a],a);else for(a=0;a<r;a++)e.call(i,t[a],a);else if(o(t))for(l=Object.keys(t),r=l.length,a=0;a<r;a++)e.call(i,t[l[a]],l[a])}function f(t,e){let i,s,n,o;if(!t||!e||t.length!==e.length)return!1;for(i=0,s=t.length;i<s;++i)if(n=t[i],o=e[i],n.datasetIndex!==o.datasetIndex||n.index!==o.index)return!1;return!0}function g(t){if(n(t))return t.map(g);if(o(t)){const e=Object.create(null),i=Object.keys(t),s=i.length;let n=0;for(;n<s;++n)e[i[n]]=g(t[i[n]]);return e}return t}function p(t){return-1===["__proto__","prototype","constructor"].indexOf(t)}function m(t,e,i,s){if(!p(t))return;const n=e[t],a=i[t];o(n)&&o(a)?x(n,a,s):e[t]=g(a)}function x(t,e,i){const s=n(e)?e:[e],a=s.length;if(!o(t))return t;const r=(i=i||{}).merger||m;let l;for(let e=0;e<a;++e){if(l=s[e],!o(l))continue;const n=Object.keys(l);for(let e=0,s=n.length;e<s;++e)r(n[e],t,l,i)}return t}function b(t,e){return x(t,e,{merger:_})}function _(t,e,i){if(!p(t))return;const s=e[t],n=i[t];o(s)&&o(n)?b(s,n):Object.prototype.hasOwnProperty.call(e,t)||(e[t]=g(n))}const y={"":t=>t,x:t=>t.x,y:t=>t.y};function v(t){const e=t.split("."),i=[];let s="";for(const t of e)s+=t,s.endsWith("\\")?s=s.slice(0,-1)+".":(i.push(s),s="");return i}function M(t,e){const i=y[e]||(y[e]=function(t){const e=v(t);return t=>{for(const i of e){if(""===i)break;t=t&&t[i]}return t}}(e));return i(t)}function w(t){return t.charAt(0).toUpperCase()+t.slice(1)}const k=t=>void 0!==t,S=t=>"function"==typeof t,P=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};function D(t){return"mouseup"===t.type||"click"===t.type||"contextmenu"===t.type}const C=Math.PI,O=2*C,A=O+C,T=Number.POSITIVE_INFINITY,L=C/180,E=C/2,R=C/4,I=2*C/3,z=Math.log10,F=Math.sign;function V(t,e,i){return Math.abs(t-e)<i}function B(t){const e=Math.round(t);t=V(t,e,t/1e3)?e:t;const i=Math.pow(10,Math.floor(z(t))),s=t/i;return(s<=1?1:s<=2?2:s<=5?5:10)*i}function W(t){const e=[],i=Math.sqrt(t);let s;for(s=1;s<i;s++)t%s==0&&(e.push(s),e.push(t/s));return i===(0|i)&&e.push(i),e.sort(((t,e)=>t-e)).pop(),e}function N(t){return!function(t){return"symbol"==typeof t||"object"==typeof t&&null!==t&&!(Symbol.toPrimitive in t||"toString"in t||"valueOf"in t)}(t)&&!isNaN(parseFloat(t))&&isFinite(t)}function H(t,e){const i=Math.round(t);return i-e<=t&&i+e>=t}function j(t,e,i){let s,n,o;for(s=0,n=t.length;s<n;s++)o=t[s][i],isNaN(o)||(e.min=Math.min(e.min,o),e.max=Math.max(e.max,o))}function $(t){return t*(C/180)}function Y(t){return t*(180/C)}function U(t){if(!a(t))return;let e=1,i=0;for(;Math.round(t*e)/e!==t;)e*=10,i++;return i}function X(t,e){const i=e.x-t.x,s=e.y-t.y,n=Math.sqrt(i*i+s*s);let o=Math.atan2(s,i);return o<-.5*C&&(o+=O),{angle:o,distance:n}}function q(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function K(t,e){return(t-e+A)%O-C}function G(t){return(t%O+O)%O}function J(t,e,i,s){const n=G(t),o=G(e),a=G(i),r=G(o-n),l=G(a-n),h=G(n-o),c=G(n-a);return n===o||n===a||s&&o===a||r>l&&h<c}function Z(t,e,i){return Math.max(e,Math.min(i,t))}function Q(t){return Z(t,-32768,32767)}function tt(t,e,i,s=1e-6){return t>=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function et(t,e,i){i=i||(i=>t[i]<e);let s,n=t.length-1,o=0;for(;n-o>1;)s=o+n>>1,i(s)?o=s:n=s;return{lo:o,hi:n}}const it=(t,e,i,s)=>et(t,i,s?s=>{const n=t[s][e];return n<i||n===i&&t[s+1][e]===i}:s=>t[s][e]<i),st=(t,e,i)=>et(t,i,(s=>t[s][e]>=i));function nt(t,e,i){let s=0,n=t.length;for(;s<n&&t[s]<e;)s++;for(;n>s&&t[n-1]>i;)n--;return s>0||n<t.length?t.slice(s,n):t}const ot=["push","pop","shift","splice","unshift"];function at(t,e){t._chartjs?t._chartjs.listeners.push(e):(Object.defineProperty(t,"_chartjs",{configurable:!0,enumerable:!1,value:{listeners:[e]}}),ot.forEach((e=>{const i="_onData"+w(e),s=t[e];Object.defineProperty(t,e,{configurable:!0,enumerable:!1,value(...eLine truncated
|
||||
/*!
|
||||
* @kurkle/color v0.3.2
|
||||
* https://github.com/kurkle/color#readme
|
||||
* (c) 2023 Jukka Kurkela
|
||||
* Released under the MIT License
|
||||
*/function _t(t){return t+.5|0}const yt=(t,e,i)=>Math.max(Math.min(t,i),e);function vt(t){return yt(_t(2.55*t),0,255)}function Mt(t){return yt(_t(255*t),0,255)}function wt(t){return yt(_t(t/2.55)/100,0,1)}function kt(t){return yt(_t(100*t),0,100)}const St={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},Pt=[..."0123456789ABCDEF"],Dt=t=>Pt[15&t],Ct=t=>Pt[(240&t)>>4]+Pt[15&t],Ot=t=>(240&t)>>4==(15&t);function At(t){var e=(t=>Ot(t.r)&&Ot(t.g)&&Ot(t.b)&&Ot(t.a))(t)?Dt:Ct;return t?"#"+e(t.r)+e(t.g)+e(t.b)+((t,e)=>t<255?e(t):"")(t.a,e):void 0}const Tt=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function Lt(t,e,i){const s=e*Math.min(i,1-i),n=(e,n=(e+t/30)%12)=>i-s*Math.max(Math.min(n-3,9-n,1),-1);return[n(0),n(8),n(4)]}function Et(t,e,i){const s=(s,n=(s+t/60)%6)=>i-i*e*Math.max(Math.min(n,4-n,1),0);return[s(5),s(3),s(1)]}function Rt(t,e,i){const s=Lt(t,1,.5);let n;for(e+i>1&&(n=1/(e+i),e*=n,i*=n),n=0;n<3;n++)s[n]*=1-e-i,s[n]+=e;return s}function It(t){const e=t.r/255,i=t.g/255,s=t.b/255,n=Math.max(e,i,s),o=Math.min(e,i,s),a=(n+o)/2;let r,l,h;return n!==o&&(h=n-o,l=a>.5?h/(2-n-o):h/(n+o),r=function(t,e,i,s,n){return t===n?(e-i)/s+(e<i?6:0):e===n?(i-t)/s+2:(t-e)/s+4}(e,i,s,h,n),r=60*r+.5),[0|r,l||0,a]}function zt(t,e,i,s){return(Array.isArray(e)?t(e[0],e[1],e[2]):t(e,i,s)).map(Mt)}function Ft(t,e,i){return zt(Lt,t,e,i)}function Vt(t){return(t%360+360)%360}function Bt(t){const e=Tt.exec(t);let i,s=255;if(!e)return;e[5]!==i&&(s=e[6]?vt(+e[5]):Mt(+e[5]));const n=Vt(+e[2]),o=+e[3]/100,a=+e[4]/100;return i="hwb"===e[1]?function(t,e,i){return zt(Rt,t,e,i)}(n,o,a):"hsv"===e[1]?function(t,e,i){return zt(Et,t,e,i)}(n,o,a):Ft(n,o,a),{r:i[0],g:i[1],b:i[2],a:s}}const Wt={x:"dark",Z:"light",Y:"re",X:"blu",W:"gr",V:"medium",U:"slate",A:"ee",T:"ol",S:"or",B:"ra",C:"lateg",D:"ights",R:"in",Q:"turquois",E:"hi",P:"ro",O:"al",N:"le",M:"de",L:"yello",F:"en",K:"ch",G:"arks",H:"ea",I:"ightg",J:"wh"},Nt={OiceXe:"f0f8ff",antiquewEte:"faebd7",aqua:"ffff",aquamarRe:"7fffd4",azuY:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"0",blanKedOmond:"ffebcd",Xe:"ff",XeviTet:"8a2be2",bPwn:"a52a2a",burlywood:"deb887",caMtXe:"5f9ea0",KartYuse:"7fff00",KocTate:"d2691e",cSO:"ff7f50",cSnflowerXe:"6495ed",cSnsilk:"fff8dc",crimson:"dc143c",cyan:"ffff",xXe:"8b",xcyan:"8b8b",xgTMnPd:"b8860b",xWay:"a9a9a9",xgYF:"6400",xgYy:"a9a9a9",xkhaki:"bdb76b",xmagFta:"8b008b",xTivegYF:"556b2f",xSange:"ff8c00",xScEd:"9932cc",xYd:"8b0000",xsOmon:"e9967a",xsHgYF:"8fbc8f",xUXe:"483d8b",xUWay:"2f4f4f",xUgYy:"2f4f4f",xQe:"ced1",xviTet:"9400d3",dAppRk:"ff1493",dApskyXe:"bfff",dimWay:"696969",dimgYy:"696969",dodgerXe:"1e90ff",fiYbrick:"b22222",flSOwEte:"fffaf0",foYstWAn:"228b22",fuKsia:"ff00ff",gaRsbSo:"dcdcdc",ghostwEte:"f8f8ff",gTd:"ffd700",gTMnPd:"daa520",Way:"808080",gYF:"8000",gYFLw:"adff2f",gYy:"808080",honeyMw:"f0fff0",hotpRk:"ff69b4",RdianYd:"cd5c5c",Rdigo:"4b0082",ivSy:"fffff0",khaki:"f0e68c",lavFMr:"e6e6fa",lavFMrXsh:"fff0f5",lawngYF:"7cfc00",NmoncEffon:"fffacd",ZXe:"add8e6",ZcSO:"f08080",Zcyan:"e0ffff",ZgTMnPdLw:"fafad2",ZWay:"d3d3d3",ZgYF:"90ee90",ZgYy:"d3d3d3",ZpRk:"ffb6c1",ZsOmon:"ffa07a",ZsHgYF:"20b2aa",ZskyXe:"87cefa",ZUWay:"778899",ZUgYy:"778899",ZstAlXe:"b0c4de",ZLw:"ffffe0",lime:"ff00",limegYF:"32cd32",lRF:"faf0e6",magFta:"ff00ff",maPon:"800000",VaquamarRe:"66cdaa",VXe:"cd",VScEd:"ba55d3",VpurpN:"9370db",VsHgYF:"3cb371",VUXe:"7b68ee",VsprRggYF:"fa9a",VQe:"48d1cc",VviTetYd:"c71585",midnightXe:"191970",mRtcYam:"f5fffa",mistyPse:"ffe4e1",moccasR:"ffe4b5",navajowEte:"ffdead",navy:"80",Tdlace:"fdf5e6",Tive:"808000",TivedBb:"6b8e23",Sange:"ffa500",SangeYd:"ff4500",ScEd:"da70d6",pOegTMnPd:"eee8aa",pOegYF:"98fb98",pOeQe:"afeeee",pOeviTetYd:"db7093",papayawEp:"ffefd5",pHKpuff:"ffdab9",peru:"cd853f",pRk:"ffc0cb",plum:"dda0dd",powMrXe:"b0e0e6",purpN:"800080",YbeccapurpN:"663399",Yd:"ff0000",Psybrown:"bc8f8f",PyOXe:"4169e1",saddNbPwn:"8b4513",sOmon:"fa8072",sandybPwn:"f4a460",sHgYF:"2e8b57",sHshell:"fff5ee",siFna:"a0522d",silver:"c0c0c0",skyXe:"87ceeb",UXe:"6a5acd",UWay:"708090",UgYy:"708090",snow:"fffafa",sprRggYF:"ff7f",stAlXe:"4682b4",tan:"d2b48c",teO:"8080",tEstN:"d8bfd8",tomato:"ff6347",Qe:"40e0d0",viTet:"ee82ee",JHt:"f5deb3",wEte:"ffffff",wEtesmoke:"f5f5f5",Lw:"ffff00",LwgYF:"9acd32"};let Ht;function jt(t){Ht||(Ht=function(){const t={},e=Object.keys(Nt),i=Object.keys(Wt);let s,n,o,a,r;for(s=0;s<e.length;s++){for(a=r=e[s],n=0;n<i.length;n++)o=i[n],r=r.replace(o,Wt[o]);o=parseInt(Nt[a],16),t[r]=[o>>16&255,o>>8&255,255&o]}return t}(),Ht.transparent=[0,0,0,0]);const e=Ht[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:4===e.length?e[3]:255}}const $t=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;const Yt=t=>t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,Ut=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function Xt(t,e,i){if(t){let s=It(t);s[e]=Math.max(0,Math.min(s[e]+s[e]*i,0===e?360:1)),Line truncated
|
||||
//# sourceMappingURL=chart.umd.min.js.map
|
||||
@@ -0,0 +1,9 @@
|
||||
/*!
|
||||
* Font Awesome Free 6.4.0 by @fontawesome - https://fontawesome.com
|
||||
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
|
||||
* Copyright 2023 Fonticons, Inc.
|
||||
*/
|
||||
.fa{font-family:var(--fa-style-family,"Font Awesome 6 Free");font-weight:var(--fa-style,900)}.fa,.fa-brands,.fa-classic,.fa-regular,.fa-sharp,.fa-solid,.fab,.far,.fas{-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;display:var(--fa-display,inline-block);font-style:normal;font-variant:normal;line-height:1;text-rendering:auto}.fa-classic,.fa-regular,.fa-solid,.far,.fas{font-family:"Font Awesome 6 Free"}.fa-brands,.fab{font-family:"Font Awesome 6 Brands"}.fa-1x{font-size:1em}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-6x{font-size:6em}.fa-7x{font-size:7em}.fa-8x{font-size:8em}.fa-9x{font-size:9em}.fa-10x{font-size:10em}.fa-2xs{font-size:.625em;line-height:.1em;vertical-align:.225em}.fa-xs{font-size:.75em;line-height:.08333em;vertical-align:.125em}.fa-sm{font-size:.875em;line-height:.07143em;vertical-align:.05357em}.fa-lg{font-size:1.25em;line-height:.05em;vertical-align:-.075em}.fa-xl{font-size:1.5em;line-height:.04167em;vertical-align:-.125em}.fa-2xl{font-size:2em;line-height:.03125em;vertical-align:-.1875em}.fa-fw{text-align:center;width:1.25em}.fa-ul{list-style-type:none;margin-left:var(--fa-li-margin,2.5em);padding-left:0}.fa-ul>li{position:relative}.fa-li{left:calc(var(--fa-li-width, 2em)*-1);position:absolute;text-align:center;width:var(--fa-li-width,2em);line-height:inherit}.fa-border{border-radius:var(--fa-border-radius,.1em);border:var(--fa-border-width,.08em) var(--fa-border-style,solid) var(--fa-border-color,#eee);padding:var(--fa-border-padding,.2em .25em .15em)}.fa-pull-left{float:left;margin-right:var(--fa-pull-margin,.3em)}.fa-pull-right{float:right;margin-left:var(--fa-pull-margin,.3em)}.fa-beat{-webkit-animation-name:fa-beat;animation-name:fa-beat;-webkit-animation-delay:var(--fa-animation-delay,0s);animation-delay:var(--fa-animation-delay,0s);-webkit-animation-direction:var(--fa-animation-direction,normal);animation-direction:var(--fa-animation-direction,normal);-webkit-animation-duration:var(--fa-animation-duration,1s);animation-duration:var(--fa-animation-duration,1s);-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,ease-in-out);animation-timing-function:var(--fa-animation-timing,ease-in-out)}.fa-bounce{-webkit-animation-name:fa-bounce;animation-name:fa-bounce;-webkit-animation-delay:var(--fa-animation-delay,0s);animation-delay:var(--fa-animation-delay,0s);-webkit-animation-direction:var(--fa-animation-direction,normal);animation-direction:var(--fa-animation-direction,normal);-webkit-animation-duration:var(--fa-animation-duration,1s);animation-duration:var(--fa-animation-duration,1s);-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,cubic-bezier(.28,.84,.42,1));animation-timing-function:var(--fa-animation-timing,cubic-bezier(.28,.84,.42,1))}.fa-fade{-webkit-animation-name:fa-fade;animation-name:fa-fade;-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,cubic-bezier(.4,0,.6,1));animation-timing-function:var(--fa-animation-timing,cubic-bezier(.4,0,.6,1))}.fa-beat-fade,.fa-fade{-webkit-animation-delay:var(--fa-animation-delay,0s);animation-delay:var(--fa-animation-delay,0s);-webkit-animation-direction:var(--fa-animation-direction,normal);animation-direction:var(--fa-animation-direction,normal);-webkit-animation-duration:var(--fa-animation-duration,1s);animation-duration:var(--fa-animation-duration,1s)}.fa-beat-fade{-webkit-animation-name:fa-beat-fade;animation-name:fa-beat-fade;-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,cubic-bezier(.4,0,.6,1));animation-timing-function:var(--fa-animation-timing,cubic-bezier(.4,0,.6,1))}.fa-flip{-webkit-animation-name:fa-flip;animation-name:fa-flip;-webkit-animation-delay:var(--fa-animation-delay,0s);animation-delay:var(--fa-animation-delay,0s);-webkit-animation-direction:var(--fa-animation-direction,normal);animation-direction:var(--fa-animation-direction,normal);-webkit-animation-duration:var(--fa-animation-duration,1s);animation-duration:var(--fa-animation-duration,1s);-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,ease-in-out);animation-timing-function:var(--fa-animation-timing,ease-in-out)}.fa-shake{-webkit-animation-name:fa-shake;animation-name:fa-shake;-webkit-animation-duration:var(--fa-animatLine truncated
|
||||
|
||||
.fa-0:before{content:"\30"}.fa-1:before{content:"\31"}.fa-2:before{content:"\32"}.fa-3:before{content:"\33"}.fa-4:before{content:"\34"}.fa-5:before{content:"\35"}.fa-6:before{content:"\36"}.fa-7:before{content:"\37"}.fa-8:before{content:"\38"}.fa-9:before{content:"\39"}.fa-fill-drip:before{content:"\f576"}.fa-arrows-to-circle:before{content:"\e4bd"}.fa-chevron-circle-right:before,.fa-circle-chevron-right:before{content:"\f138"}.fa-at:before{content:"\40"}.fa-trash-alt:before,.fa-trash-can:before{content:"\f2ed"}.fa-text-height:before{content:"\f034"}.fa-user-times:before,.fa-user-xmark:before{content:"\f235"}.fa-stethoscope:before{content:"\f0f1"}.fa-comment-alt:before,.fa-message:before{content:"\f27a"}.fa-info:before{content:"\f129"}.fa-compress-alt:before,.fa-down-left-and-up-right-to-center:before{content:"\f422"}.fa-explosion:before{content:"\e4e9"}.fa-file-alt:before,.fa-file-lines:before,.fa-file-text:before{content:"\f15c"}.fa-wave-square:before{content:"\f83e"}.fa-ring:before{content:"\f70b"}.fa-building-un:before{content:"\e4d9"}.fa-dice-three:before{content:"\f527"}.fa-calendar-alt:before,.fa-calendar-days:before{content:"\f073"}.fa-anchor-circle-check:before{content:"\e4aa"}.fa-building-circle-arrow-right:before{content:"\e4d1"}.fa-volleyball-ball:before,.fa-volleyball:before{content:"\f45f"}.fa-arrows-up-to-line:before{content:"\e4c2"}.fa-sort-desc:before,.fa-sort-down:before{content:"\f0dd"}.fa-circle-minus:before,.fa-minus-circle:before{content:"\f056"}.fa-door-open:before{content:"\f52b"}.fa-right-from-bracket:before,.fa-sign-out-alt:before{content:"\f2f5"}.fa-atom:before{content:"\f5d2"}.fa-soap:before{content:"\e06e"}.fa-heart-music-camera-bolt:before,.fa-icons:before{content:"\f86d"}.fa-microphone-alt-slash:before,.fa-microphone-lines-slash:before{content:"\f539"}.fa-bridge-circle-check:before{content:"\e4c9"}.fa-pump-medical:before{content:"\e06a"}.fa-fingerprint:before{content:"\f577"}.fa-hand-point-right:before{content:"\f0a4"}.fa-magnifying-glass-location:before,.fa-search-location:before{content:"\f689"}.fa-forward-step:before,.fa-step-forward:before{content:"\f051"}.fa-face-smile-beam:before,.fa-smile-beam:before{content:"\f5b8"}.fa-flag-checkered:before{content:"\f11e"}.fa-football-ball:before,.fa-football:before{content:"\f44e"}.fa-school-circle-exclamation:before{content:"\e56c"}.fa-crop:before{content:"\f125"}.fa-angle-double-down:before,.fa-angles-down:before{content:"\f103"}.fa-users-rectangle:before{content:"\e594"}.fa-people-roof:before{content:"\e537"}.fa-people-line:before{content:"\e534"}.fa-beer-mug-empty:before,.fa-beer:before{content:"\f0fc"}.fa-diagram-predecessor:before{content:"\e477"}.fa-arrow-up-long:before,.fa-long-arrow-up:before{content:"\f176"}.fa-burn:before,.fa-fire-flame-simple:before{content:"\f46a"}.fa-male:before,.fa-person:before{content:"\f183"}.fa-laptop:before{content:"\f109"}.fa-file-csv:before{content:"\f6dd"}.fa-menorah:before{content:"\f676"}.fa-truck-plane:before{content:"\e58f"}.fa-record-vinyl:before{content:"\f8d9"}.fa-face-grin-stars:before,.fa-grin-stars:before{content:"\f587"}.fa-bong:before{content:"\f55c"}.fa-pastafarianism:before,.fa-spaghetti-monster-flying:before{content:"\f67b"}.fa-arrow-down-up-across-line:before{content:"\e4af"}.fa-spoon:before,.fa-utensil-spoon:before{content:"\f2e5"}.fa-jar-wheat:before{content:"\e517"}.fa-envelopes-bulk:before,.fa-mail-bulk:before{content:"\f674"}.fa-file-circle-exclamation:before{content:"\e4eb"}.fa-circle-h:before,.fa-hospital-symbol:before{content:"\f47e"}.fa-pager:before{content:"\f815"}.fa-address-book:before,.fa-contact-book:before{content:"\f2b9"}.fa-strikethrough:before{content:"\f0cc"}.fa-k:before{content:"\4b"}.fa-landmark-flag:before{content:"\e51c"}.fa-pencil-alt:before,.fa-pencil:before{content:"\f303"}.fa-backward:before{content:"\f04a"}.fa-caret-right:before{content:"\f0da"}.fa-comments:before{content:"\f086"}.fa-file-clipboard:before,.fa-paste:before{content:"\f0ea"}.fa-code-pull-request:before{content:"\e13c"}.fa-clipboard-list:before{content:"\f46d"}.fa-truck-loading:before,.fa-truck-ramp-box:before{content:"\f4de"}.fa-user-check:before{content:"\f4fc"}.fa-vial-virus:before{content:"\e597"}.fa-sheet-plastic:before{content:"\e571"}.fa-blog:before{content:"\f781"}.fa-user-ninja:before{content:"\f504"}.fa-person-arrow-up-from-line:before{content:"\e539"}.fa-scroll-torah:before,.fa-torah:before{content:"\f6a0"}.fa-broom-ball:before,.fa-quidditch-broom-ball:before,.fa-quidditch:before{content:"\f458"}.fa-toggle-off:before{content:"\f204"}.fa-archive:before,.fa-box-archive:before{content:"\f187"}.fa-person-drowning:before{content:"\e545"}.fa-arrow-down-9-1:before,.fa-sort-numeric-desc:before,.fa-sort-numeric-down-alt:before{content:"\f886"}.fa-face-grin-tongue-squint:before,.fa-grin-tongue-squint:before{content:"\f58a"}.fa-spray-can:before{content:"\f5bd"}.fa-truck-monster:before{content:"\f63b"}.fa-w:before{content:"\57"}.fa-earth-africa:before,.fa-globe-africa:before{content:"\f57Line truncated
|
||||
.fa-sr-only,.fa-sr-only-focusable:not(:focus),.sr-only,.sr-only-focusable:not(:focus){position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}:host,:root{--fa-style-family-brands:"Font Awesome 6 Brands";--fa-font-brands:normal 400 1em/1 "Font Awesome 6 Brands"}@font-face{font-family:"Font Awesome 6 Brands";font-style:normal;font-weight:400;font-display:block;src:url(/vendor/font-awesome/webfonts/fa-brands-400.woff2) format("woff2"),url(/vendor/font-awesome/webfonts/fa-brands-400.ttf) format("truetype")}.fa-brands,.fab{font-weight:400}.fa-monero:before{content:"\f3d0"}.fa-hooli:before{content:"\f427"}.fa-yelp:before{content:"\f1e9"}.fa-cc-visa:before{content:"\f1f0"}.fa-lastfm:before{content:"\f202"}.fa-shopware:before{content:"\f5b5"}.fa-creative-commons-nc:before{content:"\f4e8"}.fa-aws:before{content:"\f375"}.fa-redhat:before{content:"\f7bc"}.fa-yoast:before{content:"\f2b1"}.fa-cloudflare:before{content:"\e07d"}.fa-ups:before{content:"\f7e0"}.fa-wpexplorer:before{content:"\f2de"}.fa-dyalog:before{content:"\f399"}.fa-bity:before{content:"\f37a"}.fa-stackpath:before{content:"\f842"}.fa-buysellads:before{content:"\f20d"}.fa-first-order:before{content:"\f2b0"}.fa-modx:before{content:"\f285"}.fa-guilded:before{content:"\e07e"}.fa-vnv:before{content:"\f40b"}.fa-js-square:before,.fa-square-js:before{content:"\f3b9"}.fa-microsoft:before{content:"\f3ca"}.fa-qq:before{content:"\f1d6"}.fa-orcid:before{content:"\f8d2"}.fa-java:before{content:"\f4e4"}.fa-invision:before{content:"\f7b0"}.fa-creative-commons-pd-alt:before{content:"\f4ed"}.fa-centercode:before{content:"\f380"}.fa-glide-g:before{content:"\f2a6"}.fa-drupal:before{content:"\f1a9"}.fa-hire-a-helper:before{content:"\f3b0"}.fa-creative-commons-by:before{content:"\f4e7"}.fa-unity:before{content:"\e049"}.fa-whmcs:before{content:"\f40d"}.fa-rocketchat:before{content:"\f3e8"}.fa-vk:before{content:"\f189"}.fa-untappd:before{content:"\f405"}.fa-mailchimp:before{content:"\f59e"}.fa-css3-alt:before{content:"\f38b"}.fa-reddit-square:before,.fa-square-reddit:before{content:"\f1a2"}.fa-vimeo-v:before{content:"\f27d"}.fa-contao:before{content:"\f26d"}.fa-square-font-awesome:before{content:"\e5ad"}.fa-deskpro:before{content:"\f38f"}.fa-sistrix:before{content:"\f3ee"}.fa-instagram-square:before,.fa-square-instagram:before{content:"\e055"}.fa-battle-net:before{content:"\f835"}.fa-the-red-yeti:before{content:"\f69d"}.fa-hacker-news-square:before,.fa-square-hacker-news:before{content:"\f3af"}.fa-edge:before{content:"\f282"}.fa-napster:before{content:"\f3d2"}.fa-snapchat-square:before,.fa-square-snapchat:before{content:"\f2ad"}.fa-google-plus-g:before{content:"\f0d5"}.fa-artstation:before{content:"\f77a"}.fa-markdown:before{content:"\f60f"}.fa-sourcetree:before{content:"\f7d3"}.fa-google-plus:before{content:"\f2b3"}.fa-diaspora:before{content:"\f791"}.fa-foursquare:before{content:"\f180"}.fa-stack-overflow:before{content:"\f16c"}.fa-github-alt:before{content:"\f113"}.fa-phoenix-squadron:before{content:"\f511"}.fa-pagelines:before{content:"\f18c"}.fa-algolia:before{content:"\f36c"}.fa-red-river:before{content:"\f3e3"}.fa-creative-commons-sa:before{content:"\f4ef"}.fa-safari:before{content:"\f267"}.fa-google:before{content:"\f1a0"}.fa-font-awesome-alt:before,.fa-square-font-awesome-stroke:before{content:"\f35c"}.fa-atlassian:before{content:"\f77b"}.fa-linkedin-in:before{content:"\f0e1"}.fa-digital-ocean:before{content:"\f391"}.fa-nimblr:before{content:"\f5a8"}.fa-chromecast:before{content:"\f838"}.fa-evernote:before{content:"\f839"}.fa-hacker-news:before{content:"\f1d4"}.fa-creative-commons-sampling:before{content:"\f4f0"}.fa-adversal:before{content:"\f36a"}.fa-creative-commons:before{content:"\f25e"}.fa-watchman-monitoring:before{content:"\e087"}.fa-fonticons:before{content:"\f280"}.fa-weixin:before{content:"\f1d7"}.fa-shirtsinbulk:before{content:"\f214"}.fa-codepen:before{content:"\f1cb"}.fa-git-alt:before{content:"\f841"}.fa-lyft:before{content:"\f3c3"}.fa-rev:before{content:"\f5b2"}.fa-windows:before{content:"\f17a"}.fa-wizards-of-the-coast:before{content:"\f730"}.fa-square-viadeo:before,.fa-viadeo-square:before{content:"\f2aa"}.fa-meetup:before{content:"\f2e0"}.fa-centos:before{content:"\f789"}.fa-adn:before{content:"\f170"}.fa-cloudsmith:before{content:"\f384"}.fa-pied-piper-alt:before{content:"\f1a8"}.fa-dribbble-square:before,.fa-square-dribbble:before{content:"\f397"}.fa-codiepie:before{content:"\f284"}.fa-node:before{content:"\f419"}.fa-mix:before{content:"\f3cb"}.fa-steam:before{content:"\f1b6"}.fa-cc-apple-pay:before{content:"\f416"}.fa-scribd:before{content:"\f28a"}.fa-openid:before{content:"\f19b"}.fa-instalod:before{content:"\e081"}.fa-expeditedssl:before{content:"\f23e"}.fa-sellcast:before{content:"\f2da"}.fa-square-twitter:before,.fa-twitter-square:before{content:"\f081"}.fa-r-project:before{content:"\f4f7"}.fa-delicious:before{content:"\f1a5"}.fa-freebsd:before{content:"\f3a4"}.fa-vuejs:bLine truncated
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* marked v15.0.12 - a markdown parser
|
||||
* Copyright (c) 2011-2025, Christopher Jeffrey. (MIT Licensed)
|
||||
* https://github.com/markedjs/marked
|
||||
*/
|
||||
|
||||
/**
|
||||
* DO NOT EDIT THIS FILE
|
||||
* The code in this file is generated from files in ./src/
|
||||
*/
|
||||
(function(g,f){if(typeof exports=="object"&&typeof module<"u"){module.exports=f()}else if("function"==typeof define && define.amd){define("marked",f)}else {g["marked"]=f()}}(typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : this,function(){var exports={};var __exports=exports;var module={exports};
|
||||
"use strict";var H=Object.defineProperty;var be=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var we=Object.prototype.hasOwnProperty;var ye=(l,e)=>{for(var t in e)H(l,t,{get:e[t],enumerable:!0})},Re=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Te(e))!we.call(l,s)&&s!==t&&H(l,s,{get:()=>e[s],enumerable:!(n=be(e,s))||n.enumerable});return l};var Se=l=>Re(H({},"__esModule",{value:!0}),l);var kt={};ye(kt,{Hooks:()=>L,Lexer:()=>x,Marked:()=>E,Parser:()=>b,Renderer:()=>$,TextRenderer:()=>_,Tokenizer:()=>S,defaults:()=>w,getDefaults:()=>z,lexer:()=>ht,marked:()=>k,options:()=>it,parse:()=>pt,parseInline:()=>ct,parser:()=>ut,setOptions:()=>ot,use:()=>lt,walkTokens:()=>at});module.exports=Se(kt);function z(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var w=z();function N(l){w=l}var I={exec:()=>null};function h(l,e=""){let t=typeof l=="string"?l:l.source,n={replace:(s,i)=>{let r=typeof i=="string"?i:i.source;return r=r.replace(m.caret,"$1"),t=t.replace(s,r),n},getRegex:()=>new RegExp(t,e)};return n}var m={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l=>new RegExp(`^( {0,3}${l})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}#`),htmlBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}<(?:[a-z].*>|!--)`,"i")},$e=/^(?:[ \t]*(?:\n|$))+/,_e=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Le=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,O=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ze=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,F=/(?:[*+-]|\d{1,9}[.)])/,ie=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,oe=h(ie).replace(/bull/g,F).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Me=h(ie).replace(/bull/g,F).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Q=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Pe=/^[^\n]+/,U=/(?!\s*\])(?:\\.|[^\[\]\\])+/,Ae=h(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",U).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ee=h(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,F).getRegex(),v="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",K=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ce=h("^ {Line truncated
|
||||
]`).replace("lheading",oe).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},qe=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ve=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ae=/^( {2,}|\\)\n(?!\s*$)/,De=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,D=/[\p{P}\p{S}]/u,W=/[\s\p{P}\p{S}]/u,ce=/[^\s\p{P}\p{S}]/u,Ze=h(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,W).getRegex(),pe=/(?!~)[\p{P}\p{S}]/u,Ge=/(?!~)[\s\p{P}\p{S}]/u,He=/(?:[^\s\p{P}\p{S}]|~)/u,Ne=/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g,ue=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,je=h(ue,"u").replace(/punct/g,D).getRegex(),Fe=h(ue,"u").replace(/punct/g,pe).getRegex(),he="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Qe=h(he,"gu").replace(/notPunctSpace/g,ce).replace(/punctSpace/g,W).replace(/punct/g,D).getRegex(),Ue=h(he,"gu").replace(/notPunctSpace/g,He).replace(/punctSpace/g,Ge).replace(/punct/g,pe).getRegex(),Ke=h("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ce).replace(/punctSpace/g,W).replace(/punct/g,D).getRegex(),Xe=h(/\\(punct)/,"gu").replace(/punct/g,D).getRegex(),We=h(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Je=h(K).replace("(?:-->|$)","-->").getRegex(),Ve=h("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Je).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),q=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Ye=h(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",q).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ke=h(/^!?\[(label)\]\[(ref)\]/).replace("label",q).replace("ref",U).getRegex(),ge=h(/^!?\[(ref)\](?:\[\])?/).replace("ref",U).getRegex(),et=h("reflink|nolink(?!\\()","g").replace("reflink",ke).replace("nolink",ge).getRegex(),J={_backpedal:I,anyPunctuation:Xe,autolink:We,blockSkip:Ne,br:ae,code:ve,del:I,emStrongLDelim:je,emStrongRDelimAst:Qe,emStrongRDelimUnd:Ke,escape:qe,link:Ye,nolink:ge,punctuation:Ze,reflink:ke,reflinkSearch:et,tag:Ve,text:De,url:I},tt={...J,link:h(/^!?\[(label)\]\((.*?)\)/).replace("label",q).getRegex(),reflink:h(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",q).getRegex()},j={...J,emStrongRDelimAst:Ue,emStrongLDelim:Fe,url:h(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},nt={...j,br:h(ae).replace("{2,}","*").getRegex(),text:h(j.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},B={normal:X,gfm:Oe,pedantic:Be},P={normal:J,gfm:j,breaks:nt,pedantic:tt};var st={"&":"&","<":"<",">":">",'"':""","'":"'"},fe=l=>st[l];function R(l,e){if(e){if(m.escapeTest.test(l))return l.replace(m.escapeReplace,fe)}else if(m.escapeTestNoEncode.test(l))return l.replace(m.escapeReplaceNoEncode,fe);return l}function V(l){try{l=encodeURI(l).replace(m.percentDecode,"%")}catch{return null}return l}function Y(l,e){let t=l.replace(m.findPipe,(i,r,o)=>{let a=!1,c=r;for(;--c>=0&&o[c]==="\\";)a=!a;return a?"|":" |"}),n=t.split(m.splitPipe),s=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;s<n.length;s++)n[s]=n[s].trim().replace(m.slashPipe,"|");return n}function A(l,e,t){let n=l.length;if(n===0)return"";let s=0;for(;s<n;){let i=l.charAt(n-s-1);if(i===e&&!t)s++;else if(i!==e&&t)s++;else break}return l.slice(0,n-s)}function de(l,e){if(l.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<l.length;n++)if(l[n]==="\\")n++;else if(l[n]===e[0])t++;else if(l[n]===e[1]&&(t--,t<0))return n;return t>0?-2:-1}fLine truncated
|
||||
`).map(i=>{let r=i.match(t.other.beginningSpace);if(r===null)return i;let[o]=r;return o.length>=s.length?i.slice(s.length):i}).join(`
|
||||
`)}var S=class{options;rules;lexer;constructor(e){this.options=e||w}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:A(n,`
|
||||
`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=rt(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let s=A(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(n=s.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:A(t[0],`
|
||||
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=A(t[0],`
|
||||
`).split(`
|
||||
`),s="",i="",r=[];for(;n.length>0;){let o=!1,a=[],c;for(c=0;c<n.length;c++)if(this.rules.other.blockquoteStart.test(n[c]))a.push(n[c]),o=!0;else if(!o)a.push(n[c]);else break;n=n.slice(c);let p=a.join(`
|
||||
`),u=p.replace(this.rules.other.blockquoteSetextReplace,`
|
||||
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
|
||||
${p}`:p,i=i?`${i}
|
||||
${u}`:u;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,r,!0),this.lexer.state.top=d,n.length===0)break;let g=r.at(-1);if(g?.type==="code")break;if(g?.type==="blockquote"){let T=g,f=T.raw+`
|
||||
`+n.join(`
|
||||
`),y=this.blockquote(f);r[r.length-1]=y,s=s.substring(0,s.length-T.raw.length)+y.raw,i=i.substring(0,i.length-T.text.length)+y.text;break}else if(g?.type==="list"){let T=g,f=T.raw+`
|
||||
`+n.join(`
|
||||
`),y=this.list(f);r[r.length-1]=y,s=s.substring(0,s.length-g.raw.length)+y.raw,i=i.substring(0,i.length-T.raw.length)+y.raw,n=f.substring(r.at(-1).raw.length).split(`
|
||||
`);continue}}return{type:"blockquote",raw:s,tokens:r,text:i}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),s=n.length>1,i={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let r=this.rules.other.listItemRegex(n),o=!1;for(;e;){let c=!1,p="",u="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let d=t[2].split(`
|
||||
`,1)[0].replace(this.rules.other.listReplaceTabs,Z=>" ".repeat(3*Z.length)),g=e.split(`
|
||||
`,1)[0],T=!d.trim(),f=0;if(this.options.pedantic?(f=2,u=d.trimStart()):T?f=t[1].length+1:(f=t[2].search(this.rules.other.nonSpaceChar),f=f>4?1:f,u=d.slice(f),f+=t[1].length),T&&this.rules.other.blankLine.test(g)&&(p+=g+`
|
||||
`,e=e.substring(g.length+1),c=!0),!c){let Z=this.rules.other.nextBulletRegex(f),te=this.rules.other.hrRegex(f),ne=this.rules.other.fencesBeginRegex(f),se=this.rules.other.headingBeginRegex(f),xe=this.rules.other.htmlBeginRegex(f);for(;e;){let G=e.split(`
|
||||
`,1)[0],C;if(g=G,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),C=g):C=g.replace(this.rules.other.tabCharGlobal," "),ne.test(g)||se.test(g)||xe.test(g)||Z.test(g)||te.test(g))break;if(C.search(this.rules.other.nonSpaceChar)>=f||!g.trim())u+=`
|
||||
`+C.slice(f);else{if(T||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ne.test(d)||se.test(d)||te.test(d))break;u+=`
|
||||
`+g}!T&&!g.trim()&&(T=!0),p+=G+`
|
||||
`,e=e.substring(G.length+1),d=C.slice(f)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(o=!0));let y=null,ee;this.options.gfm&&(y=this.rules.other.listIsTask.exec(u),y&&(ee=y[0]!=="[ ] ",u=u.replace(this.rules.other.listReplaceTask,""))),i.items.push({type:"list_item",raw:p,task:!!y,checked:ee,loose:!1,text:u,tokens:[]}),i.raw+=p}let a=i.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let c=0;c<i.items.length;c++)if(this.lexer.state.top=!1,i.items[c].tokens=this.lexer.blockTokens(i.items[c].text,[]),!i.loose){let p=i.items[c].tokens.filter(d=>d.type==="space"),u=p.length>0&&p.some(d=>this.rules.other.anyLine.test(d.raw));i.loose=u}if(i.loose)for(let c=0;c<i.items.length;c++)i.items[c].loose=!0;return i}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:t[0],href:s,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Y(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
||||
`):[],r={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===s.length){for(let o of s)this.rules.other.tableAlignRight.test(o)?r.align.push("right"):this.rules.other.tableAlignCenter.test(o)?r.align.push("center"):this.rules.other.tableAlignLeft.test(o)?r.align.push("left"):r.align.push(null);for(let o=0;o<n.length;o++)r.header.push({text:n[o],tokens:this.lexer.inline(n[o]),header:!0,align:r.align[o]});for(let o of i)r.rows.push(Y(o,r.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:r.align[c]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
|
||||
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let r=A(n.slice(0,-1),"\\");if((n.length-r.length)%2===0)return}else{let r=de(t[2],"()");if(r===-2)return;if(r>-1){let a=(t[0].indexOf("!")===0?5:4)+t[1].length+r;t[2]=t[2].substring(0,r),t[0]=t[0].substring(0,a).trim(),t[3]=""}}let s=t[2],i="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(s);r&&(s=r[1],i=r[3])}else i=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),me(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let s=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[s.toLowerCase()];if(!i){let r=n[0].charAt(0);return{type:"text",raw:r,text:r}}return me(n,i,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s||s[3]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(s[1]||s[2]||"")||!n||this.rules.inline.punctuation.exec(n)){let r=[...s[0]].length-1,o,a,c=r,p=0,u=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(u.lastIndex=0,t=t.slice(-1*e.length+r);(s=u.exec(t))!=null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(a=[...o].length,s[3]||s[4]){c+=a;continue}else if((s[5]||s[6])&&r%3&&!((r+a)%3)){p+=a;continue}if(c-=a,c>0)continue;a=Math.min(a,a+c+p);let d=[...s[0]][0].length,g=e.slice(0,r+s.index+d+a);if(Math.min(r,a)%2){let f=g.slice(1,-1);return{type:"em",raw:g,text:f,tokens:this.lexer.inlineTokens(f)}}let T=g.slice(2,-2);return{type:"strong",raw:g,text:T,tokens:this.lexer.inlineTokens(T)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]==="@"?(n=t[1],s="mailto:"+n):(n=t[1],s=n),{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,s;if(t[2]==="@")n=t[0],s="mailto:"+n;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);n=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}};var x=class l{tokens;options;state;tokenizer;inlineQueue;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||w,this.options.tokenizer=this.options.tokenizer||new S,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:m,block:B.normal,inline:P.normal};this.options.pedantic?(t.block=B.pedantic,t.inline=P.pedantic):this.options.gfm&&(t.block=B.gfm,this.options.breaks?t.inline=P.breaks:t.inline=P.gfm),this.tokenizer.rules=t}static get rules(){return{block:B,inline:P}}static lex(e,t){return new l(t).lex(e)}static lexInline(e,t){return new l(t).inlineTokens(e)}lex(e){e=e.replace(m.carriageReturn,`
|
||||
`),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let n=this.inlineQueue[t];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){for(this.options.pedantic&&(e=e.replace(m.tabCharGlobal," ").replace(m.spaceLine,""));e;){let s;if(this.options.extensions?.block?.some(r=>(s=r.call({lexer:this},e,t))?(e=e.substring(s.raw.length),t.push(s),!0):!1))continue;if(s=this.tokenizer.space(e)){e=e.substring(s.raw.length);let r=t.at(-1);s.raw.length===1&&r!==void 0?r.raw+=`
|
||||
`:t.push(s);continue}if(s=this.tokenizer.code(e)){e=e.substring(s.raw.length);let r=t.at(-1);r?.type==="paragraph"||r?.type==="text"?(r.raw+=`
|
||||
`+s.raw,r.text+=`
|
||||
`+s.text,this.inlineQueue.at(-1).src=r.text):t.push(s);continue}if(s=this.tokenizer.fences(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.heading(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.hr(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.blockquote(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.list(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.html(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.def(e)){e=e.substring(s.raw.length);let r=t.at(-1);r?.type==="paragraph"||r?.type==="text"?(r.raw+=`
|
||||
`+s.raw,r.text+=`
|
||||
`+s.raw,this.inlineQueue.at(-1).src=r.text):this.tokens.links[s.tag]||(this.tokens.links[s.tag]={href:s.href,title:s.title});continue}if(s=this.tokenizer.table(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.lheading(e)){e=e.substring(s.raw.length),t.push(s);continue}let i=e;if(this.options.extensions?.startBlock){let r=1/0,o=e.slice(1),a;this.options.extensions.startBlock.forEach(c=>{a=c.call({lexer:this},o),typeof a=="number"&&a>=0&&(r=Math.min(r,a))}),r<1/0&&r>=0&&(i=e.substring(0,r+1))}if(this.state.top&&(s=this.tokenizer.paragraph(i))){let r=t.at(-1);n&&r?.type==="paragraph"?(r.raw+=`
|
||||
`+s.raw,r.text+=`
|
||||
`+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(s),n=i.length!==e.length,e=e.substring(s.raw.length);continue}if(s=this.tokenizer.text(e)){e=e.substring(s.raw.length);let r=t.at(-1);r?.type==="text"?(r.raw+=`
|
||||
`+s.raw,r.text+=`
|
||||
`+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(s);continue}if(e){let r="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(r);break}else throw new Error(r)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n=e,s=null;if(this.tokens.links){let o=Object.keys(this.tokens.links);if(o.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(n))!=null;)o.includes(s[0].slice(s[0].lastIndexOf("[")+1,-1))&&(n=n.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(n))!=null;)n=n.slice(0,s.index)+"++"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;(s=this.tokenizer.rules.inline.blockSkip.exec(n))!=null;)n=n.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);let i=!1,r="";for(;e;){i||(r=""),i=!1;let o;if(this.options.extensions?.inline?.some(c=>(o=c.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))continue;if(o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.tag(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);let c=t.at(-1);o.type==="text"&&c?.type==="text"?(c.raw+=o.raw,c.text+=o.text):t.push(o);continue}if(o=this.tokenizer.emStrong(e,n,r)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.br(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.del(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.autolink(e)){e=e.substring(o.raw.length),t.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),t.push(o);continue}let a=e;if(this.options.extensions?.startInline){let c=1/0,p=e.slice(1),u;this.options.extensions.startInline.forEach(d=>{u=d.call({lexer:this},p),typeof u=="number"&&u>=0&&(c=Math.min(c,u))}),c<1/0&&c>=0&&(a=e.substring(0,c+1))}if(o=this.tokenizer.inlineText(a)){e=e.substring(o.raw.length),o.raw.slice(-1)!=="_"&&(r=o.raw.slice(-1)),i=!0;let c=t.at(-1);c?.type==="text"?(c.raw+=o.raw,c.text+=o.text):t.push(o);continue}if(e){let c="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(c);break}else throw new Error(c)}}return t}};var $=class{options;parser;constructor(e){this.options=e||w}space(e){return""}code({text:e,lang:t,escaped:n}){let s=(t||"").match(m.notSpaceStart)?.[0],i=e.replace(m.endingNewline,"")+`
|
||||
`;return s?'<pre><code class="language-'+R(s)+'">'+(n?i:R(i,!0))+`</code></pre>
|
||||
`:"<pre><code>"+(n?i:R(i,!0))+`</code></pre>
|
||||
`}blockquote({tokens:e}){return`<blockquote>
|
||||
${this.parser.parse(e)}</blockquote>
|
||||
`}html({text:e}){return e}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
||||
`}hr(e){return`<hr>
|
||||
`}list(e){let t=e.ordered,n=e.start,s="";for(let o=0;o<e.items.length;o++){let a=e.items[o];s+=this.listitem(a)}let i=t?"ol":"ul",r=t&&n!==1?' start="'+n+'"':"";return"<"+i+r+`>
|
||||
`+s+"</"+i+`>
|
||||
`}listitem(e){let t="";if(e.task){let n=this.checkbox({checked:!!e.checked});e.loose?e.tokens[0]?.type==="paragraph"?(e.tokens[0].text=n+" "+e.tokens[0].text,e.tokens[0].tokens&&e.tokens[0].tokens.length>0&&e.tokens[0].tokens[0].type==="text"&&(e.tokens[0].tokens[0].text=n+" "+R(e.tokens[0].tokens[0].text),e.tokens[0].tokens[0].escaped=!0)):e.tokens.unshift({type:"text",raw:n+" ",text:n+" ",escaped:!0}):t+=n+" "}return t+=this.parser.parse(e.tokens,!!e.loose),`<li>${t}</li>
|
||||
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
||||
`}table(e){let t="",n="";for(let i=0;i<e.header.length;i++)n+=this.tablecell(e.header[i]);t+=this.tablerow({text:n});let s="";for(let i=0;i<e.rows.length;i++){let r=e.rows[i];n="";for(let o=0;o<r.length;o++)n+=this.tablecell(r[o]);s+=this.tablerow({text:n})}return s&&(s=`<tbody>${s}</tbody>`),`<table>
|
||||
<thead>
|
||||
`+t+`</thead>
|
||||
`+s+`</table>
|
||||
`}tablerow({text:e}){return`<tr>
|
||||
${e}</tr>
|
||||
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
||||
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${R(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),i=V(e);if(i===null)return s;e=i;let r='<a href="'+e+'"';return t&&(r+=' title="'+R(t)+'"'),r+=">"+s+"</a>",r}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let i=V(e);if(i===null)return R(n);e=i;let r=`<img src="${e}" alt="${n}"`;return t&&(r+=` title="${R(t)}"`),r+=">",r}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:R(e.text)}};var _=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}};var b=class l{options;renderer;textRenderer;constructor(e){this.options=e||w,this.options.renderer=this.options.renderer||new $,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new _}static parse(e,t){return new l(t).parse(e)}static parseInline(e,t){return new l(t).parseInline(e)}parse(e,t=!0){let n="";for(let s=0;s<e.length;s++){let i=e[s];if(this.options.extensions?.renderers?.[i.type]){let o=i,a=this.options.extensions.renderers[o.type].call({parser:this},o);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(o.type)){n+=a||"";continue}}let r=i;switch(r.type){case"space":{n+=this.renderer.space(r);continue}case"hr":{n+=this.renderer.hr(r);continue}case"heading":{n+=this.renderer.heading(r);continue}case"code":{n+=this.renderer.code(r);continue}case"table":{n+=this.renderer.table(r);continue}case"blockquote":{n+=this.renderer.blockquote(r);continue}case"list":{n+=this.renderer.list(r);continue}case"html":{n+=this.renderer.html(r);continue}case"paragraph":{n+=this.renderer.paragraph(r);continue}case"text":{let o=r,a=this.renderer.text(o);for(;s+1<e.length&&e[s+1].type==="text";)o=e[++s],a+=`
|
||||
`+this.renderer.text(o);t?n+=this.renderer.paragraph({type:"paragraph",raw:a,text:a,tokens:[{type:"text",raw:a,text:a,escaped:!0}]}):n+=a;continue}default:{let o='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return n}parseInline(e,t=this.renderer){let n="";for(let s=0;s<e.length;s++){let i=e[s];if(this.options.extensions?.renderers?.[i.type]){let o=this.options.extensions.renderers[i.type].call({parser:this},i);if(o!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(i.type)){n+=o||"";continue}}let r=i;switch(r.type){case"escape":{n+=t.text(r);break}case"html":{n+=t.html(r);break}case"link":{n+=t.link(r);break}case"image":{n+=t.image(r);break}case"strong":{n+=t.strong(r);break}case"em":{n+=t.em(r);break}case"codespan":{n+=t.codespan(r);break}case"br":{n+=t.br(r);break}case"del":{n+=t.del(r);break}case"text":{n+=t.text(r);break}default:{let o='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return n}};var L=class{options;block;constructor(e){this.options=e||w}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}provideLexer(){return this.block?x.lex:x.lexInline}provideParser(){return this.block?b.parse:b.parseInline}};var E=class{defaults=z();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=b;Renderer=$;TextRenderer=_;Lexer=x;Tokenizer=S;Hooks=L;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let s of e)switch(n=n.concat(t.call(this,s)),s.type){case"table":{let i=s;for(let r of i.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of i.rows)for(let o of r)n=n.concat(this.walkTokens(o.tokens,t));break}case"list":{let i=s;n=n.concat(this.walkTokens(i.items,t));break}default:{let i=s;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(r=>{let o=i[r].flat(1/0);n=n.concat(this.walkTokens(o,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let r=t.renderers[i.name];r?t.renderers[i.name]=function(...o){let a=i.renderer.apply(this,o);return a===!1&&(a=r.apply(this,o)),a}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=t[i.level];r?r.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),s.extensions=t),n.renderer){let i=this.defaults.renderer||new $(this.defaults);for(let r in n.renderer){if(!(r in i))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let o=r,a=n.renderer[o],c=i[o];i[o]=(...p)=>{let u=a.apply(i,p);return u===!1&&(u=c.apply(i,p)),u||""}}s.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new S(this.defaults);for(let r in n.tokenizer){if(!(r in i))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let o=r,a=n.tokenizer[o],c=i[o];i[o]=(...p)=>{let u=a.apply(i,p);return u===!1&&(u=c.apply(i,p)),u}}s.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new L;for(let r in n.hooks){if(!(r in i))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let o=r,a=n.hooks[o],c=i[o];L.passThroughHooks.has(r)?i[o]=p=>{if(this.defaults.async)return Promise.resolve(a.call(i,p)).then(d=>c.call(i,d));let u=a.call(i,p);return c.call(i,u)}:i[o]=(...p)=>{let u=a.apply(i,p);return u===!1&&(u=c.apply(i,p)),u}}s.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,r=n.walkTokens;s.walkTokens=function(o){let a=[];return a.push(r.call(this,o)),i&&(a=a.concat(i.call(this,o))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(n,s)=>{let i={...s},r={...this.defaults,...i},o=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&i.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.
Line truncated
|
||||
Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+R(n.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}};var M=new E;function k(l,e){return M.parse(l,e)}k.options=k.setOptions=function(l){return M.setOptions(l),k.defaults=M.defaults,N(k.defaults),k};k.getDefaults=z;k.defaults=w;k.use=function(...l){return M.use(...l),k.defaults=M.defaults,N(k.defaults),k};k.walkTokens=function(l,e){return M.walkTokens(l,e)};k.parseInline=M.parseInline;k.Parser=b;k.parser=b.parse;k.Renderer=$;k.TextRenderer=_;k.Lexer=x;k.lexer=x.lex;k.Tokenizer=S;k.Hooks=L;k.parse=k;var it=k.options,ot=k.setOptions,lt=k.use,at=k.walkTokens,ct=k.parseInline,pt=k,ut=b.parse,ht=x.lex;
|
||||
|
||||
if(__exports != exports)module.exports = exports;return module.exports}));
|
||||
@@ -0,0 +1,83 @@
|
||||
(()=>{var qv=Object.create;var Hi=Object.defineProperty;var $v=Object.getOwnPropertyDescriptor;var Lv=Object.getOwnPropertyNames;var Mv=Object.getPrototypeOf,Nv=Object.prototype.hasOwnProperty;var df=r=>Hi(r,"__esModule",{value:!0});var hf=r=>{if(typeof require!="undefined")return require(r);throw new Error('Dynamic require of "'+r+'" is not supported')};var P=(r,e)=>()=>(r&&(e=r(r=0)),e);var x=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ge=(r,e)=>{df(r);for(var t in e)Hi(r,t,{get:e[t],enumerable:!0})},Bv=(r,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Lv(e))!Nv.call(r,i)&&i!=="default"&&Hi(r,i,{get:()=>e[i],enumerable:!(t=$v(e,i))||t.enumerable});return r},pe=r=>Bv(df(Hi(r!=null?qv(Mv(r)):{},"default",r&&r.__esModule&&"default"in r?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r);var m,u=P(()=>{m={platform:"",env:{},versions:{node:"14.17.6"}}});var Fv,be,ft=P(()=>{u();Fv=0,be={readFileSync:r=>self[r]||"",statSync:()=>({mtimeMs:Fv++}),promises:{readFile:r=>Promise.resolve(self[r]||"")}}});var Fs=x((oP,gf)=>{u();"use strict";var mf=class{constructor(e={}){if(!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge=="number"&&e.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.maxSize=e.maxSize,this.maxAge=e.maxAge||1/0,this.onEviction=e.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}_emitEvictions(e){if(typeof this.onEviction=="function")for(let[t,i]of e)this.onEviction(t,i.value)}_deleteIfExpired(e,t){return typeof t.expiry=="number"&&t.expiry<=Date.now()?(typeof this.onEviction=="function"&&this.onEviction(e,t.value),this.delete(e)):!1}_getOrDeleteIfExpired(e,t){if(this._deleteIfExpired(e,t)===!1)return t.value}_getItemValue(e,t){return t.expiry?this._getOrDeleteIfExpired(e,t):t.value}_peek(e,t){let i=t.get(e);return this._getItemValue(e,i)}_set(e,t){this.cache.set(e,t),this._size++,this._size>=this.maxSize&&(this._size=0,this._emitEvictions(this.oldCache),this.oldCache=this.cache,this.cache=new Map)}_moveToRecent(e,t){this.oldCache.delete(e),this._set(e,t)}*_entriesAscending(){for(let e of this.oldCache){let[t,i]=e;this.cache.has(t)||this._deleteIfExpired(t,i)===!1&&(yield e)}for(let e of this.cache){let[t,i]=e;this._deleteIfExpired(t,i)===!1&&(yield e)}}get(e){if(this.cache.has(e)){let t=this.cache.get(e);return this._getItemValue(e,t)}if(this.oldCache.has(e)){let t=this.oldCache.get(e);if(this._deleteIfExpired(e,t)===!1)return this._moveToRecent(e,t),t.value}}set(e,t,{maxAge:i=this.maxAge===1/0?void 0:Date.now()+this.maxAge}={}){this.cache.has(e)?this.cache.set(e,{value:t,maxAge:i}):this._set(e,{value:t,expiry:i})}has(e){return this.cache.has(e)?!this._deleteIfExpired(e,this.cache.get(e)):this.oldCache.has(e)?!this._deleteIfExpired(e,this.oldCache.get(e)):!1}peek(e){if(this.cache.has(e))return this._peek(e,this.cache);if(this.oldCache.has(e))return this._peek(e,this.oldCache)}delete(e){let t=this.cache.delete(e);return t&&this._size--,this.oldCache.delete(e)||t}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");let t=[...this._entriesAscending()],i=t.length-e;i<0?(this.cache=new Map(t),this.oldCache=new Map,this._size=t.length):(i>0&&this._emitEvictions(t.slice(0,i)),this.oldCache=new Map(t.slice(i)),this.cache=new Map,this._size=0),this.maxSize=e}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.cache){let[t,i]=e;this._deleteIfExpired(t,i)===!1&&(yield[t,i.value])}for(let e of this.oldCache){let[t,i]=e;this.cache.has(t)||this._deleteIfExpired(t,i)===!1&&(yield[t,i.value])}}*entriesDescending(){let e=[...this.cache];for(let t=e.length-1;t>=0;--t){let i=e[t],[n,s]=i;this._deleteIfExpired(n,s)===!1&&(yield[n,s.value])}e=[...this.oldCache];for(let t=e.length-1;t>=0;--t){let i=e[t],[n,s]=i;this.cache.has(n)||this._deleteIfExpired(n,s)===!1&&(yield[n,s.value])}}*entriesAscending(){for(let[e,t]of this._entriesAscending())yield[e,t.value]}get size(){if(!this._size)return this.oldCache.size;let e=0;for(let t of this.oldCache.keys())this.cache.has(t)||e++;return Math.min(this._size+e,this.maxSize)}};gf.exports=mf});var yf,bf=P(()=>{u();yf=r=>r&&r._hash});function Wi(r){return yf(r,{ignoreUnknown:!0})}var wf=P(()=>{u();bf()});function xt(r){if(r=`${r}`,r==="0")return"0";if(/^[+-]?(\d+|\d*\.\d+)(e[+-]?\d+)?(%|\w+)?$/.test(r))return r.replace(/^[+-]?/,t=>t==="-"?"":"-");let e=["var","calc","min","max","clamp"];for(let t of e)if(r.includes(`${t}(`))return`calc(${r} * -1)`}var Gi=P(()=>{u()});var vf,xf=P(()=>{u();vf=["preflight","container","accessibility","pointerEvents","visibility","position","inset","isolation","zIndex","order","gridColumn","gridColumnStart","gridColumnEnd","gridRow","gridRowStart","gridRowEnd","float","clear","margin","boxSizing","lineClamp","display","aspectRatio","size","height","maxHeight"Line truncated
|
||||
`+S+n("^")}let b=i(h.replace(/\d/g," "))+f.slice(0,this.column-1).replace(/[^\t]/g," ");return n(">")+i(h)+s(f)+`
|
||||
`+b+n("^")}return" "+i(h)+s(f)}).join(`
|
||||
`)}toString(){let e=this.showSourceCode();return e&&(e=`
|
||||
|
||||
`+e+`
|
||||
`),this.name+": "+this.message+e}};cc.exports=Jt;Jt.default=Jt});var fa=x((x3,dc)=>{u();"use strict";var pc={after:`
|
||||
`,beforeClose:`
|
||||
`,beforeComment:`
|
||||
`,beforeDecl:`
|
||||
`,beforeOpen:" ",beforeRule:`
|
||||
`,colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};function vx(r){return r[0].toUpperCase()+r.slice(1)}var on=class{constructor(e){this.builder=e}atrule(e,t){let i="@"+e.name,n=e.params?this.rawValue(e,"params"):"";if(typeof e.raws.afterName!="undefined"?i+=e.raws.afterName:n&&(i+=" "),e.nodes)this.block(e,i+n);else{let s=(e.raws.between||"")+(t?";":"");this.builder(i+n+s,e)}}beforeAfter(e,t){let i;e.type==="decl"?i=this.raw(e,null,"beforeDecl"):e.type==="comment"?i=this.raw(e,null,"beforeComment"):t==="before"?i=this.raw(e,null,"beforeRule"):i=this.raw(e,null,"beforeClose");let n=e.parent,s=0;for(;n&&n.type!=="root";)s+=1,n=n.parent;if(i.includes(`
|
||||
`)){let a=this.raw(e,null,"indent");if(a.length)for(let o=0;o<s;o++)i+=a}return i}block(e,t){let i=this.raw(e,"between","beforeOpen");this.builder(t+i+"{",e,"start");let n;e.nodes&&e.nodes.length?(this.body(e),n=this.raw(e,"after")):n=this.raw(e,"after","emptyBody"),n&&this.builder(n),this.builder("}",e,"end")}body(e){let t=e.nodes.length-1;for(;t>0&&e.nodes[t].type==="comment";)t-=1;let i=this.raw(e,"semicolon");for(let n=0;n<e.nodes.length;n++){let s=e.nodes[n],a=this.raw(s,"before");a&&this.builder(a),this.stringify(s,t!==n||i)}}comment(e){let t=this.raw(e,"left","commentLeft"),i=this.raw(e,"right","commentRight");this.builder("/*"+t+e.text+i+"*/",e)}decl(e,t){let i=this.raw(e,"between","colon"),n=e.prop+i+this.rawValue(e,"value");e.important&&(n+=e.raws.important||" !important"),t&&(n+=";"),this.builder(n,e)}document(e){this.body(e)}raw(e,t,i){let n;if(i||(i=t),t&&(n=e.raws[t],typeof n!="undefined"))return n;let s=e.parent;if(i==="before"&&(!s||s.type==="root"&&s.first===e||s&&s.type==="document"))return"";if(!s)return pc[i];let a=e.root();if(a.rawCache||(a.rawCache={}),typeof a.rawCache[i]!="undefined")return a.rawCache[i];if(i==="before"||i==="after")return this.beforeAfter(e,i);{let o="raw"+vx(i);this[o]?n=this[o](a,e):a.walk(l=>{if(n=l.raws[t],typeof n!="undefined")return!1})}return typeof n=="undefined"&&(n=pc[i]),a.rawCache[i]=n,n}rawBeforeClose(e){let t;return e.walk(i=>{if(i.nodes&&i.nodes.length>0&&typeof i.raws.after!="undefined")return t=i.raws.after,t.includes(`
|
||||
`)&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawBeforeComment(e,t){let i;return e.walkComments(n=>{if(typeof n.raws.before!="undefined")return i=n.raws.before,i.includes(`
|
||||
`)&&(i=i.replace(/[^\n]+$/,"")),!1}),typeof i=="undefined"?i=this.raw(t,null,"beforeDecl"):i&&(i=i.replace(/\S/g,"")),i}rawBeforeDecl(e,t){let i;return e.walkDecls(n=>{if(typeof n.raws.before!="undefined")return i=n.raws.before,i.includes(`
|
||||
`)&&(i=i.replace(/[^\n]+$/,"")),!1}),typeof i=="undefined"?i=this.raw(t,null,"beforeRule"):i&&(i=i.replace(/\S/g,"")),i}rawBeforeOpen(e){let t;return e.walk(i=>{if(i.type!=="decl"&&(t=i.raws.between,typeof t!="undefined"))return!1}),t}rawBeforeRule(e){let t;return e.walk(i=>{if(i.nodes&&(i.parent!==e||e.first!==i)&&typeof i.raws.before!="undefined")return t=i.raws.before,t.includes(`
|
||||
`)&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawColon(e){let t;return e.walkDecls(i=>{if(typeof i.raws.between!="undefined")return t=i.raws.between.replace(/[^\s:]/g,""),!1}),t}rawEmptyBody(e){let t;return e.walk(i=>{if(i.nodes&&i.nodes.length===0&&(t=i.raws.after,typeof t!="undefined"))return!1}),t}rawIndent(e){if(e.raws.indent)return e.raws.indent;let t;return e.walk(i=>{let n=i.parent;if(n&&n!==e&&n.parent&&n.parent===e&&typeof i.raws.before!="undefined"){let s=i.raws.before.split(`
|
||||
`);return t=s[s.length-1],t=t.replace(/\S/g,""),!1}}),t}rawSemicolon(e){let t;return e.walk(i=>{if(i.nodes&&i.nodes.length&&i.last.type==="decl"&&(t=i.raws.semicolon,typeof t!="undefined"))return!1}),t}rawValue(e,t){let i=e[t],n=e.raws[t];return n&&n.value===i?n.raw:i}root(e){this.body(e),e.raws.after&&this.builder(e.raws.after)}rule(e){this.block(e,this.rawValue(e,"selector")),e.raws.ownSemicolon&&this.builder(e.raws.ownSemicolon,e,"end")}stringify(e,t){if(!this[e.type])throw new Error("Unknown AST node type "+e.type+". Maybe you need to change PostCSS stringifier.");this[e.type](e,t)}};dc.exports=on;on.default=on});var Vr=x((k3,hc)=>{u();"use strict";var xx=fa();function ca(r,e){new xx(e).stringify(r)}hc.exports=ca;ca.default=ca});var ln=x((S3,pa)=>{u();"use strict";pa.exports.isClean=Symbol("isClean");pa.exports.my=Symbol("my")});var Gr=x((A3,mc)=>{u();"use strict";var kx=an(),Sx=fa(),Ax=Vr(),{isClean:Hr,my:Cx}=ln();function da(r,e){let t=new r.constructor;for(let i in r){if(!Object.prototype.hasOwnProperty.call(r,i)||i==="proxyCache")continue;let n=r[i],s=typeof n;i==="parent"&&s==="object"?e&&(t[i]=e):i==="source"?t[i]=n:Array.isArray(n)?t[i]=n.map(a=>da(a,t)):(s==="object"&&n!==null&&(n=da(n)),t[i]=n)}return t}function Wr(r,e){if(e&&typeof e.offset!="undefined")return e.offset;let t=1,i=1,n=0;for(let s=0;s<r.length;s++){if(i===e.line&&t===e.column){n=s;break}r[s]===`
|
||||
`?(t=1,i+=1):t+=1}return n}var un=class{constructor(e={}){this.raws={},this[Hr]=!1,this[Cx]=!0;for(let t in e)if(t==="nodes"){this.nodes=[];for(let i of e[t])typeof i.clone=="function"?this.append(i.clone()):this.append(i)}else this[t]=e[t]}addToError(e){if(e.postcssNode=this,e.stack&&this.source&&/\n\s{4}at /.test(e.stack)){let t=this.source;e.stack=e.stack.replace(/\n\s{4}at /,`$&${t.input.from}:${t.start.line}:${t.start.column}$&`)}return e}after(e){return this.parent.insertAfter(this,e),this}assign(e={}){for(let t in e)this[t]=e[t];return this}before(e){return this.parent.insertBefore(this,e),this}cleanRaws(e){delete this.raws.before,delete this.raws.after,e||delete this.raws.between}clone(e={}){let t=da(this);for(let i in e)t[i]=e[i];return t}cloneAfter(e={}){let t=this.clone(e);return this.parent.insertAfter(this,t),t}cloneBefore(e={}){let t=this.clone(e);return this.parent.insertBefore(this,t),t}error(e,t={}){if(this.source){let{end:i,start:n}=this.rangeBy(t);return this.source.input.error(e,{column:n.column,line:n.line},{column:i.column,line:i.line},t)}return new kx(e)}getProxyProcessor(){return{get(e,t){return t==="proxyOf"?e:t==="root"?()=>e.root().toProxy():e[t]},set(e,t,i){return e[t]===i||(e[t]=i,(t==="prop"||t==="value"||t==="name"||t==="params"||t==="important"||t==="text")&&e.markDirty()),!0}}}markClean(){this[Hr]=!0}markDirty(){if(this[Hr]){this[Hr]=!1;let e=this;for(;e=e.parent;)e[Hr]=!1}}next(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e+1]}positionBy(e){let t=this.source.start;if(e.index)t=this.positionInside(e.index);else if(e.word){let n=this.source.input.css.slice(Wr(this.source.input.css,this.source.start),Wr(this.source.input.css,this.source.end)).indexOf(e.word);n!==-1&&(t=this.positionInside(n))}return t}positionInside(e){let t=this.source.start.column,i=this.source.start.line,n=Wr(this.source.input.css,this.source.start),s=n+e;for(let a=n;a<s;a++)this.source.input.css[a]===`
|
||||
`?(t=1,i+=1):t+=1;return{column:t,line:i}}prev(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e-1]}rangeBy(e){let t={column:this.source.start.column,line:this.source.start.line},i=this.source.end?{column:this.source.end.column+1,line:this.source.end.line}:{column:t.column+1,line:t.line};if(e.word){let s=this.source.input.css.slice(Wr(this.source.input.css,this.source.start),Wr(this.source.input.css,this.source.end)).indexOf(e.word);s!==-1&&(t=this.positionInside(s),i=this.positionInside(s+e.word.length))}else e.start?t={column:e.start.column,line:e.start.line}:e.index&&(t=this.positionInside(e.index)),e.end?i={column:e.end.column,line:e.end.line}:typeof e.endIndex=="number"?i=this.positionInside(e.endIndex):e.index&&(i=this.positionInside(e.index+1));return(i.line<t.line||i.line===t.line&&i.column<=t.column)&&(i={column:t.column+1,line:t.line}),{end:i,start:t}}raw(e,t){return new Sx().raw(this,e,t)}remove(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this}replaceWith(...e){if(this.parent){let t=this,i=!1;for(let n of e)n===this?i=!0:i?(this.parent.insertAfter(t,n),t=n):this.parent.insertBefore(t,n);i||this.remove()}return this}root(){let e=this;for(;e.parent&&e.parent.type!=="document";)e=e.parent;return e}toJSON(e,t){let i={},n=t==null;t=t||new Map;let s=0;for(let a in this){if(!Object.prototype.hasOwnProperty.call(this,a)||a==="parent"||a==="proxyCache")continue;let o=this[a];if(Array.isArray(o))i[a]=o.map(l=>typeof l=="object"&&l.toJSON?l.toJSON(null,t):l);else if(typeof o=="object"&&o.toJSON)i[a]=o.toJSON(null,t);else if(a==="source"){let l=t.get(o.input);l==null&&(l=s,t.set(o.input,s),s++),i[a]={end:o.end,inputId:l,start:o.start}}else i[a]=o}return n&&(i.inputs=[...t.keys()].map(a=>a.toJSON())),i}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(e=Ax){e.stringify&&(e=e.stringify);let t="";return e(this,i=>{t+=i}),t}warn(e,t,i){let n={node:this};for(let s in i)n[s]=i[s];return e.warn(t,n)}get proxyOf(){return this}};mc.exports=un;un.default=un});var Qr=x((C3,gc)=>{u();"use strict";var _x=Gr(),fn=class extends _x{constructor(e){super(e);this.type="comment"}};gc.exports=fn;fn.default=fn});var Yr=x((_3,yc)=>{u();"use strict";var Ex=Gr(),cn=class extends Ex{constructor(e){e&&typeof e.value!="undefined"&&typeof e.value!="string"&&(e={...e,value:String(e.value)});super(e);this.type="decl"}get variable(){return this.prop.startsWith("--")||this.prop[0]==="$"}};yc.exports=cn;cn.default=cn});var Et=x((E3,_c)=>{u();"use strict";var bc=Qr(),wc=Yr(),Ox=Gr(),{isClean:vc,my:xc}=ln(),ha,kc,Sc,ma;function Ac(r){return r.map(e=>(e.nodes&&(e.nodes=Ac(e.nodes)),delete e.source,e))}function Cc(r){if(r[vc]=!1,r.proxyOf.nodes)for(let e of r.proxyOf.nodes)Cc(e)}var Fe=class extends Ox{append(...e){for(let t of e){let i=this.normalize(t,this.last);for(let n of i)this.proxyOf.nodes.push(n)}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let t of this.nodes)t.cleanRaws(e)}each(e){if(!this.proxyOf.nodes)return;let t=this.getIterator(),i,n;for(;this.indexes[t]<this.proxyOf.nodes.length&&(i=this.indexes[t],n=e(this.proxyOf.nodes[i],i),n!==!1);)this.indexes[t]+=1;return delete this.indexes[t],n}every(e){return this.nodes.every(e)}getIterator(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;let e=this.lastEach;return this.indexes[e]=0,e}getProxyProcessor(){return{get(e,t){return t==="proxyOf"?e:e[t]?t==="each"||typeof t=="string"&&t.startsWith("walk")?(...i)=>e[t](...i.map(n=>typeof n=="function"?(s,a)=>n(s.toProxy(),a):n)):t==="every"||t==="some"?i=>e[t]((n,...s)=>i(n.toProxy(),...s)):t==="root"?()=>e.root().toProxy():t==="nodes"?e.nodes.map(i=>i.toProxy()):t==="first"||t==="last"?e[t].toProxy():e[t]:e[t]},set(e,t,i){return e[t]===i||(e[t]=i,(t==="name"||t==="params"||t==="selector")&&e.markDirty()),!0}}}index(e){return typeof e=="number"?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}insertAfter(e,t){let i=this.index(e),n=this.normalize(t,this.proxyOf.nodes[i]).reverse();i=this.index(e);for(let a of n)this.proxyOf.nodes.splice(i+1,0,a);let s;for(let a in this.indexes)s=this.indexes[a],i<s&&(this.indexes[a]=s+n.length);return this.markDirty(),this}insertBefore(e,t){let i=this.index(e),n=i===0?"prepend":!1,s=this.normalize(t,this.proxyOf.nodes[i],n).reverse();i=this.index(e);for(let o of s)this.proxyOf.nodes.splice(i,0,o);let a;for(let o in this.indexes)a=this.indexes[o],i<=a&&(this.indexes[o]=a+s.length);return this.markDirty(),this}normalize(e,t){if(typeof e=="string")e=Ac(kc(e).nodes);else if(typeof e=="undefined")e=[];else if(Array.isArray(e)){e=e.slice(0);for(let n of e)n.parent&&n.parent.removeChild(n,"ignore")}else if(e.type==="root"&&this.type!=="document"){e=e.nodes.slice(0);for(let n of e)n.parent&&n.parent.removeChild(n,"ignore")}else if(e.type)e=[e];else if(e.prop){if(typeof e.value=="undefined")throw new Error("Value fie
Line truncated
|
||||
`);i=new Array(s.length);let a=0;for(let o=0,l=s.length;o<l;o++)i[o]=a,a+=s[o].length+1;this[va]=i}t=i[i.length-1];let n=0;if(e>=t)n=i.length-1;else{let s=i.length-2,a;for(;n<s;)if(a=n+(s-n>>1),e<i[a])s=a-1;else if(e>=i[a+1])n=a+1;else{n=a;break}}return{col:e-i[n]+1,line:n+1}}mapResolve(e){return/^\w+:\/\//.test(e)?e:ba(this.map.consumer().sourceRoot||this.map.root||".",e)}origin(e,t,i,n){if(!this.map)return!1;let s=this.map.consumer(),a=s.originalPositionFor({column:t,line:e});if(!a.source)return!1;let o;typeof i=="number"&&(o=s.originalPositionFor({column:n,line:i}));let l;ya(a.source)?l=hn(a.source):l=new URL(a.source,this.map.consumer().sourceRoot||hn(this.map.mapFile));let c={column:a.column,endColumn:o&&o.column,endLine:o&&o.line,line:a.line,url:l.toString()};if(l.protocol==="file:")if(Lc)c.file=Lc(l);else throw new Error("file: protocol is not available in this PostCSS build");let f=s.sourceContentFor(a.source);return f&&(c.source=f),c}toJSON(){let e={};for(let t of["hasBOM","css","file","id"])this[t]!=null&&(e[t]=this[t]);return this.map&&(e.map={...this.map},e.map.consumerCache&&(e.map.consumerCache=void 0)),e}get from(){return this.file||this.id}};Bc.exports=Xr;Xr.default=Xr;wa&&wa.registerInput&&wa.registerInput(Xr)});var tr=x(($3,Uc)=>{u();"use strict";var Fc=Et(),jc,zc,Ut=class extends Fc{constructor(e){super(e);this.type="root",this.nodes||(this.nodes=[])}normalize(e,t,i){let n=super.normalize(e);if(t){if(i==="prepend")this.nodes.length>1?t.raws.before=this.nodes[1].raws.before:delete t.raws.before;else if(this.first!==t)for(let s of n)s.raws.before=t.raws.before}return n}removeChild(e,t){let i=this.index(e);return!t&&i===0&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[i].raws.before),super.removeChild(e)}toResult(e={}){return new jc(new zc,this,e).stringify()}};Ut.registerLazyResult=r=>{jc=r};Ut.registerProcessor=r=>{zc=r};Uc.exports=Ut;Ut.default=Ut;Fc.registerRoot(Ut)});var xa=x((L3,Vc)=>{u();"use strict";var Zr={comma(r){return Zr.split(r,[","],!0)},space(r){let e=[" ",`
|
||||
`," "];return Zr.split(r,e)},split(r,e,t){let i=[],n="",s=!1,a=0,o=!1,l="",c=!1;for(let f of r)c?c=!1:f==="\\"?c=!0:o?f===l&&(o=!1):f==='"'||f==="'"?(o=!0,l=f):f==="("?a+=1:f===")"?a>0&&(a-=1):a===0&&e.includes(f)&&(s=!0),s?(n!==""&&i.push(n.trim()),n="",s=!1):n+=f;return(t||n!=="")&&i.push(n.trim()),i}};Vc.exports=Zr;Zr.default=Zr});var gn=x((M3,Wc)=>{u();"use strict";var Hc=Et(),Nx=xa(),Jr=class extends Hc{constructor(e){super(e);this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Nx.comma(this.selector)}set selectors(e){let t=this.selector?this.selector.match(/,\s*/):null,i=t?t[0]:","+this.raw("between","beforeOpen");this.selector=e.join(i)}};Wc.exports=Jr;Jr.default=Jr;Hc.registerRule(Jr)});var Qc=x((N3,Gc)=>{u();"use strict";var Bx=pn(),Fx=Qr(),jx=Yr(),zx=mn(),Ux=ga(),Vx=tr(),Hx=gn();function ei(r,e){if(Array.isArray(r))return r.map(n=>ei(n));let{inputs:t,...i}=r;if(t){e=[];for(let n of t){let s={...n,__proto__:zx.prototype};s.map&&(s.map={...s.map,__proto__:Ux.prototype}),e.push(s)}}if(i.nodes&&(i.nodes=r.nodes.map(n=>ei(n,e))),i.source){let{inputId:n,...s}=i.source;i.source=s,n!=null&&(i.source.input=e[n])}if(i.type==="root")return new Vx(i);if(i.type==="decl")return new jx(i);if(i.type==="rule")return new Hx(i);if(i.type==="comment")return new Fx(i);if(i.type==="atrule")return new Bx(i);throw new Error("Unknown node type: "+r.type)}Gc.exports=ei;ei.default=ei});var ka=x((B3,Yc)=>{u();Yc.exports=function(r,e){return{generate:()=>{let t="";return r(e,i=>{t+=i}),[t]}}}});var ep=x((F3,Jc)=>{u();"use strict";var Sa="'".charCodeAt(0),Kc='"'.charCodeAt(0),yn="\\".charCodeAt(0),Xc="/".charCodeAt(0),bn=`
|
||||
`.charCodeAt(0),ti=" ".charCodeAt(0),wn="\f".charCodeAt(0),vn=" ".charCodeAt(0),xn="\r".charCodeAt(0),Wx="[".charCodeAt(0),Gx="]".charCodeAt(0),Qx="(".charCodeAt(0),Yx=")".charCodeAt(0),Kx="{".charCodeAt(0),Xx="}".charCodeAt(0),Zx=";".charCodeAt(0),Jx="*".charCodeAt(0),e1=":".charCodeAt(0),t1="@".charCodeAt(0),kn=/[\t\n\f\r "#'()/;[\\\]{}]/g,Sn=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,r1=/.[\r\n"'(/\\]/,Zc=/[\da-f]/i;Jc.exports=function(e,t={}){let i=e.css.valueOf(),n=t.ignoreErrors,s,a,o,l,c,f,d,p,h,b,v=i.length,y=0,w=[],k=[];function S(){return y}function E(R){throw e.error("Unclosed "+R,y)}function T(){return k.length===0&&y>=v}function B(R){if(k.length)return k.pop();if(y>=v)return;let F=R?R.ignoreUnclosed:!1;switch(s=i.charCodeAt(y),s){case bn:case ti:case vn:case xn:case wn:{l=y;do l+=1,s=i.charCodeAt(l);while(s===ti||s===bn||s===vn||s===xn||s===wn);f=["space",i.slice(y,l)],y=l-1;break}case Wx:case Gx:case Kx:case Xx:case e1:case Zx:case Yx:{let Y=String.fromCharCode(s);f=[Y,Y,y];break}case Qx:{if(b=w.length?w.pop()[1]:"",h=i.charCodeAt(y+1),b==="url"&&h!==Sa&&h!==Kc&&h!==ti&&h!==bn&&h!==vn&&h!==wn&&h!==xn){l=y;do{if(d=!1,l=i.indexOf(")",l+1),l===-1)if(n||F){l=y;break}else E("bracket");for(p=l;i.charCodeAt(p-1)===yn;)p-=1,d=!d}while(d);f=["brackets",i.slice(y,l+1),y,l],y=l}else l=i.indexOf(")",y+1),a=i.slice(y,l+1),l===-1||r1.test(a)?f=["(","(",y]:(f=["brackets",a,y,l],y=l);break}case Sa:case Kc:{c=s===Sa?"'":'"',l=y;do{if(d=!1,l=i.indexOf(c,l+1),l===-1)if(n||F){l=y+1;break}else E("string");for(p=l;i.charCodeAt(p-1)===yn;)p-=1,d=!d}while(d);f=["string",i.slice(y,l+1),y,l],y=l;break}case t1:{kn.lastIndex=y+1,kn.test(i),kn.lastIndex===0?l=i.length-1:l=kn.lastIndex-2,f=["at-word",i.slice(y,l+1),y,l],y=l;break}case yn:{for(l=y,o=!0;i.charCodeAt(l+1)===yn;)l+=1,o=!o;if(s=i.charCodeAt(l+1),o&&s!==Xc&&s!==ti&&s!==bn&&s!==vn&&s!==xn&&s!==wn&&(l+=1,Zc.test(i.charAt(l)))){for(;Zc.test(i.charAt(l+1));)l+=1;i.charCodeAt(l+1)===ti&&(l+=1)}f=["word",i.slice(y,l+1),y,l],y=l;break}default:{s===Xc&&i.charCodeAt(y+1)===Jx?(l=i.indexOf("*/",y+2)+1,l===0&&(n||F?l=i.length:E("comment")),f=["comment",i.slice(y,l+1),y,l],y=l):(Sn.lastIndex=y+1,Sn.test(i),Sn.lastIndex===0?l=i.length-1:l=Sn.lastIndex-2,f=["word",i.slice(y,l+1),y,l],w.push(f),y=l);break}}return y++,f}function N(R){k.push(R)}return{back:N,endOfFile:T,nextToken:B,position:S}}});var sp=x((j3,np)=>{u();"use strict";var i1=pn(),n1=Qr(),s1=Yr(),a1=tr(),tp=gn(),o1=ep(),rp={empty:!0,space:!0};function l1(r){for(let e=r.length-1;e>=0;e--){let t=r[e],i=t[3]||t[2];if(i)return i}}var ip=class{constructor(e){this.input=e,this.root=new a1,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:e,start:{column:1,line:1,offset:0}}}atrule(e){let t=new i1;t.name=e[1].slice(1),t.name===""&&this.unnamedAtrule(t,e),this.init(t,e[2]);let i,n,s,a=!1,o=!1,l=[],c=[];for(;!this.tokenizer.endOfFile();){if(e=this.tokenizer.nextToken(),i=e[0],i==="("||i==="["?c.push(i==="("?")":"]"):i==="{"&&c.length>0?c.push("}"):i===c[c.length-1]&&c.pop(),c.length===0)if(i===";"){t.source.end=this.getPosition(e[2]),t.source.end.offset++,this.semicolon=!0;break}else if(i==="{"){o=!0;break}else if(i==="}"){if(l.length>0){for(s=l.length-1,n=l[s];n&&n[0]==="space";)n=l[--s];n&&(t.source.end=this.getPosition(n[3]||n[2]),t.source.end.offset++)}this.end(e);break}else l.push(e);else l.push(e);if(this.tokenizer.endOfFile()){a=!0;break}}t.raws.between=this.spacesAndCommentsFromEnd(l),l.length?(t.raws.afterName=this.spacesAndCommentsFromStart(l),this.raw(t,"params",l),a&&(e=l[l.length-1],t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++,this.spaces=t.raws.between,t.raws.between="")):(t.raws.afterName="",t.params=""),o&&(t.nodes=[],this.current=t)}checkMissedSemicolon(e){let t=this.colon(e);if(t===!1)return;let i=0,n;for(let s=t-1;s>=0&&(n=e[s],!(n[0]!=="space"&&(i+=1,i===2)));s--);throw this.input.error("Missed semicolon",n[0]==="word"?n[3]+1:n[2])}colon(e){let t=0,i,n,s;for(let[a,o]of e.entries()){if(n=o,s=n[0],s==="("&&(t+=1),s===")"&&(t-=1),t===0&&s===":")if(!i)this.doubleColon(n);else{if(i[0]==="word"&&i[1]==="progid")continue;return a}i=n}return!1}comment(e){let t=new n1;this.init(t,e[2]),t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++;let i=e[1].slice(2,-2);if(/^\s*$/.test(i))t.text="",t.raws.left=i,t.raws.right="";else{let n=i.match(/^(\s*)([^]*\S)(\s*)$/);t.text=n[2],t.raws.left=n[1],t.raws.right=n[3]}}createTokenizer(){this.tokenizer=o1(this.input)}decl(e,t){let i=new s1;this.init(i,e[0][2]);let n=e[e.length-1];for(n[0]===";"&&(this.semicolon=!0,e.pop()),i.source.end=this.getPosition(n[3]||n[2]||l1(e)),i.source.end.offset++;e[0][0]!=="word";)e.length===1&&this.unknownWord(e),i.raws.before+=e.shift()[1];for(i.source.start=this.getPosition(e[0][2]),i.prop="";e.length;){let c=e[0][0];if(c===":"||c==="space"||c==="comment")break;i.prop+=e.shift()[1]}i.raws.between="";let s;for(;e.length;)if(s=e.shift(),s[0]===":"){i.raws.between+=s[1
Line truncated
|
||||
https://evilmartians.com/chronicles/postcss-8-plugin-migration`),m.env.LANG&&m.env.LANG.startsWith("cn")&&console.warn(e+`: \u91CC\u9762 postcss.plugin \u88AB\u5F03\u7528. \u8FC1\u79FB\u6307\u5357:
|
||||
https://www.w3ctech.com/topic/2226`));let o=t(...a);return o.postcssPlugin=e,o.postcssVersion=new Ta().version,o}let s;return Object.defineProperty(n,"postcss",{get(){return s||(s=n()),s}}),n.process=function(a,o,l){return J([n(l)]).process(a,o)},n};J.stringify=F1;J.parse=N1;J.fromJSON=D1;J.list=L1;J.comment=r=>new vp(r);J.atRule=r=>new wp(r);J.decl=r=>new xp(r);J.rule=r=>new Ap(r);J.root=r=>new Sp(r);J.document=r=>new kp(r);J.CssSyntaxError=I1;J.Declaration=xp;J.Container=P1;J.Processor=Ta;J.Document=kp;J.Comment=vp;J.Warning=j1;J.AtRule=wp;J.Result=B1;J.Input=q1;J.Rule=Ap;J.Root=Sp;J.Node=M1;$1.registerPostcss(J);Cp.exports=J;J.default=J});var re,ee,Z3,J3,eI,tI,rI,iI,nI,sI,aI,oI,lI,uI,fI,cI,pI,dI,hI,mI,gI,yI,bI,wI,vI,xI,Ot=P(()=>{u();re=pe($e()),ee=re.default,Z3=re.default.stringify,J3=re.default.fromJSON,eI=re.default.plugin,tI=re.default.parse,rI=re.default.list,iI=re.default.document,nI=re.default.comment,sI=re.default.atRule,aI=re.default.rule,oI=re.default.decl,lI=re.default.root,uI=re.default.CssSyntaxError,fI=re.default.Declaration,cI=re.default.Container,pI=re.default.Processor,dI=re.default.Document,hI=re.default.Comment,mI=re.default.Warning,gI=re.default.AtRule,yI=re.default.Result,bI=re.default.Input,wI=re.default.Rule,vI=re.default.Root,xI=re.default.Node});var Ra=x((SI,_p)=>{u();_p.exports=function(r,e,t,i,n){for(e=e.split?e.split("."):e,i=0;i<e.length;i++)r=r?r[e[i]]:n;return r===n?t:r}});var Pn=x((Rn,Ep)=>{u();"use strict";Rn.__esModule=!0;Rn.default=V1;function z1(r){for(var e=r.toLowerCase(),t="",i=!1,n=0;n<6&&e[n]!==void 0;n++){var s=e.charCodeAt(n),a=s>=97&&s<=102||s>=48&&s<=57;if(i=s===32,!a)break;t+=e[n]}if(t.length!==0){var o=parseInt(t,16),l=o>=55296&&o<=57343;return l||o===0||o>1114111?["\uFFFD",t.length+(i?1:0)]:[String.fromCodePoint(o),t.length+(i?1:0)]}}var U1=/\\/;function V1(r){var e=U1.test(r);if(!e)return r;for(var t="",i=0;i<r.length;i++){if(r[i]==="\\"){var n=z1(r.slice(i+1,i+7));if(n!==void 0){t+=n[0],i+=n[1];continue}if(r[i+1]==="\\"){t+="\\",i++;continue}r.length===i+1&&(t+=r[i]);continue}t+=r[i]}return t}Ep.exports=Rn.default});var Tp=x((In,Op)=>{u();"use strict";In.__esModule=!0;In.default=H1;function H1(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),i=1;i<e;i++)t[i-1]=arguments[i];for(;t.length>0;){var n=t.shift();if(!r[n])return;r=r[n]}return r}Op.exports=In.default});var Pp=x((Dn,Rp)=>{u();"use strict";Dn.__esModule=!0;Dn.default=W1;function W1(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),i=1;i<e;i++)t[i-1]=arguments[i];for(;t.length>0;){var n=t.shift();r[n]||(r[n]={}),r=r[n]}}Rp.exports=Dn.default});var Dp=x((qn,Ip)=>{u();"use strict";qn.__esModule=!0;qn.default=G1;function G1(r){for(var e="",t=r.indexOf("/*"),i=0;t>=0;){e=e+r.slice(i,t);var n=r.indexOf("*/",t+2);if(n<0)return e;i=n+2,t=r.indexOf("/*",i)}return e=e+r.slice(i),e}Ip.exports=qn.default});var ii=x(rt=>{u();"use strict";rt.__esModule=!0;rt.unesc=rt.stripComments=rt.getProp=rt.ensureObject=void 0;var Q1=$n(Pn());rt.unesc=Q1.default;var Y1=$n(Tp());rt.getProp=Y1.default;var K1=$n(Pp());rt.ensureObject=K1.default;var X1=$n(Dp());rt.stripComments=X1.default;function $n(r){return r&&r.__esModule?r:{default:r}}});var dt=x((ni,Lp)=>{u();"use strict";ni.__esModule=!0;ni.default=void 0;var qp=ii();function $p(r,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(r,i.key,i)}}function Z1(r,e,t){return e&&$p(r.prototype,e),t&&$p(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}var J1=function r(e,t){if(typeof e!="object"||e===null)return e;var i=new e.constructor;for(var n in e)if(!!e.hasOwnProperty(n)){var s=e[n],a=typeof s;n==="parent"&&a==="object"?t&&(i[n]=t):s instanceof Array?i[n]=s.map(function(o){return r(o,i)}):i[n]=r(s,i)}return i},ek=function(){function r(t){t===void 0&&(t={}),Object.assign(this,t),this.spaces=this.spaces||{},this.spaces.before=this.spaces.before||"",this.spaces.after=this.spaces.after||""}var e=r.prototype;return e.remove=function(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this},e.replaceWith=function(){if(this.parent){for(var i in arguments)this.parent.insertBefore(this,arguments[i]);this.remove()}return this},e.next=function(){return this.parent.at(this.parent.index(this)+1)},e.prev=function(){return this.parent.at(this.parent.index(this)-1)},e.clone=function(i){i===void 0&&(i={});var n=J1(this);for(var s in i)n[s]=i[s];return n},e.appendToPropertyAndEscape=function(i,n,s){this.raws||(this.raws={});var a=this[i],o=this.raws[i];this[i]=a+n,o||s!==n?this.raws[i]=(o||a)+s:delete this.raws[i]},e.setPropertyAndEscape=function(i,n,s){this.raws||(this.raws={}),this[i]=n,this.raws[i]=s},e.setPropertyWithoutEscape=function(i,n){this[i]=n,this.raws&&delete this.raws[i]},e.isAtPosition=function(i,n){if(this.source&&this.source.start&&this.source.end)return!(this.source.start.line>i||this.source.end.line<i||this.source.start.line===i&&this.source.start.col
Line truncated
|
||||
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function yk(r,e){if(!!r){if(typeof r=="string")return Np(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return Np(r,e)}}function Np(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,i=new Array(e);t<e;t++)i[t]=r[t];return i}function Bp(r,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(r,i.key,i)}}function bk(r,e,t){return e&&Bp(r.prototype,e),t&&Bp(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function wk(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,Pa(r,e)}function Pa(r,e){return Pa=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Pa(r,e)}var vk=function(r){wk(e,r);function e(i){var n;return n=r.call(this,i)||this,n.nodes||(n.nodes=[]),n}var t=e.prototype;return t.append=function(n){return n.parent=this,this.nodes.push(n),this},t.prepend=function(n){return n.parent=this,this.nodes.unshift(n),this},t.at=function(n){return this.nodes[n]},t.index=function(n){return typeof n=="number"?n:this.nodes.indexOf(n)},t.removeChild=function(n){n=this.index(n),this.at(n).parent=void 0,this.nodes.splice(n,1);var s;for(var a in this.indexes)s=this.indexes[a],s>=n&&(this.indexes[a]=s-1);return this},t.removeAll=function(){for(var n=gk(this.nodes),s;!(s=n()).done;){var a=s.value;a.parent=void 0}return this.nodes=[],this},t.empty=function(){return this.removeAll()},t.insertAfter=function(n,s){s.parent=this;var a=this.index(n);this.nodes.splice(a+1,0,s),s.parent=this;var o;for(var l in this.indexes)o=this.indexes[l],a<=o&&(this.indexes[l]=o+1);return this},t.insertBefore=function(n,s){s.parent=this;var a=this.index(n);this.nodes.splice(a,0,s),s.parent=this;var o;for(var l in this.indexes)o=this.indexes[l],o<=a&&(this.indexes[l]=o+1);return this},t._findChildAtPosition=function(n,s){var a=void 0;return this.each(function(o){if(o.atPosition){var l=o.atPosition(n,s);if(l)return a=l,!1}else if(o.isAtPosition(n,s))return a=o,!1}),a},t.atPosition=function(n,s){if(this.isAtPosition(n,s))return this._findChildAtPosition(n,s)||this},t._inferEndPosition=function(){this.last&&this.last.source&&this.last.source.end&&(this.source=this.source||{},this.source.end=this.source.end||{},Object.assign(this.source.end,this.last.source.end))},t.each=function(n){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach++;var s=this.lastEach;if(this.indexes[s]=0,!!this.length){for(var a,o;this.indexes[s]<this.length&&(a=this.indexes[s],o=n(this.at(a),a),o!==!1);)this.indexes[s]+=1;if(delete this.indexes[s],o===!1)return!1}},t.walk=function(n){return this.each(function(s,a){var o=n(s,a);if(o!==!1&&s.length&&(o=s.walk(n)),o===!1)return!1})},t.walkAttributes=function(n){var s=this;return this.walk(function(a){if(a.type===ht.ATTRIBUTE)return n.call(s,a)})},t.walkClasses=function(n){var s=this;return this.walk(function(a){if(a.type===ht.CLASS)return n.call(s,a)})},t.walkCombinators=function(n){var s=this;return this.walk(function(a){if(a.type===ht.COMBINATOR)return n.call(s,a)})},t.walkComments=function(n){var s=this;return this.walk(function(a){if(a.type===ht.COMMENT)return n.call(s,a)})},t.walkIds=function(n){var s=this;return this.walk(function(a){if(a.type===ht.ID)return n.call(s,a)})},t.walkNesting=function(n){var s=this;return this.walk(function(a){if(a.type===ht.NESTING)return n.call(s,a)})},t.walkPseudos=function(n){var s=this;return this.walk(function(a){if(a.type===ht.PSEUDO)return n.call(s,a)})},t.walkTags=function(n){var s=this;return this.walk(function(a){if(a.type===ht.TAG)return n.call(s,a)})},t.walkUniversals=function(n){var s=this;return this.walk(function(a){if(a.type===ht.UNIVERSAL)return n.call(s,a)})},t.split=function(n){var s=this,a=[];return this.reduce(function(o,l,c){var f=n.call(s,l);return a.push(l),f?(o.push(a),a=[]):c===s.length-1&&o.push(a),o},[])},t.map=function(n){return this.nodes.map(n)},t.reduce=function(n,s){return this.nodes.reduce(n,s)},t.every=function(n){return this.nodes.every(n)},t.some=function(n){return this.nodes.some(n)},t.filter=function(n){return this.nodes.filter(n)},t.sort=function(n){return this.nodes.sort(n)},t.toString=function(){return this.map(String).join("")},bk(e,[{key:"first",get:function(){return this.at(0)}},{key:"last",get:function(){return this.at(this.length-1)}},{key:"length",get:function(){return this.nodes.length}}]),e}(dk.default);si.default=vk;Fp.exports=si.default});var Da=x((ai,zp)=>{u();"use strict";ai.__esModule=!0;ai.default=void 0;var xk=Sk(Ln()),kk=Se();function Sk(r){return r&&r.__esModule?r:{default:r}}function jp(r,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable
Line truncated
|
||||
`),v=y.length-1,v>0?(k=a+v,S=w-y[v].length):(k=a,S=s),T=D.comment,a=k,p=k,d=w-S):c===D.slash?(w=o,T=c,p=a,d=o-s,l=w+1):(w=OA(t,o),T=D.word,p=a,d=w-s),l=w+1;break}e.push([T,a,o-s,p,d,o,l]),S&&(s=S,S=null),o=l}return e}});var kd=x((ki,xd)=>{u();"use strict";ki.__esModule=!0;ki.default=void 0;var IA=je(Da()),fo=je($a()),DA=je(Na()),md=je(Fa()),qA=je(za()),$A=je(Ha()),co=je(Ga()),LA=je(Ya()),gd=Vn(to()),MA=je(io()),po=je(so()),NA=je(oo()),BA=je(fd()),O=Vn(hd()),q=Vn(lo()),FA=Vn(Se()),ue=ii(),Vt,ho;function yd(r){if(typeof WeakMap!="function")return null;var e=new WeakMap,t=new WeakMap;return(yd=function(n){return n?t:e})(r)}function Vn(r,e){if(!e&&r&&r.__esModule)return r;if(r===null||typeof r!="object"&&typeof r!="function")return{default:r};var t=yd(e);if(t&&t.has(r))return t.get(r);var i={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in r)if(s!=="default"&&Object.prototype.hasOwnProperty.call(r,s)){var a=n?Object.getOwnPropertyDescriptor(r,s):null;a&&(a.get||a.set)?Object.defineProperty(i,s,a):i[s]=r[s]}return i.default=r,t&&t.set(r,i),i}function je(r){return r&&r.__esModule?r:{default:r}}function bd(r,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(r,i.key,i)}}function jA(r,e,t){return e&&bd(r.prototype,e),t&&bd(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}var mo=(Vt={},Vt[q.space]=!0,Vt[q.cr]=!0,Vt[q.feed]=!0,Vt[q.newline]=!0,Vt[q.tab]=!0,Vt),zA=Object.assign({},mo,(ho={},ho[q.comment]=!0,ho));function wd(r){return{line:r[O.FIELDS.START_LINE],column:r[O.FIELDS.START_COL]}}function vd(r){return{line:r[O.FIELDS.END_LINE],column:r[O.FIELDS.END_COL]}}function Ht(r,e,t,i){return{start:{line:r,column:e},end:{line:t,column:i}}}function sr(r){return Ht(r[O.FIELDS.START_LINE],r[O.FIELDS.START_COL],r[O.FIELDS.END_LINE],r[O.FIELDS.END_COL])}function go(r,e){if(!!r)return Ht(r[O.FIELDS.START_LINE],r[O.FIELDS.START_COL],e[O.FIELDS.END_LINE],e[O.FIELDS.END_COL])}function ar(r,e){var t=r[e];if(typeof t=="string")return t.indexOf("\\")!==-1&&((0,ue.ensureObject)(r,"raws"),r[e]=(0,ue.unesc)(t),r.raws[e]===void 0&&(r.raws[e]=t)),r}function yo(r,e){for(var t=-1,i=[];(t=r.indexOf(e,t+1))!==-1;)i.push(t);return i}function UA(){var r=Array.prototype.concat.apply([],arguments);return r.filter(function(e,t){return t===r.indexOf(e)})}var VA=function(){function r(t,i){i===void 0&&(i={}),this.rule=t,this.options=Object.assign({lossy:!1,safe:!1},i),this.position=0,this.css=typeof this.rule=="string"?this.rule:this.rule.selector,this.tokens=(0,O.default)({css:this.css,error:this._errorGenerator(),safe:this.options.safe});var n=go(this.tokens[0],this.tokens[this.tokens.length-1]);this.root=new IA.default({source:n}),this.root.errorGenerator=this._errorGenerator();var s=new fo.default({source:{start:{line:1,column:1}},sourceIndex:0});this.root.append(s),this.current=s,this.loop()}var e=r.prototype;return e._errorGenerator=function(){var i=this;return function(n,s){return typeof i.rule=="string"?new Error(n):i.rule.error(n,s)}},e.attribute=function(){var i=[],n=this.currToken;for(this.position++;this.position<this.tokens.length&&this.currToken[O.FIELDS.TYPE]!==q.closeSquare;)i.push(this.currToken),this.position++;if(this.currToken[O.FIELDS.TYPE]!==q.closeSquare)return this.expected("closing square bracket",this.currToken[O.FIELDS.START_POS]);var s=i.length,a={source:Ht(n[1],n[2],this.currToken[3],this.currToken[4]),sourceIndex:n[O.FIELDS.START_POS]};if(s===1&&!~[q.word].indexOf(i[0][O.FIELDS.TYPE]))return this.expected("attribute",i[0][O.FIELDS.START_POS]);for(var o=0,l="",c="",f=null,d=!1;o<s;){var p=i[o],h=this.content(p),b=i[o+1];switch(p[O.FIELDS.TYPE]){case q.space:if(d=!0,this.options.lossy)break;if(f){(0,ue.ensureObject)(a,"spaces",f);var v=a.spaces[f].after||"";a.spaces[f].after=v+h;var y=(0,ue.getProp)(a,"raws","spaces",f,"after")||null;y&&(a.raws.spaces[f].after=y+h)}else l=l+h,c=c+h;break;case q.asterisk:if(b[O.FIELDS.TYPE]===q.equals)a.operator=h,f="operator";else if((!a.namespace||f==="namespace"&&!d)&&b){l&&((0,ue.ensureObject)(a,"spaces","attribute"),a.spaces.attribute.before=l,l=""),c&&((0,ue.ensureObject)(a,"raws","spaces","attribute"),a.raws.spaces.attribute.before=l,c=""),a.namespace=(a.namespace||"")+h;var w=(0,ue.getProp)(a,"raws","namespace")||null;w&&(a.raws.namespace+=h),f="namespace"}d=!1;break;case q.dollar:if(f==="value"){var k=(0,ue.getProp)(a,"raws","value");a.value+="$",k&&(a.raws.value=k+"$");break}case q.caret:b[O.FIELDS.TYPE]===q.equals&&(a.operator=h,f="operator"),d=!1;break;case q.combinator:if(h==="~"&&b[O.FIELDS.TYPE]===q.equals&&(a.operator=h,f="operator"),h!=="|"){d=!1;break}b[O.FIELDS.TYPE]===q.equals?(a.operator=h,f="operator"):!a.namespace&&!a.attribute&&(a.namespace=!0),d=!1;break;case q.word:if(b&&this.content(b)==="|"&&i[o+2]&&i[o+2][O.FIELDS.TYPE]!==q.equals&&!a.operator&&!a.namespace)a.namespace=h,f="namespace";else if(!a.attribute||f==="attribute"&&!d){l&&((0,ue.
Line truncated
|
||||
`).slice(1,-1).map(N=>N.trim()).map(N=>` ${N}`).join(`
|
||||
`)).join(`
|
||||
|
||||
`);w.push(` Use \`${r.replace("[",`[${E}:`)}\` for \`${T.trim()}\``);break}G.warn([`The class \`${r}\` is ambiguous and matches multiple utilities.`,...w,`If this is content and not a class, replace it with \`${r.replace("[","[").replace("]","]")}\` to silence this warning.`]);continue}}o=o.map(p=>p.filter(h=>Eh(h[1])))}o=o.flat(),o=Array.from(P_(o,i)),o=k_(o,e),s&&(o=S_(o,i));for(let p of n)o=A_(p,o,e);for(let p of o)p[1].raws.tailwind={...p[1].raws.tailwind,candidate:r},p=I_(p,{context:e,candidate:r}),p!==null&&(yield p)}}function I_(r,{context:e,candidate:t}){if(!r[0].collectedFormats)return r;let i=!0,n;try{n=dr(r[0].collectedFormats,{context:e,candidate:t})}catch{return null}let s=ee.root({nodes:[r[1].clone()]});return s.walkRules(a=>{if(!ss(a))try{let o=rs(a.selector,n,{candidate:t,context:e});if(o===null){a.remove();return}a.selector=o}catch{return i=!1,!1}}),!i||s.nodes.length===0?null:(r[1]=s.nodes[0],r)}function ss(r){return r.parent&&r.parent.type==="atrule"&&r.parent.name==="keyframes"}function D_(r){if(r===!0)return e=>{ss(e)||e.walkDecls(t=>{t.parent.type==="rule"&&!ss(t.parent)&&(t.important=!0)})};if(typeof r=="string")return e=>{ss(e)||(e.selectors=e.selectors.map(t=>is(t,r)))}}function as(r,e,t=!1){let i=[],n=D_(e.tailwindConfig.important);for(let s of r){if(e.notClassCache.has(s))continue;if(e.candidateRuleCache.has(s)){i=i.concat(Array.from(e.candidateRuleCache.get(s)));continue}let a=Array.from(Yo(s,e));if(a.length===0){e.notClassCache.add(s);continue}e.classCache.set(s,a);let o=e.candidateRuleCache.get(s)??new Set;e.candidateRuleCache.set(s,o);for(let l of a){let[{sort:c,options:f},d]=l;if(f.respectImportant&&n){let h=ee.root({nodes:[d.clone()]});h.walkRules(n),d=h.nodes[0]}let p=[c,t?d.clone():d];o.add(p),e.ruleCache.add(p),i.push(p)}}return i}function Ko(r){return r.startsWith("[")&&r.endsWith("]")}var ns,v_,C_,os=P(()=>{u();Ot();ns=pe(it());qo();Kt();Gn();Fr();Be();It();Vo();Lo();Br();Oi();Bo();zt();ct();Wo();v_=(0,ns.default)(r=>r.first.filter(({type:e})=>e==="class").pop().value);C_=/^[a-z_-]/});var Th,Rh=P(()=>{u();Th={}});function q_(r){try{return Th.createHash("md5").update(r,"utf-8").digest("binary")}catch(e){return""}}function Ph(r,e){let t=e.toString();if(!t.includes("@tailwind"))return!1;let i=No.get(r),n=q_(t),s=i!==n;return No.set(r,n),s}var Ih=P(()=>{u();Rh();It()});function us(r){return(r>0n)-(r<0n)}var Dh=P(()=>{u()});function qh(r,e){let t=0n,i=0n;for(let[n,s]of e)r&n&&(t=t|n,i=i|s);return r&~t|i}var $h=P(()=>{u()});function Lh(r){let e=null;for(let t of r)e=e??t,e=e>t?e:t;return e}function $_(r,e){let t=r.length,i=e.length,n=t<i?t:i;for(let s=0;s<n;s++){let a=r.charCodeAt(s)-e.charCodeAt(s);if(a!==0)return a}return t-i}var Xo,Mh=P(()=>{u();Dh();$h();Xo=class{constructor(){this.offsets={defaults:0n,base:0n,components:0n,utilities:0n,variants:0n,user:0n},this.layerPositions={defaults:0n,base:1n,components:2n,utilities:3n,user:4n,variants:5n},this.reservedVariantBits=0n,this.variantOffsets=new Map}create(e){return{layer:e,parentLayer:e,arbitrary:0n,variants:0n,parallelIndex:0n,index:this.offsets[e]++,propertyOffset:0n,property:"",options:[]}}arbitraryProperty(e){return{...this.create("utilities"),arbitrary:1n,property:e}}forVariant(e,t=0){let i=this.variantOffsets.get(e);if(i===void 0)throw new Error(`Cannot find offset for unknown variant ${e}`);return{...this.create("variants"),variants:i<<BigInt(t)}}applyVariantOffset(e,t,i){return i.variant=t.variants,{...e,layer:"variants",parentLayer:e.layer==="variants"?e.parentLayer:e.layer,variants:e.variants|t.variants,options:i.sort?[].concat(i,e.options):e.options,parallelIndex:Lh([e.parallelIndex,t.parallelIndex])}}applyParallelOffset(e,t){return{...e,parallelIndex:BigInt(t)}}recordVariants(e,t){for(let i of e)this.recordVariant(i,t(i))}recordVariant(e,t=1){return this.variantOffsets.set(e,1n<<this.reservedVariantBits),this.reservedVariantBits+=BigInt(t),{...this.create("variants"),variants:this.variantOffsets.get(e)}}compare(e,t){if(e.layer!==t.layer)return this.layerPositions[e.layer]-this.layerPositions[t.layer];if(e.parentLayer!==t.parentLayer)return this.layerPositions[e.parentLayer]-this.layerPositions[t.parentLayer];for(let i of e.options)for(let n of t.options){if(i.id!==n.id||!i.sort||!n.sort)continue;let s=Lh([i.variant,n.variant])??0n,a=~(s|s-1n),o=e.variants&a,l=t.variants&a;if(o!==l)continue;let c=i.sort({value:i.value,modifier:i.modifier},{value:n.value,modifier:n.modifier});if(c!==0)return c}return e.variants!==t.variants?e.variants-t.variants:e.parallelIndex!==t.parallelIndex?e.parallelIndex-t.parallelIndex:e.arbitrary!==t.arbitrary?e.arbitrary-t.arbitrary:e.propertyOffset!==t.propertyOffset?e.propertyOffset-t.propertyOffset:e.index-t.index}recalculateVariantOffsets(){let e=Array.from(this.variantOffsets.entries()).filter(([n])=>n.startsWith("[")).sort(([n],[s])=>$_(n,s)),t=e.map(([,n])=>n).sort((n,s)=>us(n-s));return e.map(([,n],s)=>[n,t[s]]).filter(([n,s])=>n!==s)}remapArbitraryVariantOffsets(eLine truncated
|
||||
`,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var Nm=x((s6,Mm)=>{u();"use strict";var mE=hs(),{MAX_LENGTH:qm,CHAR_BACKSLASH:dl,CHAR_BACKTICK:gE,CHAR_COMMA:yE,CHAR_DOT:bE,CHAR_LEFT_PARENTHESES:wE,CHAR_RIGHT_PARENTHESES:vE,CHAR_LEFT_CURLY_BRACE:xE,CHAR_RIGHT_CURLY_BRACE:kE,CHAR_LEFT_SQUARE_BRACKET:$m,CHAR_RIGHT_SQUARE_BRACKET:Lm,CHAR_DOUBLE_QUOTE:SE,CHAR_SINGLE_QUOTE:AE,CHAR_NO_BREAK_SPACE:CE,CHAR_ZERO_WIDTH_NOBREAK_SPACE:_E}=Dm(),EE=(r,e={})=>{if(typeof r!="string")throw new TypeError("Expected a string");let t=e||{},i=typeof t.maxLength=="number"?Math.min(qm,t.maxLength):qm;if(r.length>i)throw new SyntaxError(`Input length (${r.length}), exceeds max characters (${i})`);let n={type:"root",input:r,nodes:[]},s=[n],a=n,o=n,l=0,c=r.length,f=0,d=0,p,h=()=>r[f++],b=v=>{if(v.type==="text"&&o.type==="dot"&&(o.type="text"),o&&o.type==="text"&&v.type==="text"){o.value+=v.value;return}return a.nodes.push(v),v.parent=a,v.prev=o,o=v,v};for(b({type:"bos"});f<c;)if(a=s[s.length-1],p=h(),!(p===_E||p===CE)){if(p===dl){b({type:"text",value:(e.keepEscaping?p:"")+h()});continue}if(p===Lm){b({type:"text",value:"\\"+p});continue}if(p===$m){l++;let v;for(;f<c&&(v=h());){if(p+=v,v===$m){l++;continue}if(v===dl){p+=h();continue}if(v===Lm&&(l--,l===0))break}b({type:"text",value:p});continue}if(p===wE){a=b({type:"paren",nodes:[]}),s.push(a),b({type:"text",value:p});continue}if(p===vE){if(a.type!=="paren"){b({type:"text",value:p});continue}a=s.pop(),b({type:"text",value:p}),a=s[s.length-1];continue}if(p===SE||p===AE||p===gE){let v=p,y;for(e.keepQuotes!==!0&&(p="");f<c&&(y=h());){if(y===dl){p+=y+h();continue}if(y===v){e.keepQuotes===!0&&(p+=y);break}p+=y}b({type:"text",value:p});continue}if(p===xE){d++;let v=o.value&&o.value.slice(-1)==="$"||a.dollar===!0;a=b({type:"brace",open:!0,close:!1,dollar:v,depth:d,commas:0,ranges:0,nodes:[]}),s.push(a),b({type:"open",value:p});continue}if(p===kE){if(a.type!=="brace"){b({type:"text",value:p});continue}let v="close";a=s.pop(),a.close=!0,b({type:v,value:p}),d--,a=s[s.length-1];continue}if(p===yE&&d>0){if(a.ranges>0){a.ranges=0;let v=a.nodes.shift();a.nodes=[v,{type:"text",value:mE(a)}]}b({type:"comma",value:p}),a.commas++;continue}if(p===bE&&d>0&&a.commas===0){let v=a.nodes;if(d===0||v.length===0){b({type:"text",value:p});continue}if(o.type==="dot"){if(a.range=[],o.value+=p,o.type="range",a.nodes.length!==3&&a.nodes.length!==5){a.invalid=!0,a.ranges=0,o.type="text";continue}a.ranges++,a.args=[];continue}if(o.type==="range"){v.pop();let y=v[v.length-1];y.value+=o.value+p,o=y,a.ranges--;continue}b({type:"dot",value:p});continue}b({type:"text",value:p})}do if(a=s.pop(),a.type!=="root"){a.nodes.forEach(w=>{w.nodes||(w.type==="open"&&(w.isOpen=!0),w.type==="close"&&(w.isClose=!0),w.nodes||(w.type="text"),w.invalid=!0)});let v=s[s.length-1],y=v.nodes.indexOf(a);v.nodes.splice(y,1,...a.nodes)}while(s.length>0);return b({type:"eos"}),n};Mm.exports=EE});var jm=x((a6,Fm)=>{u();"use strict";var Bm=hs(),OE=Om(),TE=Pm(),RE=Nm(),Le=(r,e={})=>{let t=[];if(Array.isArray(r))for(let i of r){let n=Le.create(i,e);Array.isArray(n)?t.push(...n):t.push(n)}else t=[].concat(Le.create(r,e));return e&&e.expand===!0&&e.nodupes===!0&&(t=[...new Set(t)]),t};Le.parse=(r,e={})=>RE(r,e);Le.stringify=(r,e={})=>typeof r=="string"?Bm(Le.parse(r,e),e):Bm(r,e);Le.compile=(r,e={})=>(typeof r=="string"&&(r=Le.parse(r,e)),OE(r,e));Le.expand=(r,e={})=>{typeof r=="string"&&(r=Le.parse(r,e));let t=TE(r,e);return e.noempty===!0&&(t=t.filter(Boolean)),e.nodupes===!0&&(t=[...new Set(t)]),t};Le.create=(r,e={})=>r===""||r.length<3?[r]:e.expand!==!0?Le.compile(r,e):Le.expand(r,e);Fm.exports=Le});var Di=x((o6,Wm)=>{u();"use strict";var PE=(et(),Ur),at="\\\\/",zm=`[^${at}]`,yt="\\.",IE="\\+",DE="\\?",ys="\\/",qE="(?=.)",Um="[^/]",hl=`(?:${ys}|$)`,Vm=`(?:^|${ys})`,ml=`${yt}{1,2}${hl}`,$E=`(?!${yt})`,LE=`(?!${Vm}${ml})`,ME=`(?!${yt}{0,1}${hl})`,NE=`(?!${ml})`,BE=`[^.${ys}]`,FE=`${Um}*?`,Hm={DOT_LITERAL:yt,PLUS_LITERAL:IE,QMARK_LITERAL:DE,SLASH_LITERAL:ys,ONE_CHAR:qE,QMARK:Um,END_ANCHOR:hl,DOTS_SLASH:ml,NO_DOT:$E,NO_DOTS:LE,NO_DOT_SLASH:ME,NO_DOTS_SLASH:NE,QMARK_NO_DOT:BE,STAR:FE,START_ANCHOR:Vm},jE={...Hm,SLASH_LITERAL:`[${at}]`,QMARK:zm,STAR:`${zm}*?`,DOTS_SLASH:`${yt}{1,2}(?:[${at}]|$)`,NO_DOT:`(?!${yt})`,NO_DOTS:`(?!(?:^|[${at}])${yt}{1,2}(?:[${at}]|$))`,NO_DOT_SLASH:`(?!${yt}{0,1}(?:[${at}]|$))`,NO_DOTS_SLASH:`(?!${yt}{1,2}(?:[${at}]|$))`,QMARK_NO_DOT:`[^.${at}]`,START_ANCHOR:`(?:^|[${at}])`,END_ANCHOR:`(?:[${at}]|$)`},zE={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_Line truncated
|
||||
`))if(n=n.trim(),!i.has(n))if(i.add(n),Li.get(e).has(n))for(let s of Li.get(e).get(n))t.add(s);else{let s=e(n).filter(o=>o!=="!*"),a=new Set(s);for(let o of a)t.add(o);Li.get(e).set(n,a)}}function T2(r,e){let t=e.offsets.sort(r),i={base:new Set,defaults:new Set,components:new Set,utilities:new Set,variants:new Set};for(let[n,s]of t)i[n.layer].add(s);return i}function Pl(r){return async e=>{let t={base:null,components:null,utilities:null,variants:null};if(e.walkAtRules(y=>{y.name==="tailwind"&&Object.keys(t).includes(y.params)&&(t[y.params]=y)}),Object.values(t).every(y=>y===null))return e;let i=new Set([...r.candidates??[],gt]),n=new Set;bt.DEBUG&&console.time("Reading changed files");let s=[];for(let y of r.changedContent){let w=E2(r.tailwindConfig,y.extension),k=_2(r,y.extension);s.push([y,{transformer:w,extractor:k}])}let a=500;for(let y=0;y<s.length;y+=a){let w=s.slice(y,y+a);await Promise.all(w.map(async([{file:k,content:S},{transformer:E,extractor:T}])=>{S=k?await be.promises.readFile(k,"utf8"):S,O2(E(S),T,i,n)}))}bt.DEBUG&&console.timeEnd("Reading changed files");let o=r.classCache.size;bt.DEBUG&&console.time("Generate rules"),bt.DEBUG&&console.time("Sorting candidates");let l=new Set([...i].sort((y,w)=>y===w?0:y<w?-1:1));bt.DEBUG&&console.timeEnd("Sorting candidates"),as(l,r),bt.DEBUG&&console.timeEnd("Generate rules"),bt.DEBUG&&console.time("Build stylesheet"),(r.stylesheetCache===null||r.classCache.size!==o)&&(r.stylesheetCache=T2([...r.ruleCache],r)),bt.DEBUG&&console.timeEnd("Build stylesheet");let{defaults:c,base:f,components:d,utilities:p,variants:h}=r.stylesheetCache;t.base&&(t.base.before(Qt([...c,...f],t.base.source,{layer:"base"})),t.base.remove()),t.components&&(t.components.before(Qt([...d],t.components.source,{layer:"components"})),t.components.remove()),t.utilities&&(t.utilities.before(Qt([...p],t.utilities.source,{layer:"utilities"})),t.utilities.remove());let b=Array.from(h).filter(y=>{let w=y.raws.tailwind?.parentLayer;return w==="components"?t.components!==null:w==="utilities"?t.utilities!==null:!0});t.variants?(t.variants.before(Qt(b,t.variants.source,{layer:"variants"})),t.variants.remove()):b.length>0&&e.append(Qt(b,e.source,{layer:"variants"})),e.source.end=e.source.end??e.source.start;let v=b.some(y=>y.raws.tailwind?.parentLayer==="utilities");t.utilities&&p.size===0&&!v&&G.warn("content-problems",["No utility classes were detected in your source files. If this is unexpected, double-check the `content` option in your Tailwind CSS configuration.","https://tailwindcss.com/docs/content-configuration"]),bt.DEBUG&&(console.log("Potential classes: ",i.size),console.log("Active contexts: ",es.size)),r.changedContent=[],e.walkAtRules("layer",y=>{Object.keys(t).includes(y.params)&&y.remove()})}}var Lg,bt,Mg,Ng,Li,Bg=P(()=>{u();ft();Lg=pe(Fs());It();os();Be();Rg();$g();bt=Ze,Mg={DEFAULT:qg},Ng={DEFAULT:r=>r,svelte:r=>r.replace(/(?:^|\s)class:/g," ")};Li=new WeakMap});function xs(r){let e=new Map;ee.root({nodes:[r.clone()]}).walkRules(s=>{(0,vs.default)(a=>{a.walkClasses(o=>{let l=o.parent.toString(),c=e.get(l);c||e.set(l,c=new Set),c.add(o.value)})}).processSync(s.selector)});let i=Array.from(e.values(),s=>Array.from(s)),n=i.flat();return Object.assign(n,{groups:i})}function Il(r){return R2.astSync(r)}function Fg(r,e){let t=new Set;for(let i of r)t.add(i.split(e).pop());return Array.from(t)}function jg(r,e){let t=r.tailwindConfig.prefix;return typeof t=="function"?t(e):t+e}function*zg(r){for(yield r;r.parent;)yield r.parent,r=r.parent}function P2(r,e={}){let t=r.nodes;r.nodes=[];let i=r.clone(e);return r.nodes=t,i}function I2(r){for(let e of zg(r))if(r!==e){if(e.type==="root")break;r=P2(e,{nodes:[r]})}return r}function D2(r,e){let t=new Map;return r.walkRules(i=>{for(let a of zg(i))if(a.raws.tailwind?.layer!==void 0)return;let n=I2(i),s=e.offsets.create("user");for(let a of xs(i)){let o=t.get(a)||[];t.set(a,o),o.push([{layer:"user",sort:s,important:!1},n])}}),t}function q2(r,e){for(let t of r){if(e.notClassCache.has(t)||e.applyClassCache.has(t))continue;if(e.classCache.has(t)){e.applyClassCache.set(t,e.classCache.get(t).map(([n,s])=>[n,s.clone()]));continue}let i=Array.from(Yo(t,e));if(i.length===0){e.notClassCache.add(t);continue}e.applyClassCache.set(t,i)}return e.applyClassCache}function $2(r){let e=null;return{get:t=>(e=e||r(),e.get(t)),has:t=>(e=e||r(),e.has(t))}}function L2(r){return{get:e=>r.flatMap(t=>t.get(e)||[]),has:e=>r.some(t=>t.has(e))}}function Ug(r){let e=r.split(/[\s\t\n]+/g);return e[e.length-1]==="!important"?[e.slice(0,-1),!0]:[e,!1]}function Vg(r,e,t){let i=new Set,n=[];if(r.walkAtRules("apply",l=>{let[c]=Ug(l.params);for(let f of c)i.add(f);n.push(l)}),n.length===0)return;let s=L2([t,q2(i,e)]);function a(l,c,f){let d=Il(l),p=Il(c),b=Il(`.${Te(f)}`).nodes[0].nodes[0];return d.each(v=>{let y=new Set;p.each(w=>{let k=!1;w=w.clone(),w.walkClasses(S=>{S.value===b.value&&(k||(S.replaceWith(...v.nodes.map(E=>E.clone())),y.add(w),k=!0))})});for(let w of y){let k=[[]];for(
Line truncated
|
||||
`))});c.push([p,d,h])}}for(let[l,[c,f]]of o){let d=[];for(let[h,b,v]of c){let y=[h,...Fg([h],e.tailwindConfig.separator)];for(let[w,k]of v){let S=xs(l),E=xs(k);if(E=E.groups.filter(R=>R.some(F=>y.includes(F))).flat(),E=E.concat(Fg(E,e.tailwindConfig.separator)),S.some(R=>E.includes(R)))throw k.error(`You cannot \`@apply\` the \`${h}\` utility here because it creates a circular dependency.`);let B=ee.root({nodes:[k.clone()]});B.walk(R=>{R.source=f}),(k.type!=="atrule"||k.type==="atrule"&&k.name!=="keyframes")&&B.walkRules(R=>{if(!xs(R).some(U=>U===h)){R.remove();return}let F=typeof e.tailwindConfig.important=="string"?e.tailwindConfig.important:null,_=l.raws.tailwind!==void 0&&F&&l.selector.indexOf(F)===0?l.selector.slice(F.length):l.selector;_===""&&(_=l.selector),R.selector=a(_,R.selector,h),F&&_!==l.selector&&(R.selector=is(R.selector,F)),R.walkDecls(U=>{U.important=w.important||b});let Q=(0,vs.default)().astSync(R.selector);Q.each(U=>pr(U)),R.selector=Q.toString()}),!!B.nodes[0]&&d.push([w.sort,B.nodes[0]])}}let p=e.offsets.sort(d).map(h=>h[1]);l.after(p)}for(let l of n)l.parent.nodes.length>1?l.remove():l.parent.remove();Vg(r,e,t)}function Dl(r){return e=>{let t=$2(()=>D2(e,r));Vg(e,r,t)}}var vs,R2,Hg=P(()=>{u();Ot();vs=pe(it());os();fr();Wo();ts();R2=(0,vs.default)()});var Wg=x((nq,ks)=>{u();(function(){"use strict";function r(i,n,s){if(!i)return null;r.caseSensitive||(i=i.toLowerCase());var a=r.threshold===null?null:r.threshold*i.length,o=r.thresholdAbsolute,l;a!==null&&o!==null?l=Math.min(a,o):a!==null?l=a:o!==null?l=o:l=null;var c,f,d,p,h,b=n.length;for(h=0;h<b;h++)if(f=n[h],s&&(f=f[s]),!!f&&(r.caseSensitive?d=f:d=f.toLowerCase(),p=t(i,d,l),(l===null||p<l)&&(l=p,s&&r.returnWinningObject?c=n[h]:c=f,r.returnFirstMatch)))return c;return c||r.nullResultValue}r.threshold=.4,r.thresholdAbsolute=20,r.caseSensitive=!1,r.nullResultValue=null,r.returnWinningObject=null,r.returnFirstMatch=!1,typeof ks!="undefined"&&ks.exports?ks.exports=r:window.didYouMean=r;var e=Math.pow(2,32)-1;function t(i,n,s){s=s||s===0?s:e;var a=i.length,o=n.length;if(a===0)return Math.min(s+1,o);if(o===0)return Math.min(s+1,a);if(Math.abs(a-o)>s)return s+1;var l=[],c,f,d,p,h;for(c=0;c<=o;c++)l[c]=[c];for(f=0;f<=a;f++)l[0][f]=f;for(c=1;c<=o;c++){for(d=e,p=1,c>s&&(p=c-s),h=o+1,h>s+c&&(h=s+c),f=1;f<=a;f++)f<p||f>h?l[c][f]=s+1:n.charAt(c-1)===i.charAt(f-1)?l[c][f]=l[c-1][f-1]:l[c][f]=Math.min(l[c-1][f-1]+1,Math.min(l[c][f-1]+1,l[c-1][f]+1)),l[c][f]<d&&(d=l[c][f]);if(d>s)return s+1}return l[o][a]}})()});var Qg=x((sq,Gg)=>{u();var ql="(".charCodeAt(0),$l=")".charCodeAt(0),Ss="'".charCodeAt(0),Ll='"'.charCodeAt(0),Ml="\\".charCodeAt(0),yr="/".charCodeAt(0),Nl=",".charCodeAt(0),Bl=":".charCodeAt(0),As="*".charCodeAt(0),M2="u".charCodeAt(0),N2="U".charCodeAt(0),B2="+".charCodeAt(0),F2=/^[a-f0-9?-]+$/i;Gg.exports=function(r){for(var e=[],t=r,i,n,s,a,o,l,c,f,d=0,p=t.charCodeAt(d),h=t.length,b=[{nodes:e}],v=0,y,w="",k="",S="";d<h;)if(p<=32){i=d;do i+=1,p=t.charCodeAt(i);while(p<=32);a=t.slice(d,i),s=e[e.length-1],p===$l&&v?S=a:s&&s.type==="div"?(s.after=a,s.sourceEndIndex+=a.length):p===Nl||p===Bl||p===yr&&t.charCodeAt(i+1)!==As&&(!y||y&&y.type==="function"&&!1)?k=a:e.push({type:"space",sourceIndex:d,sourceEndIndex:i,value:a}),d=i}else if(p===Ss||p===Ll){i=d,n=p===Ss?"'":'"',a={type:"string",sourceIndex:d,quote:n};do if(o=!1,i=t.indexOf(n,i+1),~i)for(l=i;t.charCodeAt(l-1)===Ml;)l-=1,o=!o;else t+=n,i=t.length-1,a.unclosed=!0;while(o);a.value=t.slice(d+1,i),a.sourceEndIndex=a.unclosed?i:i+1,e.push(a),d=i+1,p=t.charCodeAt(d)}else if(p===yr&&t.charCodeAt(d+1)===As)i=t.indexOf("*/",d),a={type:"comment",sourceIndex:d,sourceEndIndex:i+2},i===-1&&(a.unclosed=!0,i=t.length,a.sourceEndIndex=i),a.value=t.slice(d+2,i),e.push(a),d=i+2,p=t.charCodeAt(d);else if((p===yr||p===As)&&y&&y.type==="function")a=t[d],e.push({type:"word",sourceIndex:d-k.length,sourceEndIndex:d+a.length,value:a}),d+=1,p=t.charCodeAt(d);else if(p===yr||p===Nl||p===Bl)a=t[d],e.push({type:"div",sourceIndex:d-k.length,sourceEndIndex:d+a.length,value:a,before:k,after:""}),k="",d+=1,p=t.charCodeAt(d);else if(ql===p){i=d;do i+=1,p=t.charCodeAt(i);while(p<=32);if(f=d,a={type:"function",sourceIndex:d-w.length,value:w,before:t.slice(f+1,i)},d=i,w==="url"&&p!==Ss&&p!==Ll){i-=1;do if(o=!1,i=t.indexOf(")",i+1),~i)for(l=i;t.charCodeAt(l-1)===Ml;)l-=1,o=!o;else t+=")",i=t.length-1,a.unclosed=!0;while(o);c=i;do c-=1,p=t.charCodeAt(c);while(p<=32);f<c?(d!==c+1?a.nodes=[{type:"word",sourceIndex:d,sourceEndIndex:c+1,value:t.slice(d,c+1)}]:a.nodes=[],a.unclosed&&c+1!==i?(a.after="",a.nodes.push({type:"space",sourceIndex:c+1,sourceEndIndex:i,value:t.slice(c+1,i)})):(a.after=t.slice(c+1,i),a.sourceEndIndex=i)):(a.after="",a.nodes=[]),d=i+1,a.sourceEndIndex=a.unclosed?i:d,p=t.charCodeAt(d),e.push(a)}else v+=1,a.after="",a.sourceEndIndex=d+1,e.push(a),b.push(a),e=a.nodes=[],y=a;w=""}else if($l===p&&v)d+=1,p=t.charCodeAt(d),y.after=S,y.sourceEndIndex+=S.length,S="",v-=1,b[b.length-1].sourceEndIndex=d,b.pop(),y=bLine truncated
|
||||
`),console.time("JIT TOTAL"),t},async function(t,i){e=ky(t,i)??e;let n=El(e);if(t.type==="document"){let s=t.nodes.filter(a=>a.type==="root");for(let a of s)a.type==="root"&&await Ts(n)(a,i);return}await Ts(n)(t,i)},Ze.DEBUG&&function(t){return console.timeEnd("JIT TOTAL"),console.log(`
|
||||
`),t}].filter(Boolean)}};Ql.exports.postcss=!0});var _y=x((Gq,Cy)=>{u();Cy.exports=Ay()});var Yl=x((Qq,Ey)=>{u();Ey.exports=()=>["and_chr 114","and_uc 15.5","chrome 114","chrome 113","chrome 109","edge 114","firefox 114","ios_saf 16.5","ios_saf 16.4","ios_saf 16.3","ios_saf 16.1","opera 99","safari 16.5","samsung 21"]});var Rs={};Ge(Rs,{agents:()=>nO,feature:()=>sO});function sO(){return{status:"cr",title:"CSS Feature Queries",stats:{ie:{"6":"n","7":"n","8":"n","9":"n","10":"n","11":"n","5.5":"n"},edge:{"12":"y","13":"y","14":"y","15":"y","16":"y","17":"y","18":"y","79":"y","80":"y","81":"y","83":"y","84":"y","85":"y","86":"y","87":"y","88":"y","89":"y","90":"y","91":"y","92":"y","93":"y","94":"y","95":"y","96":"y","97":"y","98":"y","99":"y","100":"y","101":"y","102":"y","103":"y","104":"y","105":"y","106":"y","107":"y","108":"y","109":"y","110":"y","111":"y","112":"y","113":"y","114":"y"},firefox:{"2":"n","3":"n","4":"n","5":"n","6":"n","7":"n","8":"n","9":"n","10":"n","11":"n","12":"n","13":"n","14":"n","15":"n","16":"n","17":"n","18":"n","19":"n","20":"n","21":"n","22":"y","23":"y","24":"y","25":"y","26":"y","27":"y","28":"y","29":"y","30":"y","31":"y","32":"y","33":"y","34":"y","35":"y","36":"y","37":"y","38":"y","39":"y","40":"y","41":"y","42":"y","43":"y","44":"y","45":"y","46":"y","47":"y","48":"y","49":"y","50":"y","51":"y","52":"y","53":"y","54":"y","55":"y","56":"y","57":"y","58":"y","59":"y","60":"y","61":"y","62":"y","63":"y","64":"y","65":"y","66":"y","67":"y","68":"y","69":"y","70":"y","71":"y","72":"y","73":"y","74":"y","75":"y","76":"y","77":"y","78":"y","79":"y","80":"y","81":"y","82":"y","83":"y","84":"y","85":"y","86":"y","87":"y","88":"y","89":"y","90":"y","91":"y","92":"y","93":"y","94":"y","95":"y","96":"y","97":"y","98":"y","99":"y","100":"y","101":"y","102":"y","103":"y","104":"y","105":"y","106":"y","107":"y","108":"y","109":"y","110":"y","111":"y","112":"y","113":"y","114":"y","115":"y","116":"y","117":"y","3.5":"n","3.6":"n"},chrome:{"4":"n","5":"n","6":"n","7":"n","8":"n","9":"n","10":"n","11":"n","12":"n","13":"n","14":"n","15":"n","16":"n","17":"n","18":"n","19":"n","20":"n","21":"n","22":"n","23":"n","24":"n","25":"n","26":"n","27":"n","28":"y","29":"y","30":"y","31":"y","32":"y","33":"y","34":"y","35":"y","36":"y","37":"y","38":"y","39":"y","40":"y","41":"y","42":"y","43":"y","44":"y","45":"y","46":"y","47":"y","48":"y","49":"y","50":"y","51":"y","52":"y","53":"y","54":"y","55":"y","56":"y","57":"y","58":"y","59":"y","60":"y","61":"y","62":"y","63":"y","64":"y","65":"y","66":"y","67":"y","68":"y","69":"y","70":"y","71":"y","72":"y","73":"y","74":"y","75":"y","76":"y","77":"y","78":"y","79":"y","80":"y","81":"y","83":"y","84":"y","85":"y","86":"y","87":"y","88":"y","89":"y","90":"y","91":"y","92":"y","93":"y","94":"y","95":"y","96":"y","97":"y","98":"y","99":"y","100":"y","101":"y","102":"y","103":"y","104":"y","105":"y","106":"y","107":"y","108":"y","109":"y","110":"y","111":"y","112":"y","113":"y","114":"y","115":"y","116":"y","117":"y"},safari:{"4":"n","5":"n","6":"n","7":"n","8":"n","9":"y","10":"y","11":"y","12":"y","13":"y","14":"y","15":"y","17":"y","9.1":"y","10.1":"y","11.1":"y","12.1":"y","13.1":"y","14.1":"y","15.1":"y","15.2-15.3":"y","15.4":"y","15.5":"y","15.6":"y","16.0":"y","16.1":"y","16.2":"y","16.3":"y","16.4":"y","16.5":"y","16.6":"y",TP:"y","3.1":"n","3.2":"n","5.1":"n","6.1":"n","7.1":"n"},opera:{"9":"n","11":"n","12":"n","15":"y","16":"y","17":"y","18":"y","19":"y","20":"y","21":"y","22":"y","23":"y","24":"y","25":"y","26":"y","27":"y","28":"y","29":"y","30":"y","31":"y","32":"y","33":"y","34":"y","35":"y","36":"y","37":"y","38":"y","39":"y","40":"y","41":"y","42":"y","43":"y","44":"y","45":"y","46":"y","47":"y","48":"y","49":"y","50":"y","51":"y","52":"y","53":"y","54":"y","55":"y","56":"y","57":"y","58":"y","60":"y","62":"y","63":"y","64":"y","65":"y","66":"y","67":"y","68":"y","69":"y","70":"y","71":"y","72":"y","73":"y","74":"y","75":"y","76":"y","77":"y","78":"y","79":"y","80":"y","81":"y","82":"y","83":"y","84":"y","85":"y","86":"y","87":"y","88":"y","89":"y","90":"y","91":"y","92":"y","93":"y","94":"y","95":"y","96":"y","97":"y","98":"y","99":"y","100":"y","12.1":"y","9.5-9.6":"n","10.0-10.1":"n","10.5":"n","10.6":"n","11.1":"n","11.5":"n","11.6":"n"},ios_saf:{"8":"n","17":"y","9.0-9.2":"y","9.3":"y","10.0-10.2":"y","10.3":"y","11.0-11.2":"y","11.3-11.4":"y","12.0-12.1":"y","12.2-12.5":"y","13.0-13.1":"y","13.2":"y","13.3":"y","13.4-13.7":"y","14.0-14.4":"y","14.5-14.8":"y","15.0-15.1":"y","15.2-15.3":"y","15.4":"y","15.5":"y","15.6":"y","16.0":"y","16.1":"y","16.2":"y","16.3":"y","16.4":"y","16.5":"y","16.6":"y","3.2":"n","4.0-4.1":"n","4.2-4.3":"n","5.0-5.1":"n","6.0-6.1":"n","7.0-7.1":"n","8.1-8.4":"n"},op_mini:{all:"y"},android:{"3":"n","4":"n","114":"y","4.4":"y","4.4.3-4.4.4":"y","2.1":"n","2.2":"n","2.3":"n","4.1":"n","4.2-4.3":"n"},bb:{"7":"n","10":"n"},op_mob:{"10":"n","11":"n","12":"n","73":"y","11.1":"n","11.5":"n","12.1":"n"},and_chr:
Line truncated
|
||||
`)),e._autoprefixerCascade}maxPrefixed(e,t){if(t._autoprefixerMax)return t._autoprefixerMax;let i=0;for(let n of e)n=$y.removeNote(n),n.length>i&&(i=n.length);return t._autoprefixerMax=i,t._autoprefixerMax}calcBefore(e,t,i=""){let s=this.maxPrefixed(e,t)-$y.removeNote(i).length,a=t.raw("before");return s>0&&(a+=Array(s).fill(" ").join("")),a}restoreBefore(e){let t=e.raw("before").split(`
|
||||
`),i=t[t.length-1];this.all.group(e).up(n=>{let s=n.raw("before").split(`
|
||||
`),a=s[s.length-1];a.length<i.length&&(i=a)}),t[t.length-1]=i,e.raws.before=t.join(`
|
||||
`)}insert(e,t,i){let n=this.set(this.clone(e),t);if(!(!n||e.parent.some(a=>a.prop===n.prop&&a.value===n.value)))return this.needCascade(e)&&(n.raws.before=this.calcBefore(i,e,t)),e.parent.insertBefore(e,n)}isAlready(e,t){let i=this.all.group(e).up(n=>n.prop===t);return i||(i=this.all.group(e).down(n=>n.prop===t)),i}add(e,t,i,n){let s=this.prefixed(e.prop,t);if(!(this.isAlready(e,s)||this.otherPrefixes(e.value,t)))return this.insert(e,t,i,n)}process(e,t){if(!this.needCascade(e)){super.process(e,t);return}let i=super.process(e,t);!i||!i.length||(this.restoreBefore(e),e.raws.before=this.calcBefore(i,e))}old(e,t){return[this.prefixed(e,t)]}};My.exports=Ly});var By=x((r$,Ny)=>{u();Ny.exports=function r(e){return{mul:t=>new r(e*t),div:t=>new r(e/t),simplify:()=>new r(e),toString:()=>e.toString()}}});var zy=x((i$,jy)=>{u();var pO=By(),dO=wr(),Zl=_e(),hO=/(min|max)-resolution\s*:\s*\d*\.?\d+(dppx|dpcm|dpi|x)/gi,mO=/(min|max)-resolution(\s*:\s*)(\d*\.?\d+)(dppx|dpcm|dpi|x)/i,Fy=class extends dO{prefixName(e,t){return e==="-moz-"?t+"--moz-device-pixel-ratio":e+t+"-device-pixel-ratio"}prefixQuery(e,t,i,n,s){return n=new pO(n),s==="dpi"?n=n.div(96):s==="dpcm"&&(n=n.mul(2.54).div(96)),n=n.simplify(),e==="-o-"&&(n=n.n+"/"+n.d),this.prefixName(e,t)+i+n}clean(e){if(!this.bad){this.bad=[];for(let t of this.prefixes)this.bad.push(this.prefixName(t,"min")),this.bad.push(this.prefixName(t,"max"))}e.params=Zl.editList(e.params,t=>t.filter(i=>this.bad.every(n=>!i.includes(n))))}process(e){let t=this.parentPrefix(e),i=t?[t]:this.prefixes;e.params=Zl.editList(e.params,(n,s)=>{for(let a of n){if(!a.includes("min-resolution")&&!a.includes("max-resolution")){s.push(a);continue}for(let o of i){let l=a.replace(hO,c=>{let f=c.match(mO);return this.prefixQuery(o,f[1],f[2],f[3],f[4])});s.push(l)}s.push(a)}return Zl.uniq(s)})}};jy.exports=Fy});var Vy=x((n$,Uy)=>{u();var Jl="(".charCodeAt(0),eu=")".charCodeAt(0),Ds="'".charCodeAt(0),tu='"'.charCodeAt(0),ru="\\".charCodeAt(0),vr="/".charCodeAt(0),iu=",".charCodeAt(0),nu=":".charCodeAt(0),qs="*".charCodeAt(0),gO="u".charCodeAt(0),yO="U".charCodeAt(0),bO="+".charCodeAt(0),wO=/^[a-f0-9?-]+$/i;Uy.exports=function(r){for(var e=[],t=r,i,n,s,a,o,l,c,f,d=0,p=t.charCodeAt(d),h=t.length,b=[{nodes:e}],v=0,y,w="",k="",S="";d<h;)if(p<=32){i=d;do i+=1,p=t.charCodeAt(i);while(p<=32);a=t.slice(d,i),s=e[e.length-1],p===eu&&v?S=a:s&&s.type==="div"?(s.after=a,s.sourceEndIndex+=a.length):p===iu||p===nu||p===vr&&t.charCodeAt(i+1)!==qs&&(!y||y&&y.type==="function"&&y.value!=="calc")?k=a:e.push({type:"space",sourceIndex:d,sourceEndIndex:i,value:a}),d=i}else if(p===Ds||p===tu){i=d,n=p===Ds?"'":'"',a={type:"string",sourceIndex:d,quote:n};do if(o=!1,i=t.indexOf(n,i+1),~i)for(l=i;t.charCodeAt(l-1)===ru;)l-=1,o=!o;else t+=n,i=t.length-1,a.unclosed=!0;while(o);a.value=t.slice(d+1,i),a.sourceEndIndex=a.unclosed?i:i+1,e.push(a),d=i+1,p=t.charCodeAt(d)}else if(p===vr&&t.charCodeAt(d+1)===qs)i=t.indexOf("*/",d),a={type:"comment",sourceIndex:d,sourceEndIndex:i+2},i===-1&&(a.unclosed=!0,i=t.length,a.sourceEndIndex=i),a.value=t.slice(d+2,i),e.push(a),d=i+2,p=t.charCodeAt(d);else if((p===vr||p===qs)&&y&&y.type==="function"&&y.value==="calc")a=t[d],e.push({type:"word",sourceIndex:d-k.length,sourceEndIndex:d+a.length,value:a}),d+=1,p=t.charCodeAt(d);else if(p===vr||p===iu||p===nu)a=t[d],e.push({type:"div",sourceIndex:d-k.length,sourceEndIndex:d+a.length,value:a,before:k,after:""}),k="",d+=1,p=t.charCodeAt(d);else if(Jl===p){i=d;do i+=1,p=t.charCodeAt(i);while(p<=32);if(f=d,a={type:"function",sourceIndex:d-w.length,value:w,before:t.slice(f+1,i)},d=i,w==="url"&&p!==Ds&&p!==tu){i-=1;do if(o=!1,i=t.indexOf(")",i+1),~i)for(l=i;t.charCodeAt(l-1)===ru;)l-=1,o=!o;else t+=")",i=t.length-1,a.unclosed=!0;while(o);c=i;do c-=1,p=t.charCodeAt(c);while(p<=32);f<c?(d!==c+1?a.nodes=[{type:"word",sourceIndex:d,sourceEndIndex:c+1,value:t.slice(d,c+1)}]:a.nodes=[],a.unclosed&&c+1!==i?(a.after="",a.nodes.push({type:"space",sourceIndex:c+1,sourceEndIndex:i,value:t.slice(c+1,i)})):(a.after=t.slice(c+1,i),a.sourceEndIndex=i)):(a.after="",a.nodes=[]),d=i+1,a.sourceEndIndex=a.unclosed?i:d,p=t.charCodeAt(d),e.push(a)}else v+=1,a.after="",a.sourceEndIndex=d+1,e.push(a),b.push(a),e=a.nodes=[],y=a;w=""}else if(eu===p&&v)d+=1,p=t.charCodeAt(d),y.after=S,y.sourceEndIndex+=S.length,S="",v-=1,b[b.length-1].sourceEndIndex=d,b.pop(),y=b[v],e=y.nodes;else{i=d;do p===ru&&(i+=1),i+=1,p=t.charCodeAt(i);while(i<h&&!(p<=32||p===Ds||p===tu||p===iu||p===nu||p===vr||p===Jl||p===qs&&y&&y.type==="function"&&y.value==="calc"||p===vr&&y.type==="function"&&y.value==="calc"||p===eu&&v));a=t.slice(d,i),Jl===p?w=a:(gO===a.charCodeAt(0)||yO===a.charCodeAt(0))&&bO===a.charCodeAt(1)&&wO.test(a.slice(2))?e.push({type:"unicode-range",sourceIndex:d,sourceEndIndex:i,value:a}):e.push({type:"word",sourceIndex:d,sourceEndIndex:i,value:a}),d=i}for(d=b.length-1;d;d-=1)b[d].unclosed=!0,b[d].sourceEndIndex=t.length;return b[0].nodes}});var Wy=x((s$,Hy)=>{u();Hy.exports=function r(e,t,i){var n,s
Line truncated
|
||||
`)&&this.reduceSpaces(n),a.removeChild(s);return}}for(let l of this.prefixes.values("remove",o)){if(!l.check||!l.check(n.value))continue;if(o=l.unprefixed,this.prefixes.group(n).down(f=>f.value.includes(o))){a.removeChild(s);return}}})}withHackValue(e){return e.prop==="-webkit-background-clip"&&e.value==="text"}disabledValue(e,t){return this.gridStatus(e,t)===!1&&e.type==="decl"&&e.prop==="display"&&e.value.includes("grid")||this.prefixes.options.flexbox===!1&&e.type==="decl"&&e.prop==="display"&&e.value.includes("flex")||e.type==="decl"&&e.prop==="content"?!0:this.disabled(e,t)}disabledDecl(e,t){if(this.gridStatus(e,t)===!1&&e.type==="decl"&&(e.prop.includes("grid")||e.prop==="justify-items"))return!0;if(this.prefixes.options.flexbox===!1&&e.type==="decl"){let i=["order","justify-content","align-items","align-content"];if(e.prop.includes("flex")||i.includes(e.prop))return!0}return this.disabled(e,t)}disabled(e,t){if(!e)return!1;if(e._autoprefixerDisabled!==void 0)return e._autoprefixerDisabled;if(e.parent){let n=e.prev();if(n&&n.type==="comment"&&$O.test(n.text))return e._autoprefixerDisabled=!0,e._autoprefixerSelfDisabled=!0,!0}let i=null;if(e.nodes){let n;e.each(s=>{s.type==="comment"&&/(!\s*)?autoprefixer:\s*(off|on)/i.test(s.text)&&(typeof n!="undefined"?t.warn("Second Autoprefixer control comment was ignored. Autoprefixer applies control comment to whole block, not to next rules.",{node:s}):n=/on/i.test(s.text))}),n!==void 0&&(i=!n)}if(!e.nodes||i===null)if(e.parent){let n=this.disabled(e.parent,t);e.parent._autoprefixerSelfDisabled===!0?i=!1:i=n}else i=!1;return e._autoprefixerDisabled=i,i}reduceSpaces(e){let t=!1;if(this.prefixes.group(e).up(()=>(t=!0,!0)),t)return;let i=e.raw("before").split(`
|
||||
`),n=i[i.length-1].length,s=!1;this.prefixes.group(e).down(a=>{i=a.raw("before").split(`
|
||||
`);let o=i.length-1;i[o].length>n&&(s===!1&&(s=i[o].length-n),i[o]=i[o].slice(0,-s),a.raws.before=i.join(`
|
||||
`))})}displayType(e){for(let t of e.parent.nodes)if(t.prop==="display"){if(t.value.includes("flex"))return"flex";if(t.value.includes("grid"))return"grid"}return!1}gridStatus(e,t){if(!e)return!1;if(e._autoprefixerGridStatus!==void 0)return e._autoprefixerGridStatus;let i=null;if(e.nodes){let n;e.each(s=>{if(s.type==="comment"&&LO.test(s.text)){let a=/:\s*autoplace/i.test(s.text),o=/no-autoplace/i.test(s.text);typeof n!="undefined"?t.warn("Second Autoprefixer grid control comment was ignored. Autoprefixer applies control comments to the whole block, not to the next rules.",{node:s}):a?n="autoplace":o?n=!0:n=/on/i.test(s.text)}}),n!==void 0&&(i=n)}if(e.type==="atrule"&&e.name==="supports"){let n=e.params;n.includes("grid")&&n.includes("auto")&&(i=!1)}if(!e.nodes||i===null)if(e.parent){let n=this.gridStatus(e.parent,t);e.parent._autoprefixerSelfDisabled===!0?i=!1:i=n}else typeof this.prefixes.options.grid!="undefined"?i=this.prefixes.options.grid:typeof m.env.AUTOPREFIXER_GRID!="undefined"?m.env.AUTOPREFIXER_GRID==="autoplace"?i="autoplace":i=!0:i=!1;return e._autoprefixerGridStatus=i,i}};hb.exports=db});var gb=x((h$,mb)=>{u();mb.exports={A:{A:{"2":"K E F G A B JC"},B:{"1":"C L M H N D O P Q R S T U V W X Y Z a b c d e f g h i j n o p q r s t u v w x y z I"},C:{"1":"2 3 4 5 6 7 8 9 AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB ZB aB bB cB 0B dB 1B eB fB gB hB iB jB kB lB mB nB oB m pB qB rB sB tB P Q R 2B S T U V W X Y Z a b c d e f g h i j n o p q r s t u v w x y z I uB 3B 4B","2":"0 1 KC zB J K E F G A B C L M H N D O k l LC MC"},D:{"1":"8 9 AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB ZB aB bB cB 0B dB 1B eB fB gB hB iB jB kB lB mB nB oB m pB qB rB sB tB P Q R S T U V W X Y Z a b c d e f g h i j n o p q r s t u v w x y z I uB 3B 4B","2":"0 1 2 3 4 5 6 7 J K E F G A B C L M H N D O k l"},E:{"1":"G A B C L M H D RC 6B vB wB 7B SC TC 8B 9B xB AC yB BC CC DC EC FC GC UC","2":"0 J K E F NC 5B OC PC QC"},F:{"1":"1 2 3 4 5 6 7 8 9 H N D O k l AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB m pB qB rB sB tB P Q R 2B S T U V W X Y Z a b c d e f g h i j wB","2":"G B C VC WC XC YC vB HC ZC"},G:{"1":"D fC gC hC iC jC kC lC mC nC oC pC qC rC sC tC 8B 9B xB AC yB BC CC DC EC FC GC","2":"F 5B aC IC bC cC dC eC"},H:{"1":"uC"},I:{"1":"I zC 0C","2":"zB J vC wC xC yC IC"},J:{"2":"E A"},K:{"1":"m","2":"A B C vB HC wB"},L:{"1":"I"},M:{"1":"uB"},N:{"2":"A B"},O:{"1":"xB"},P:{"1":"J k l 1C 2C 3C 4C 5C 6B 6C 7C 8C 9C AD yB BD CD DD"},Q:{"1":"7B"},R:{"1":"ED"},S:{"1":"FD GD"}},B:4,C:"CSS Feature Queries"}});var vb=x((m$,wb)=>{u();function yb(r){return r[r.length-1]}var bb={parse(r){let e=[""],t=[e];for(let i of r){if(i==="("){e=[""],yb(t).push(e),t.push(e);continue}if(i===")"){t.pop(),e=yb(t),e.push("");continue}e[e.length-1]+=i}return t[0]},stringify(r){let e="";for(let t of r){if(typeof t=="object"){e+=`(${bb.stringify(t)})`;continue}e+=t}return e}};wb.exports=bb});var Cb=x((g$,Ab)=>{u();var BO=gb(),{feature:FO}=(Ps(),Rs),{parse:jO}=$e(),zO=Mt(),lu=vb(),UO=He(),VO=_e(),xb=FO(BO),kb=[];for(let r in xb.stats){let e=xb.stats[r];for(let t in e){let i=e[t];/y/.test(i)&&kb.push(r+" "+t)}}var Sb=class{constructor(e,t){this.Prefixes=e,this.all=t}prefixer(){if(this.prefixerCache)return this.prefixerCache;let e=this.all.browsers.selected.filter(i=>kb.includes(i)),t=new zO(this.all.browsers.data,e,this.all.options);return this.prefixerCache=new this.Prefixes(this.all.data,t,this.all.options),this.prefixerCache}parse(e){let t=e.split(":"),i=t[0],n=t[1];return n||(n=""),[i.trim(),n.trim()]}virtual(e){let[t,i]=this.parse(e),n=jO("a{}").first;return n.append({prop:t,value:i,raws:{before:""}}),n}prefixed(e){let t=this.virtual(e);if(this.disabled(t.first))return t.nodes;let i={warn:()=>null},n=this.prefixer().add[t.first.prop];n&&n.process&&n.process(t.first,i);for(let s of t.nodes){for(let a of this.prefixer().values("add",t.first.prop))a.process(s);UO.save(this.all,s)}return t.nodes}isNot(e){return typeof e=="string"&&/not\s*/i.test(e)}isOr(e){return typeof e=="string"&&/\s*or\s*/i.test(e)}isProp(e){return typeof e=="object"&&e.length===1&&typeof e[0]=="string"}isHack(e,t){return!new RegExp(`(\\(|\\s)${VO.escapeRegexp(t)}:`).test(e)}toRemove(e,t){let[i,n]=this.parse(e),s=this.all.unprefixed(i),a=this.all.cleaner();if(a.remove[i]&&a.remove[i].remove&&!this.isHack(t,s))return!0;for(let o of a.values("remove",s))if(o.check(n))return!0;return!1}remove(e,t){let i=0;for(;i<e.length;){if(!this.isNot(e[i-1])&&this.isProp(e[i])&&this.isOr(e[i+1])){if(this.toRemove(e[i][0],t)){e.splice(i,2);continue}i+=2;continue}typeof e[i]=="object"&&(e[i]=this.remove(e[i],t)),i+=1}return e}cleanBrackets(e){return e.map(t=>typeof t!="object"?t:t.length===1&&typeof t[0]=="object"?this.cleanBrackets(t[0]):this.cleanBrackets(t))}convert(e){let t=[""];for(let i of e)t.push([`${i.prop}: ${i.value}`]),t.push(" or ");return t[t.length-1]="",t}n
Line truncated
|
||||
Replace Autoprefixer \`browsers\` option to Browserslist config.
|
||||
Use \`browserslist\` key in \`package.json\` or \`.browserslistrc\` file.
|
||||
|
||||
Using \`browsers\` option can cause errors. Browserslist config can
|
||||
be used for Babel, Autoprefixer, postcss-normalize and other tools.
|
||||
|
||||
If you really need to use option, rename it to \`overrideBrowserslist\`.
|
||||
|
||||
Learn more at:
|
||||
https://github.com/browserslist/browserslist#readme
|
||||
https://twitter.com/browserslist
|
||||
|
||||
`;function V5(r){return Object.prototype.toString.apply(r)==="[object Object]"}var lf=new Map;function H5(r,e){e.browsers.selected.length!==0&&(e.add.selectors.length>0||Object.keys(e.add).length>2||r.warn(`Autoprefixer target browsers do not need any prefixes.You do not need Autoprefixer anymore.
|
||||
Check your Browserslist config to be sure that your targets are set up correctly.
|
||||
|
||||
Learn more at:
|
||||
https://github.com/postcss/autoprefixer#readme
|
||||
https://github.com/browserslist/browserslist#readme
|
||||
|
||||
`))}gv.exports=Dr;function Dr(...r){let e;if(r.length===1&&V5(r[0])?(e=r[0],r=void 0):r.length===0||r.length===1&&!r[0]?r=void 0:r.length<=2&&(Array.isArray(r[0])||!r[0])?(e=r[1],r=r[0]):typeof r[r.length-1]=="object"&&(e=r.pop()),e||(e={}),e.browser)throw new Error("Change `browser` option to `overrideBrowserslist` in Autoprefixer");if(e.browserslist)throw new Error("Change `browserslist` option to `overrideBrowserslist` in Autoprefixer");e.overrideBrowserslist?r=e.overrideBrowserslist:e.browsers&&(typeof console!="undefined"&&console.warn&&(of.red?console.warn(of.red(mv.replace(/`[^`]+`/g,n=>of.yellow(n.slice(1,-1))))):console.warn(mv)),r=e.browsers);let t={ignoreUnknownVersions:e.ignoreUnknownVersions,stats:e.stats,env:e.env};function i(n){let s=hv,a=new F5(s.browsers,r,n,t),o=a.selected.join(", ")+JSON.stringify(e);return lf.has(o)||lf.set(o,new j5(s.prefixes,a,e)),lf.get(o)}return{postcssPlugin:"autoprefixer",prepare(n){let s=i({from:n.opts.from,env:e.env});return{OnceExit(a){H5(n,s),e.remove!==!1&&s.processor.remove(a,n),e.add!==!1&&s.processor.add(a,n)}}},info(n){return n=n||{},n.from=n.from||m.cwd(),U5(i(n))},options:e,browsers:r}}Dr.postcss=!0;Dr.data=hv;Dr.defaults=N5.defaults;Dr.info=()=>Dr().info()});var bv={};Ge(bv,{default:()=>W5});var W5,wv=P(()=>{u();W5=[]});var xv={};Ge(xv,{default:()=>G5});var vv,G5,kv=P(()=>{u();Xi();vv=pe(rn()),G5=St(vv.default.theme)});var Av={};Ge(Av,{default:()=>Q5});var Sv,Q5,Cv=P(()=>{u();Xi();Sv=pe(rn()),Q5=St(Sv.default)});u();"use strict";var Y5=vt(_y()),K5=vt($e()),X5=vt(yv()),Z5=vt((wv(),bv)),J5=vt((kv(),xv)),eP=vt((Cv(),Av)),tP=vt((Vs(),_f)),rP=vt((al(),sl)),iP=vt((sa(),sc));function vt(r){return r&&r.__esModule?r:{default:r}}console.warn("cdn.tailwindcss.com should not be used in production. To use Tailwind CSS in production, install it as a PostCSS plugin or use the Tailwind CLI: https://tailwindcss.com/docs/installation");var Ns="tailwind",uf="text/tailwindcss",_v="/template.html",Yt,Ev=!0,Ov=0,ff=new Set,cf,Tv="",Rv=(r=!1)=>({get(e,t){return(!r||t==="config")&&typeof e[t]=="object"&&e[t]!==null?new Proxy(e[t],Rv()):e[t]},set(e,t,i){return e[t]=i,(!r||t==="config")&&pf(!0),!0}});window[Ns]=new Proxy({config:{},defaultTheme:J5.default,defaultConfig:eP.default,colors:tP.default,plugin:rP.default,resolveConfig:iP.default},Rv(!0));function Pv(r){cf.observe(r,{attributes:!0,attributeFilter:["type"],characterData:!0,subtree:!0,childList:!0})}new MutationObserver(async r=>{let e=!1;if(!cf){cf=new MutationObserver(async()=>await pf(!0));for(let t of document.querySelectorAll(`style[type="${uf}"]`))Pv(t)}for(let t of r)for(let i of t.addedNodes)i.nodeType===1&&i.tagName==="STYLE"&&i.getAttribute("type")===uf&&(Pv(i),e=!0);await pf(e)}).observe(document.documentElement,{attributes:!0,attributeFilter:["class"],childList:!0,subtree:!0});async function pf(r=!1){r&&(Ov++,ff.clear());let e="";for(let i of document.querySelectorAll(`style[type="${uf}"]`))e+=i.textContent;let t=new Set;for(let i of document.querySelectorAll("[class]"))for(let n of i.classList)ff.has(n)||t.add(n);if(document.body&&(Ev||t.size>0||e!==Tv||!Yt||!Yt.isConnected)){for(let n of t)ff.add(n);Ev=!1,Tv=e,self[_v]=Array.from(t).join(" ");let{css:i}=await(0,K5.default)([(0,Y5.default)({...window[Ns].config,_hash:Ov,content:{files:[_v],extract:{html:n=>n.split(" ")}},plugins:[...Z5.default,...Array.isArray(window[Ns].config.plugins)?window[Ns].config.plugins:[]]}),(0,X5.default)({remove:!1})]).process(`@tailwind base;@tailwind components;@tailwind utilities;${e}`);(!Yt||!Yt.isConnected)&&(Yt=document.createElement("style"),document.head.append(Yt)),Yt.textContent=i}}})();
|
||||
/*!
|
||||
* fill-range <https://github.com/jonschlinkert/fill-range>
|
||||
*
|
||||
* Copyright (c) 2014-present, Jon Schlinkert.
|
||||
* Licensed under the MIT License.
|
||||
*/
|
||||
/*!
|
||||
* is-number <https://github.com/jonschlinkert/is-number>
|
||||
*
|
||||
* Copyright (c) 2014-present, Jon Schlinkert.
|
||||
* Released under the MIT License.
|
||||
*/
|
||||
/*!
|
||||
* to-regex-range <https://github.com/micromatch/to-regex-range>
|
||||
*
|
||||
* Copyright (c) 2015-present, Jon Schlinkert.
|
||||
* Released under the MIT License.
|
||||
*/
|
||||
/*! https://mths.be/cssesc v3.0.0 by @mathias */
|
||||
@@ -0,0 +1,537 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { getPrisma } = require('../config/prisma');
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const monitorService = require('../services/monitorService');
|
||||
const pingService = require('../services/pingService');
|
||||
const actionService = require('../services/actionService');
|
||||
const gatewayService = require('../services/gatewayService');
|
||||
const chalk = require('../utils/colors');
|
||||
const { validateTargetInput } = require('../middleware/auth');
|
||||
|
||||
// Get all targets
|
||||
router.get('/targets', async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const targets = await prisma.target.findMany();
|
||||
|
||||
const targetsWithStatus = targets.map((target) => ({
|
||||
...target,
|
||||
_id: target.id,
|
||||
currentStatus: monitorService.getTargetStatus(target.id),
|
||||
}));
|
||||
|
||||
res.json({ success: true, targets: targetsWithStatus });
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error fetching targets:'), error.message);
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Get target by ID
|
||||
router.get('/targets/:id', async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const target = await prisma.target.findUnique({ where: { id: req.params.id } });
|
||||
|
||||
if (!target) {
|
||||
return res.status(404).json({ success: false, error: 'Target not found' });
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
target: { ...target, _id: target.id, currentStatus: monitorService.getTargetStatus(target.id) },
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Create target
|
||||
router.post('/targets', validateTargetInput, async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const faviconService = require('../services/faviconService');
|
||||
|
||||
const {
|
||||
name, host, port, protocol, interval, enabled, publicVisible,
|
||||
publicShowDetails, publicShowStatus, publicShowAppLink, path, appUrl, appIcon,
|
||||
retries, retryInterval, timeout, httpMethod, statusCodes, maxRedirects,
|
||||
ignoreSsl, upsideDown, important, auth, position, group, quickCommands,
|
||||
} = req.body;
|
||||
|
||||
if (!name || !host || !protocol) {
|
||||
return res.status(400).json({ success: false, error: 'Missing required fields: name, host, protocol' });
|
||||
}
|
||||
|
||||
const protocolLower = protocol.toUpperCase();
|
||||
const defaultPort = protocolLower === 'HTTPS' ? 443 : protocolLower === 'HTTP' ? 80 : null;
|
||||
const targetPort = port || defaultPort;
|
||||
const targetPath = path || '/';
|
||||
const targetUrl = targetPort && targetPort !== defaultPort
|
||||
? `${protocolLower.toLowerCase()}://${host}:${targetPort}${targetPath}`
|
||||
: `${protocolLower.toLowerCase()}://${host}${targetPath}`;
|
||||
|
||||
let fetchedAppIcon = appIcon;
|
||||
let finalAppUrl = appUrl;
|
||||
|
||||
if ((protocolLower === 'HTTP' || protocolLower === 'HTTPS') && !appIcon) {
|
||||
try {
|
||||
let authObj = auth;
|
||||
if (auth && typeof auth === 'string') {
|
||||
try { authObj = JSON.parse(auth); } catch (e) { authObj = null; }
|
||||
}
|
||||
|
||||
const faviconUrl = await faviconService.getFaviconUrlFromHtml(targetUrl, {
|
||||
timeout: (timeout || 30) * 1000,
|
||||
maxRedirects: maxRedirects !== undefined ? maxRedirects : 5,
|
||||
ignoreSsl: ignoreSsl === true,
|
||||
auth: authObj,
|
||||
});
|
||||
|
||||
if (faviconUrl) {
|
||||
fetchedAppIcon = faviconUrl;
|
||||
if (!finalAppUrl) finalAppUrl = targetUrl;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to fetch favicon for ${targetUrl}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
const target = await prisma.target.create({
|
||||
data: {
|
||||
name, host, port: port || null, protocol: protocol.toUpperCase(), path: path || null,
|
||||
interval: interval || 60, enabled: enabled !== false, publicVisible: publicVisible !== false,
|
||||
publicShowDetails: publicShowDetails === true, publicShowStatus: publicShowStatus !== false,
|
||||
publicShowAppLink: publicShowAppLink !== false, appUrl: finalAppUrl || null,
|
||||
appIcon: fetchedAppIcon || null, retries: retries !== undefined ? retries : 0,
|
||||
retryInterval: retryInterval !== undefined ? retryInterval : 5,
|
||||
timeout: timeout !== undefined ? timeout : 30, httpMethod: httpMethod || 'GET',
|
||||
statusCodes: statusCodes || '200-299', maxRedirects: maxRedirects !== undefined ? maxRedirects : 5,
|
||||
ignoreSsl: ignoreSsl === true, upsideDown: upsideDown === true, important: important === true, auth: auth || null,
|
||||
position: position !== undefined ? position : 0, group: group || null, quickCommands: quickCommands || [],
|
||||
},
|
||||
});
|
||||
|
||||
if (target.enabled) {
|
||||
monitorService.startTargetMonitor({ ...target, _id: target.id });
|
||||
}
|
||||
require('../services/cacheService').invalidateCollection('public-all');
|
||||
|
||||
res.json({ success: true, targetId: target.id, target: { ...target, _id: target.id } });
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Update target
|
||||
router.put('/targets/:id', validateTargetInput, async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const targetId = req.params.id;
|
||||
const existingTarget = await prisma.target.findUnique({ where: { id: targetId } });
|
||||
if (!existingTarget) return res.status(404).json({ success: false, error: 'Target not found' });
|
||||
|
||||
const {
|
||||
name, host, port, protocol, interval, enabled, publicVisible,
|
||||
publicShowDetails, publicShowStatus, publicShowAppLink, path, appUrl, appIcon,
|
||||
retries, retryInterval, timeout, httpMethod, statusCodes, maxRedirects,
|
||||
ignoreSsl, upsideDown, important, auth, position, group, quickCommands,
|
||||
} = req.body;
|
||||
|
||||
const updateData = {};
|
||||
if (name !== undefined) updateData.name = name;
|
||||
if (host !== undefined) updateData.host = host;
|
||||
if (port !== undefined) updateData.port = port;
|
||||
if (protocol !== undefined) updateData.protocol = protocol.toUpperCase();
|
||||
if (interval !== undefined) updateData.interval = interval;
|
||||
if (path !== undefined) updateData.path = path;
|
||||
if (appUrl !== undefined) updateData.appUrl = appUrl;
|
||||
if (appIcon !== undefined) updateData.appIcon = appIcon;
|
||||
if (retries !== undefined) updateData.retries = retries;
|
||||
if (retryInterval !== undefined) updateData.retryInterval = retryInterval;
|
||||
if (timeout !== undefined) updateData.timeout = timeout;
|
||||
if (httpMethod !== undefined) updateData.httpMethod = httpMethod;
|
||||
if (statusCodes !== undefined) updateData.statusCodes = statusCodes;
|
||||
if (maxRedirects !== undefined) updateData.maxRedirects = maxRedirects;
|
||||
if (ignoreSsl !== undefined) updateData.ignoreSsl = ignoreSsl === true;
|
||||
if (upsideDown !== undefined) updateData.upsideDown = upsideDown === true;
|
||||
if (auth !== undefined) updateData.auth = auth;
|
||||
if (position !== undefined) updateData.position = position;
|
||||
if (group !== undefined) updateData.group = group;
|
||||
if (quickCommands !== undefined) updateData.quickCommands = quickCommands;
|
||||
if (publicVisible !== undefined) updateData.publicVisible = publicVisible === true;
|
||||
if (publicShowDetails !== undefined) updateData.publicShowDetails = publicShowDetails === true;
|
||||
if (publicShowStatus !== undefined) updateData.publicShowStatus = publicShowStatus !== false;
|
||||
if (publicShowAppLink !== undefined) updateData.publicShowAppLink = publicShowAppLink !== false;
|
||||
if (important !== undefined) updateData.important = important === true;
|
||||
|
||||
if (enabled !== undefined) updateData.enabled = enabled === true;
|
||||
const updatedTarget = await prisma.target.update({ where: { id: targetId }, data: updateData });
|
||||
|
||||
// Restart only when ping behavior changed. Metadata/visibility edits must
|
||||
// keep an active outage timer intact, otherwise saving a monitor at minute
|
||||
// four would silently postpone its sustained-outage notification.
|
||||
const monitorConfigFields = [
|
||||
'host', 'port', 'protocol', 'path', 'interval', 'retries', 'retryInterval',
|
||||
'timeout', 'httpMethod', 'statusCodes', 'maxRedirects', 'ignoreSsl',
|
||||
'upsideDown', 'auth',
|
||||
];
|
||||
const valuesEqual = (left, right) => {
|
||||
if (left === right || (left == null && right == null)) return true;
|
||||
return JSON.stringify(left) === JSON.stringify(right);
|
||||
};
|
||||
const requiresRestart = monitorConfigFields.some(field => (
|
||||
Object.prototype.hasOwnProperty.call(updateData, field)
|
||||
&& !valuesEqual(updateData[field], existingTarget[field])
|
||||
));
|
||||
const isActive = monitorService.getActiveMonitors().includes(targetId);
|
||||
|
||||
if (requiresRestart || (!updatedTarget.enabled && isActive)) {
|
||||
monitorService.stopTargetMonitor(targetId);
|
||||
if (updatedTarget.enabled) monitorService.startTargetMonitor({ ...updatedTarget, _id: updatedTarget.id });
|
||||
} else if (updatedTarget.enabled && !isActive) {
|
||||
monitorService.startTargetMonitor({ ...updatedTarget, _id: updatedTarget.id });
|
||||
} else {
|
||||
monitorService.updateTargetReference({ ...updatedTarget, _id: updatedTarget.id });
|
||||
}
|
||||
|
||||
require('../services/cacheService').invalidateCollection('public-all');
|
||||
res.json({ success: true, message: 'Target updated' });
|
||||
} catch (error) {
|
||||
if (error.code === 'P2025') return res.status(404).json({ success: false, error: 'Target not found' });
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Delete target
|
||||
router.delete('/targets/:id', async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const targetId = req.params.id;
|
||||
|
||||
monitorService.stopTargetMonitor(targetId);
|
||||
|
||||
// Manually delete related data to avoid foreign key constraint issues
|
||||
await prisma.pingResult.deleteMany({ where: { targetId } });
|
||||
await prisma.alert.deleteMany({ where: { targetId } });
|
||||
await prisma.statistic.deleteMany({ where: { targetId } });
|
||||
await prisma.action.deleteMany({ where: { targetId } });
|
||||
|
||||
// Now delete the target
|
||||
await prisma.target.delete({ where: { id: targetId } });
|
||||
require('../services/cacheService').invalidateCollection('public-all');
|
||||
|
||||
res.json({ success: true, message: 'Target deleted' });
|
||||
} catch (error) {
|
||||
if (error.code === 'P2025') return res.status(404).json({ success: false, error: 'Target not found' });
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Get ping results for target
|
||||
router.get('/targets/:id/results', async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const targetId = req.params.id;
|
||||
const limit = parseInt(req.query.limit) || 100;
|
||||
const skip = parseInt(req.query.skip) || 0;
|
||||
|
||||
const results = await prisma.pingResult.findMany({
|
||||
where: { targetId },
|
||||
orderBy: { timestamp: 'desc' },
|
||||
take: limit,
|
||||
skip: skip,
|
||||
});
|
||||
|
||||
const count = await prisma.pingResult.count({ where: { targetId } });
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
results: results.map(r => ({ ...r, _id: r.id })),
|
||||
total: count,
|
||||
limit,
|
||||
skip,
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Get statistics for target
|
||||
router.get('/targets/:id/statistics', async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const targetId = req.params.id;
|
||||
const period = req.query.period || '24h';
|
||||
|
||||
let startDateObj = new Date();
|
||||
let endDateObj = new Date();
|
||||
let intervalMinutes = 30;
|
||||
let maxPoints = 48;
|
||||
|
||||
if (period === '1h') {
|
||||
startDateObj.setHours(startDateObj.getHours() - 1);
|
||||
intervalMinutes = 1;
|
||||
maxPoints = 60;
|
||||
} else if (period === '24h') {
|
||||
startDateObj.setHours(startDateObj.getHours() - 24);
|
||||
intervalMinutes = 30;
|
||||
maxPoints = 48;
|
||||
} else if (period === '7d') {
|
||||
startDateObj.setDate(startDateObj.getDate() - 7);
|
||||
intervalMinutes = 180;
|
||||
maxPoints = 56;
|
||||
} else if (period === '30d') {
|
||||
startDateObj.setDate(startDateObj.getDate() - 30);
|
||||
intervalMinutes = 720;
|
||||
maxPoints = 60;
|
||||
} else if (period === 'all' || period === 'ALL') {
|
||||
// For ALL period, use daily statistics (much more efficient)
|
||||
const dailyStats = await prisma.statistic.findMany({
|
||||
where: { targetId },
|
||||
orderBy: { date: 'asc' },
|
||||
select: {
|
||||
date: true,
|
||||
totalPings: true,
|
||||
successfulPings: true,
|
||||
avgResponseTime: true,
|
||||
},
|
||||
});
|
||||
|
||||
const stats = dailyStats.map(s => ({
|
||||
date: s.date.toISOString(),
|
||||
totalPings: s.totalPings || 0,
|
||||
successfulPings: s.successfulPings || 0,
|
||||
failedPings: (s.totalPings || 0) - (s.successfulPings || 0),
|
||||
uptime: s.totalPings > 0 ? parseFloat(((s.successfulPings / s.totalPings) * 100).toFixed(2)) : 0,
|
||||
avgResponseTime: s.avgResponseTime || 0,
|
||||
}));
|
||||
|
||||
// Get uptime data using aggregation
|
||||
const uptime24hStart = new Date();
|
||||
uptime24hStart.setDate(uptime24hStart.getDate() - 1);
|
||||
const uptime30dStart = new Date();
|
||||
uptime30dStart.setDate(uptime30dStart.getDate() - 30);
|
||||
|
||||
const [uptime24h, uptime30d] = await Promise.all([
|
||||
prisma.statistic.aggregate({
|
||||
where: { targetId, date: { gte: uptime24hStart } },
|
||||
_sum: { totalPings: true, successfulPings: true },
|
||||
}),
|
||||
prisma.statistic.aggregate({
|
||||
where: { targetId, date: { gte: uptime30dStart } },
|
||||
_sum: { totalPings: true, successfulPings: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const totalPings24h = uptime24h._sum.totalPings || 0;
|
||||
const successfulPings24h = uptime24h._sum.successfulPings || 0;
|
||||
const totalPings30d = uptime30d._sum.totalPings || 0;
|
||||
const successfulPings30d = uptime30d._sum.successfulPings || 0;
|
||||
|
||||
return res.json({
|
||||
success: true,
|
||||
statistics: stats,
|
||||
uptime: {
|
||||
'24h': {
|
||||
uptime: totalPings24h > 0 ? parseFloat(((successfulPings24h / totalPings24h) * 100).toFixed(2)) : 0,
|
||||
totalPings: totalPings24h,
|
||||
successfulPings: successfulPings24h,
|
||||
failedPings: totalPings24h - successfulPings24h,
|
||||
},
|
||||
'30d': {
|
||||
uptime: totalPings30d > 0 ? parseFloat(((successfulPings30d / totalPings30d) * 100).toFixed(2)) : 0,
|
||||
totalPings: totalPings30d,
|
||||
successfulPings: successfulPings30d,
|
||||
failedPings: totalPings30d - successfulPings30d,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const intervalSeconds = intervalMinutes * 60;
|
||||
const startEpoch = Math.floor(startDateObj.getTime() / 1000);
|
||||
const endEpoch = Math.floor(endDateObj.getTime() / 1000);
|
||||
|
||||
const result = await prisma.$queryRaw`
|
||||
WITH time_buckets AS (
|
||||
-- Keep the database join in UTC while returning an absolute instant
|
||||
-- for browser-local rendering.
|
||||
SELECT
|
||||
to_timestamp(bucket_epoch) AT TIME ZONE 'UTC' AS bucket_start,
|
||||
to_timestamp(bucket_epoch) AS bucket_time
|
||||
FROM generate_series(${startEpoch}::bigint, ${endEpoch}::bigint, ${intervalSeconds}::bigint) as bucket_epoch
|
||||
ORDER BY bucket_epoch
|
||||
LIMIT ${maxPoints}
|
||||
)
|
||||
SELECT
|
||||
-- Keep the value as a timestamptz; browsers render the UTC instant in
|
||||
-- each client's own local timezone.
|
||||
time_buckets.bucket_time as date,
|
||||
COALESCE(COUNT(pr."_id"), 0)::integer as "totalPings",
|
||||
COALESCE(SUM(CASE WHEN pr.success = true THEN 1 ELSE 0 END), 0)::integer as "successfulPings",
|
||||
COALESCE(AVG(CASE WHEN pr."responseTime" IS NOT NULL THEN pr."responseTime"::real ELSE NULL END), 0) as "avgResponseTime"
|
||||
FROM time_buckets
|
||||
LEFT JOIN "pingResults" pr ON
|
||||
pr."targetId" = ${targetId}
|
||||
AND pr.timestamp >= time_buckets.bucket_start
|
||||
AND pr.timestamp < (time_buckets.bucket_start + (${intervalSeconds} || ' seconds')::interval)
|
||||
GROUP BY time_buckets.bucket_start, time_buckets.bucket_time
|
||||
ORDER BY time_buckets.bucket_time ASC
|
||||
`;
|
||||
|
||||
const stats = result.map(r => ({
|
||||
date: new Date(r.date).toISOString(),
|
||||
totalPings: Number(r.totalPings) || 0,
|
||||
successfulPings: Number(r.successfulPings) || 0,
|
||||
failedPings: (Number(r.totalPings) || 0) - (Number(r.successfulPings) || 0),
|
||||
uptime: r.totalPings > 0 ? ((r.successfulPings / r.totalPings) * 100) : 0,
|
||||
avgResponseTime: Number(r.avgResponseTime) || 0,
|
||||
}));
|
||||
|
||||
const uptime24hStart = new Date();
|
||||
uptime24hStart.setDate(uptime24hStart.getDate() - 1);
|
||||
const uptime30dStart = new Date();
|
||||
uptime30dStart.setDate(uptime30dStart.getDate() - 30);
|
||||
|
||||
// Use aggregation queries instead of fetching all records
|
||||
const [uptime24h, uptime30d] = await Promise.all([
|
||||
prisma.statistic.aggregate({
|
||||
where: { targetId, date: { gte: uptime24hStart } },
|
||||
_sum: { totalPings: true, successfulPings: true },
|
||||
}),
|
||||
prisma.statistic.aggregate({
|
||||
where: { targetId, date: { gte: uptime30dStart } },
|
||||
_sum: { totalPings: true, successfulPings: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const totalPings24h = uptime24h._sum.totalPings || 0;
|
||||
const successfulPings24h = uptime24h._sum.successfulPings || 0;
|
||||
const totalPings30d = uptime30d._sum.totalPings || 0;
|
||||
const successfulPings30d = uptime30d._sum.successfulPings || 0;
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
statistics: stats,
|
||||
uptime: {
|
||||
'24h': {
|
||||
uptime: totalPings24h > 0 ? (successfulPings24h / totalPings24h) * 100 : 0,
|
||||
totalPings: totalPings24h,
|
||||
successfulPings: successfulPings24h,
|
||||
failedPings: totalPings24h - successfulPings24h,
|
||||
},
|
||||
'30d': {
|
||||
uptime: totalPings30d > 0 ? (successfulPings30d / totalPings30d) * 100 : 0,
|
||||
totalPings: totalPings30d,
|
||||
successfulPings: successfulPings30d,
|
||||
failedPings: totalPings30d - successfulPings30d,
|
||||
},
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Get alerts
|
||||
router.get('/alerts', async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const limit = parseInt(req.query.limit) || 50;
|
||||
const targetId = req.query.targetId || null;
|
||||
|
||||
const where = targetId ? { targetId } : {};
|
||||
const alerts = await prisma.alert.findMany({
|
||||
where,
|
||||
orderBy: { timestamp: 'desc' },
|
||||
take: limit,
|
||||
});
|
||||
|
||||
res.json({ success: true, alerts: alerts.map(a => ({ ...a, _id: a.id })) });
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Test ping a target
|
||||
router.post('/targets/:id/test', async (req, res) => {
|
||||
const timeout = setTimeout(() => {
|
||||
if (!res.headersSent) res.status(504).json({ success: false, error: 'Test timeout' });
|
||||
}, 60000);
|
||||
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const target = await prisma.target.findUnique({ where: { id: req.params.id } });
|
||||
|
||||
if (!target) {
|
||||
clearTimeout(timeout);
|
||||
return res.status(404).json({ success: false, error: 'Target not found' });
|
||||
}
|
||||
|
||||
const result = await pingService.ping({ ...target, _id: target.id });
|
||||
clearTimeout(timeout);
|
||||
|
||||
if (!res.headersSent) res.json({ success: result.success, result });
|
||||
} catch (error) {
|
||||
clearTimeout(timeout);
|
||||
if (!res.headersSent) res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Execute action
|
||||
router.post('/actions/:id/execute', async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const action = await prisma.action.findUnique({ where: { id: req.params.id } });
|
||||
|
||||
if (!action) {
|
||||
return res.status(404).json({ success: false, error: 'Action not found' });
|
||||
}
|
||||
|
||||
const result = await actionService.executeAction(action);
|
||||
res.json({ success: result.success, result });
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Get gateway information
|
||||
router.get('/gateway', (req, res) => {
|
||||
const gateways = gatewayService.getAllGateways();
|
||||
res.json({
|
||||
success: true,
|
||||
primaryGateway: gatewayService.getPrimaryGateway(),
|
||||
allGateways: gateways,
|
||||
});
|
||||
});
|
||||
|
||||
// Get system status
|
||||
router.get('/status', async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
|
||||
const targetCount = await prisma.target.count();
|
||||
const enabledCount = await prisma.target.count({ where: { enabled: true } });
|
||||
const recentAlerts = await prisma.alert.findMany({
|
||||
orderBy: { timestamp: 'desc' },
|
||||
take: 10,
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
status: {
|
||||
totalTargets: targetCount,
|
||||
enabledTargets: enabledCount,
|
||||
activeMonitors: monitorService.getActiveMonitors().length,
|
||||
gateway: gatewayService.getPrimaryGateway(),
|
||||
},
|
||||
recentAlerts: recentAlerts.map(a => ({ ...a, _id: a.id })),
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,788 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const axios = require('axios');
|
||||
const { getPrisma } = require('../config/prisma');
|
||||
const monitorService = require('../services/monitorService');
|
||||
const faviconService = require('../services/faviconService');
|
||||
|
||||
// The public summary and on-demand graph responses are immutable enough to
|
||||
// keep for an hour. Live status is still refreshed by `hydrateSummary` on
|
||||
// every request, so a warm summary never hides a current outage.
|
||||
const PUBLIC_DATA_CACHE_TTL = 60 * 60 * 1000;
|
||||
const PUBLIC_DATA_CACHE_MAX_AGE = Math.floor(PUBLIC_DATA_CACHE_TTL / 1000);
|
||||
|
||||
function publicCacheKey(cacheService, type, req, extra = {}) {
|
||||
return cacheService.generateKey('public-all', {
|
||||
type,
|
||||
...extra,
|
||||
privileged: isPrivilegedViewer(req),
|
||||
});
|
||||
}
|
||||
|
||||
function setPublicCacheHeaders(res) {
|
||||
res.set('Cache-Control', `private, max-age=${PUBLIC_DATA_CACHE_MAX_AGE}, stale-while-revalidate=60`);
|
||||
}
|
||||
|
||||
function isAdminViewer(req) {
|
||||
return req.session?.adminAuthenticated === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Public routes are mounted before the authenticated `/api` router so the
|
||||
* browser can use the same `/api/*` paths without an API key. When a caller
|
||||
* does send an API credential, preserve the REST API contract and let it see
|
||||
* the complete monitor inventory (including private monitors). In local
|
||||
* development authentication is intentionally disabled, so the presence of
|
||||
* an API header is the only useful signal there.
|
||||
*/
|
||||
function isApiClient(req) {
|
||||
const authHeader = req.headers.authorization || '';
|
||||
const xApiKey = req.headers['x-api-key'] || '';
|
||||
const providedKey = authHeader.replace(/^Bearer\s+/i, '') || xApiKey;
|
||||
if (!providedKey) return false;
|
||||
const configuredKey = process.env.ADMIN_API_KEY;
|
||||
return !configuredKey || providedKey === configuredKey;
|
||||
}
|
||||
|
||||
function isPrivilegedViewer(req) {
|
||||
return isAdminViewer(req) || isApiClient(req);
|
||||
}
|
||||
|
||||
// The public router is mounted before the authenticated API router. Exit this
|
||||
// router whenever a caller explicitly presents API credentials so valid keys
|
||||
// reach the protected API implementation and invalid keys receive its 401
|
||||
// response instead of being silently downgraded to public data.
|
||||
router.use('/api', (req, res, next) => {
|
||||
if (req.headers.authorization || req.headers['x-api-key']) {
|
||||
return next('router');
|
||||
}
|
||||
return next();
|
||||
});
|
||||
|
||||
function targetVisibilityWhere(req) {
|
||||
return isPrivilegedViewer(req) ? {} : { enabled: true, publicVisible: true };
|
||||
}
|
||||
|
||||
function liveNotificationState(targetId) {
|
||||
if (typeof monitorService.getNotificationState !== 'function') return {};
|
||||
return monitorService.getNotificationState(targetId);
|
||||
}
|
||||
|
||||
function publicTargetStatus(target, req) {
|
||||
const adminViewer = isPrivilegedViewer(req);
|
||||
const status = monitorService.getTargetStatus(target.id);
|
||||
const showDetails = adminViewer || target.publicShowDetails === true;
|
||||
const result = {
|
||||
_id: target.id,
|
||||
name: target.name,
|
||||
currentStatus: status,
|
||||
isUp: status === 'up',
|
||||
isDown: status === 'down',
|
||||
notification: liveNotificationState(target.id),
|
||||
publicShowDetails: showDetails,
|
||||
publicShowStatus: adminViewer || target.publicShowStatus !== false,
|
||||
publicShowAppLink: adminViewer || target.publicShowAppLink !== false,
|
||||
};
|
||||
|
||||
if (target.enabled !== undefined) result.enabled = target.enabled;
|
||||
if (target.publicVisible !== undefined) result.publicVisible = target.publicVisible;
|
||||
if (showDetails) {
|
||||
result.host = target.host;
|
||||
result.protocol = target.protocol;
|
||||
if (target.port !== undefined) result.port = target.port;
|
||||
}
|
||||
if (target.appUrl && (adminViewer || target.publicShowAppLink !== false)) result.appUrl = target.appUrl;
|
||||
if (target.appIcon) result.appIcon = target.appIcon;
|
||||
if (target.position !== undefined) result.position = target.position || 0;
|
||||
if (target.group) result.group = target.group;
|
||||
if (target.quickCommands && (adminViewer || target.publicShowAppLink !== false)) result.quickCommands = target.quickCommands;
|
||||
return result;
|
||||
}
|
||||
|
||||
function hydrateSummary(cached, req) {
|
||||
const targets = cached.targets.map((target) => {
|
||||
const currentStatus = monitorService.getTargetStatus(target._id);
|
||||
return {
|
||||
...target,
|
||||
currentStatus,
|
||||
isUp: currentStatus === 'up',
|
||||
isDown: currentStatus === 'down',
|
||||
notification: liveNotificationState(target._id),
|
||||
};
|
||||
});
|
||||
const upTargets = targets.filter((target) => target.isUp).length;
|
||||
const downTargets = targets.filter((target) => target.isDown).length;
|
||||
const overallStatus = downTargets === 0 ? 'operational' : downTargets === targets.length ? 'down' : 'degraded';
|
||||
return {
|
||||
success: true,
|
||||
status: { overallStatus, upTargets, downTargets, totalTargets: targets.length },
|
||||
targets,
|
||||
viewer: { isAdmin: isAdminViewer(req), isApiClient: isApiClient(req) },
|
||||
timestamp: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
async function renderPublicPage(req, res, initialPage) {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const settings = await prisma.publicUISettings.findUnique({ where: { id: 'settings' } }) || {};
|
||||
return res.render('public/index', {
|
||||
title: settings.title || 'Homelab',
|
||||
subtitle: settings.subtitle || 'System Status & Application Dashboard',
|
||||
customCSS: settings.customCSS || '',
|
||||
initialPage,
|
||||
isAdminViewer: isAdminViewer(req),
|
||||
});
|
||||
} catch (error) {
|
||||
return res.render('public/index', {
|
||||
title: 'Homelab',
|
||||
subtitle: 'System Status & Application Dashboard',
|
||||
customCSS: '',
|
||||
initialPage,
|
||||
isAdminViewer: isAdminViewer(req),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Public status page
|
||||
router.get('/', async (req, res) => {
|
||||
return renderPublicPage(req, res, 'home');
|
||||
});
|
||||
|
||||
router.get('/uptime', (req, res) => renderPublicPage(req, res, 'status'));
|
||||
router.get('/blog', (req, res) => renderPublicPage(req, res, 'blog'));
|
||||
|
||||
// Public API - Get all targets (read-only)
|
||||
router.get('/api/targets', async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const targets = await prisma.target.findMany({
|
||||
where: targetVisibilityWhere(req),
|
||||
});
|
||||
|
||||
const targetsWithStatus = targets.map((target) => publicTargetStatus(target, req));
|
||||
|
||||
res.json({ success: true, targets: targetsWithStatus });
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Public API - Get target statistics (read-only)
|
||||
router.get('/api/targets/:id/statistics', async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const cacheService = require('../services/cacheService');
|
||||
const targetId = req.params.id;
|
||||
// Support both 'period' and 'days' query parameters
|
||||
const period = req.query.period || (req.query.days ? `${req.query.days}d` : '24h');
|
||||
const days = parseInt(req.query.days) || null;
|
||||
const cacheKey = publicCacheKey(cacheService, 'statistics', req, { targetId, period, days });
|
||||
const cachedStatistics = cacheService.get(cacheKey);
|
||||
if (cachedStatistics) {
|
||||
setPublicCacheHeaders(res);
|
||||
return res.json(cachedStatistics);
|
||||
}
|
||||
|
||||
const target = await prisma.target.findFirst({
|
||||
where: { id: targetId, ...targetVisibilityWhere(req) },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
|
||||
if (!target) {
|
||||
return res.status(404).json({ success: false, error: 'Target not found' });
|
||||
}
|
||||
|
||||
let startDateObj = new Date();
|
||||
let endDateObj = new Date();
|
||||
let intervalMinutes = 30;
|
||||
let maxPoints = 48;
|
||||
let useDailyStats = false;
|
||||
|
||||
// Handle 'days' parameter for daily statistics
|
||||
if (days !== null) {
|
||||
if (days === 1) {
|
||||
startDateObj.setHours(startDateObj.getHours() - 24);
|
||||
intervalMinutes = 30;
|
||||
maxPoints = 48;
|
||||
useDailyStats = false;
|
||||
} else if (days === 30) {
|
||||
// For 30 days, use daily statistics table instead of raw ping results
|
||||
useDailyStats = true;
|
||||
startDateObj.setDate(startDateObj.getDate() - 30);
|
||||
} else {
|
||||
startDateObj.setDate(startDateObj.getDate() - days);
|
||||
intervalMinutes = Math.max(60, Math.floor((days * 24 * 60) / 60));
|
||||
maxPoints = 60;
|
||||
useDailyStats = days >= 7;
|
||||
}
|
||||
} else if (period === '1h') {
|
||||
startDateObj.setHours(startDateObj.getHours() - 1);
|
||||
intervalMinutes = 1;
|
||||
maxPoints = 60;
|
||||
} else if (period === '24h') {
|
||||
startDateObj.setHours(startDateObj.getHours() - 24);
|
||||
intervalMinutes = 30;
|
||||
maxPoints = 48;
|
||||
} else if (period === '7d') {
|
||||
startDateObj.setDate(startDateObj.getDate() - 7);
|
||||
intervalMinutes = 180;
|
||||
maxPoints = 56;
|
||||
} else if (period === '30d') {
|
||||
startDateObj.setDate(startDateObj.getDate() - 30);
|
||||
useDailyStats = true;
|
||||
} else if (period === 'all' || period === 'ALL') {
|
||||
// For ALL period, use daily statistics (much more efficient)
|
||||
useDailyStats = true;
|
||||
startDateObj = new Date(0); // Start from beginning
|
||||
}
|
||||
|
||||
let stats = [];
|
||||
|
||||
if (useDailyStats) {
|
||||
// Use pre-aggregated daily statistics for better performance
|
||||
const dailyStats = await prisma.statistic.findMany({
|
||||
where: {
|
||||
targetId,
|
||||
date: { gte: startDateObj },
|
||||
},
|
||||
orderBy: { date: 'asc' },
|
||||
select: {
|
||||
date: true,
|
||||
totalPings: true,
|
||||
successfulPings: true,
|
||||
avgResponseTime: true,
|
||||
},
|
||||
});
|
||||
|
||||
stats = dailyStats.map(s => ({
|
||||
date: s.date.toISOString(),
|
||||
totalPings: s.totalPings || 0,
|
||||
successfulPings: s.successfulPings || 0,
|
||||
failedPings: (s.totalPings || 0) - (s.successfulPings || 0),
|
||||
uptime: s.totalPings > 0 ? ((s.successfulPings / s.totalPings) * 100) : 0,
|
||||
avgResponseTime: s.avgResponseTime || 0,
|
||||
}));
|
||||
} else {
|
||||
// Use optimized raw query for shorter time periods
|
||||
const intervalSeconds = intervalMinutes * 60;
|
||||
const startEpoch = Math.floor(startDateObj.getTime() / 1000);
|
||||
const endEpoch = Math.floor(endDateObj.getTime() / 1000);
|
||||
|
||||
// Optimized query with proper index usage
|
||||
const result = await prisma.$queryRaw`
|
||||
WITH time_buckets AS (
|
||||
-- Prisma DateTime columns are stored as UTC timestamp values without
|
||||
-- a timezone. Keep the join in UTC, but return a timestamptz instant
|
||||
-- so browsers can render it in their own local timezone.
|
||||
SELECT
|
||||
to_timestamp(bucket_epoch) AT TIME ZONE 'UTC' AS bucket_start,
|
||||
to_timestamp(bucket_epoch) AS bucket_time
|
||||
FROM generate_series(${startEpoch}::bigint, ${endEpoch}::bigint, ${intervalSeconds}::bigint) as bucket_epoch
|
||||
ORDER BY bucket_epoch
|
||||
LIMIT ${maxPoints}
|
||||
)
|
||||
SELECT
|
||||
-- Keep the value as a timestamptz; browsers render the UTC instant in
|
||||
-- each client's own local timezone.
|
||||
time_buckets.bucket_time as date,
|
||||
COALESCE(COUNT(pr."_id"), 0)::integer as "totalPings",
|
||||
COALESCE(SUM(CASE WHEN pr.success = true THEN 1 ELSE 0 END), 0)::integer as "successfulPings",
|
||||
COALESCE(AVG(CASE WHEN pr."responseTime" IS NOT NULL THEN pr."responseTime"::real ELSE NULL END), 0) as "avgResponseTime"
|
||||
FROM time_buckets
|
||||
LEFT JOIN "pingResults" pr ON
|
||||
pr."targetId" = ${targetId}
|
||||
AND pr.timestamp >= time_buckets.bucket_start
|
||||
AND pr.timestamp < (time_buckets.bucket_start + (${intervalSeconds} || ' seconds')::interval)
|
||||
GROUP BY time_buckets.bucket_start, time_buckets.bucket_time
|
||||
ORDER BY time_buckets.bucket_time ASC
|
||||
`;
|
||||
|
||||
stats = result.map(r => ({
|
||||
date: new Date(r.date).toISOString(),
|
||||
totalPings: Number(r.totalPings) || 0,
|
||||
successfulPings: Number(r.successfulPings) || 0,
|
||||
failedPings: (Number(r.totalPings) || 0) - (Number(r.successfulPings) || 0),
|
||||
uptime: r.totalPings > 0 ? ((r.successfulPings / r.totalPings) * 100) : 0,
|
||||
avgResponseTime: Number(r.avgResponseTime) || 0,
|
||||
}));
|
||||
}
|
||||
|
||||
// Get uptime summary using aggregated statistics (much faster)
|
||||
const uptime24hStart = new Date();
|
||||
uptime24hStart.setDate(uptime24hStart.getDate() - 1);
|
||||
const uptime30dStart = new Date();
|
||||
uptime30dStart.setDate(uptime30dStart.getDate() - 30);
|
||||
|
||||
// Use single aggregation query instead of fetching all records
|
||||
const uptime24h = await prisma.statistic.aggregate({
|
||||
where: {
|
||||
targetId,
|
||||
date: { gte: uptime24hStart },
|
||||
},
|
||||
_sum: {
|
||||
totalPings: true,
|
||||
successfulPings: true,
|
||||
},
|
||||
});
|
||||
|
||||
const uptime30d = await prisma.statistic.aggregate({
|
||||
where: {
|
||||
targetId,
|
||||
date: { gte: uptime30dStart },
|
||||
},
|
||||
_sum: {
|
||||
totalPings: true,
|
||||
successfulPings: true,
|
||||
},
|
||||
});
|
||||
|
||||
const totalPings24h = uptime24h._sum.totalPings || 0;
|
||||
const successfulPings24h = uptime24h._sum.successfulPings || 0;
|
||||
const totalPings30d = uptime30d._sum.totalPings || 0;
|
||||
const successfulPings30d = uptime30d._sum.successfulPings || 0;
|
||||
|
||||
const response = {
|
||||
success: true,
|
||||
statistics: stats,
|
||||
uptime: {
|
||||
'24h': {
|
||||
uptime: totalPings24h > 0 ? (successfulPings24h / totalPings24h) * 100 : 0,
|
||||
totalPings: totalPings24h,
|
||||
successfulPings: successfulPings24h,
|
||||
failedPings: totalPings24h - successfulPings24h,
|
||||
},
|
||||
'30d': {
|
||||
uptime: totalPings30d > 0 ? (successfulPings30d / totalPings30d) * 100 : 0,
|
||||
totalPings: totalPings30d,
|
||||
successfulPings: successfulPings30d,
|
||||
failedPings: totalPings30d - successfulPings30d,
|
||||
},
|
||||
},
|
||||
target: {
|
||||
_id: target.id,
|
||||
name: target.name,
|
||||
},
|
||||
};
|
||||
cacheService.set(cacheKey, response, PUBLIC_DATA_CACHE_TTL);
|
||||
setPublicCacheHeaders(res);
|
||||
res.json(response);
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Public API - Get target uptime summary (read-only)
|
||||
router.get('/api/targets/:id/uptime', async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const cacheService = require('../services/cacheService');
|
||||
const targetId = req.params.id;
|
||||
const days = parseInt(req.query.days) || 30;
|
||||
const cacheKey = publicCacheKey(cacheService, 'uptime', req, { targetId, days });
|
||||
const cachedUptime = cacheService.get(cacheKey);
|
||||
if (cachedUptime) {
|
||||
setPublicCacheHeaders(res);
|
||||
return res.json(cachedUptime);
|
||||
}
|
||||
|
||||
const target = await prisma.target.findFirst({
|
||||
where: { id: targetId, ...targetVisibilityWhere(req) },
|
||||
});
|
||||
|
||||
if (!target) {
|
||||
return res.status(404).json({ success: false, error: 'Target not found' });
|
||||
}
|
||||
|
||||
const startDate = new Date();
|
||||
startDate.setDate(startDate.getDate() - days);
|
||||
|
||||
// Use aggregation instead of fetching all records
|
||||
const stats = await prisma.statistic.aggregate({
|
||||
where: { targetId, date: { gte: startDate } },
|
||||
_sum: { totalPings: true, successfulPings: true },
|
||||
});
|
||||
|
||||
const totalPings = stats._sum.totalPings || 0;
|
||||
const successfulPings = stats._sum.successfulPings || 0;
|
||||
const uptime = totalPings > 0 ? ((successfulPings / totalPings) * 100).toFixed(2) : 0;
|
||||
|
||||
const response = {
|
||||
success: true,
|
||||
targetName: target.name,
|
||||
uptime: parseFloat(uptime),
|
||||
daysTracked: days,
|
||||
totalPings,
|
||||
successfulPings,
|
||||
failedPings: totalPings - successfulPings,
|
||||
};
|
||||
cacheService.set(cacheKey, response, PUBLIC_DATA_CACHE_TTL);
|
||||
setPublicCacheHeaders(res);
|
||||
res.json(response);
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Public API - Get all data for public UI (consolidated endpoint)
|
||||
router.get('/api/public/all', async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const cacheService = require('../services/cacheService');
|
||||
const cacheKey = publicCacheKey(cacheService, 'summary', req);
|
||||
const cachedSummary = cacheService.get(cacheKey);
|
||||
if (cachedSummary) {
|
||||
setPublicCacheHeaders(res);
|
||||
return res.json(hydrateSummary(cachedSummary, req));
|
||||
}
|
||||
|
||||
// Get all visible targets
|
||||
const targets = await prisma.target.findMany({
|
||||
where: targetVisibilityWhere(req),
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
host: true,
|
||||
protocol: true,
|
||||
appUrl: true,
|
||||
appIcon: true,
|
||||
position: true,
|
||||
group: true,
|
||||
quickCommands: true,
|
||||
publicShowDetails: true,
|
||||
publicShowStatus: true,
|
||||
publicShowAppLink: true,
|
||||
enabled: true,
|
||||
publicVisible: true,
|
||||
},
|
||||
orderBy: { position: 'asc' },
|
||||
});
|
||||
|
||||
// Calculate date ranges
|
||||
const uptime24hStart = new Date();
|
||||
uptime24hStart.setDate(uptime24hStart.getDate() - 1);
|
||||
const uptime30dStart = new Date();
|
||||
uptime30dStart.setDate(uptime30dStart.getDate() - 30);
|
||||
// Mini graphs use one point per hour for the latest 24 hours. Align the
|
||||
// window to a bucket boundary so every monitor receives the same compact
|
||||
// timeline from one batched query.
|
||||
const miniBucketSeconds = 60 * 60;
|
||||
// Date.now() is milliseconds while PostgreSQL's to_timestamp and the
|
||||
// generated bucket values use Unix seconds. Convert before aligning to a
|
||||
// bucket boundary; passing milliseconds here creates dates thousands of
|
||||
// years in the future and causes `Invalid time value` during serialization.
|
||||
const miniEndEpoch = Math.floor(Date.now() / 1000 / miniBucketSeconds) * miniBucketSeconds;
|
||||
const miniStartEpoch = miniEndEpoch - (23 * miniBucketSeconds);
|
||||
|
||||
// Get uptime statistics for all targets in parallel using aggregation
|
||||
const targetIds = targets.map(t => t.id);
|
||||
|
||||
if (targetIds.length === 0) {
|
||||
const emptySummary = {
|
||||
success: true,
|
||||
status: {
|
||||
overallStatus: 'operational',
|
||||
upTargets: 0,
|
||||
downTargets: 0,
|
||||
totalTargets: 0,
|
||||
},
|
||||
targets: [],
|
||||
};
|
||||
cacheService.set(cacheKey, emptySummary, PUBLIC_DATA_CACHE_TTL);
|
||||
setPublicCacheHeaders(res);
|
||||
return res.json(hydrateSummary(emptySummary, req));
|
||||
}
|
||||
|
||||
// Use raw SQL for efficient aggregation across all targets
|
||||
const [uptime24hData, uptime30dData, miniStatsData] = await Promise.all([
|
||||
// 24h uptime aggregation for all targets
|
||||
prisma.$queryRaw`
|
||||
SELECT
|
||||
"targetId",
|
||||
COALESCE(SUM("totalPings"), 0)::bigint as "totalPings",
|
||||
COALESCE(SUM("successfulPings"), 0)::bigint as "successfulPings"
|
||||
FROM statistics
|
||||
WHERE "targetId" = ANY(${targetIds}::text[])
|
||||
AND date >= ${uptime24hStart}
|
||||
GROUP BY "targetId"
|
||||
`,
|
||||
// 30d uptime aggregation for all targets
|
||||
prisma.$queryRaw`
|
||||
SELECT
|
||||
"targetId",
|
||||
COALESCE(SUM("totalPings"), 0)::bigint as "totalPings",
|
||||
COALESCE(SUM("successfulPings"), 0)::bigint as "successfulPings"
|
||||
FROM statistics
|
||||
WHERE "targetId" = ANY(${targetIds}::text[])
|
||||
AND date >= ${uptime30dStart}
|
||||
GROUP BY "targetId"
|
||||
`,
|
||||
// Raw ping buckets power the compact 24-hour graph shown for every
|
||||
// service. Cross joining the small 24-bucket timeline with the target
|
||||
// IDs keeps this to one indexed query instead of one request per row.
|
||||
prisma.$queryRaw`
|
||||
WITH time_buckets AS (
|
||||
SELECT
|
||||
to_timestamp(bucket_epoch) AT TIME ZONE 'UTC' AS bucket_start,
|
||||
to_timestamp(bucket_epoch) AS bucket_time
|
||||
FROM generate_series(
|
||||
${miniStartEpoch}::bigint,
|
||||
${miniEndEpoch}::bigint,
|
||||
${miniBucketSeconds}::bigint
|
||||
) AS bucket_epoch
|
||||
)
|
||||
SELECT
|
||||
target_ids."targetId",
|
||||
time_buckets.bucket_time AS date,
|
||||
COALESCE(COUNT(pr."_id"), 0)::integer AS "totalPings",
|
||||
COALESCE(SUM(CASE WHEN pr.success = true THEN 1 ELSE 0 END), 0)::integer AS "successfulPings",
|
||||
COALESCE(AVG(CASE WHEN pr."responseTime" IS NOT NULL THEN pr."responseTime"::real ELSE NULL END), 0) AS "avgResponseTime"
|
||||
FROM time_buckets
|
||||
CROSS JOIN unnest(${targetIds}::text[]) AS target_ids("targetId")
|
||||
LEFT JOIN "pingResults" pr ON
|
||||
pr."targetId" = target_ids."targetId"
|
||||
AND pr.timestamp >= time_buckets.bucket_start
|
||||
AND pr.timestamp < (time_buckets.bucket_start + interval '1 hour')
|
||||
GROUP BY target_ids."targetId", time_buckets.bucket_start, time_buckets.bucket_time
|
||||
ORDER BY target_ids."targetId", time_buckets.bucket_time ASC
|
||||
`,
|
||||
]);
|
||||
|
||||
// Create lookup maps for fast access
|
||||
const uptime24hMap = new Map();
|
||||
uptime24hData.forEach(item => {
|
||||
const total = Number(item.totalPings) || 0;
|
||||
const successful = Number(item.successfulPings) || 0;
|
||||
const uptime = total > 0 ? (successful / total) * 100 : 0;
|
||||
uptime24hMap.set(item.targetId, {
|
||||
uptime: parseFloat(uptime.toFixed(2)),
|
||||
totalPings: total,
|
||||
successfulPings: successful,
|
||||
failedPings: total - successful,
|
||||
});
|
||||
});
|
||||
|
||||
const uptime30dMap = new Map();
|
||||
uptime30dData.forEach(item => {
|
||||
const total = Number(item.totalPings) || 0;
|
||||
const successful = Number(item.successfulPings) || 0;
|
||||
const uptime = total > 0 ? (successful / total) * 100 : 0;
|
||||
uptime30dMap.set(item.targetId, {
|
||||
uptime: parseFloat(uptime.toFixed(2)),
|
||||
totalPings: total,
|
||||
successfulPings: successful,
|
||||
failedPings: total - successful,
|
||||
});
|
||||
});
|
||||
|
||||
// Group the fixed 24-hour buckets by target so the browser can draw all
|
||||
// rows from the consolidated response without additional network calls.
|
||||
const miniStatsMap = new Map();
|
||||
miniStatsData.forEach(stat => {
|
||||
if (!miniStatsMap.has(stat.targetId)) {
|
||||
miniStatsMap.set(stat.targetId, []);
|
||||
}
|
||||
miniStatsMap.get(stat.targetId).push({
|
||||
date: new Date(stat.date).toISOString(),
|
||||
totalPings: Number(stat.totalPings) || 0,
|
||||
successfulPings: Number(stat.successfulPings) || 0,
|
||||
failedPings: (Number(stat.totalPings) || 0) - (Number(stat.successfulPings) || 0),
|
||||
avgResponseTime: Number(stat.avgResponseTime) || 0,
|
||||
});
|
||||
});
|
||||
|
||||
// Build response with targets and their statistics (only include needed fields)
|
||||
const targetsWithStats = targets.map(target => {
|
||||
const status = monitorService.getTargetStatus(target.id);
|
||||
const uptime24h = uptime24hMap.get(target.id) || { uptime: 0, totalPings: 0, successfulPings: 0, failedPings: 0 };
|
||||
const uptime30d = uptime30dMap.get(target.id) || { uptime: 0, totalPings: 0, successfulPings: 0, failedPings: 0 };
|
||||
const miniStats = miniStatsMap.get(target.id) || [];
|
||||
const adminViewer = isPrivilegedViewer(req);
|
||||
const showDetails = adminViewer || target.publicShowDetails === true;
|
||||
|
||||
const result = {
|
||||
_id: target.id,
|
||||
name: target.name,
|
||||
currentStatus: status,
|
||||
isUp: status === 'up',
|
||||
isDown: status === 'down',
|
||||
enabled: target.enabled,
|
||||
publicVisible: target.publicVisible,
|
||||
notification: liveNotificationState(target.id),
|
||||
publicShowDetails: showDetails,
|
||||
publicShowStatus: adminViewer ? true : target.publicShowStatus !== false,
|
||||
publicShowAppLink: adminViewer ? true : target.publicShowAppLink !== false,
|
||||
uptime: {
|
||||
'24h': uptime24h,
|
||||
'30d': uptime30d,
|
||||
},
|
||||
miniStats,
|
||||
};
|
||||
|
||||
// Only include host/protocol if publicShowDetails is true
|
||||
if (showDetails) {
|
||||
result.host = target.host;
|
||||
result.protocol = target.protocol;
|
||||
}
|
||||
|
||||
// Only expose an app URL when the public app-link setting allows it.
|
||||
// Icons remain available for service rows even when linking is disabled.
|
||||
if (target.appUrl && (adminViewer || target.publicShowAppLink !== false)) {
|
||||
result.appUrl = target.appUrl;
|
||||
}
|
||||
if (target.appIcon) {
|
||||
result.appIcon = target.appIcon;
|
||||
}
|
||||
|
||||
// Only include group/position/quickCommands if they have values
|
||||
if (target.group) {
|
||||
result.group = target.group;
|
||||
}
|
||||
if (target.position !== 0) {
|
||||
result.position = target.position;
|
||||
}
|
||||
if (target.quickCommands && target.quickCommands.length > 0 && (adminViewer || target.publicShowAppLink !== false)) {
|
||||
result.quickCommands = target.quickCommands;
|
||||
}
|
||||
|
||||
return result;
|
||||
});
|
||||
|
||||
// Calculate overall status
|
||||
const upCount = targetsWithStats.filter(t => t.isUp).length;
|
||||
const downCount = targetsWithStats.filter(t => t.isDown).length;
|
||||
let overallStatus = 'operational';
|
||||
if (downCount > 0) {
|
||||
overallStatus = downCount === targetsWithStats.length ? 'down' : 'degraded';
|
||||
}
|
||||
|
||||
const summary = {
|
||||
success: true,
|
||||
status: {
|
||||
overallStatus,
|
||||
upTargets: upCount,
|
||||
downTargets: downCount,
|
||||
totalTargets: targetsWithStats.length,
|
||||
},
|
||||
targets: targetsWithStats,
|
||||
};
|
||||
cacheService.set(cacheKey, summary, PUBLIC_DATA_CACHE_TTL);
|
||||
setPublicCacheHeaders(res);
|
||||
res.json(hydrateSummary(summary, req));
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Public API - Get overall status
|
||||
router.get('/api/status', async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
|
||||
const targets = await prisma.target.findMany({
|
||||
where: targetVisibilityWhere(req),
|
||||
});
|
||||
|
||||
const targetsWithStatus = targets.map((target) => publicTargetStatus(target, req));
|
||||
|
||||
const upCount = targetsWithStatus.filter((t) => t.isUp).length;
|
||||
const downCount = targetsWithStatus.filter((t) => t.isDown).length;
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
status: {
|
||||
totalTargets: targetsWithStatus.length,
|
||||
upTargets: upCount,
|
||||
downTargets: downCount,
|
||||
overallStatus: downCount === 0 ? 'operational' : downCount === targetsWithStatus.length ? 'down' : 'degraded',
|
||||
},
|
||||
targets: targetsWithStatus,
|
||||
viewer: { isAdmin: isAdminViewer(req), isApiClient: isApiClient(req) },
|
||||
timestamp: new Date(),
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Proxy endpoint for icons
|
||||
router.get('/api/proxy-icon', async (req, res) => {
|
||||
try {
|
||||
const { url } = req.query;
|
||||
if (!url) return res.status(400).json({ success: false, error: 'URL parameter is required' });
|
||||
|
||||
let targetUrl;
|
||||
try {
|
||||
targetUrl = new URL(url);
|
||||
} catch (e) {
|
||||
return res.status(400).json({ success: false, error: 'Invalid URL' });
|
||||
}
|
||||
|
||||
const https = require('https');
|
||||
const response = await axios.get(url, {
|
||||
responseType: 'arraybuffer',
|
||||
timeout: 10000,
|
||||
headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' },
|
||||
validateStatus: (status) => status < 500,
|
||||
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
|
||||
});
|
||||
|
||||
if (response.status >= 400) {
|
||||
return res.status(404).json({ success: false, error: 'Icon not found' });
|
||||
}
|
||||
|
||||
const contentType = response.headers['content-type'] || 'image/png';
|
||||
res.setHeader('Content-Type', contentType);
|
||||
res.setHeader('Cache-Control', 'public, max-age=86400');
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.send(Buffer.from(response.data));
|
||||
} catch (error) {
|
||||
console.error('Error proxying icon:', error.message);
|
||||
res.status(500).json({ success: false, error: 'Failed to fetch icon' });
|
||||
}
|
||||
});
|
||||
|
||||
// Public API - Get incidents (read-only)
|
||||
router.get('/api/incidents', async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const incidents = await prisma.incident.findMany({ orderBy: { createdAt: 'desc' } });
|
||||
res.json({ success: true, incidents: incidents.map(i => ({ ...i, _id: i.id })) });
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Public API - Get posts (read-only, only published)
|
||||
router.get('/api/posts', async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const posts = await prisma.post.findMany({
|
||||
where: { published: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
res.json({ success: true, posts: posts.map(p => ({ ...p, _id: p.id })) });
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Public API - Get single post (read-only, only published)
|
||||
router.get('/api/posts/:id', async (req, res) => {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const post = await prisma.post.findFirst({
|
||||
where: { id: req.params.id, published: true },
|
||||
});
|
||||
|
||||
if (!post) {
|
||||
return res.status(404).json({ success: false, error: 'Post not found' });
|
||||
}
|
||||
|
||||
res.json({ success: true, post: { ...post, _id: post.id } });
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,192 @@
|
||||
const express = require('express');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const chalk = require('../utils/colors');
|
||||
const { getPrisma } = require('../config/prisma');
|
||||
const { isSetupComplete } = require('../middleware/setupCheck');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Get gateway IP using default-gateway package
|
||||
async function detectGateway() {
|
||||
try {
|
||||
const defaultGateway = require('default-gateway');
|
||||
// The package exports gateway4 and gateway6 for IPv4/IPv6
|
||||
const result = await defaultGateway.gateway4async();
|
||||
|
||||
if (result && result.gateway) {
|
||||
console.log(chalk.cyan(`Detected gateway: ${result.gateway}`));
|
||||
return result.gateway;
|
||||
}
|
||||
|
||||
console.warn(chalk.yellow('Could not detect gateway, no gateway found'));
|
||||
return null;
|
||||
} catch (err) {
|
||||
console.warn(chalk.yellow(`Gateway detection error: ${err.message}`));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// GET setup page
|
||||
router.get('/', async (req, res) => {
|
||||
// If already set up, redirect to admin
|
||||
if (isSetupComplete()) {
|
||||
return res.redirect('/admin/login');
|
||||
}
|
||||
|
||||
try {
|
||||
const detectedGateway = await detectGateway();
|
||||
res.render('setup/wizard', {
|
||||
detectedGateway: detectedGateway || null,
|
||||
error: null,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(chalk.red('Setup page error:'), err.message);
|
||||
res.render('setup/wizard', {
|
||||
detectedGateway: null,
|
||||
error: 'Failed to load setup page',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// POST setup form
|
||||
router.post('/', async (req, res) => {
|
||||
try {
|
||||
// If already set up, redirect to admin
|
||||
if (isSetupComplete()) {
|
||||
return res.redirect('/admin/login');
|
||||
}
|
||||
|
||||
const { adminUsername, adminPassword, passwordConfirm, gatewayIp } = req.body;
|
||||
|
||||
// Validation
|
||||
const errors = [];
|
||||
|
||||
if (!adminUsername || adminUsername.trim().length === 0) {
|
||||
errors.push('Admin username is required');
|
||||
}
|
||||
|
||||
if (!adminPassword || adminPassword.length < 6) {
|
||||
errors.push('Password must be at least 6 characters');
|
||||
}
|
||||
|
||||
if (adminPassword !== passwordConfirm) {
|
||||
errors.push('Passwords do not match');
|
||||
}
|
||||
|
||||
if (!gatewayIp || gatewayIp.trim().length === 0) {
|
||||
errors.push('Gateway IP is required');
|
||||
}
|
||||
|
||||
// Validate IP format
|
||||
const ipRegex = /^(\d{1,3}\.){3}\d{1,3}$/;
|
||||
if (gatewayIp && !ipRegex.test(gatewayIp)) {
|
||||
errors.push('Invalid IP address format');
|
||||
}
|
||||
|
||||
if (errors.length > 0) {
|
||||
const detectedGateway = await detectGateway();
|
||||
return res.status(400).render('setup/wizard', {
|
||||
detectedGateway: detectedGateway || '192.168.1.1',
|
||||
error: errors[0],
|
||||
formData: { adminUsername, gatewayIp },
|
||||
});
|
||||
}
|
||||
|
||||
// Update .env file
|
||||
const envPath = path.join(process.cwd(), '.env');
|
||||
let envContent = '';
|
||||
|
||||
if (fs.existsSync(envPath)) {
|
||||
envContent = fs.readFileSync(envPath, 'utf8');
|
||||
}
|
||||
|
||||
// Add admin credentials - handle both commented and uncommented lines
|
||||
if (!envContent.includes('ADMIN_PASSWORD') || envContent.includes('# ADMIN_PASSWORD')) {
|
||||
// Either no ADMIN_PASSWORD at all, or it's commented out - replace commented line or add new line
|
||||
if (envContent.includes('# ADMIN_PASSWORD')) {
|
||||
// Replace commented line with uncommented one
|
||||
envContent = envContent.replace(/# ADMIN_PASSWORD=.*/g, `ADMIN_PASSWORD=${adminPassword}`);
|
||||
envContent = envContent.replace(/# ADMIN_USERNAME=.*/g, `ADMIN_USERNAME=${adminUsername}`);
|
||||
} else {
|
||||
// Add new lines
|
||||
envContent += `\n# Admin Credentials (set during setup)\nADMIN_PASSWORD=${adminPassword}\nADMIN_USERNAME=${adminUsername}\n`;
|
||||
}
|
||||
} else {
|
||||
// Update existing uncommented lines
|
||||
envContent = envContent.replace(/ADMIN_PASSWORD=.*/g, `ADMIN_PASSWORD=${adminPassword}`);
|
||||
envContent = envContent.replace(/ADMIN_USERNAME=.*/g, `ADMIN_USERNAME=${adminUsername}`);
|
||||
}
|
||||
|
||||
fs.writeFileSync(envPath, envContent);
|
||||
|
||||
// Update in-memory environment variables so isSetupComplete() works
|
||||
process.env.ADMIN_PASSWORD = adminPassword;
|
||||
process.env.ADMIN_USERNAME = adminUsername;
|
||||
|
||||
// Create default monitors in database using Prisma
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
|
||||
// Create default targets
|
||||
const targets = [
|
||||
{
|
||||
name: 'Gateway',
|
||||
host: gatewayIp,
|
||||
protocol: 'ICMP',
|
||||
group: 'Network',
|
||||
position: 0,
|
||||
},
|
||||
{
|
||||
name: 'Cloudflare DNS',
|
||||
host: '1.1.1.1',
|
||||
protocol: 'ICMP',
|
||||
group: 'Network',
|
||||
position: 1,
|
||||
},
|
||||
];
|
||||
|
||||
for (const target of targets) {
|
||||
try {
|
||||
await prisma.target.create({
|
||||
data: {
|
||||
name: target.name,
|
||||
host: target.host,
|
||||
protocol: target.protocol,
|
||||
group: target.group,
|
||||
position: target.position,
|
||||
enabled: true,
|
||||
interval: 60,
|
||||
timeout: 30,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
// Ignore duplicate key errors (P2002 is Prisma's unique constraint error)
|
||||
if (err.code !== 'P2002') {
|
||||
console.error(chalk.yellow(`Warning creating ${target.name}:`), err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(chalk.red('Database error during setup:'), err.message);
|
||||
}
|
||||
|
||||
console.log(chalk.green('✓ Setup completed successfully'));
|
||||
|
||||
// Automatically log the user in after setup
|
||||
req.session.adminAuthenticated = true;
|
||||
|
||||
// Redirect to admin dashboard - middleware will set cookie automatically
|
||||
res.redirect('/admin');
|
||||
} catch (err) {
|
||||
console.error(chalk.red('Setup error:'), err.message);
|
||||
const detectedGateway = await detectGateway();
|
||||
res.status(500).render('setup/wizard', {
|
||||
detectedGateway: detectedGateway || '192.168.1.1',
|
||||
error: 'An error occurred during setup. Please try again.',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,147 @@
|
||||
// Slim, cache-friendly JSON for the static public site (src/site).
|
||||
const express = require('express');
|
||||
const { getPrisma } = require('../config/prisma');
|
||||
const monitorService = require('../services/monitorService');
|
||||
const router = express.Router();
|
||||
|
||||
const TTL = 30 * 1000;
|
||||
let cache = { at: 0, data: null, inflight: null };
|
||||
|
||||
async function build() {
|
||||
const prisma = getPrisma();
|
||||
const targets = await prisma.target.findMany({
|
||||
where: { enabled: true, publicVisible: true },
|
||||
select: { id: true, name: true, appUrl: true, appIcon: true, position: true, group: true, publicShowStatus: true, publicShowAppLink: true, description: true, tier: true, linkPublic: true },
|
||||
orderBy: { position: 'asc' },
|
||||
});
|
||||
const ids = targets.map((t) => t.id);
|
||||
const now = Date.now();
|
||||
const d1 = new Date(now - 24 * 3600e3), d30 = new Date(now - 30 * 24 * 3600e3);
|
||||
const end = Math.floor(now / 3600e3) * 3600, start = end - 23 * 3600;
|
||||
const [u24, u30, hourly] = ids.length ? await Promise.all([
|
||||
prisma.$queryRaw`SELECT "targetId", SUM("totalPings")::int t, SUM("successfulPings")::int s FROM statistics WHERE "targetId" = ANY(${ids}::text[]) AND date >= ${d1} GROUP BY "targetId"`,
|
||||
prisma.$queryRaw`SELECT "targetId", SUM("totalPings")::int t, SUM("successfulPings")::int s FROM statistics WHERE "targetId" = ANY(${ids}::text[]) AND date >= ${d30} GROUP BY "targetId"`,
|
||||
prisma.$queryRaw`
|
||||
SELECT "targetId", floor(extract(epoch from timestamp)/3600)::bigint*3600 AS b,
|
||||
count(*)::int t, sum(CASE WHEN success THEN 1 ELSE 0 END)::int s,
|
||||
COALESCE(avg("responseTime"),0)::int rt
|
||||
FROM "pingResults"
|
||||
WHERE "targetId" = ANY(${ids}::text[]) AND timestamp >= to_timestamp(${start}::bigint)
|
||||
GROUP BY 1,2`,
|
||||
]) : [[], [], []];
|
||||
const pct = (r) => (r && r.t ? Math.round((r.s / r.t) * 10000) / 100 : null);
|
||||
const m24 = new Map(u24.map((r) => [r.targetId, r])), m30 = new Map(u30.map((r) => [r.targetId, r]));
|
||||
const hb = new Map();
|
||||
for (const r of hourly) {
|
||||
if (!hb.has(r.targetId)) hb.set(r.targetId, new Map());
|
||||
hb.get(r.targetId).set(Number(r.b), r);
|
||||
}
|
||||
const services = targets.map((t) => {
|
||||
const status = monitorService.getTargetStatus(t.id);
|
||||
const h = hb.get(t.id) || new Map();
|
||||
// 24 hourly buckets: 0 = no data, 1 = ok, 2 = partial, 3 = down
|
||||
const bars = [];
|
||||
let rtSum = 0, rtN = 0;
|
||||
for (let i = 0; i < 24; i++) {
|
||||
const r = h.get(start + i * 3600);
|
||||
if (!r || !r.t) { bars.push(0); continue; }
|
||||
const f = r.s / r.t;
|
||||
bars.push(f >= 0.98 ? 1 : f >= 0.5 ? 2 : 3);
|
||||
if (r.rt) { rtSum += r.rt; rtN++; }
|
||||
}
|
||||
return {
|
||||
id: t.id, name: t.name, status,
|
||||
url: t.publicShowAppLink !== false && t.linkPublic !== false ? t.appUrl || null : null,
|
||||
description: t.description || null, tier: t.tier || 'normal',
|
||||
icon: t.appIcon || null, group: t.group || null,
|
||||
up24: pct(m24.get(t.id)), up30: pct(m30.get(t.id)),
|
||||
rt: rtN ? Math.round(rtSum / rtN) : null, bars,
|
||||
};
|
||||
});
|
||||
const down = services.filter((s) => s.status === 'down').length;
|
||||
const incidents = (await prisma.incident.findMany({ orderBy: { createdAt: 'desc' }, take: 30 })).map((i) => ({
|
||||
id: i.id, title: i.title, description: i.description, severity: i.severity, status: i.status,
|
||||
services: i.affectedServices || [], updates: i.updates || [],
|
||||
scheduled: i.isScheduled, start: i.scheduledStart, end: i.scheduledEnd,
|
||||
createdAt: i.createdAt, resolvedAt: i.resolvedAt,
|
||||
}));
|
||||
return {
|
||||
generatedAt: new Date().toISOString(),
|
||||
overall: !services.length ? 'unknown' : down === 0 ? 'operational' : down === services.length ? 'down' : 'degraded',
|
||||
up: services.filter((s) => s.status === 'up').length, down, total: services.length,
|
||||
services, incidents,
|
||||
};
|
||||
}
|
||||
|
||||
async function get() {
|
||||
if (cache.data && Date.now() - cache.at < TTL) return cache.data;
|
||||
if (!cache.inflight) {
|
||||
cache.inflight = build().then((d) => { cache = { at: Date.now(), data: d, inflight: null }; return d; })
|
||||
.catch((e) => { cache.inflight = null; if (cache.data) return cache.data; throw e; });
|
||||
}
|
||||
return cache.inflight;
|
||||
}
|
||||
|
||||
router.get('/api/site/summary', async (req, res) => {
|
||||
try {
|
||||
const d = await get();
|
||||
res.set('Cache-Control', 'public, max-age=15, stale-while-revalidate=60');
|
||||
res.json(d);
|
||||
} catch (e) { res.status(500).json({ error: 'unavailable' }); }
|
||||
});
|
||||
|
||||
router.get('/api/site/news', async (req, res) => {
|
||||
try {
|
||||
const posts = await getPrisma().post.findMany({ where: { published: true }, orderBy: { createdAt: 'desc' }, take: 50 });
|
||||
res.set('Cache-Control', 'public, max-age=60, stale-while-revalidate=300');
|
||||
res.json({ posts: posts.map((p) => ({ id: p.id, title: p.title, content: p.content, createdAt: p.createdAt, updatedAt: p.updatedAt })) });
|
||||
} catch (e) { res.status(500).json({ error: 'unavailable' }); }
|
||||
});
|
||||
|
||||
router.get('/api/site/news.rss', async (req, res) => {
|
||||
try {
|
||||
const base = process.env.SITE_URL || `${req.protocol}://${req.get('host')}`;
|
||||
const esc = (s) => String(s).replace(/[<>&"]/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"' }[c]));
|
||||
const posts = await getPrisma().post.findMany({ where: { published: true }, orderBy: { createdAt: 'desc' }, take: 30 });
|
||||
res.type('application/rss+xml').send(`<?xml version="1.0"?><rss version="2.0"><channel><title>${esc(process.env.SITE_NAME || 'Status')} news</title><link>${base}/news</link><description>News and status updates</description>${posts.map((p) => `<item><title>${esc(p.title)}</title><link>${base}/news#${p.id}</link><guid isPermaLink="false">${p.id}</guid><pubDate>${p.createdAt.toUTCString()}</pubDate><description>${esc(p.content)}</description></item>`).join('')}</channel></rss>`);
|
||||
} catch (e) { res.status(500).end(); }
|
||||
});
|
||||
|
||||
router.get('/api/site/tools/ip', (req, res) => {
|
||||
const ip = req.headers['cf-connecting-ip'] || req.ip;
|
||||
res.set('Cache-Control', 'no-store');
|
||||
res.json({ ip });
|
||||
});
|
||||
|
||||
// ---- Branding / PWA ----
|
||||
const fs = require('fs'), path = require('path');
|
||||
const BR = path.join(__dirname, '..', 'site', 'brand');
|
||||
let brandCache = null;
|
||||
async function brand() {
|
||||
if (brandCache && Date.now() - brandCache.at < 15000) return brandCache.v;
|
||||
let b = null;
|
||||
try { b = await getPrisma().siteBrand.findUnique({ where: { id: 'brand' } }); } catch (e) {}
|
||||
const v = { name: b?.name || process.env.SITE_NAME || 'LocalPing', accent: b?.accent || '#6ea8ff', tagline: b?.tagline || '', icon: b?.iconData ? Buffer.from(b.iconData) : null, iconType: b?.iconType || 'image/png', v: b?.updatedAt?.getTime() || 0 };
|
||||
brandCache = { at: Date.now(), v };
|
||||
return v;
|
||||
}
|
||||
router.get('/api/site/brand', async (req, res) => { const b = await brand(); res.set('Cache-Control', 'public, max-age=60'); res.json({ name: b.name, accent: b.accent, tagline: b.tagline, v: b.v }); });
|
||||
router.get(['/brand/icon.svg', '/brand/icon-:size.png', '/favicon.ico'], async (req, res) => {
|
||||
const b = await brand();
|
||||
res.set('Cache-Control', 'public, max-age=3600');
|
||||
if (b.icon) return res.type(b.iconType).send(b.icon);
|
||||
if (req.path.endsWith('.svg')) return res.type('image/svg+xml').sendFile(path.join(BR, 'icon.svg'));
|
||||
const size = [512, 192, 180, 32].includes(+req.params.size) ? +req.params.size : req.path === '/favicon.ico' ? 32 : 512;
|
||||
res.type('image/png').sendFile(path.join(BR, `icon-${size}.png`));
|
||||
});
|
||||
router.get('/manifest.webmanifest', async (req, res) => {
|
||||
const b = await brand();
|
||||
res.type('application/manifest+json').set('Cache-Control', 'public, max-age=300').json({
|
||||
name: b.name, short_name: b.name.slice(0, 12), start_url: '/', display: 'standalone', background_color: '#0b0d12', theme_color: b.accent,
|
||||
icons: [192, 512].map((n) => ({ src: `/brand/icon-${n}.png?v=${b.v}`, sizes: `${n}x${n}`, type: 'image/png', purpose: 'any maskable' })),
|
||||
});
|
||||
});
|
||||
router.invalidateBrand = () => { brandCache = null; };
|
||||
router.invalidate = () => { cache = { at: 0, data: null, inflight: null }; };
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,235 @@
|
||||
const { exec } = require('child_process');
|
||||
const { promisify } = require('util');
|
||||
const axios = require('axios');
|
||||
const chalk = require('../utils/colors');
|
||||
const sh = require('shell-escape');
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
class ActionService {
|
||||
/**
|
||||
* Execute a quick-fix action
|
||||
*/
|
||||
async executeAction(action) {
|
||||
try {
|
||||
const start = Date.now();
|
||||
|
||||
switch (action.type) {
|
||||
case 'command':
|
||||
return await this.executeCommand(action);
|
||||
case 'ssh':
|
||||
return await this.executeSSH(action);
|
||||
case 'http':
|
||||
return await this.executeHTTP(action);
|
||||
case 'script':
|
||||
return await this.executeScript(action);
|
||||
default:
|
||||
return {
|
||||
success: false,
|
||||
error: 'Unknown action type: ' + action.type,
|
||||
executionTime: Date.now() - start,
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.message,
|
||||
executionTime: 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a local shell command
|
||||
*/
|
||||
async executeCommand(action) {
|
||||
const start = Date.now();
|
||||
|
||||
try {
|
||||
const { stdout, stderr } = await execAsync(action.command, {
|
||||
timeout: action.timeout || 30000,
|
||||
maxBuffer: 1024 * 1024 * 10, // 10MB
|
||||
});
|
||||
|
||||
const executionTime = Date.now() - start;
|
||||
|
||||
return {
|
||||
success: true,
|
||||
stdout,
|
||||
stderr,
|
||||
executionTime,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.message,
|
||||
stdout: error.stdout,
|
||||
stderr: error.stderr,
|
||||
executionTime: Date.now() - start,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a command via SSH
|
||||
*/
|
||||
async executeSSH(action) {
|
||||
const start = Date.now();
|
||||
|
||||
try {
|
||||
// Build SSH command with proper argument escaping
|
||||
const sshArgs = [];
|
||||
|
||||
// Add port if specified
|
||||
if (action.port) {
|
||||
sshArgs.push('-p', String(action.port));
|
||||
}
|
||||
|
||||
// Add user@host
|
||||
const host = action.user ? `${action.user}@${action.host}` : action.host;
|
||||
sshArgs.push(host);
|
||||
|
||||
// Add the remote command - properly escaped
|
||||
sshArgs.push(action.command);
|
||||
|
||||
// Use shell-escape to properly quote the entire command
|
||||
const cmd = sh(['ssh', ...sshArgs]);
|
||||
|
||||
const { stdout, stderr } = await execAsync(cmd, {
|
||||
timeout: action.timeout || 30000,
|
||||
maxBuffer: 1024 * 1024 * 10,
|
||||
});
|
||||
|
||||
const executionTime = Date.now() - start;
|
||||
|
||||
return {
|
||||
success: true,
|
||||
stdout,
|
||||
stderr,
|
||||
executionTime,
|
||||
host: action.host,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.message,
|
||||
stdout: error.stdout,
|
||||
stderr: error.stderr,
|
||||
executionTime: Date.now() - start,
|
||||
host: action.host,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute an HTTP request
|
||||
*/
|
||||
async executeHTTP(action) {
|
||||
const start = Date.now();
|
||||
|
||||
try {
|
||||
const method = action.method || 'GET';
|
||||
const url = action.url;
|
||||
const headers = action.headers || {};
|
||||
const data = action.data || null;
|
||||
|
||||
const response = await axios({
|
||||
method,
|
||||
url,
|
||||
headers,
|
||||
data,
|
||||
timeout: action.timeout || 10000,
|
||||
validateStatus: () => true,
|
||||
});
|
||||
|
||||
const executionTime = Date.now() - start;
|
||||
|
||||
return {
|
||||
success: response.status >= 200 && response.status < 400,
|
||||
statusCode: response.status,
|
||||
responseData: response.data,
|
||||
executionTime,
|
||||
url,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.message,
|
||||
executionTime: Date.now() - start,
|
||||
url: action.url,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a script file
|
||||
*/
|
||||
async executeScript(action) {
|
||||
const start = Date.now();
|
||||
|
||||
try {
|
||||
// Build script command with proper argument escaping
|
||||
const scriptArgs = [action.scriptPath];
|
||||
|
||||
// Add arguments if provided - each argument is separately escaped
|
||||
if (action.args && Array.isArray(action.args)) {
|
||||
scriptArgs.push(...action.args);
|
||||
}
|
||||
|
||||
// Use shell-escape to properly quote the command and arguments
|
||||
const cmd = sh(scriptArgs);
|
||||
|
||||
const { stdout, stderr } = await execAsync(cmd, {
|
||||
timeout: action.timeout || 60000,
|
||||
maxBuffer: 1024 * 1024 * 10,
|
||||
});
|
||||
|
||||
const executionTime = Date.now() - start;
|
||||
|
||||
return {
|
||||
success: true,
|
||||
stdout,
|
||||
stderr,
|
||||
executionTime,
|
||||
script: action.scriptPath,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.message,
|
||||
stdout: error.stdout,
|
||||
stderr: error.stderr,
|
||||
executionTime: Date.now() - start,
|
||||
script: action.scriptPath,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute multiple actions in sequence
|
||||
*/
|
||||
async executeActionSequence(actions) {
|
||||
const results = [];
|
||||
|
||||
for (const action of actions) {
|
||||
const result = await this.executeAction(action);
|
||||
results.push(result);
|
||||
|
||||
// Stop on first failure if stopOnError is true
|
||||
if (!result.success && action.stopOnError) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute multiple actions in parallel
|
||||
*/
|
||||
async executeActionParallel(actions) {
|
||||
return Promise.all(actions.map((action) => this.executeAction(action)));
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new ActionService();
|
||||
@@ -0,0 +1,451 @@
|
||||
const { getPrisma } = require('../config/prisma');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
/**
|
||||
* Export data from the database
|
||||
* @param {Object} options - Export options
|
||||
* @param {boolean} options.full - Export everything
|
||||
* @param {boolean} options.monitors - Export monitors (targets)
|
||||
* @param {boolean} options.incidents - Export incidents
|
||||
* @param {boolean} options.posts - Export blog posts
|
||||
* @param {boolean} options.dataPoints - Export ping results and statistics
|
||||
* @param {boolean} options.actions - Export actions
|
||||
* @param {boolean} options.alerts - Export alerts
|
||||
* @param {boolean} options.settings - Export admin and public UI settings
|
||||
* @param {boolean} options.favicons - Export favicons
|
||||
* @returns {Promise<Object>} Exported data
|
||||
*/
|
||||
async function exportData(options = {}) {
|
||||
const prisma = getPrisma();
|
||||
const exportResult = {
|
||||
version: '1.0.0',
|
||||
exportDate: new Date().toISOString(),
|
||||
data: {}
|
||||
};
|
||||
|
||||
// If full export, set all options to true
|
||||
if (options.full) {
|
||||
options.monitors = true;
|
||||
options.incidents = true;
|
||||
options.posts = true;
|
||||
options.dataPoints = true;
|
||||
options.actions = true;
|
||||
options.alerts = true;
|
||||
options.settings = true;
|
||||
options.favicons = true;
|
||||
}
|
||||
|
||||
// Export monitors (targets)
|
||||
if (options.monitors) {
|
||||
const targets = await prisma.target.findMany();
|
||||
// Map id to _id for compatibility
|
||||
exportResult.data.targets = targets.map(target => ({
|
||||
...target,
|
||||
_id: target.id,
|
||||
}));
|
||||
}
|
||||
|
||||
// Export incidents
|
||||
if (options.incidents) {
|
||||
const incidents = await prisma.incident.findMany();
|
||||
exportResult.data.incidents = incidents.map(inc => ({ ...inc, _id: inc.id }));
|
||||
}
|
||||
|
||||
// Export posts
|
||||
if (options.posts) {
|
||||
const posts = await prisma.post.findMany();
|
||||
exportResult.data.posts = posts.map(post => ({ ...post, _id: post.id }));
|
||||
}
|
||||
|
||||
// Export data points (ping results and statistics)
|
||||
if (options.dataPoints) {
|
||||
const pingResults = await prisma.pingResult.findMany();
|
||||
const statistics = await prisma.statistic.findMany();
|
||||
|
||||
// Map id to _id for compatibility
|
||||
exportResult.data.pingResults = pingResults.map(pr => ({ ...pr, _id: pr.id }));
|
||||
exportResult.data.statistics = statistics.map(s => ({ ...s, _id: s.id }));
|
||||
|
||||
// Legacy format names for compatibility
|
||||
exportResult.data.ping_results = exportResult.data.pingResults;
|
||||
exportResult.data.daily_stats = exportResult.data.statistics;
|
||||
}
|
||||
|
||||
// Export actions
|
||||
if (options.actions) {
|
||||
const actions = await prisma.action.findMany();
|
||||
exportResult.data.actions = actions.map(a => ({ ...a, _id: a.id }));
|
||||
}
|
||||
|
||||
// Export alerts
|
||||
if (options.alerts) {
|
||||
const alerts = await prisma.alert.findMany();
|
||||
exportResult.data.alerts = alerts.map(a => ({ ...a, _id: a.id }));
|
||||
}
|
||||
|
||||
// Export settings
|
||||
if (options.settings) {
|
||||
const adminSettings = await prisma.adminSettings.findUnique({ where: { id: 'settings' } });
|
||||
const publicUISettings = await prisma.publicUISettings.findUnique({ where: { id: 'settings' } });
|
||||
exportResult.data.adminSettings = adminSettings ? { ...adminSettings, _id: adminSettings.id } : null;
|
||||
exportResult.data.publicUISettings = publicUISettings ? { ...publicUISettings, _id: publicUISettings.id } : null;
|
||||
}
|
||||
|
||||
// Export favicons
|
||||
if (options.favicons) {
|
||||
const favicons = await prisma.favicon.findMany();
|
||||
exportResult.data.favicons = favicons.map(f => ({ ...f, _id: f.id }));
|
||||
}
|
||||
|
||||
return exportResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Import data into the database
|
||||
* @param {Object} importData - Data to import
|
||||
* @param {Object} options - Import options
|
||||
* @param {boolean} options.overwrite - Overwrite existing data
|
||||
* @returns {Promise<Object>} Import result
|
||||
*/
|
||||
async function importData(importDataObj, options = {}) {
|
||||
const prisma = getPrisma();
|
||||
const results = {
|
||||
imported: {},
|
||||
errors: []
|
||||
};
|
||||
|
||||
try {
|
||||
// Validate import data structure
|
||||
if (!importDataObj.data || typeof importDataObj.data !== 'object') {
|
||||
throw new Error('Invalid import data format');
|
||||
}
|
||||
|
||||
// Import targets (monitors)
|
||||
if (importDataObj.data.targets && Array.isArray(importDataObj.data.targets)) {
|
||||
try {
|
||||
let imported = 0;
|
||||
let updated = 0;
|
||||
let skipped = 0;
|
||||
for (const target of importDataObj.data.targets) {
|
||||
try {
|
||||
const targetId = target.id || target._id;
|
||||
// Check if target exists by id
|
||||
const existingById = await prisma.target.findUnique({ where: { id: targetId } });
|
||||
if (existingById) {
|
||||
if (options.overwrite) {
|
||||
const { id, _id, ...updateData } = target;
|
||||
await prisma.target.update({
|
||||
where: { id: targetId },
|
||||
data: updateData,
|
||||
});
|
||||
updated++;
|
||||
} else {
|
||||
skipped++;
|
||||
}
|
||||
} else {
|
||||
// Check if target with same name exists (UNIQUE constraint on name)
|
||||
const existingByName = await prisma.target.findUnique({ where: { name: target.name } });
|
||||
if (existingByName) {
|
||||
if (options.overwrite) {
|
||||
const { id, _id, ...updateData } = target;
|
||||
await prisma.target.update({
|
||||
where: { id: existingByName.id },
|
||||
data: updateData,
|
||||
});
|
||||
updated++;
|
||||
} else {
|
||||
skipped++;
|
||||
}
|
||||
} else {
|
||||
const { _id, ...insertData } = target;
|
||||
await prisma.target.create({
|
||||
data: {
|
||||
id: targetId,
|
||||
...insertData,
|
||||
},
|
||||
});
|
||||
imported++;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// Handle individual target errors (e.g., UNIQUE constraint)
|
||||
if (error.code === 'P2002') {
|
||||
skipped++;
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
results.imported.targets = { imported, updated, skipped };
|
||||
} catch (error) {
|
||||
results.errors.push({ type: 'targets', error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
// Import incidents
|
||||
if (importDataObj.data.incidents && Array.isArray(importDataObj.data.incidents)) {
|
||||
try {
|
||||
let imported = 0;
|
||||
let updated = 0;
|
||||
for (const incident of importDataObj.data.incidents) {
|
||||
const incidentId = incident.id || incident._id;
|
||||
const existing = await prisma.incident.findUnique({ where: { id: incidentId } });
|
||||
if (existing) {
|
||||
if (options.overwrite) {
|
||||
const { id, _id, ...updateData } = incident;
|
||||
await prisma.incident.update({ where: { id: incidentId }, data: updateData });
|
||||
updated++;
|
||||
}
|
||||
} else {
|
||||
const { _id, ...insertData } = incident;
|
||||
await prisma.incident.create({ data: { id: incidentId, ...insertData } });
|
||||
imported++;
|
||||
}
|
||||
}
|
||||
results.imported.incidents = { imported, updated };
|
||||
} catch (error) {
|
||||
results.errors.push({ type: 'incidents', error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
// Import posts
|
||||
if (importDataObj.data.posts && Array.isArray(importDataObj.data.posts)) {
|
||||
try {
|
||||
let imported = 0;
|
||||
let updated = 0;
|
||||
for (const post of importDataObj.data.posts) {
|
||||
const postId = post.id || post._id;
|
||||
const existing = await prisma.post.findUnique({ where: { id: postId } });
|
||||
if (existing) {
|
||||
if (options.overwrite) {
|
||||
const { id, _id, ...updateData } = post;
|
||||
await prisma.post.update({ where: { id: postId }, data: updateData });
|
||||
updated++;
|
||||
}
|
||||
} else {
|
||||
const { _id, ...insertData } = post;
|
||||
await prisma.post.create({ data: { id: postId, ...insertData } });
|
||||
imported++;
|
||||
}
|
||||
}
|
||||
results.imported.posts = { imported, updated };
|
||||
} catch (error) {
|
||||
results.errors.push({ type: 'posts', error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
// Import data points
|
||||
if (importDataObj.data.pingResults && Array.isArray(importDataObj.data.pingResults)) {
|
||||
try {
|
||||
let imported = 0;
|
||||
for (const pingResult of importDataObj.data.pingResults) {
|
||||
const pingResultId = pingResult.id || pingResult._id;
|
||||
const existing = await prisma.pingResult.findUnique({ where: { id: pingResultId } });
|
||||
if (!existing) {
|
||||
const { _id, ...insertData } = pingResult;
|
||||
await prisma.pingResult.create({ data: { id: pingResultId, ...insertData } });
|
||||
imported++;
|
||||
}
|
||||
}
|
||||
results.imported.pingResults = { imported };
|
||||
} catch (error) {
|
||||
results.errors.push({ type: 'pingResults', error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
if (importDataObj.data.statistics && Array.isArray(importDataObj.data.statistics)) {
|
||||
try {
|
||||
let imported = 0;
|
||||
for (const stat of importDataObj.data.statistics) {
|
||||
const statId = stat.id || stat._id;
|
||||
const existing = await prisma.statistic.findUnique({ where: { id: statId } });
|
||||
if (!existing) {
|
||||
const { _id, ...insertData } = stat;
|
||||
await prisma.statistic.create({ data: { id: statId, ...insertData } });
|
||||
imported++;
|
||||
}
|
||||
}
|
||||
results.imported.statistics = { imported };
|
||||
} catch (error) {
|
||||
results.errors.push({ type: 'statistics', error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
// Import ping_results (legacy format) - convert to pingResults
|
||||
if (importDataObj.data.ping_results && Array.isArray(importDataObj.data.ping_results)) {
|
||||
try {
|
||||
let imported = 0;
|
||||
for (const pingResult of importDataObj.data.ping_results) {
|
||||
try {
|
||||
await prisma.pingResult.create({
|
||||
data: {
|
||||
targetId: pingResult.targetId,
|
||||
success: pingResult.success === 1 || pingResult.success === true,
|
||||
responseTime: pingResult.responseTime || null,
|
||||
timestamp: pingResult.timestamp ? new Date(pingResult.timestamp) : new Date(),
|
||||
statusCode: pingResult.statusCode || null,
|
||||
error: pingResult.error || null,
|
||||
protocol: pingResult.protocol || null,
|
||||
},
|
||||
});
|
||||
imported++;
|
||||
} catch (error) {
|
||||
// Skip duplicates
|
||||
}
|
||||
}
|
||||
results.imported.ping_results = { imported };
|
||||
} catch (error) {
|
||||
results.errors.push({ type: 'ping_results', error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
// Import daily_stats (legacy format) - convert to statistics
|
||||
if (importDataObj.data.daily_stats && Array.isArray(importDataObj.data.daily_stats)) {
|
||||
try {
|
||||
let imported = 0;
|
||||
for (const stat of importDataObj.data.daily_stats) {
|
||||
try {
|
||||
await prisma.statistic.create({
|
||||
data: {
|
||||
targetId: stat.targetId,
|
||||
date: stat.date ? new Date(stat.date) : new Date(),
|
||||
totalPings: stat.totalPings || 0,
|
||||
successfulPings: stat.successfulPings || 0,
|
||||
failedPings: (stat.totalPings || 0) - (stat.successfulPings || 0),
|
||||
uptime: stat.totalPings > 0 ? (stat.successfulPings / stat.totalPings) * 100 : 0,
|
||||
lastResponseTime: 0,
|
||||
avgResponseTime: stat.avgResponseTime || 0,
|
||||
minResponseTime: stat.minResponseTime || null,
|
||||
maxResponseTime: stat.maxResponseTime || null,
|
||||
},
|
||||
});
|
||||
imported++;
|
||||
} catch (error) {
|
||||
// Skip duplicates
|
||||
}
|
||||
}
|
||||
results.imported.daily_stats = { imported };
|
||||
} catch (error) {
|
||||
results.errors.push({ type: 'daily_stats', error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
// Import actions
|
||||
if (importDataObj.data.actions && Array.isArray(importDataObj.data.actions)) {
|
||||
try {
|
||||
let imported = 0;
|
||||
let updated = 0;
|
||||
for (const action of importDataObj.data.actions) {
|
||||
const actionId = action.id || action._id;
|
||||
const existing = await prisma.action.findUnique({ where: { id: actionId } });
|
||||
if (existing) {
|
||||
if (options.overwrite) {
|
||||
const { id, _id, ...updateData } = action;
|
||||
await prisma.action.update({ where: { id: actionId }, data: updateData });
|
||||
updated++;
|
||||
}
|
||||
} else {
|
||||
const { _id, ...insertData } = action;
|
||||
await prisma.action.create({ data: { id: actionId, ...insertData } });
|
||||
imported++;
|
||||
}
|
||||
}
|
||||
results.imported.actions = { imported, updated };
|
||||
} catch (error) {
|
||||
results.errors.push({ type: 'actions', error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
// Import alerts
|
||||
if (importDataObj.data.alerts && Array.isArray(importDataObj.data.alerts)) {
|
||||
try {
|
||||
let imported = 0;
|
||||
for (const alert of importDataObj.data.alerts) {
|
||||
const alertId = alert.id || alert._id;
|
||||
const existing = await prisma.alert.findUnique({ where: { id: alertId } });
|
||||
if (!existing) {
|
||||
const { _id, ...insertData } = alert;
|
||||
await prisma.alert.create({ data: { id: alertId, ...insertData } });
|
||||
imported++;
|
||||
}
|
||||
}
|
||||
results.imported.alerts = { imported };
|
||||
} catch (error) {
|
||||
results.errors.push({ type: 'alerts', error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
// Import settings
|
||||
if (importDataObj.data.adminSettings) {
|
||||
try {
|
||||
const existing = await prisma.adminSettings.findUnique({ where: { id: 'settings' } });
|
||||
const { id, _id, ...settingsData } = importDataObj.data.adminSettings;
|
||||
if (existing) {
|
||||
if (options.overwrite) {
|
||||
await prisma.adminSettings.update({ where: { id: 'settings' }, data: settingsData });
|
||||
results.imported.adminSettings = { updated: 1 };
|
||||
}
|
||||
} else {
|
||||
await prisma.adminSettings.create({ data: { id: 'settings', ...settingsData } });
|
||||
results.imported.adminSettings = { imported: 1 };
|
||||
}
|
||||
} catch (error) {
|
||||
results.errors.push({ type: 'adminSettings', error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
if (importDataObj.data.publicUISettings) {
|
||||
try {
|
||||
const existing = await prisma.publicUISettings.findUnique({ where: { id: 'settings' } });
|
||||
const { id, _id, ...settingsData } = importDataObj.data.publicUISettings;
|
||||
if (existing) {
|
||||
if (options.overwrite) {
|
||||
await prisma.publicUISettings.update({ where: { id: 'settings' }, data: settingsData });
|
||||
results.imported.publicUISettings = { updated: 1 };
|
||||
}
|
||||
} else {
|
||||
await prisma.publicUISettings.create({ data: { id: 'settings', ...settingsData } });
|
||||
results.imported.publicUISettings = { imported: 1 };
|
||||
}
|
||||
} catch (error) {
|
||||
results.errors.push({ type: 'publicUISettings', error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
// Import favicons
|
||||
if (importDataObj.data.favicons && Array.isArray(importDataObj.data.favicons)) {
|
||||
try {
|
||||
let imported = 0;
|
||||
let updated = 0;
|
||||
for (const favicon of importDataObj.data.favicons) {
|
||||
const faviconId = favicon.id || favicon._id;
|
||||
const existing = await prisma.favicon.findUnique({ where: { id: faviconId } });
|
||||
if (existing) {
|
||||
if (options.overwrite) {
|
||||
const { id, _id, ...updateData } = favicon;
|
||||
await prisma.favicon.update({ where: { id: faviconId }, data: updateData });
|
||||
updated++;
|
||||
}
|
||||
} else {
|
||||
const { _id, ...insertData } = favicon;
|
||||
await prisma.favicon.create({ data: { id: faviconId, ...insertData } });
|
||||
imported++;
|
||||
}
|
||||
}
|
||||
results.imported.favicons = { imported, updated };
|
||||
} catch (error) {
|
||||
results.errors.push({ type: 'favicons', error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
} catch (error) {
|
||||
throw new Error(`Import failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
exportData,
|
||||
importData,
|
||||
};
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* In-memory cache service for database queries
|
||||
* Improves performance by caching frequently accessed data
|
||||
*/
|
||||
|
||||
class CacheService {
|
||||
constructor() {
|
||||
this.cache = new Map();
|
||||
this.defaultTTL = 60000; // 60 seconds default TTL
|
||||
this.maxSize = 1000; // Maximum cache entries
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a cache key from collection name and query
|
||||
*/
|
||||
generateKey(collection, query, options = {}) {
|
||||
const queryStr = JSON.stringify(query || {});
|
||||
const optionsStr = JSON.stringify(options || {});
|
||||
return `${collection}:${queryStr}:${optionsStr}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get cached value
|
||||
*/
|
||||
get(key) {
|
||||
const entry = this.cache.get(key);
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check if expired
|
||||
if (Date.now() > entry.expiresAt) {
|
||||
this.cache.delete(key);
|
||||
return null;
|
||||
}
|
||||
|
||||
return entry.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set cached value with TTL
|
||||
*/
|
||||
set(key, value, ttl = null) {
|
||||
// If cache is too large, remove oldest entries
|
||||
if (this.cache.size >= this.maxSize) {
|
||||
this.evictOldest();
|
||||
}
|
||||
|
||||
const expiresAt = Date.now() + (ttl || this.defaultTTL);
|
||||
this.cache.set(key, { value, expiresAt, createdAt: Date.now() });
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove entry from cache
|
||||
*/
|
||||
delete(key) {
|
||||
this.cache.delete(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate all entries for a collection
|
||||
*/
|
||||
invalidateCollection(collection) {
|
||||
const keysToDelete = [];
|
||||
for (const key of this.cache.keys()) {
|
||||
if (key.startsWith(`${collection}:`)) {
|
||||
keysToDelete.push(key);
|
||||
}
|
||||
}
|
||||
keysToDelete.forEach(key => this.cache.delete(key));
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate all cache entries
|
||||
*/
|
||||
clear() {
|
||||
this.cache.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove oldest entries when cache is full
|
||||
*/
|
||||
evictOldest() {
|
||||
const entries = Array.from(this.cache.entries())
|
||||
.map(([key, value]) => ({ key, createdAt: value.createdAt }))
|
||||
.sort((a, b) => a.createdAt - b.createdAt);
|
||||
|
||||
// Remove oldest 10% of entries
|
||||
const toRemove = Math.max(1, Math.floor(entries.length * 0.1));
|
||||
for (let i = 0; i < toRemove; i++) {
|
||||
this.cache.delete(entries[i].key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get cache statistics
|
||||
*/
|
||||
getStats() {
|
||||
const now = Date.now();
|
||||
let expired = 0;
|
||||
let active = 0;
|
||||
|
||||
for (const entry of this.cache.values()) {
|
||||
if (now > entry.expiresAt) {
|
||||
expired++;
|
||||
} else {
|
||||
active++;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
total: this.cache.size,
|
||||
active,
|
||||
expired,
|
||||
maxSize: this.maxSize,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Singleton instance
|
||||
const cacheService = new CacheService();
|
||||
|
||||
module.exports = cacheService;
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
const { getPrisma } = require('../config/prisma');
|
||||
const chalk = require('../utils/colors');
|
||||
|
||||
/**
|
||||
* Data Retention Service
|
||||
*
|
||||
* Manages data retention by:
|
||||
* 1. Keeping all data points within the retention period
|
||||
* 2. For data older than retention period, minimizing data points
|
||||
* by keeping only important ones (min, max, and strategic samples)
|
||||
*/
|
||||
class DataRetentionService {
|
||||
/**
|
||||
* Get data retention settings
|
||||
*/
|
||||
async getRetentionSettings() {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const settings = await prisma.adminSettings.findUnique({ where: { id: 'settings' } });
|
||||
return settings?.dataRetentionDays || 30;
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error getting retention settings:'), error.message);
|
||||
return 30; // Default to 30 days
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process data retention for a specific target
|
||||
* Optimized strategy:
|
||||
* - Last 30 days: Keep all raw data (for 1H, 24H, 7D, 30D graphs)
|
||||
* - 31-90 days: Aggregate to hourly buckets (keep 1 point per hour)
|
||||
* - 90+ days: Aggregate to daily buckets (keep 1 point per day)
|
||||
* - Statistics table always maintained for uptime calculations
|
||||
*/
|
||||
async processRetentionForTarget(targetId) {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const now = new Date();
|
||||
|
||||
// Define retention periods
|
||||
const keepRawDays = 30; // Keep all raw data for last 30 days
|
||||
const keepHourlyDays = 90; // Keep hourly aggregations for 31-90 days
|
||||
|
||||
const rawCutoff = new Date(now);
|
||||
rawCutoff.setDate(rawCutoff.getDate() - keepRawDays);
|
||||
|
||||
const hourlyCutoff = new Date(now);
|
||||
hourlyCutoff.setDate(hourlyCutoff.getDate() - keepHourlyDays);
|
||||
|
||||
let totalDeleted = 0;
|
||||
|
||||
// Step 1: Process 31-90 days range - aggregate to hourly buckets
|
||||
const hourlyData = await prisma.pingResult.findMany({
|
||||
where: {
|
||||
targetId: targetId,
|
||||
timestamp: {
|
||||
gte: hourlyCutoff,
|
||||
lt: rawCutoff,
|
||||
},
|
||||
},
|
||||
orderBy: { timestamp: 'asc' },
|
||||
});
|
||||
|
||||
if (hourlyData.length > 0) {
|
||||
// Group by hour
|
||||
const hourlyBuckets = new Map();
|
||||
hourlyData.forEach(row => {
|
||||
const hourKey = new Date(row.timestamp);
|
||||
hourKey.setMinutes(0, 0, 0);
|
||||
const key = hourKey.toISOString();
|
||||
|
||||
if (!hourlyBuckets.has(key)) {
|
||||
hourlyBuckets.set(key, []);
|
||||
}
|
||||
hourlyBuckets.get(key).push(row);
|
||||
});
|
||||
|
||||
// For each hour, keep only representative points (min, max, first, last, status changes)
|
||||
const idsToKeep = new Set();
|
||||
|
||||
for (const [hourKey, hourData] of hourlyBuckets.entries()) {
|
||||
if (hourData.length === 0) continue;
|
||||
|
||||
// Always keep first and last of the hour
|
||||
idsToKeep.add(hourData[0].id);
|
||||
idsToKeep.add(hourData[hourData.length - 1].id);
|
||||
|
||||
// Keep min and max response times
|
||||
const withResponseTime = hourData.filter(d => d.responseTime !== null);
|
||||
if (withResponseTime.length > 0) {
|
||||
const minPoint = withResponseTime.reduce((min, d) =>
|
||||
d.responseTime < min.responseTime ? d : min
|
||||
);
|
||||
const maxPoint = withResponseTime.reduce((max, d) =>
|
||||
d.responseTime > max.responseTime ? d : max
|
||||
);
|
||||
idsToKeep.add(minPoint.id);
|
||||
idsToKeep.add(maxPoint.id);
|
||||
}
|
||||
|
||||
// Keep status change points
|
||||
for (let i = 1; i < hourData.length; i++) {
|
||||
if (hourData[i].success !== hourData[i - 1].success) {
|
||||
idsToKeep.add(hourData[i - 1].id);
|
||||
idsToKeep.add(hourData[i].id);
|
||||
}
|
||||
}
|
||||
|
||||
// If hour has many points, sample evenly (keep ~5-10 points per hour)
|
||||
if (hourData.length > 10) {
|
||||
const sampleRate = Math.max(1, Math.floor(hourData.length / 8));
|
||||
for (let i = 0; i < hourData.length; i += sampleRate) {
|
||||
idsToKeep.add(hourData[i].id);
|
||||
}
|
||||
} else {
|
||||
// Keep all if less than 10 points
|
||||
hourData.forEach(row => idsToKeep.add(row.id));
|
||||
}
|
||||
}
|
||||
|
||||
// Delete points not in keep set
|
||||
const idsToDelete = hourlyData
|
||||
.filter(row => !idsToKeep.has(row.id))
|
||||
.map(row => row.id);
|
||||
|
||||
if (idsToDelete.length > 0) {
|
||||
await prisma.pingResult.deleteMany({
|
||||
where: { id: { in: idsToDelete } },
|
||||
});
|
||||
totalDeleted += idsToDelete.length;
|
||||
}
|
||||
}
|
||||
|
||||
// Step 2: Process 90+ days range - aggregate to daily buckets
|
||||
const dailyData = await prisma.pingResult.findMany({
|
||||
where: {
|
||||
targetId: targetId,
|
||||
timestamp: { lt: hourlyCutoff },
|
||||
},
|
||||
orderBy: { timestamp: 'asc' },
|
||||
});
|
||||
|
||||
if (dailyData.length > 0) {
|
||||
// Group by day
|
||||
const dailyBuckets = new Map();
|
||||
dailyData.forEach(row => {
|
||||
const dayKey = new Date(row.timestamp);
|
||||
dayKey.setHours(0, 0, 0, 0);
|
||||
const key = dayKey.toISOString().split('T')[0];
|
||||
|
||||
if (!dailyBuckets.has(key)) {
|
||||
dailyBuckets.set(key, []);
|
||||
}
|
||||
dailyBuckets.get(key).push(row);
|
||||
});
|
||||
|
||||
// For each day, keep only representative points
|
||||
const idsToKeep = new Set();
|
||||
|
||||
for (const [dayKey, dayData] of dailyBuckets.entries()) {
|
||||
if (dayData.length === 0) continue;
|
||||
|
||||
// Always keep first and last of the day
|
||||
idsToKeep.add(dayData[0].id);
|
||||
idsToKeep.add(dayData[dayData.length - 1].id);
|
||||
|
||||
// Keep min and max response times
|
||||
const withResponseTime = dayData.filter(d => d.responseTime !== null);
|
||||
if (withResponseTime.length > 0) {
|
||||
const minPoint = withResponseTime.reduce((min, d) =>
|
||||
d.responseTime < min.responseTime ? d : min
|
||||
);
|
||||
const maxPoint = withResponseTime.reduce((max, d) =>
|
||||
d.responseTime > max.responseTime ? d : max
|
||||
);
|
||||
idsToKeep.add(minPoint.id);
|
||||
idsToKeep.add(maxPoint.id);
|
||||
}
|
||||
|
||||
// Keep status change points
|
||||
for (let i = 1; i < dayData.length; i++) {
|
||||
if (dayData[i].success !== dayData[i - 1].success) {
|
||||
idsToKeep.add(dayData[i - 1].id);
|
||||
idsToKeep.add(dayData[i].id);
|
||||
}
|
||||
}
|
||||
|
||||
// Sample evenly - keep ~3-5 points per day for very old data
|
||||
if (dayData.length > 5) {
|
||||
const sampleRate = Math.max(1, Math.floor(dayData.length / 4));
|
||||
for (let i = 0; i < dayData.length; i += sampleRate) {
|
||||
idsToKeep.add(dayData[i].id);
|
||||
}
|
||||
} else {
|
||||
// Keep all if less than 5 points
|
||||
dayData.forEach(row => idsToKeep.add(row.id));
|
||||
}
|
||||
}
|
||||
|
||||
// Delete points not in keep set
|
||||
const idsToDelete = dailyData
|
||||
.filter(row => !idsToKeep.has(row.id))
|
||||
.map(row => row.id);
|
||||
|
||||
if (idsToDelete.length > 0) {
|
||||
await prisma.pingResult.deleteMany({
|
||||
where: { id: { in: idsToDelete } },
|
||||
});
|
||||
totalDeleted += idsToDelete.length;
|
||||
}
|
||||
}
|
||||
|
||||
if (totalDeleted > 0) {
|
||||
console.log(chalk.yellow(`⊘ Processed retention for target ${targetId}: deleted ${totalDeleted} old data points`));
|
||||
}
|
||||
|
||||
return { processed: hourlyData.length + dailyData.length, deleted: totalDeleted };
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Error processing retention for target ${targetId}:`), error.message);
|
||||
return { processed: 0, deleted: 0, error: error.message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process retention for all targets
|
||||
*/
|
||||
async processRetentionForAllTargets() {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const targets = await prisma.target.findMany();
|
||||
|
||||
let totalProcessed = 0;
|
||||
let totalDeleted = 0;
|
||||
|
||||
for (const target of targets) {
|
||||
const result = await this.processRetentionForTarget(target.id);
|
||||
totalProcessed += result.processed || 0;
|
||||
totalDeleted += result.deleted || 0;
|
||||
}
|
||||
|
||||
if (totalDeleted > 0) {
|
||||
console.log(chalk.green(`✓ Data retention complete: processed ${totalProcessed} points, deleted ${totalDeleted} redundant points`));
|
||||
}
|
||||
|
||||
return { totalProcessed, totalDeleted };
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error processing retention for all targets:'), error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up data older than retention period (hard delete)
|
||||
* This is a more aggressive cleanup that removes data entirely
|
||||
*/
|
||||
async cleanupOldData() {
|
||||
try {
|
||||
const retentionDays = await this.getRetentionSettings();
|
||||
const prisma = getPrisma();
|
||||
|
||||
const cutoffDate = new Date();
|
||||
cutoffDate.setDate(cutoffDate.getDate() - retentionDays);
|
||||
|
||||
// Delete all data older than retention period
|
||||
const result = await prisma.pingResult.deleteMany({
|
||||
where: { timestamp: { lt: cutoffDate } },
|
||||
});
|
||||
|
||||
if (result.count > 0) {
|
||||
console.log(chalk.yellow(`⊘ Cleaned up ${result.count} data points older than ${retentionDays} days`));
|
||||
}
|
||||
|
||||
return { deleted: result.count };
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error cleaning up old data:'), error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Limit total ping results per target to optimize database performance
|
||||
* Keeps the most recent N results per target
|
||||
*/
|
||||
async limitPingResultsPerTarget(maxResultsPerTarget = 10000) {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const targets = await prisma.target.findMany();
|
||||
let totalDeleted = 0;
|
||||
|
||||
for (const target of targets) {
|
||||
// Count total ping results for this target
|
||||
const count = await prisma.pingResult.count({
|
||||
where: { targetId: target.id },
|
||||
});
|
||||
|
||||
if (count > maxResultsPerTarget) {
|
||||
// Get the oldest results to delete
|
||||
const toDelete = count - maxResultsPerTarget;
|
||||
|
||||
// Get the timestamp of the Nth oldest result (where N = maxResultsPerTarget)
|
||||
const oldestToKeep = await prisma.pingResult.findMany({
|
||||
where: { targetId: target.id },
|
||||
orderBy: { timestamp: 'desc' },
|
||||
take: maxResultsPerTarget,
|
||||
skip: 0,
|
||||
});
|
||||
|
||||
if (oldestToKeep.length > 0) {
|
||||
const cutoffTimestamp = oldestToKeep[oldestToKeep.length - 1].timestamp;
|
||||
|
||||
// Delete all results older than the cutoff
|
||||
const result = await prisma.pingResult.deleteMany({
|
||||
where: {
|
||||
targetId: target.id,
|
||||
timestamp: { lt: cutoffTimestamp },
|
||||
},
|
||||
});
|
||||
|
||||
totalDeleted += result.count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (totalDeleted > 0) {
|
||||
console.log(chalk.yellow(`⊘ Limited ping results: deleted ${totalDeleted} old data points`));
|
||||
}
|
||||
|
||||
return { deleted: totalDeleted };
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error limiting ping results:'), error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new DataRetentionService();
|
||||
@@ -0,0 +1,566 @@
|
||||
const { getPrisma } = require('../config/prisma');
|
||||
const IncidentService = require('./incidentService');
|
||||
const chalk = require('../utils/colors');
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
|
||||
class EventDetectionService {
|
||||
constructor() {
|
||||
this.prisma = null;
|
||||
this.incidentService = null;
|
||||
this.activeIncidents = new Map(); // Track incidents created by events to avoid duplicates
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the service
|
||||
*/
|
||||
async initialize() {
|
||||
this.prisma = getPrisma();
|
||||
this.incidentService = new IncidentService(this.prisma);
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate all enabled event rules and create incidents if conditions are met
|
||||
*/
|
||||
async evaluateRules(context = {}) {
|
||||
try {
|
||||
if (!this.prisma) {
|
||||
await this.initialize();
|
||||
}
|
||||
|
||||
const rules = await this.prisma.eventRule.findMany({
|
||||
where: { enabled: true },
|
||||
});
|
||||
|
||||
for (const rule of rules) {
|
||||
try {
|
||||
const shouldTrigger = await this.evaluateRule(rule, context);
|
||||
|
||||
if (shouldTrigger) {
|
||||
await this.triggerRule(rule, context);
|
||||
} else {
|
||||
// Check if we should auto-resolve incidents created by this rule
|
||||
await this.checkAutoResolve(rule, context);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Error evaluating rule ${rule.name}:`), error.message);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error evaluating event rules:'), error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate a single rule to see if it should trigger
|
||||
*/
|
||||
async evaluateRule(rule, context) {
|
||||
const { eventType } = rule;
|
||||
// Parse conditions from JSON string if needed and attach to rule for use in evaluation methods
|
||||
if (typeof rule.conditions === 'string') {
|
||||
try {
|
||||
rule.conditions = JSON.parse(rule.conditions);
|
||||
} catch (e) {
|
||||
console.error(chalk.red(`Error parsing conditions for rule ${rule.name}:`), e.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
switch (eventType) {
|
||||
case 'monitor_down':
|
||||
return await this.evaluateMonitorDown(rule, context);
|
||||
case 'monitor_up':
|
||||
return await this.evaluateMonitorUp(rule, context);
|
||||
case 'multiple_monitors_down':
|
||||
return await this.evaluateMultipleMonitorsDown(rule, context);
|
||||
case 'monitor_response_time':
|
||||
return await this.evaluateResponseTime(rule, context);
|
||||
case 'uptime_threshold':
|
||||
return await this.evaluateUptimeThreshold(rule, context);
|
||||
case 'custom_condition':
|
||||
return await this.evaluateCustomCondition(rule, context);
|
||||
default:
|
||||
console.warn(chalk.yellow(`Unknown event type: ${eventType}`));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate monitor down condition
|
||||
*/
|
||||
async evaluateMonitorDown(rule, context) {
|
||||
let conditions = rule.conditions;
|
||||
if (typeof conditions === 'string') {
|
||||
try {
|
||||
conditions = JSON.parse(conditions);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const { targetId, targetIds, targetGroups } = conditions;
|
||||
|
||||
// If context has a specific target, check if it matches
|
||||
if (context.targetId) {
|
||||
// Check if this target is in the list
|
||||
if (targetIds && Array.isArray(targetIds) && targetIds.includes(context.targetId)) {
|
||||
const status = context.status || await this.getTargetStatus(context.targetId);
|
||||
return status === 'down';
|
||||
}
|
||||
// Legacy support for single targetId
|
||||
if (targetId && context.targetId === targetId) {
|
||||
const status = context.status || await this.getTargetStatus(context.targetId);
|
||||
return status === 'down';
|
||||
}
|
||||
if (targetGroups && context.targetGroup) {
|
||||
if (targetGroups.includes(context.targetGroup)) {
|
||||
const status = context.status || await this.getTargetStatus(context.targetId);
|
||||
return status === 'down';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise check all matching targets
|
||||
// Prioritize targetIds array (new format)
|
||||
if (targetIds && Array.isArray(targetIds) && targetIds.length > 0) {
|
||||
for (const id of targetIds) {
|
||||
const status = await this.getTargetStatus(id);
|
||||
if (status === 'down') return true;
|
||||
}
|
||||
}
|
||||
// Legacy support for single targetId
|
||||
else if (targetId) {
|
||||
const status = await this.getTargetStatus(targetId);
|
||||
return status === 'down';
|
||||
}
|
||||
|
||||
if (targetGroups && targetGroups.length > 0) {
|
||||
const targets = await this.prisma.target.findMany({
|
||||
where: { group: { in: targetGroups }, enabled: true },
|
||||
});
|
||||
|
||||
for (const target of targets) {
|
||||
const status = await this.getTargetStatus(target._id);
|
||||
if (status === 'down') return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate monitor up condition (for auto-resolve)
|
||||
*/
|
||||
async evaluateMonitorUp(rule, context) {
|
||||
let conditions = rule.conditions;
|
||||
if (typeof conditions === 'string') {
|
||||
try {
|
||||
conditions = JSON.parse(conditions);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const { targetId, targetIds, targetGroups } = conditions;
|
||||
|
||||
if (context.targetId) {
|
||||
// Check if this target is in the list
|
||||
if (targetIds && Array.isArray(targetIds) && targetIds.includes(context.targetId)) {
|
||||
const status = context.status || await this.getTargetStatus(context.targetId);
|
||||
return status === 'up';
|
||||
}
|
||||
// Legacy support for single targetId
|
||||
if (targetId && context.targetId === targetId) {
|
||||
const status = context.status || await this.getTargetStatus(context.targetId);
|
||||
return status === 'up';
|
||||
}
|
||||
if (targetGroups && context.targetGroup) {
|
||||
if (targetGroups.includes(context.targetGroup)) {
|
||||
const status = context.status || await this.getTargetStatus(context.targetId);
|
||||
return status === 'up';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate multiple monitors down condition
|
||||
*/
|
||||
async evaluateMultipleMonitorsDown(rule, context) {
|
||||
let conditions = rule.conditions;
|
||||
if (typeof conditions === 'string') {
|
||||
try {
|
||||
conditions = JSON.parse(conditions);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const { targetIds, targetGroups, count, operator = 'gte' } = conditions;
|
||||
|
||||
let downCount = 0;
|
||||
const targetsToCheck = [];
|
||||
|
||||
if (targetIds && targetIds.length > 0) {
|
||||
const targets = await this.prisma.target.findMany({
|
||||
where: { id: { in: targetIds }, enabled: true },
|
||||
});
|
||||
targetsToCheck.push(...targets);
|
||||
}
|
||||
|
||||
if (targetGroups && targetGroups.length > 0) {
|
||||
const targets = await this.prisma.target.findMany({
|
||||
where: { group: { in: targetGroups }, enabled: true },
|
||||
});
|
||||
targetsToCheck.push(...targets);
|
||||
}
|
||||
|
||||
for (const target of targetsToCheck) {
|
||||
const status = await this.getTargetStatus(target._id);
|
||||
if (status === 'down') {
|
||||
downCount++;
|
||||
}
|
||||
}
|
||||
|
||||
if (operator === 'gte') {
|
||||
return downCount >= count;
|
||||
} else if (operator === 'eq') {
|
||||
return downCount === count;
|
||||
} else if (operator === 'gt') {
|
||||
return downCount > count;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate response time condition
|
||||
*/
|
||||
async evaluateResponseTime(rule, context) {
|
||||
let conditions = rule.conditions;
|
||||
if (typeof conditions === 'string') {
|
||||
try {
|
||||
conditions = JSON.parse(conditions);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const { targetId, threshold, operator = 'gt' } = conditions;
|
||||
|
||||
if (!context.targetId || context.targetId !== targetId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const responseTime = context.responseTime || await this.getLatestResponseTime(targetId);
|
||||
if (responseTime === null) return false;
|
||||
|
||||
if (operator === 'gt') {
|
||||
return responseTime > threshold;
|
||||
} else if (operator === 'gte') {
|
||||
return responseTime >= threshold;
|
||||
} else if (operator === 'lt') {
|
||||
return responseTime < threshold;
|
||||
} else if (operator === 'lte') {
|
||||
return responseTime <= threshold;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate uptime threshold condition
|
||||
*/
|
||||
async evaluateUptimeThreshold(rule, context) {
|
||||
let conditions = rule.conditions;
|
||||
if (typeof conditions === 'string') {
|
||||
try {
|
||||
conditions = JSON.parse(conditions);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const { targetId, threshold, period = '24h' } = conditions;
|
||||
|
||||
if (!targetId) return false;
|
||||
|
||||
const uptime = await this.getUptimePercentage(targetId, period);
|
||||
if (uptime === null) return false;
|
||||
|
||||
return uptime < threshold;
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate custom condition (JavaScript expression)
|
||||
*/
|
||||
async evaluateCustomCondition(rule, context) {
|
||||
let conditions = rule.conditions;
|
||||
if (typeof conditions === 'string') {
|
||||
try {
|
||||
conditions = JSON.parse(conditions);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const { expression } = conditions;
|
||||
|
||||
if (!expression) return false;
|
||||
|
||||
try {
|
||||
// Create a safe evaluation context
|
||||
const evalContext = {
|
||||
targetId: context.targetId,
|
||||
status: context.status,
|
||||
responseTime: context.responseTime,
|
||||
target: context.target,
|
||||
getTargetStatus: async (id) => await this.getTargetStatus(id),
|
||||
getLatestResponseTime: async (id) => await this.getLatestResponseTime(id),
|
||||
getUptimePercentage: async (id, period) => await this.getUptimePercentage(id, period),
|
||||
};
|
||||
|
||||
// Evaluate the expression (in a limited way - be careful with this)
|
||||
// Note: Using eval is dangerous, but for admin-controlled rules it's acceptable
|
||||
const result = await eval(`(async () => { ${expression} })()`);
|
||||
return Boolean(result);
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Error evaluating custom condition for rule ${rule.name}:`), error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger a rule and create an incident
|
||||
*/
|
||||
async triggerRule(rule, context) {
|
||||
try {
|
||||
// Check if we already created an incident for this rule
|
||||
const incidentKey = `${rule._id}_${this.getContextKey(context)}`;
|
||||
if (this.activeIncidents.has(incidentKey)) {
|
||||
return; // Already created
|
||||
}
|
||||
|
||||
// Check cooldown period
|
||||
if (rule.cooldownMinutes) {
|
||||
const lastTrigger = this.getLastTriggerTime(rule._id);
|
||||
if (lastTrigger && (Date.now() - lastTrigger) < (rule.cooldownMinutes * 60 * 1000)) {
|
||||
return; // Still in cooldown
|
||||
}
|
||||
}
|
||||
|
||||
// Build incident data from rule template
|
||||
const incidentData = {
|
||||
title: this.interpolateTemplate(rule.incidentTitle, context),
|
||||
description: this.interpolateTemplate(rule.incidentDescription, context),
|
||||
status: rule.incidentStatus || 'investigating',
|
||||
severity: rule.incidentSeverity || 'major',
|
||||
affectedServices: await this.getAffectedServices(rule, context),
|
||||
};
|
||||
|
||||
const result = await this.incidentService.createIncident(incidentData);
|
||||
|
||||
if (result.success) {
|
||||
// Track this incident
|
||||
this.activeIncidents.set(incidentKey, {
|
||||
incidentId: result.incidentId,
|
||||
ruleId: rule._id,
|
||||
createdAt: Date.now(),
|
||||
});
|
||||
|
||||
// Store last trigger time
|
||||
this.setLastTriggerTime(rule._id, Date.now());
|
||||
|
||||
console.log(chalk.green(`✓ Event rule "${rule.name}" triggered, incident created: ${result.incidentId}`));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Error triggering rule ${rule.name}:`), error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if we should auto-resolve incidents created by a rule
|
||||
*/
|
||||
async checkAutoResolve(rule, context) {
|
||||
if (!rule.autoResolve) return;
|
||||
|
||||
const incidentKey = `${rule._id}_${this.getContextKey(context)}`;
|
||||
const activeIncident = this.activeIncidents.get(incidentKey);
|
||||
|
||||
if (!activeIncident) return;
|
||||
|
||||
// Check if condition is now false (e.g., monitor is back up)
|
||||
const conditionMet = await this.evaluateRule(rule, context);
|
||||
|
||||
if (!conditionMet) {
|
||||
// Condition is no longer met, resolve the incident
|
||||
try {
|
||||
const incident = await this.incidentService.getIncidentById(activeIncident.incidentId);
|
||||
if (incident && incident.status !== 'resolved') {
|
||||
await this.incidentService.updateIncident(activeIncident.incidentId, {
|
||||
status: 'resolved',
|
||||
updateMessage: rule.autoResolveMessage || 'Service restored - automatically resolved by event detection system',
|
||||
});
|
||||
|
||||
// Remove from active incidents
|
||||
this.activeIncidents.delete(incidentKey);
|
||||
|
||||
console.log(chalk.green(`✓ Auto-resolved incident ${activeIncident.incidentId} for rule "${rule.name}"`));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Error auto-resolving incident:`), error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get target status
|
||||
*/
|
||||
async getTargetStatus(targetId) {
|
||||
const monitorService = require('./monitorService');
|
||||
return monitorService.getTargetStatus(targetId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get latest response time for a target
|
||||
*/
|
||||
async getLatestResponseTime(targetId) {
|
||||
try {
|
||||
const result = await this.prisma.pingResult.findFirst({
|
||||
where: { targetId },
|
||||
orderBy: { timestamp: 'desc' },
|
||||
});
|
||||
|
||||
return result?.responseTime || null;
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get uptime percentage for a target over a period
|
||||
*/
|
||||
async getUptimePercentage(targetId, period = '24h') {
|
||||
try {
|
||||
const hours = this.parsePeriod(period);
|
||||
const since = new Date(Date.now() - hours * 60 * 60 * 1000);
|
||||
|
||||
const results = await this.prisma.pingResult.findMany({
|
||||
where: { targetId, timestamp: { gte: since } },
|
||||
});
|
||||
|
||||
if (results.length === 0) return null;
|
||||
|
||||
const successful = results.filter(r => r.success).length;
|
||||
return (successful / results.length) * 100;
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse period string (e.g., "24h", "7d") to hours
|
||||
*/
|
||||
parsePeriod(period) {
|
||||
const match = period.match(/^(\d+)([hd])$/);
|
||||
if (!match) return 24; // Default to 24 hours
|
||||
|
||||
const value = parseInt(match[1]);
|
||||
const unit = match[2];
|
||||
|
||||
return unit === 'd' ? value * 24 : value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get affected services for an incident
|
||||
*/
|
||||
async getAffectedServices(rule, context) {
|
||||
const services = [];
|
||||
|
||||
if (context.target) {
|
||||
services.push(context.target.name);
|
||||
} else if (context.targetId) {
|
||||
const target = await this.prisma.target.findUnique({ where: { id: context.targetId } });
|
||||
if (target) {
|
||||
services.push(target.name);
|
||||
}
|
||||
}
|
||||
|
||||
let conditions = rule.conditions;
|
||||
if (typeof conditions === 'string') {
|
||||
try {
|
||||
conditions = JSON.parse(conditions);
|
||||
} catch (e) {
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
||||
if (conditions.targetIds) {
|
||||
for (const id of conditions.targetIds) {
|
||||
const target = await this.prisma.target.findUnique({ where: { id } });
|
||||
if (target && !services.includes(target.name)) {
|
||||
services.push(target.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interpolate template string with context variables
|
||||
*/
|
||||
interpolateTemplate(template, context) {
|
||||
if (!template) return '';
|
||||
|
||||
let result = template;
|
||||
|
||||
// Replace {{variable}} with context values
|
||||
result = result.replace(/\{\{target\.name\}\}/g, context.target?.name || 'Unknown');
|
||||
result = result.replace(/\{\{target\.host\}\}/g, context.target?.host || 'Unknown');
|
||||
result = result.replace(/\{\{status\}\}/g, context.status || 'unknown');
|
||||
result = result.replace(/\{\{responseTime\}\}/g, context.responseTime || 'N/A');
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get context key for tracking incidents
|
||||
*/
|
||||
getContextKey(context) {
|
||||
if (context.targetId) {
|
||||
return context.targetId;
|
||||
}
|
||||
return 'default';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get last trigger time for a rule
|
||||
*/
|
||||
getLastTriggerTime(ruleId) {
|
||||
const key = `lastTrigger_${ruleId}`;
|
||||
return this[key] || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set last trigger time for a rule
|
||||
*/
|
||||
setLastTriggerTime(ruleId, timestamp) {
|
||||
const key = `lastTrigger_${ruleId}`;
|
||||
this[key] = timestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up resolved incidents from tracking
|
||||
*/
|
||||
async cleanupResolvedIncidents() {
|
||||
try {
|
||||
for (const [key, incident] of this.activeIncidents.entries()) {
|
||||
const incidentData = await this.incidentService.getIncidentById(incident.incidentId);
|
||||
if (incidentData && incidentData.status === 'resolved') {
|
||||
this.activeIncidents.delete(key);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// Silently fail
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new EventDetectionService();
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
const axios = require('axios');
|
||||
|
||||
class FaviconService {
|
||||
/**
|
||||
* Get favicon for a URL
|
||||
* Tries multiple methods to find the favicon
|
||||
* @param {string} url - The URL to get favicon from (e.g., https://example.com)
|
||||
* @returns {Promise<string|null>} - Base64 encoded favicon data or null if not found
|
||||
*/
|
||||
async getFavicon(url, options = {}) {
|
||||
if (!url) return null;
|
||||
|
||||
try {
|
||||
// Normalize URL
|
||||
const urlObj = new URL(url);
|
||||
const baseUrl = `${urlObj.protocol}//${urlObj.host}`;
|
||||
|
||||
// Method 1: Try /favicon.ico
|
||||
const faviconUrl = `${baseUrl}/favicon.ico`;
|
||||
const faviconData = await this.fetchFaviconAsBase64(faviconUrl);
|
||||
if (faviconData) {
|
||||
return faviconData;
|
||||
}
|
||||
|
||||
// Method 2: Try fetching HTML and looking for favicon link tag
|
||||
const htmlFavicon = await this.getFaviconFromHtml(baseUrl, options);
|
||||
if (htmlFavicon) {
|
||||
return htmlFavicon;
|
||||
}
|
||||
|
||||
// Method 3: Use Google's favicon service as fallback
|
||||
const googleFavicon = await this.getFaviconFromGoogle(baseUrl);
|
||||
if (googleFavicon) {
|
||||
return googleFavicon;
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error(`Error getting favicon for ${url}:`, error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch favicon file and convert to base64
|
||||
*/
|
||||
async fetchFaviconAsBase64(url) {
|
||||
try {
|
||||
const response = await axios.get(url, {
|
||||
timeout: 5000,
|
||||
responseType: 'arraybuffer',
|
||||
validateStatus: (status) => status < 400,
|
||||
maxRedirects: 5,
|
||||
});
|
||||
|
||||
if (response.status === 200 && response.data && response.data.length > 0) {
|
||||
const base64 = Buffer.from(response.data).toString('base64');
|
||||
const mimeType = this.getMimeType(response.headers['content-type']);
|
||||
return `data:${mimeType};base64,${base64}`;
|
||||
}
|
||||
return null;
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse HTML and extract favicon link
|
||||
*/
|
||||
async getFaviconFromHtml(baseUrl, options = {}) {
|
||||
try {
|
||||
const axiosConfig = {
|
||||
timeout: options.timeout || 5000,
|
||||
validateStatus: (status) => status < 400,
|
||||
maxRedirects: options.maxRedirects || 5,
|
||||
};
|
||||
|
||||
// Handle SSL/TLS options
|
||||
if (options.ignoreSsl === true) {
|
||||
const httpsAgent = require('https').Agent({ rejectUnauthorized: false });
|
||||
const httpAgent = require('http').Agent({ rejectUnauthorized: false });
|
||||
axiosConfig.httpsAgent = httpsAgent;
|
||||
axiosConfig.httpAgent = httpAgent;
|
||||
}
|
||||
|
||||
// Handle authentication
|
||||
if (options.auth) {
|
||||
if (options.auth.type === 'basic') {
|
||||
axiosConfig.auth = {
|
||||
username: options.auth.username,
|
||||
password: options.auth.password,
|
||||
};
|
||||
} else if (options.auth.type === 'bearer') {
|
||||
axiosConfig.headers = {
|
||||
'Authorization': `Bearer ${options.auth.token}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const response = await axios.get(baseUrl, axiosConfig);
|
||||
|
||||
if (response.status !== 200 || !response.data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const html = response.data;
|
||||
|
||||
// Extract all link tags with rel containing icon
|
||||
const linkMatches = html.matchAll(/<link[^>]*>/gi);
|
||||
const faviconLinks = [];
|
||||
|
||||
for (const linkMatch of linkMatches) {
|
||||
const linkTag = linkMatch[0];
|
||||
const relMatch = linkTag.match(/rel=["']([^"']+)["']/i);
|
||||
if (relMatch && /icon/i.test(relMatch[1])) {
|
||||
const hrefMatch = linkTag.match(/href=["']([^"']+)["']/i);
|
||||
if (hrefMatch) {
|
||||
faviconLinks.push({
|
||||
rel: relMatch[1].toLowerCase(),
|
||||
href: hrefMatch[1],
|
||||
priority: this.getFaviconPriority(relMatch[1])
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by priority (higher priority first)
|
||||
faviconLinks.sort((a, b) => b.priority - a.priority);
|
||||
|
||||
// Try each favicon in priority order
|
||||
for (const link of faviconLinks) {
|
||||
const iconUrl = this.resolveUrl(link.href, baseUrl);
|
||||
const faviconData = await this.fetchFaviconAsBase64(iconUrl);
|
||||
if (faviconData) {
|
||||
return faviconData;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get favicon URL from HTML (returns URL string instead of base64)
|
||||
* Useful for storing just the URL
|
||||
*/
|
||||
async getFaviconUrlFromHtml(baseUrl, options = {}) {
|
||||
try {
|
||||
const axiosConfig = {
|
||||
timeout: options.timeout || 5000,
|
||||
validateStatus: (status) => status < 400,
|
||||
maxRedirects: options.maxRedirects || 5,
|
||||
};
|
||||
|
||||
// Handle SSL/TLS options
|
||||
if (options.ignoreSsl === true) {
|
||||
const httpsAgent = require('https').Agent({ rejectUnauthorized: false });
|
||||
const httpAgent = require('http').Agent({ rejectUnauthorized: false });
|
||||
axiosConfig.httpsAgent = httpsAgent;
|
||||
axiosConfig.httpAgent = httpAgent;
|
||||
}
|
||||
|
||||
// Handle authentication
|
||||
if (options.auth) {
|
||||
if (options.auth.type === 'basic') {
|
||||
axiosConfig.auth = {
|
||||
username: options.auth.username,
|
||||
password: options.auth.password,
|
||||
};
|
||||
} else if (options.auth.type === 'bearer') {
|
||||
axiosConfig.headers = {
|
||||
'Authorization': `Bearer ${options.auth.token}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const response = await axios.get(baseUrl, axiosConfig);
|
||||
|
||||
if (response.status !== 200 || !response.data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const html = response.data;
|
||||
|
||||
// Extract all link tags with rel containing icon
|
||||
const linkMatches = html.matchAll(/<link[^>]*>/gi);
|
||||
const faviconLinks = [];
|
||||
|
||||
for (const linkMatch of linkMatches) {
|
||||
const linkTag = linkMatch[0];
|
||||
const relMatch = linkTag.match(/rel=["']([^"']+)["']/i);
|
||||
if (relMatch && /icon/i.test(relMatch[1])) {
|
||||
const hrefMatch = linkTag.match(/href=["']([^"']+)["']/i);
|
||||
if (hrefMatch) {
|
||||
faviconLinks.push({
|
||||
rel: relMatch[1].toLowerCase(),
|
||||
href: hrefMatch[1],
|
||||
priority: this.getFaviconPriority(relMatch[1])
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by priority (higher priority first)
|
||||
faviconLinks.sort((a, b) => b.priority - a.priority);
|
||||
|
||||
// Return the highest priority favicon URL
|
||||
if (faviconLinks.length > 0) {
|
||||
return this.resolveUrl(faviconLinks[0].href, baseUrl);
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Use Google's favicon service as fallback
|
||||
*/
|
||||
async getFaviconFromGoogle(baseUrl) {
|
||||
try {
|
||||
const urlObj = new URL(baseUrl);
|
||||
const domain = urlObj.host;
|
||||
const googleFaviconUrl = `https://www.google.com/s2/favicons?sz=64&domain=${domain}`;
|
||||
|
||||
const response = await axios.get(googleFaviconUrl, {
|
||||
timeout: 5000,
|
||||
responseType: 'arraybuffer',
|
||||
validateStatus: (status) => status < 400,
|
||||
maxRedirects: 5,
|
||||
});
|
||||
|
||||
if (response.status === 200 && response.data && response.data.length > 0) {
|
||||
const base64 = Buffer.from(response.data).toString('base64');
|
||||
return `data:image/png;base64,${base64}`;
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve relative URLs to absolute
|
||||
*/
|
||||
resolveUrl(url, baseUrl) {
|
||||
// Remove query strings and fragments for matching
|
||||
const cleanUrl = url.split('?')[0].split('#')[0];
|
||||
|
||||
if (cleanUrl.startsWith('http://') || cleanUrl.startsWith('https://')) {
|
||||
return url; // Return original with query string if present
|
||||
}
|
||||
|
||||
try {
|
||||
const urlObj = new URL(baseUrl);
|
||||
if (cleanUrl.startsWith('/')) {
|
||||
return `${urlObj.protocol}//${urlObj.host}${url}`;
|
||||
}
|
||||
|
||||
// Handle relative paths
|
||||
const basePath = urlObj.pathname || '/';
|
||||
const baseDir = basePath.substring(0, basePath.lastIndexOf('/') + 1);
|
||||
return `${urlObj.protocol}//${urlObj.host}${baseDir}${url}`;
|
||||
} catch (error) {
|
||||
// If URL parsing fails, try simple string concatenation
|
||||
if (cleanUrl.startsWith('/')) {
|
||||
return baseUrl.replace(/\/$/, '') + url;
|
||||
}
|
||||
return baseUrl.replace(/\/$/, '') + '/' + url;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get MIME type from content-type header
|
||||
*/
|
||||
getMimeType(contentType) {
|
||||
if (!contentType) return 'image/x-icon';
|
||||
|
||||
const type = contentType.split(';')[0].trim();
|
||||
if (type.includes('svg')) return 'image/svg+xml';
|
||||
if (type.includes('png')) return 'image/png';
|
||||
if (type.includes('jpeg') || type.includes('jpg')) return 'image/jpeg';
|
||||
if (type.includes('gif')) return 'image/gif';
|
||||
if (type.includes('webp')) return 'image/webp';
|
||||
|
||||
return 'image/x-icon';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get priority for favicon rel types (higher = better)
|
||||
*/
|
||||
getFaviconPriority(rel) {
|
||||
const relLower = rel.toLowerCase();
|
||||
if (relLower.includes('apple-touch-icon')) return 5;
|
||||
if (relLower.includes('icon') && relLower.includes('mask')) return 4;
|
||||
if (relLower === 'icon') return 3;
|
||||
if (relLower.includes('shortcut') && relLower.includes('icon')) return 2;
|
||||
if (relLower.includes('icon')) return 1;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new FaviconService();
|
||||
@@ -0,0 +1,85 @@
|
||||
const { gateway4async, gateway6async } = require('default-gateway');
|
||||
const chalk = require('../utils/colors');
|
||||
|
||||
class GatewayService {
|
||||
constructor() {
|
||||
this.gateway4 = null;
|
||||
this.gateway6 = null;
|
||||
this.interface4 = null;
|
||||
this.interface6 = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect the default IPv4 gateway
|
||||
*/
|
||||
async detectGateway4() {
|
||||
try {
|
||||
const result = await gateway4async();
|
||||
if (result && result.gateway) {
|
||||
this.gateway4 = result.gateway;
|
||||
this.interface4 = result.interface;
|
||||
console.log(
|
||||
chalk.green('✓ Detected IPv4 gateway:'),
|
||||
`${this.gateway4} (${this.interface4})`
|
||||
);
|
||||
return this.gateway4;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(chalk.yellow('⚠ Could not detect IPv4 gateway:'), error.message);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect the default IPv6 gateway
|
||||
*/
|
||||
async detectGateway6() {
|
||||
try {
|
||||
const result = await gateway6async();
|
||||
if (result && result.gateway) {
|
||||
this.gateway6 = result.gateway;
|
||||
this.interface6 = result.interface;
|
||||
console.log(
|
||||
chalk.green('✓ Detected IPv6 gateway:'),
|
||||
`${this.gateway6} (${this.interface6})`
|
||||
);
|
||||
return this.gateway6;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(chalk.yellow('⚠ Could not detect IPv6 gateway:'), error.message);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect both IPv4 and IPv6 gateways
|
||||
*/
|
||||
async detectAllGateways() {
|
||||
await Promise.all([this.detectGateway4(), this.detectGateway6()]);
|
||||
return {
|
||||
gateway4: this.gateway4,
|
||||
gateway6: this.gateway6,
|
||||
interface4: this.interface4,
|
||||
interface6: this.interface6,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the primary gateway (IPv4 preferably)
|
||||
*/
|
||||
getPrimaryGateway() {
|
||||
return this.gateway4 || this.gateway6 || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all detected gateways
|
||||
*/
|
||||
getAllGateways() {
|
||||
const gateways = [];
|
||||
if (this.gateway4) gateways.push({ ip: this.gateway4, version: 4, interface: this.interface4 });
|
||||
if (this.gateway6) gateways.push({ ip: this.gateway6, version: 6, interface: this.interface6 });
|
||||
return gateways;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new GatewayService();
|
||||
@@ -0,0 +1,262 @@
|
||||
const chalk = require('../utils/colors');
|
||||
|
||||
class IncidentService {
|
||||
constructor(prisma) {
|
||||
this.prisma = prisma;
|
||||
}
|
||||
|
||||
async createIncident(data) {
|
||||
try {
|
||||
// Ensure isScheduled is a boolean, not a string or date
|
||||
const isScheduled = (data.isScheduled === true || data.isScheduled === 'true') && data.scheduledStart;
|
||||
const initialStatus = isScheduled && new Date(data.scheduledStart) > new Date()
|
||||
? 'scheduled'
|
||||
: (data.status || 'investigating');
|
||||
|
||||
const incident = await this.prisma.incident.create({
|
||||
data: {
|
||||
title: data.title,
|
||||
description: data.description,
|
||||
status: initialStatus, // investigating, identified, monitoring, resolved, scheduled
|
||||
severity: data.severity || 'major', // minor, major, critical
|
||||
affectedServices: data.affectedServices || [],
|
||||
isScheduled: Boolean(isScheduled),
|
||||
scheduledStart: data.scheduledStart ? new Date(data.scheduledStart) : null,
|
||||
scheduledEnd: data.scheduledEnd ? new Date(data.scheduledEnd) : null,
|
||||
updates: [
|
||||
{
|
||||
message: data.description,
|
||||
timestamp: new Date().toISOString(),
|
||||
status: initialStatus,
|
||||
},
|
||||
],
|
||||
resolvedAt: data.status === 'resolved' ? new Date() : null,
|
||||
},
|
||||
});
|
||||
|
||||
// Send external notifications (non-blocking)
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
const notificationService = require('./notificationService');
|
||||
await notificationService.notifyIncident(incident, false);
|
||||
} catch (error) {
|
||||
// Silently fail - notifications are not critical
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.error(chalk.yellow('Notification error for incident:'), error.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { success: true, incidentId: incident.id, incident };
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error creating incident:'), error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getIncidents(filters = {}) {
|
||||
try {
|
||||
const where = {};
|
||||
if (filters.status) where.status = filters.status;
|
||||
if (filters.severity) where.severity = filters.severity;
|
||||
|
||||
const incidents = await this.prisma.incident.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
return incidents;
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error fetching incidents:'), error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getIncidentById(incidentId) {
|
||||
try {
|
||||
const incident = await this.prisma.incident.findUnique({
|
||||
where: { id: incidentId },
|
||||
});
|
||||
|
||||
return incident;
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error fetching incident:'), error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async updateIncident(incidentId, data) {
|
||||
try {
|
||||
const updateData = {};
|
||||
|
||||
if (data.title !== undefined) updateData.title = data.title;
|
||||
if (data.description !== undefined) updateData.description = data.description;
|
||||
if (data.status !== undefined) updateData.status = data.status;
|
||||
if (data.severity !== undefined) updateData.severity = data.severity;
|
||||
if (data.affectedServices !== undefined) updateData.affectedServices = data.affectedServices;
|
||||
if (data.isScheduled !== undefined) updateData.isScheduled = Boolean(data.isScheduled === true || data.isScheduled === 'true');
|
||||
if (data.scheduledStart !== undefined) updateData.scheduledStart = data.scheduledStart ? new Date(data.scheduledStart) : null;
|
||||
if (data.scheduledEnd !== undefined) updateData.scheduledEnd = data.scheduledEnd ? new Date(data.scheduledEnd) : null;
|
||||
|
||||
if (data.status === 'resolved') {
|
||||
updateData.resolvedAt = new Date();
|
||||
}
|
||||
|
||||
// Add update to the updates array
|
||||
if (data.updateMessage) {
|
||||
const existingIncident = await this.prisma.incident.findUnique({
|
||||
where: { id: incidentId },
|
||||
});
|
||||
|
||||
if (existingIncident) {
|
||||
const updates = existingIncident.updates || [];
|
||||
updates.push({
|
||||
message: data.updateMessage,
|
||||
timestamp: new Date().toISOString(),
|
||||
status: data.status || 'update',
|
||||
});
|
||||
updateData.updates = updates;
|
||||
}
|
||||
}
|
||||
|
||||
const result = await this.prisma.incident.update({
|
||||
where: { id: incidentId },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
if (result) {
|
||||
// Send external notifications (non-blocking)
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
const updatedIncident = await this.getIncidentById(incidentId);
|
||||
if (updatedIncident) {
|
||||
const notificationService = require('./notificationService');
|
||||
await notificationService.notifyIncident(updatedIncident, true);
|
||||
}
|
||||
} catch (error) {
|
||||
// Silently fail - notifications are not critical
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.error(chalk.yellow('Notification error for incident update:'), error.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error.code === 'P2025') {
|
||||
// Record not found
|
||||
return false;
|
||||
}
|
||||
console.error(chalk.red('Error updating incident:'), error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async deleteIncident(incidentId) {
|
||||
try {
|
||||
await this.prisma.incident.delete({
|
||||
where: { id: incidentId },
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error.code === 'P2025') {
|
||||
// Record not found
|
||||
return false;
|
||||
}
|
||||
console.error(chalk.red('Error deleting incident:'), error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getPublicIncidents() {
|
||||
try {
|
||||
// Return active incidents for the public status page
|
||||
const incidents = await this.prisma.incident.findMany({
|
||||
where: { status: { not: 'resolved' } },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
return incidents;
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error fetching public incidents:'), error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process scheduled incidents - activate them when start time arrives, resolve when end time passes
|
||||
*/
|
||||
async processScheduledIncidents() {
|
||||
try {
|
||||
const now = new Date();
|
||||
|
||||
// Find scheduled incidents that need to be activated (start time has passed, status is still 'scheduled')
|
||||
const scheduledToActivate = await this.prisma.incident.findMany({
|
||||
where: {
|
||||
isScheduled: true,
|
||||
status: 'scheduled',
|
||||
scheduledStart: { lte: now },
|
||||
},
|
||||
});
|
||||
|
||||
for (const incident of scheduledToActivate) {
|
||||
// Activate the incident
|
||||
await this.prisma.incident.update({
|
||||
where: { id: incident.id },
|
||||
data: {
|
||||
status: 'investigating',
|
||||
updates: [
|
||||
...(incident.updates || []),
|
||||
{
|
||||
message: 'Scheduled maintenance window has started',
|
||||
timestamp: now.toISOString(),
|
||||
status: 'investigating',
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
console.log(chalk.green(`✓ Activated scheduled incident: ${incident.title}`));
|
||||
}
|
||||
|
||||
// Find active scheduled incidents that should be resolved (end time has passed)
|
||||
const scheduledToResolve = await this.prisma.incident.findMany({
|
||||
where: {
|
||||
isScheduled: true,
|
||||
status: { not: 'resolved' },
|
||||
scheduledEnd: { lte: now },
|
||||
},
|
||||
});
|
||||
|
||||
for (const incident of scheduledToResolve) {
|
||||
// Resolve the incident
|
||||
await this.prisma.incident.update({
|
||||
where: { id: incident.id },
|
||||
data: {
|
||||
status: 'resolved',
|
||||
resolvedAt: now,
|
||||
updates: [
|
||||
...(incident.updates || []),
|
||||
{
|
||||
message: 'Scheduled maintenance window has ended',
|
||||
timestamp: now.toISOString(),
|
||||
status: 'resolved',
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
console.log(chalk.green(`✓ Resolved scheduled incident: ${incident.title}`));
|
||||
}
|
||||
|
||||
return {
|
||||
activated: scheduledToActivate.length,
|
||||
resolved: scheduledToResolve.length,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error processing scheduled incidents:'), error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = IncidentService;
|
||||
@@ -0,0 +1,683 @@
|
||||
const { getPrisma } = require('../config/prisma');
|
||||
const pingService = require('./pingService');
|
||||
const chalk = require('../utils/colors');
|
||||
|
||||
class MonitorService {
|
||||
constructor() {
|
||||
this.intervals = new Map();
|
||||
this.targetStatus = new Map(); // Track current status of targets
|
||||
this.debugLogging = false; // Cache debug logging setting
|
||||
this.debugLoggingChecked = false; // Track if we've checked the setting
|
||||
this.lastAlertTime = new Map(); // Prevent alert spam
|
||||
this.failureCount = new Map(); // Track consecutive failures for retry logic
|
||||
this.downTimestamp = new Map(); // Track when monitor went down
|
||||
this.notificationSent = new Map(); // Track if notification was sent for current down state
|
||||
this.notificationTimers = new Map(); // Delay monitor notifications until the outage is sustained
|
||||
this.notificationScheduling = new Map();
|
||||
this.monitorGeneration = new Map(); // Ignore results from monitors that were restarted
|
||||
this.inFlight = new Map(); // Prevent overlapping pings without blocking restarted monitors
|
||||
this.monitorTargets = new Map();
|
||||
this.notificationDelayMinutes = 5;
|
||||
this.notificationDelayVersion = 0;
|
||||
this.lastNotificationSentAt = new Map();
|
||||
}
|
||||
|
||||
/**
|
||||
* Start monitoring all enabled targets (non-blocking)
|
||||
*/
|
||||
startMonitoring() {
|
||||
// Run in background to avoid blocking webserver startup
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
// Prime the delay before the first failures can be recorded.
|
||||
try {
|
||||
const notificationService = require('./notificationService');
|
||||
this.setNotificationDelayMinutes(await notificationService.getMonitorDownDelayMinutes());
|
||||
} catch (error) {
|
||||
// Keep the safe five-minute default if settings are unavailable.
|
||||
}
|
||||
const prisma = getPrisma();
|
||||
const targets = await prisma.target.findMany({ where: { enabled: true } });
|
||||
|
||||
console.log(chalk.green(`✓ Starting monitor for ${targets.length} targets`));
|
||||
|
||||
// Set up monitoring intervals for all targets immediately
|
||||
for (const target of targets) {
|
||||
this.startTargetMonitor(target);
|
||||
}
|
||||
|
||||
// Ping all targets in background to get current status (non-blocking)
|
||||
if (targets.length > 0) {
|
||||
console.log(chalk.blue('↪ Pinging all monitors to get current status (background)...'));
|
||||
// Don't await - let it run in background
|
||||
Promise.allSettled(targets.map(target => this.pingTarget(target, this.monitorGeneration.get((target.id || target._id).toString()))))
|
||||
.then(() => {
|
||||
console.log(chalk.green('✓ Initial ping complete, status updated'));
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(chalk.yellow('Some initial pings failed:'), error.message);
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error starting monitoring:'), error.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Start monitoring a single target
|
||||
*/
|
||||
startTargetMonitor(target) {
|
||||
// Support both Prisma's 'id' and legacy '_id'
|
||||
const targetIdStr = (target.id || target._id).toString();
|
||||
const generation = (this.monitorGeneration.get(targetIdStr) || 0) + 1;
|
||||
this.monitorGeneration.set(targetIdStr, generation);
|
||||
this.monitorTargets.set(targetIdStr, target);
|
||||
|
||||
// Clear existing interval if any
|
||||
if (this.intervals.has(targetIdStr)) {
|
||||
clearInterval(this.intervals.get(targetIdStr));
|
||||
// A restarted generation must not inherit a timer whose callback still
|
||||
// carries the previous generation token. Keep the outage timestamp so a
|
||||
// restart does not manufacture a fresh outage, then let the next ping
|
||||
// schedule against the active delay.
|
||||
this.clearNotificationTimer(targetIdStr);
|
||||
this.notificationScheduling.delete(targetIdStr);
|
||||
}
|
||||
|
||||
// Status should already be set from initial ping in startMonitoring()
|
||||
// If not, initialize to 'unknown'
|
||||
if (!this.targetStatus.has(targetIdStr)) {
|
||||
this.targetStatus.set(targetIdStr, 'unknown');
|
||||
}
|
||||
|
||||
// Set up interval (initial ping already done in startMonitoring())
|
||||
const interval = setInterval(() => {
|
||||
const currentTarget = this.monitorTargets.get(targetIdStr) || target;
|
||||
this.pingTarget(currentTarget, generation);
|
||||
}, (target.interval || 60) * 1000);
|
||||
|
||||
this.intervals.set(targetIdStr, interval);
|
||||
console.log(chalk.blue(`↪ Monitoring ${target.name} every ${target.interval || 60}s`));
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the target metadata used by an active monitor without resetting
|
||||
* its status, retry counters, or sustained-outage timer. Public visibility,
|
||||
* labels, icons, and notification metadata can change while a service is
|
||||
* down; those changes should not restart the outage clock.
|
||||
*/
|
||||
updateTargetReference(target) {
|
||||
const targetId = target.id || target._id;
|
||||
if (targetId === undefined || targetId === null) return;
|
||||
const targetIdStr = targetId.toString();
|
||||
if (this.monitorTargets.has(targetIdStr)) {
|
||||
this.monitorTargets.set(targetIdStr, target);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ping a target and store result (non-blocking)
|
||||
*/
|
||||
async pingTarget(target, expectedGeneration = null) {
|
||||
const targetId = target.id || target._id;
|
||||
const targetIdStr = targetId.toString();
|
||||
// Give direct/manual pings the same generation protection as interval
|
||||
// pings. This also means a monitor started while a direct ping is in
|
||||
// flight can invalidate that result safely.
|
||||
if (!this.monitorGeneration.has(targetIdStr)) {
|
||||
this.monitorGeneration.set(targetIdStr, 0);
|
||||
}
|
||||
// Calls made by an interval carry an explicit generation. Direct calls
|
||||
// (for example a startup ping or an admin test) inherit the current one
|
||||
// so a result cannot update a monitor after it has been restarted.
|
||||
const pingGeneration = expectedGeneration ?? this.monitorGeneration.get(targetIdStr);
|
||||
if (this.monitorGeneration.get(targetIdStr) !== pingGeneration) return;
|
||||
const activePing = this.inFlight.get(targetIdStr);
|
||||
if (activePing && activePing.generation === pingGeneration) return;
|
||||
const pingToken = {};
|
||||
this.inFlight.set(targetIdStr, { generation: pingGeneration, token: pingToken });
|
||||
|
||||
try {
|
||||
// Support both Prisma's 'id' and legacy '_id'
|
||||
|
||||
// Check debug logging setting (cache it, check every 60 seconds)
|
||||
if (!this.debugLoggingChecked || Date.now() - (this.debugLoggingLastCheck || 0) > 60000) {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const settings = await prisma.adminSettings.findUnique({ where: { id: 'settings' } });
|
||||
this.debugLogging = settings?.debugLogging === true;
|
||||
this.debugLoggingChecked = true;
|
||||
this.debugLoggingLastCheck = Date.now();
|
||||
} catch (err) {
|
||||
// If we can't check, default to false
|
||||
this.debugLogging = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Ping is now non-blocking via worker threads
|
||||
const result = await pingService.ping(target);
|
||||
if (pingGeneration !== null && this.monitorGeneration.get(targetIdStr) !== pingGeneration) return;
|
||||
|
||||
// Debug logging
|
||||
if (this.debugLogging) {
|
||||
const timestamp = new Date().toISOString();
|
||||
const status = result.success ? chalk.green('✓ UP') : chalk.red('✗ DOWN');
|
||||
const responseTime = result.responseTime ? `${Math.round(result.responseTime)}ms` : 'N/A';
|
||||
const protocol = result.protocol || target.protocol || 'UNKNOWN';
|
||||
console.log(chalk.cyan(`[${timestamp}]`) + ` ${status} ${chalk.yellow(target.name)} (${target.host}:${target.port || 'default'}) - ${protocol} - ${responseTime}`);
|
||||
if (result.error) {
|
||||
console.log(chalk.gray(` Error: ${result.error}`));
|
||||
}
|
||||
if (result.statusCode) {
|
||||
console.log(chalk.gray(` Status Code: ${result.statusCode}`));
|
||||
}
|
||||
}
|
||||
|
||||
// Get current in-memory status (synchronous, fast)
|
||||
const currentStatus = this.targetStatus.get(targetIdStr);
|
||||
|
||||
// Determine status based on ping result and upside down mode
|
||||
let pingSuccess = result.success;
|
||||
if (target.upsideDown === true) {
|
||||
pingSuccess = !pingSuccess; // Invert the status
|
||||
}
|
||||
|
||||
// Handle retry logic
|
||||
const maxRetries = target.retries || 0;
|
||||
let newStatus = 'unknown';
|
||||
let downtimeDuration = null; // Capture downtime duration for notification
|
||||
let wasNotificationSent = false;
|
||||
|
||||
if (pingSuccess) {
|
||||
// Success - reset failure counter
|
||||
this.failureCount.set(targetIdStr, 0);
|
||||
newStatus = 'up';
|
||||
// Calculate downtime duration before clearing the timestamp
|
||||
const downTime = this.downTimestamp.get(targetIdStr);
|
||||
downtimeDuration = downTime ? Date.now() - downTime : null;
|
||||
wasNotificationSent = this.notificationSent.get(targetIdStr) === true;
|
||||
// Clear down timestamp and notification flag when coming back up
|
||||
this.downTimestamp.delete(targetIdStr);
|
||||
this.clearNotificationTimer(targetIdStr);
|
||||
this.notificationSent.delete(targetIdStr);
|
||||
} else {
|
||||
// Failure - increment counter
|
||||
const currentFailures = (this.failureCount.get(targetIdStr) || 0) + 1;
|
||||
this.failureCount.set(targetIdStr, currentFailures);
|
||||
|
||||
// Only mark as down if we've exceeded retry threshold
|
||||
if (currentFailures > maxRetries) {
|
||||
newStatus = 'down';
|
||||
// Track when monitor went down (only set once)
|
||||
if (!this.downTimestamp.has(targetIdStr)) {
|
||||
this.downTimestamp.set(targetIdStr, Date.now());
|
||||
}
|
||||
this.scheduleDownNotification(target, targetIdStr, result.responseTime, pingGeneration);
|
||||
} else {
|
||||
// Still retrying, keep current status or mark as unknown
|
||||
newStatus = currentStatus || 'unknown';
|
||||
}
|
||||
}
|
||||
|
||||
// Always update status immediately (in-memory, fast)
|
||||
this.targetStatus.set(targetIdStr, newStatus);
|
||||
|
||||
// Defer database operations to next tick to avoid blocking
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
// The monitor may have been disabled or restarted while the ping
|
||||
// result was waiting for the event loop. Do not persist or emit
|
||||
// status events from that stale generation.
|
||||
if (this.monitorGeneration.get(targetIdStr) !== pingGeneration) return;
|
||||
const prisma = getPrisma();
|
||||
const timestamp = new Date();
|
||||
|
||||
// Store ping result in database (non-blocking)
|
||||
prisma.pingResult.create({
|
||||
data: {
|
||||
targetId: targetId,
|
||||
success: result.success,
|
||||
responseTime: result.responseTime || null,
|
||||
timestamp,
|
||||
statusCode: result.statusCode || null,
|
||||
error: result.error || null,
|
||||
protocol: result.protocol || null,
|
||||
},
|
||||
}).then(() => {
|
||||
// Debug logging for successful DB write
|
||||
if (this.debugLogging) {
|
||||
console.log(chalk.gray(` → Ping result saved to database`));
|
||||
}
|
||||
}).catch(err => {
|
||||
// Log DB errors to help diagnose issues
|
||||
console.error(chalk.red(`✗ DB write error for ${target.name}:`), err.message);
|
||||
console.error(chalk.gray(' Error details:'), err);
|
||||
});
|
||||
|
||||
// Update statistics (non-blocking)
|
||||
this.updateStatistics(target, result).then(() => {
|
||||
// Debug logging for successful statistics update
|
||||
if (this.debugLogging) {
|
||||
console.log(chalk.gray(` → Statistics updated`));
|
||||
}
|
||||
}).catch((err) => {
|
||||
// Log statistics errors to help diagnose issues
|
||||
console.error(chalk.red(`✗ Statistics update error for ${target.name}:`), err.message);
|
||||
console.error(chalk.gray(' Error details:'), err);
|
||||
});
|
||||
|
||||
// Handle status changes
|
||||
if (newStatus !== currentStatus && currentStatus !== 'unknown') {
|
||||
if (newStatus === 'up') {
|
||||
// Use downtime duration calculated before timestamp was deleted (captured in closure)
|
||||
this.handleTargetUp(target, result.responseTime, downtimeDuration, wasNotificationSent).catch(err => {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.error(chalk.yellow(`Alert error for ${target.name}:`), err.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Evaluate event detection rules (non-blocking)
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
const eventDetectionService = require('./eventDetectionService');
|
||||
await eventDetectionService.evaluateRules({
|
||||
targetId: targetIdStr,
|
||||
target: target,
|
||||
status: newStatus,
|
||||
responseTime: result.responseTime,
|
||||
targetGroup: target.group,
|
||||
});
|
||||
} catch (error) {
|
||||
// Silently fail - event detection is not critical
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.error(chalk.yellow(`Event detection error for ${target.name}:`), error.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
// Silently handle errors to avoid blocking
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.error(chalk.yellow(`Error processing result for ${target.name}:`), error.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(chalk.red(`Error pinging ${target.name}:`), error.message);
|
||||
} finally {
|
||||
// A newer generation may already be pinging this target. Do not let an
|
||||
// older worker completion clear the newer request's in-flight marker.
|
||||
if (this.inFlight.get(targetIdStr)?.token === pingToken) {
|
||||
this.inFlight.delete(targetIdStr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getNotificationDelayMs() {
|
||||
return Math.max(1, this.notificationDelayMinutes || 5) * 60 * 1000;
|
||||
}
|
||||
|
||||
setNotificationDelayMinutes(value, options = {}) {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
const nextDelay = Number.isFinite(parsed) ? Math.min(1440, Math.max(1, parsed)) : 5;
|
||||
const changed = nextDelay !== this.notificationDelayMinutes;
|
||||
this.notificationDelayMinutes = nextDelay;
|
||||
if (changed) {
|
||||
this.notificationDelayVersion += 1;
|
||||
if (options.reschedule !== false) this.rescheduleNotificationTimers();
|
||||
}
|
||||
}
|
||||
|
||||
getNotificationState(targetId) {
|
||||
const id = targetId.toString ? targetId.toString() : String(targetId);
|
||||
const downSince = this.downTimestamp.get(id) || null;
|
||||
const downDurationMs = downSince ? Math.max(0, Date.now() - downSince) : 0;
|
||||
return {
|
||||
downSince: downSince ? new Date(downSince).toISOString() : null,
|
||||
downDurationMs,
|
||||
notificationDelayMinutes: this.notificationDelayMinutes,
|
||||
notificationEligible: Boolean(downSince && downDurationMs >= this.getNotificationDelayMs()),
|
||||
notificationSent: this.notificationSent.get(id) === true,
|
||||
lastNotificationSentAt: this.lastNotificationSentAt.get(id) || null,
|
||||
};
|
||||
}
|
||||
|
||||
clearNotificationTimer(targetId) {
|
||||
const timer = this.notificationTimers.get(targetId);
|
||||
if (timer) clearTimeout(timer);
|
||||
this.notificationTimers.delete(targetId);
|
||||
}
|
||||
|
||||
async scheduleDownNotification(target, targetIdStr, responseTime = null, expectedGeneration = null) {
|
||||
if (expectedGeneration !== null && this.monitorGeneration.get(targetIdStr) !== expectedGeneration) return;
|
||||
if (this.notificationSent.get(targetIdStr) || this.notificationTimers.has(targetIdStr) || this.notificationScheduling.has(targetIdStr)) return;
|
||||
const schedulingGeneration = expectedGeneration ?? this.monitorGeneration.get(targetIdStr) ?? null;
|
||||
this.notificationScheduling.set(targetIdStr, schedulingGeneration);
|
||||
const delayVersionAtStart = this.notificationDelayVersion;
|
||||
try {
|
||||
let delayMinutes = this.notificationDelayMinutes;
|
||||
try {
|
||||
const notificationService = require('./notificationService');
|
||||
if (typeof notificationService.getMonitorDownDelayMinutes === 'function') {
|
||||
delayMinutes = await notificationService.getMonitorDownDelayMinutes();
|
||||
}
|
||||
} catch (error) {
|
||||
// Keep scheduling with the safe in-memory default when the settings
|
||||
// store is temporarily unavailable. The next outage check can pick
|
||||
// up the persisted value once the database is healthy again.
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.error(chalk.yellow(`Notification settings lookup failed for ${target.name}:`), error.message);
|
||||
}
|
||||
}
|
||||
// A settings update may have happened while the database lookup was in
|
||||
// flight. Do not let an older lookup overwrite the newly selected global
|
||||
// delay; use the current in-memory value in that case.
|
||||
if (this.notificationDelayVersion === delayVersionAtStart) {
|
||||
this.setNotificationDelayMinutes(delayMinutes, { reschedule: false });
|
||||
}
|
||||
const downSince = this.downTimestamp.get(targetIdStr);
|
||||
if (!downSince || this.notificationSent.get(targetIdStr)) return;
|
||||
if ((this.monitorGeneration.get(targetIdStr) ?? null) !== schedulingGeneration) return;
|
||||
const remaining = Math.max(0, downSince + this.getNotificationDelayMs() - Date.now());
|
||||
const timer = setTimeout(() => {
|
||||
this.notificationTimers.delete(targetIdStr);
|
||||
if ((this.monitorGeneration.get(targetIdStr) ?? null) !== schedulingGeneration) return;
|
||||
if (this.targetStatus.get(targetIdStr) !== 'down' || !this.downTimestamp.has(targetIdStr) || this.notificationSent.get(targetIdStr)) return;
|
||||
this.notificationSent.set(targetIdStr, true);
|
||||
this.lastNotificationSentAt.set(targetIdStr, new Date().toISOString());
|
||||
const currentTarget = this.monitorTargets.get(targetIdStr) || target;
|
||||
this.handleTargetDown(currentTarget, responseTime).catch(err => {
|
||||
if (process.env.NODE_ENV === 'development') console.error(chalk.yellow(`Alert error for ${target.name}:`), err.message);
|
||||
});
|
||||
}, remaining);
|
||||
this.notificationTimers.set(targetIdStr, timer);
|
||||
} catch (error) {
|
||||
if (process.env.NODE_ENV === 'development') console.error(chalk.yellow(`Notification scheduling error for ${target.name}:`), error.message);
|
||||
} finally {
|
||||
if (this.notificationScheduling.get(targetIdStr) === schedulingGeneration) {
|
||||
this.notificationScheduling.delete(targetIdStr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rescheduleNotificationTimers() {
|
||||
for (const [targetIdStr, target] of this.monitorTargets.entries()) {
|
||||
if (this.downTimestamp.has(targetIdStr) && !this.notificationSent.get(targetIdStr)) {
|
||||
this.clearNotificationTimer(targetIdStr);
|
||||
this.scheduleDownNotification(target, targetIdStr, null, this.monitorGeneration.get(targetIdStr) ?? null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle target going down
|
||||
*/
|
||||
async handleTargetDown(target, responseTime = null) {
|
||||
const prisma = getPrisma();
|
||||
const targetId = target.id || target._id;
|
||||
const targetIdStr = targetId.toString();
|
||||
const now = Date.now();
|
||||
const lastAlertTime = this.lastAlertTime.get(targetIdStr) || 0;
|
||||
const alertCooldown = (process.env.ALERT_COOLDOWN || 300) * 1000; // 5 minutes default
|
||||
|
||||
// Create alert
|
||||
await prisma.alert.create({
|
||||
data: {
|
||||
targetId: targetId,
|
||||
type: 'down',
|
||||
timestamp: new Date(),
|
||||
message: `${target.name} is DOWN (${target.host} - ${target.protocol})`,
|
||||
},
|
||||
});
|
||||
|
||||
// Log alert if cooldown passed
|
||||
if (now - lastAlertTime > alertCooldown) {
|
||||
this.lastAlertTime.set(targetIdStr, now);
|
||||
console.log(chalk.red(`✗ ${target.name} is DOWN`));
|
||||
}
|
||||
|
||||
// Send external notifications (non-blocking)
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
const notificationService = require('./notificationService');
|
||||
await notificationService.notifyMonitorStatus(target, 'down', responseTime);
|
||||
} catch (error) {
|
||||
// Silently fail - notifications are not critical
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.error(chalk.yellow(`Notification error for ${target.name}:`), error.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle target coming back up
|
||||
*/
|
||||
async handleTargetUp(target, responseTime = null, downtimeDuration = null, notificationWasSent = null) {
|
||||
const prisma = getPrisma();
|
||||
const targetId = target.id || target._id;
|
||||
const shouldNotify = notificationWasSent === null
|
||||
? this.notificationSent.get(targetId.toString()) === true
|
||||
: notificationWasSent === true;
|
||||
|
||||
// Create alert
|
||||
await prisma.alert.create({
|
||||
data: {
|
||||
targetId: targetId,
|
||||
type: 'up',
|
||||
timestamp: new Date(),
|
||||
message: `${target.name} is UP (${target.host} - ${target.protocol})`,
|
||||
},
|
||||
});
|
||||
|
||||
// Log recovery
|
||||
console.log(chalk.green(`✓ ${target.name} is UP`));
|
||||
|
||||
// A recovery notification is paired with a previously emitted outage
|
||||
// notification. Short or otherwise unnotified outages stay silent while
|
||||
// the internal alert history still records the state transition.
|
||||
if (!shouldNotify) {
|
||||
return { skipped: true, reason: 'Outage shorter than notification delay' };
|
||||
}
|
||||
|
||||
// Send external notifications (non-blocking)
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
const notificationService = require('./notificationService');
|
||||
await notificationService.notifyMonitorStatus(target, 'up', responseTime, downtimeDuration);
|
||||
} catch (error) {
|
||||
// Silently fail - notifications are not critical
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.error(chalk.yellow(`Notification error for ${target.name}:`), error.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update statistics for target
|
||||
*/
|
||||
async updateStatistics(target, pingResult) {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const targetId = target.id || target._id;
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
|
||||
// Use upsert for atomic update or insert
|
||||
const stats = await prisma.statistic.findUnique({
|
||||
where: {
|
||||
targetId_date: {
|
||||
targetId: targetId,
|
||||
date: today,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (stats) {
|
||||
// Update existing stats
|
||||
const newTotalPings = stats.totalPings + 1;
|
||||
const newSuccessfulPings = pingResult.success ? stats.successfulPings + 1 : stats.successfulPings;
|
||||
const newFailedPings = !pingResult.success ? stats.failedPings + 1 : stats.failedPings;
|
||||
|
||||
await prisma.statistic.update({
|
||||
where: {
|
||||
targetId_date: {
|
||||
targetId: targetId,
|
||||
date: today,
|
||||
},
|
||||
},
|
||||
data: {
|
||||
totalPings: newTotalPings,
|
||||
successfulPings: newSuccessfulPings,
|
||||
failedPings: newFailedPings,
|
||||
uptime: (newSuccessfulPings / newTotalPings) * 100,
|
||||
lastResponseTime: pingResult.responseTime || 0,
|
||||
avgResponseTime:
|
||||
(stats.avgResponseTime * stats.totalPings + (pingResult.responseTime || 0)) / newTotalPings,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// Create new stats
|
||||
await prisma.statistic.create({
|
||||
data: {
|
||||
targetId: targetId,
|
||||
date: today,
|
||||
totalPings: 1,
|
||||
successfulPings: pingResult.success ? 1 : 0,
|
||||
failedPings: pingResult.success ? 0 : 1,
|
||||
uptime: pingResult.success ? 100 : 0,
|
||||
lastResponseTime: pingResult.responseTime || 0,
|
||||
avgResponseTime: pingResult.responseTime || 0,
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
// Handle unique constraint violation (race condition) - retry
|
||||
if (error.code === 'P2002') {
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const targetId = target.id || target._id;
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
|
||||
const existingStats = await prisma.statistic.findUnique({
|
||||
where: {
|
||||
targetId_date: {
|
||||
targetId: targetId,
|
||||
date: today,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (existingStats) {
|
||||
const newTotalPings = existingStats.totalPings + 1;
|
||||
const newSuccessfulPings = pingResult.success ? existingStats.successfulPings + 1 : existingStats.successfulPings;
|
||||
const newFailedPings = !pingResult.success ? existingStats.failedPings + 1 : existingStats.failedPings;
|
||||
|
||||
await prisma.statistic.update({
|
||||
where: {
|
||||
targetId_date: {
|
||||
targetId: targetId,
|
||||
date: today,
|
||||
},
|
||||
},
|
||||
data: {
|
||||
totalPings: newTotalPings,
|
||||
successfulPings: newSuccessfulPings,
|
||||
failedPings: newFailedPings,
|
||||
uptime: (newSuccessfulPings / newTotalPings) * 100,
|
||||
lastResponseTime: pingResult.responseTime || 0,
|
||||
avgResponseTime:
|
||||
(existingStats.avgResponseTime * existingStats.totalPings + (pingResult.responseTime || 0)) / newTotalPings,
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (retryError) {
|
||||
// Silently ignore retry errors
|
||||
}
|
||||
}
|
||||
// Silently ignore other statistics errors to avoid log spam
|
||||
// They're not critical for core functionality
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop monitoring a target
|
||||
*/
|
||||
stopTargetMonitor(targetId) {
|
||||
const targetIdStr = targetId.toString ? targetId.toString() : targetId;
|
||||
// Invalidate any ping that is still awaiting a worker response. This is
|
||||
// important when a monitor is disabled or its settings are replaced.
|
||||
this.monitorGeneration.set(targetIdStr, (this.monitorGeneration.get(targetIdStr) || 0) + 1);
|
||||
if (this.intervals.has(targetIdStr)) {
|
||||
clearInterval(this.intervals.get(targetIdStr));
|
||||
this.intervals.delete(targetIdStr);
|
||||
console.log(chalk.yellow(`⊘ Stopped monitoring ${targetIdStr}`));
|
||||
}
|
||||
this.targetStatus.delete(targetIdStr);
|
||||
this.lastAlertTime.delete(targetIdStr);
|
||||
this.failureCount.delete(targetIdStr);
|
||||
this.downTimestamp.delete(targetIdStr);
|
||||
this.notificationSent.delete(targetIdStr);
|
||||
this.lastNotificationSentAt.delete(targetIdStr);
|
||||
this.clearNotificationTimer(targetIdStr);
|
||||
this.notificationScheduling.delete(targetIdStr);
|
||||
this.monitorTargets.delete(targetIdStr);
|
||||
this.inFlight.delete(targetIdStr);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop all monitoring
|
||||
*/
|
||||
stopAllMonitoring() {
|
||||
for (const [targetId, interval] of this.intervals.entries()) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
this.intervals.clear();
|
||||
this.targetStatus.clear();
|
||||
this.lastAlertTime.clear();
|
||||
this.failureCount.clear();
|
||||
this.downTimestamp.clear();
|
||||
this.notificationSent.clear();
|
||||
this.lastNotificationSentAt.clear();
|
||||
for (const timer of this.notificationTimers.values()) clearTimeout(timer);
|
||||
this.notificationTimers.clear();
|
||||
this.notificationScheduling.clear();
|
||||
this.monitorTargets.clear();
|
||||
this.inFlight.clear();
|
||||
// Keep generation numbers monotonic so a ping from before a full stop
|
||||
// cannot be mistaken for a ping from a newly started monitor that reuses
|
||||
// the same id.
|
||||
for (const [targetId, generation] of this.monitorGeneration.entries()) {
|
||||
this.monitorGeneration.set(targetId, generation + 1);
|
||||
}
|
||||
console.log(chalk.yellow('⊘ Stopped all monitoring'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get target status
|
||||
*/
|
||||
getTargetStatus(targetId) {
|
||||
return this.targetStatus.get(targetId.toString ? targetId.toString() : targetId) || 'unknown';
|
||||
}
|
||||
|
||||
/**
|
||||
* Set target status (for manual updates like test endpoints)
|
||||
*/
|
||||
setTargetStatus(targetId, status) {
|
||||
const targetIdStr = targetId.toString ? targetId.toString() : targetId;
|
||||
this.targetStatus.set(targetIdStr, status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all monitoring intervals
|
||||
*/
|
||||
getActiveMonitors() {
|
||||
return Array.from(this.intervals.keys());
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new MonitorService();
|
||||
@@ -0,0 +1,394 @@
|
||||
const axios = require('axios');
|
||||
const chalk = require('../utils/colors');
|
||||
const { getPrisma } = require('../config/prisma');
|
||||
|
||||
class NotificationService {
|
||||
constructor() {
|
||||
this.settings = null;
|
||||
this.settingsChecked = false;
|
||||
this.settingsLastCheck = 0;
|
||||
this.settingsCacheTTL = 60000; // 1 minute cache
|
||||
}
|
||||
|
||||
/**
|
||||
* Get notification settings from database (with caching)
|
||||
*/
|
||||
async getSettings() {
|
||||
const now = Date.now();
|
||||
|
||||
// Return cached settings if still valid
|
||||
if (this.settings && (now - this.settingsLastCheck) < this.settingsCacheTTL) {
|
||||
return this.settings;
|
||||
}
|
||||
|
||||
try {
|
||||
const prisma = getPrisma();
|
||||
const settingsDoc = await prisma.notificationSettings.findUnique({ where: { id: 'settings' } });
|
||||
|
||||
if (settingsDoc) {
|
||||
// Prisma stores JSON fields as objects, no need to parse
|
||||
const discord = settingsDoc.discord || null;
|
||||
const events = settingsDoc.events || null;
|
||||
|
||||
this.settings = {
|
||||
enabled: settingsDoc.enabled !== false,
|
||||
monitorDownDelayMinutes: this.normalizeDelay(settingsDoc.monitorDownDelayMinutes),
|
||||
discord: {
|
||||
enabled: discord?.enabled === true,
|
||||
webhookUrl: discord?.webhookUrl || null,
|
||||
username: discord?.username || 'LocalPing',
|
||||
avatarUrl: discord?.avatarUrl || null,
|
||||
},
|
||||
events: {
|
||||
monitorDown: events?.monitorDown !== false,
|
||||
monitorUp: events?.monitorUp !== false,
|
||||
incidentCreated: events?.incidentCreated !== false,
|
||||
incidentUpdated: events?.incidentUpdated !== false,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
// Default settings
|
||||
this.settings = {
|
||||
enabled: false,
|
||||
monitorDownDelayMinutes: 5,
|
||||
discord: {
|
||||
enabled: false,
|
||||
webhookUrl: null,
|
||||
username: 'LocalPing',
|
||||
avatarUrl: null,
|
||||
},
|
||||
events: {
|
||||
monitorDown: true,
|
||||
monitorUp: true,
|
||||
incidentCreated: true,
|
||||
incidentUpdated: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
this.settingsLastCheck = now;
|
||||
return this.settings;
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error loading notification settings:'), error.message);
|
||||
// Return default settings on error
|
||||
return {
|
||||
enabled: false,
|
||||
monitorDownDelayMinutes: 5,
|
||||
discord: { enabled: false, webhookUrl: null, username: 'LocalPing', avatarUrl: null },
|
||||
events: { monitorDown: true, monitorUp: true, incidentCreated: true, incidentUpdated: true },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
normalizeDelay(value) {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
if (!Number.isFinite(parsed)) return 5;
|
||||
return Math.min(1440, Math.max(1, parsed));
|
||||
}
|
||||
|
||||
async getMonitorDownDelayMinutes() {
|
||||
const settings = await this.getSettings();
|
||||
return this.normalizeDelay(settings.monitorDownDelayMinutes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate settings cache
|
||||
*/
|
||||
invalidateCache() {
|
||||
this.settings = null;
|
||||
this.settingsChecked = false;
|
||||
this.settingsLastCheck = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get avatar URL for Discord webhook
|
||||
* Returns the configured avatar URL or constructs a default URL using the ms-icon
|
||||
*/
|
||||
getAvatarUrl(configuredAvatarUrl) {
|
||||
// If avatar is configured, use it
|
||||
if (configuredAvatarUrl && configuredAvatarUrl.trim() && configuredAvatarUrl.includes('http')) {
|
||||
return configuredAvatarUrl;
|
||||
}
|
||||
|
||||
// Otherwise, construct default URL using environment variable or default
|
||||
// Use PUBLIC_URL, API_URL, or construct from PORT
|
||||
let baseUrl = process.env.PUBLIC_URL || process.env.API_URL;
|
||||
|
||||
if (!baseUrl) {
|
||||
// Construct from host and port if available
|
||||
const host = process.env.HOST || 'localhost';
|
||||
const port = process.env.API_PORT || process.env.PORT || 8000;
|
||||
const protocol = process.env.PROTOCOL || (port === 443 ? 'https' : 'http');
|
||||
baseUrl = `${protocol}://${host}${port !== 80 && port !== 443 ? `:${port}` : ''}`;
|
||||
}
|
||||
|
||||
// Ensure baseUrl doesn't end with a slash
|
||||
baseUrl = baseUrl.replace(/\/$/, '');
|
||||
|
||||
return `${baseUrl}/ms-icon-310x310.png`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send notification to Discord webhook
|
||||
*/
|
||||
async sendDiscordNotification(webhookUrl, payload) {
|
||||
try {
|
||||
const response = await axios.post(webhookUrl, payload, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
timeout: 10000, // 10 second timeout
|
||||
});
|
||||
|
||||
return { success: true, response: response.data };
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Discord webhook error:'), error.message);
|
||||
if (error.response) {
|
||||
console.error(chalk.gray(' Response status:'), error.response.status);
|
||||
console.error(chalk.gray(' Response data:'), error.response.data);
|
||||
}
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format Discord embed for monitor status change
|
||||
*/
|
||||
formatMonitorEmbed(target, status, responseTime = null, downtimeDuration = null) {
|
||||
const isUp = status === 'up';
|
||||
const color = isUp ? 0x10b981 : 0xef4444; // Green or Red
|
||||
const title = isUp ? '✓ Monitor Online' : '✗ Monitor Offline';
|
||||
let description = isUp
|
||||
? `${target.name} is back online`
|
||||
: `${target.name} is currently offline`;
|
||||
|
||||
// Add downtime duration to description if available
|
||||
if (isUp && downtimeDuration !== null) {
|
||||
const seconds = Math.floor(downtimeDuration / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
let durationStr = '';
|
||||
if (days > 0) {
|
||||
durationStr = `${days} day${days > 1 ? 's' : ''}, ${hours % 24} hour${(hours % 24) !== 1 ? 's' : ''}`;
|
||||
} else if (hours > 0) {
|
||||
durationStr = `${hours} hour${hours > 1 ? 's' : ''}, ${minutes % 60} minute${(minutes % 60) !== 1 ? 's' : ''}`;
|
||||
} else if (minutes > 0) {
|
||||
durationStr = `${minutes} minute${minutes > 1 ? 's' : ''}, ${seconds % 60} second${(seconds % 60) !== 1 ? 's' : ''}`;
|
||||
} else {
|
||||
durationStr = `${seconds} second${seconds !== 1 ? 's' : ''}`;
|
||||
}
|
||||
|
||||
description += ` (was down for ${durationStr})`;
|
||||
}
|
||||
|
||||
const embed = {
|
||||
title,
|
||||
description,
|
||||
color,
|
||||
fields: [
|
||||
{
|
||||
name: 'Monitor',
|
||||
value: target.name,
|
||||
inline: true,
|
||||
},
|
||||
{
|
||||
name: 'Host',
|
||||
value: `${target.host}${target.port ? `:${target.port}` : ''}`,
|
||||
inline: true,
|
||||
},
|
||||
{
|
||||
name: 'Protocol',
|
||||
value: target.protocol || 'ICMP',
|
||||
inline: true,
|
||||
},
|
||||
],
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
if (responseTime !== null) {
|
||||
embed.fields.push({
|
||||
name: 'Response Time',
|
||||
value: `${Math.round(responseTime)}ms`,
|
||||
inline: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (target.group) {
|
||||
embed.fields.push({
|
||||
name: 'Group',
|
||||
value: target.group,
|
||||
inline: true,
|
||||
});
|
||||
}
|
||||
|
||||
return embed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format Discord embed for incident
|
||||
*/
|
||||
formatIncidentEmbed(incident, isUpdate = false) {
|
||||
const severityColors = {
|
||||
minor: 0x3b82f6, // Blue
|
||||
major: 0xf59e0b, // Yellow/Orange
|
||||
critical: 0xef4444, // Red
|
||||
};
|
||||
|
||||
const statusEmojis = {
|
||||
investigating: '🔍',
|
||||
identified: '⚠️',
|
||||
monitoring: '👁️',
|
||||
resolved: '✅',
|
||||
};
|
||||
|
||||
const color = severityColors[incident.severity] || 0x6b7280;
|
||||
const emoji = statusEmojis[incident.status] || '📢';
|
||||
const title = isUpdate
|
||||
? `${emoji} Incident Updated: ${incident.title}`
|
||||
: `🚨 New Incident: ${incident.title}`;
|
||||
|
||||
const embed = {
|
||||
title,
|
||||
description: incident.description,
|
||||
color,
|
||||
fields: [
|
||||
{
|
||||
name: 'Severity',
|
||||
value: incident.severity.toUpperCase(),
|
||||
inline: true,
|
||||
},
|
||||
{
|
||||
name: 'Status',
|
||||
value: incident.status.toUpperCase(),
|
||||
inline: true,
|
||||
},
|
||||
],
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
if (incident.affectedServices && incident.affectedServices.length > 0) {
|
||||
embed.fields.push({
|
||||
name: 'Affected Services',
|
||||
value: incident.affectedServices.join(', '),
|
||||
inline: false,
|
||||
});
|
||||
}
|
||||
|
||||
return embed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify about monitor status change
|
||||
*/
|
||||
async notifyMonitorStatus(target, status, responseTime = null, downtimeDuration = null) {
|
||||
const settings = await this.getSettings();
|
||||
|
||||
if (!settings.enabled) {
|
||||
return { success: false, reason: 'Notifications disabled' };
|
||||
}
|
||||
|
||||
const eventType = status === 'up' ? 'monitorUp' : 'monitorDown';
|
||||
if (!settings.events[eventType]) {
|
||||
return { success: false, reason: `Event ${eventType} disabled` };
|
||||
}
|
||||
|
||||
const results = [];
|
||||
|
||||
// Send Discord notification if enabled
|
||||
if (settings.discord.enabled && settings.discord.webhookUrl) {
|
||||
const embed = this.formatMonitorEmbed(target, status, responseTime, downtimeDuration);
|
||||
const payload = {
|
||||
username: settings.discord.username,
|
||||
embeds: [embed],
|
||||
avatar_url: this.getAvatarUrl(settings.discord.avatarUrl),
|
||||
};
|
||||
|
||||
// Add @everyone for important monitors going down
|
||||
if (status === 'down' && target.important === true) {
|
||||
payload.content = '@everyone';
|
||||
}
|
||||
|
||||
const result = await this.sendDiscordNotification(settings.discord.webhookUrl, payload);
|
||||
results.push({ provider: 'discord', ...result });
|
||||
}
|
||||
|
||||
return {
|
||||
success: results.some(r => r.success),
|
||||
results,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify about incident
|
||||
*/
|
||||
async notifyIncident(incident, isUpdate = false) {
|
||||
const settings = await this.getSettings();
|
||||
|
||||
if (!settings.enabled) {
|
||||
return { success: false, reason: 'Notifications disabled' };
|
||||
}
|
||||
|
||||
const eventType = isUpdate ? 'incidentUpdated' : 'incidentCreated';
|
||||
if (!settings.events[eventType]) {
|
||||
return { success: false, reason: `Event ${eventType} disabled` };
|
||||
}
|
||||
|
||||
const results = [];
|
||||
|
||||
// Send Discord notification if enabled
|
||||
if (settings.discord.enabled && settings.discord.webhookUrl) {
|
||||
const embed = this.formatIncidentEmbed(incident, isUpdate);
|
||||
const payload = {
|
||||
username: settings.discord.username,
|
||||
embeds: [embed],
|
||||
avatar_url: this.getAvatarUrl(settings.discord.avatarUrl),
|
||||
};
|
||||
|
||||
const result = await this.sendDiscordNotification(settings.discord.webhookUrl, payload);
|
||||
results.push({ provider: 'discord', ...result });
|
||||
}
|
||||
|
||||
return {
|
||||
success: results.some(r => r.success),
|
||||
results,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Test notification (for testing webhook configuration)
|
||||
*/
|
||||
async testNotification(provider = 'discord') {
|
||||
const settings = await this.getSettings();
|
||||
|
||||
if (!settings.enabled) {
|
||||
return { success: false, error: 'Notifications are disabled' };
|
||||
}
|
||||
|
||||
if (provider === 'discord') {
|
||||
if (!settings.discord.enabled || !settings.discord.webhookUrl) {
|
||||
return { success: false, error: 'Discord notifications are not configured' };
|
||||
}
|
||||
|
||||
const payload = {
|
||||
username: settings.discord.username,
|
||||
embeds: [
|
||||
{
|
||||
title: '🧪 Test Notification',
|
||||
description: 'This is a test notification from LocalPing. If you receive this, your webhook is configured correctly!',
|
||||
color: 0x06b6d4, // Cyan
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
avatar_url: this.getAvatarUrl(settings.discord.avatarUrl),
|
||||
};
|
||||
|
||||
return await this.sendDiscordNotification(settings.discord.webhookUrl, payload);
|
||||
}
|
||||
|
||||
return { success: false, error: `Unknown provider: ${provider}` };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new NotificationService();
|
||||
@@ -0,0 +1,321 @@
|
||||
const workerPool = require('./workers/workerPool');
|
||||
const { exec } = require('child_process');
|
||||
const { promisify } = require('util');
|
||||
const axios = require('axios');
|
||||
const tcpPing = require('tcp-ping');
|
||||
const dgram = require('dgram');
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
class PingService {
|
||||
constructor() {
|
||||
this.timeout = 5000; // 5 seconds default timeout
|
||||
this.useWorkers = true; // Use worker threads by default
|
||||
}
|
||||
|
||||
/**
|
||||
* Ping a target using the specified protocol (multithreaded via worker pool)
|
||||
* @param {Object} target - Target object {host, port, protocol, timeout, httpMethod, statusCodes, ...}
|
||||
* @returns {Promise<Object>} Result {success, responseTime, error}
|
||||
*/
|
||||
async ping(target) {
|
||||
if (this.useWorkers) {
|
||||
// Use worker pool for non-blocking multithreaded pings
|
||||
return await workerPool.execute(target);
|
||||
}
|
||||
|
||||
// Fallback to direct execution (shouldn't be used in production)
|
||||
return await this.pingDirect(target);
|
||||
}
|
||||
|
||||
/**
|
||||
* Direct ping (fallback method, not recommended for production)
|
||||
* @private
|
||||
*/
|
||||
async pingDirect(target) {
|
||||
const start = Date.now();
|
||||
try {
|
||||
switch (target.protocol?.toUpperCase()) {
|
||||
case 'ICMP':
|
||||
return await this.pingICMP(target.host, start);
|
||||
case 'TCP':
|
||||
return await this.pingTCP(target.host, target.port || 80, start);
|
||||
case 'UDP':
|
||||
return await this.pingUDP(target.host, target.port || 53, start);
|
||||
case 'HTTP':
|
||||
return await this.pingHTTP(`http://${target.host}:${target.port || 80}${target.path || '/'}`, start, target);
|
||||
case 'HTTPS':
|
||||
return await this.pingHTTP(`https://${target.host}:${target.port || 443}${target.path || '/'}`, start, target);
|
||||
default:
|
||||
return {
|
||||
success: false,
|
||||
responseTime: 0,
|
||||
error: 'Unknown protocol: ' + target.protocol,
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
responseTime: Date.now() - start,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ICMP Ping using system ping command
|
||||
* Requires running with elevated privileges
|
||||
*/
|
||||
async pingICMP(host, start) {
|
||||
try {
|
||||
// Using -c 1 for Linux/Mac, -n 1 for Windows
|
||||
const isWindows = process.platform === 'win32';
|
||||
const cmd = isWindows ? `ping -n 1 -w ${this.timeout} ${host}` : `ping -c 1 -W ${this.timeout / 1000} ${host}`;
|
||||
|
||||
const { stdout } = await execAsync(cmd, { timeout: this.timeout + 1000 });
|
||||
|
||||
const responseTime = Date.now() - start;
|
||||
return {
|
||||
success: true,
|
||||
responseTime,
|
||||
protocol: 'ICMP',
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
responseTime: Date.now() - start,
|
||||
error: 'ICMP ping failed: ' + error.message,
|
||||
protocol: 'ICMP',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* TCP Ping to a specific port
|
||||
*/
|
||||
async pingTCP(host, port, start) {
|
||||
return new Promise((resolve) => {
|
||||
const startTime = Date.now();
|
||||
|
||||
tcpPing.probe(host, port, (err, available) => {
|
||||
const responseTime = Date.now() - startTime;
|
||||
|
||||
if (err || !available) {
|
||||
resolve({
|
||||
success: false,
|
||||
responseTime,
|
||||
error: err ? err.message : 'Connection refused',
|
||||
protocol: 'TCP',
|
||||
});
|
||||
} else {
|
||||
resolve({
|
||||
success: true,
|
||||
responseTime,
|
||||
protocol: 'TCP',
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* UDP Ping (simple datagram send/receive)
|
||||
*/
|
||||
async pingUDP(host, port, start) {
|
||||
return new Promise((resolve) => {
|
||||
const client = dgram.createSocket('udp4');
|
||||
const message = Buffer.from('ping');
|
||||
let resolved = false; // Track if we've already resolved
|
||||
|
||||
const timeoutHandle = setTimeout(() => {
|
||||
if (!resolved) {
|
||||
resolved = true;
|
||||
client.close();
|
||||
resolve({
|
||||
success: false,
|
||||
responseTime: Date.now() - start,
|
||||
error: 'UDP ping timeout',
|
||||
protocol: 'UDP',
|
||||
});
|
||||
}
|
||||
}, this.timeout);
|
||||
|
||||
client.send(message, 0, message.length, port, host, (err) => {
|
||||
if (err && !resolved) {
|
||||
resolved = true;
|
||||
clearTimeout(timeoutHandle);
|
||||
client.close();
|
||||
resolve({
|
||||
success: false,
|
||||
responseTime: Date.now() - start,
|
||||
error: 'UDP send failed: ' + err.message,
|
||||
protocol: 'UDP',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
client.on('message', () => {
|
||||
if (!resolved) {
|
||||
resolved = true;
|
||||
clearTimeout(timeoutHandle);
|
||||
client.close(); // Close immediately before resolve
|
||||
resolve({
|
||||
success: true,
|
||||
responseTime: Date.now() - start,
|
||||
protocol: 'UDP',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
client.on('error', (err) => {
|
||||
if (!resolved) {
|
||||
resolved = true;
|
||||
clearTimeout(timeoutHandle);
|
||||
client.close();
|
||||
resolve({
|
||||
success: false,
|
||||
responseTime: Date.now() - start,
|
||||
error: 'UDP error: ' + err.message,
|
||||
protocol: 'UDP',
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP/HTTPS Ping with advanced options
|
||||
*/
|
||||
async pingHTTP(url, start, target = {}) {
|
||||
try {
|
||||
// Get timeout from target config or use default
|
||||
const timeout = (target.timeout || 30) * 1000;
|
||||
|
||||
// Build axios config
|
||||
const axiosConfig = {
|
||||
timeout,
|
||||
validateStatus: () => true, // Don't throw on any status code
|
||||
maxRedirects: target.maxRedirects !== undefined ? target.maxRedirects : 5,
|
||||
method: (target.httpMethod || 'GET').toUpperCase(),
|
||||
};
|
||||
|
||||
// Handle SSL/TLS options
|
||||
if (target.ignoreSsl === true || target.ignoreSsl === 1) {
|
||||
const httpsAgent = require('https').Agent({ rejectUnauthorized: false });
|
||||
const httpAgent = require('http').Agent({ rejectUnauthorized: false });
|
||||
axiosConfig.httpsAgent = httpsAgent;
|
||||
axiosConfig.httpAgent = httpAgent;
|
||||
}
|
||||
|
||||
// Handle authentication
|
||||
let auth = target.auth;
|
||||
if (auth && typeof auth === 'string') {
|
||||
try {
|
||||
auth = JSON.parse(auth);
|
||||
} catch (e) {
|
||||
auth = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (auth) {
|
||||
if (auth.type === 'basic') {
|
||||
axiosConfig.auth = {
|
||||
username: auth.username,
|
||||
password: auth.password,
|
||||
};
|
||||
} else if (auth.type === 'bearer') {
|
||||
axiosConfig.headers = {
|
||||
'Authorization': `Bearer ${auth.token}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const response = await axios(url, axiosConfig);
|
||||
|
||||
const responseTime = Date.now() - start;
|
||||
|
||||
// Check if status code is in accepted list
|
||||
let success = false;
|
||||
const statusCodes = target.statusCodes || '200-299';
|
||||
|
||||
if (this.isStatusCodeAccepted(response.status, statusCodes)) {
|
||||
success = true;
|
||||
}
|
||||
|
||||
return {
|
||||
success,
|
||||
responseTime,
|
||||
statusCode: response.status,
|
||||
protocol: url.startsWith('https') ? 'HTTPS' : 'HTTP',
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
responseTime: Date.now() - start,
|
||||
error: error.message,
|
||||
protocol: url.startsWith('https') ? 'HTTPS' : 'HTTP',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a status code is in the accepted list
|
||||
* Supports ranges like "200-299" and individual codes like "200,201,404"
|
||||
*/
|
||||
isStatusCodeAccepted(statusCode, statusCodes) {
|
||||
if (!statusCodes) return statusCode >= 200 && statusCode < 300;
|
||||
|
||||
const parts = statusCodes.split(',').map(s => s.trim());
|
||||
|
||||
for (const part of parts) {
|
||||
if (part.includes('-')) {
|
||||
// Range like "200-299"
|
||||
const [start, end] = part.split('-').map(s => parseInt(s.trim()));
|
||||
if (statusCode >= start && statusCode <= end) {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
// Individual code like "200"
|
||||
if (parseInt(part) === statusCode) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Batch ping multiple targets (optimized with worker pool)
|
||||
*/
|
||||
async pingBatch(targets) {
|
||||
if (this.useWorkers) {
|
||||
// Use worker pool batch execution for optimal performance
|
||||
return await workerPool.executeBatch(targets);
|
||||
}
|
||||
// Fallback
|
||||
const results = await Promise.all(targets.map((target) => this.pingDirect(target)));
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shutdown worker pool (call during graceful shutdown)
|
||||
*/
|
||||
async shutdown() {
|
||||
if (this.useWorkers) {
|
||||
await workerPool.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get worker pool statistics
|
||||
*/
|
||||
getPoolStats() {
|
||||
if (this.useWorkers) {
|
||||
return workerPool.getStats();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new PingService();
|
||||
@@ -0,0 +1,322 @@
|
||||
const Database = require('better-sqlite3');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
const chalk = require('../utils/colors');
|
||||
|
||||
let db = null;
|
||||
|
||||
// Initialize SQLite database
|
||||
function initializeDatabase() {
|
||||
const dbDir = path.join(process.cwd(), 'data');
|
||||
const dbPath = path.join(dbDir, 'localping.db');
|
||||
|
||||
// Ensure data directory exists
|
||||
if (!fs.existsSync(dbDir)) {
|
||||
fs.mkdirSync(dbDir, { recursive: true });
|
||||
}
|
||||
|
||||
db = new Database(dbPath);
|
||||
|
||||
// Enable foreign keys
|
||||
db.pragma('foreign_keys = ON');
|
||||
|
||||
createTables();
|
||||
|
||||
console.log(chalk.green('✓ SQLite database initialized at:'), dbPath);
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
// Create tables if they don't exist
|
||||
function createTables() {
|
||||
// Check if ping_results table exists and has unique constraint
|
||||
try {
|
||||
const tableInfo = db.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name='ping_results'").get();
|
||||
if (tableInfo && tableInfo.sql && tableInfo.sql.includes('UNIQUE(targetId, timestamp)')) {
|
||||
// Migration: Remove unique constraint by recreating table
|
||||
console.log(chalk.yellow('⊘ Migrating ping_results table to remove unique constraint...'));
|
||||
db.exec(`
|
||||
CREATE TABLE ping_results_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
targetId TEXT NOT NULL,
|
||||
success BOOLEAN NOT NULL,
|
||||
responseTime INTEGER,
|
||||
timestamp DATETIME NOT NULL,
|
||||
statusCode INTEGER,
|
||||
error TEXT
|
||||
);
|
||||
INSERT INTO ping_results_new SELECT * FROM ping_results;
|
||||
DROP TABLE ping_results;
|
||||
ALTER TABLE ping_results_new RENAME TO ping_results;
|
||||
CREATE INDEX IF NOT EXISTS idx_ping_results_targetId ON ping_results(targetId);
|
||||
CREATE INDEX IF NOT EXISTS idx_ping_results_timestamp ON ping_results(timestamp);
|
||||
`);
|
||||
console.log(chalk.green('✓ Migration complete'));
|
||||
}
|
||||
} catch (error) {
|
||||
// Table doesn't exist or migration not needed, continue
|
||||
}
|
||||
|
||||
// Ping results table
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS ping_results (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
targetId TEXT NOT NULL,
|
||||
success BOOLEAN NOT NULL,
|
||||
responseTime INTEGER,
|
||||
timestamp DATETIME NOT NULL,
|
||||
statusCode INTEGER,
|
||||
error TEXT
|
||||
)
|
||||
`);
|
||||
|
||||
// Daily statistics table
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS daily_stats (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
targetId TEXT NOT NULL,
|
||||
date DATE NOT NULL,
|
||||
totalPings INTEGER DEFAULT 0,
|
||||
successfulPings INTEGER DEFAULT 0,
|
||||
avgResponseTime REAL DEFAULT 0,
|
||||
minResponseTime INTEGER,
|
||||
maxResponseTime INTEGER,
|
||||
UNIQUE(targetId, date)
|
||||
)
|
||||
`);
|
||||
|
||||
// Create indices for faster queries
|
||||
db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_ping_results_targetId ON ping_results(targetId);
|
||||
CREATE INDEX IF NOT EXISTS idx_ping_results_timestamp ON ping_results(timestamp);
|
||||
CREATE INDEX IF NOT EXISTS idx_daily_stats_targetId ON daily_stats(targetId);
|
||||
CREATE INDEX IF NOT EXISTS idx_daily_stats_date ON daily_stats(date);
|
||||
`);
|
||||
}
|
||||
|
||||
// Get database instance
|
||||
function getDatabase() {
|
||||
if (!db) {
|
||||
initializeDatabase();
|
||||
}
|
||||
return db;
|
||||
}
|
||||
|
||||
// Store ping result
|
||||
function storePingResult(targetId, result, timestamp = null) {
|
||||
const database = getDatabase();
|
||||
|
||||
try {
|
||||
// Use provided timestamp or current time with millisecond precision
|
||||
const pingTimestamp = timestamp || new Date().toISOString();
|
||||
|
||||
const stmt = database.prepare(`
|
||||
INSERT INTO ping_results (targetId, success, responseTime, statusCode, error, timestamp)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
stmt.run(
|
||||
targetId,
|
||||
result.success ? 1 : 0,
|
||||
result.responseTime || null,
|
||||
result.statusCode || null,
|
||||
result.error || null,
|
||||
pingTimestamp
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error storing ping result:'), error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Get ping results for a target
|
||||
function getPingResults(targetId, options = {}) {
|
||||
const database = getDatabase();
|
||||
const { limit = 100, offset = 0, days = null } = options;
|
||||
|
||||
try {
|
||||
let query = 'SELECT * FROM ping_results WHERE targetId = ?';
|
||||
const params = [targetId];
|
||||
|
||||
if (days) {
|
||||
const startDate = new Date();
|
||||
startDate.setDate(startDate.getDate() - days);
|
||||
query += ' AND timestamp >= ?';
|
||||
params.push(startDate.toISOString());
|
||||
}
|
||||
|
||||
query += ' ORDER BY timestamp DESC LIMIT ? OFFSET ?';
|
||||
params.push(limit, offset);
|
||||
|
||||
const stmt = database.prepare(query);
|
||||
const results = stmt.all(...params);
|
||||
|
||||
return results.map(r => ({
|
||||
...r,
|
||||
success: r.success === 1,
|
||||
timestamp: new Date(r.timestamp)
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error fetching ping results:'), error.message);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// Get daily statistics for a target
|
||||
function getDailyStats(targetId, options = {}) {
|
||||
const database = getDatabase();
|
||||
const { limit = 30, offset = 0 } = options;
|
||||
|
||||
try {
|
||||
const stmt = database.prepare(`
|
||||
SELECT * FROM daily_stats
|
||||
WHERE targetId = ?
|
||||
ORDER BY date DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`);
|
||||
|
||||
return stmt.all(targetId, limit, offset);
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error fetching daily stats:'), error.message);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// Update or create daily statistics
|
||||
function updateDailyStats(targetId) {
|
||||
const database = getDatabase();
|
||||
|
||||
try {
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
// Get today's ping results
|
||||
const stmt = database.prepare(`
|
||||
SELECT
|
||||
COUNT(*) as totalPings,
|
||||
SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successfulPings,
|
||||
AVG(CASE WHEN responseTime IS NOT NULL THEN responseTime ELSE NULL END) as avgResponseTime,
|
||||
MIN(CASE WHEN responseTime IS NOT NULL THEN responseTime ELSE NULL END) as minResponseTime,
|
||||
MAX(CASE WHEN responseTime IS NOT NULL THEN responseTime ELSE NULL END) as maxResponseTime
|
||||
FROM ping_results
|
||||
WHERE targetId = ? AND DATE(timestamp) = ?
|
||||
`);
|
||||
|
||||
const stats = stmt.get(targetId, today);
|
||||
|
||||
// Insert or update daily stats
|
||||
const insertStmt = database.prepare(`
|
||||
INSERT INTO daily_stats (targetId, date, totalPings, successfulPings, avgResponseTime, minResponseTime, maxResponseTime)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(targetId, date) DO UPDATE SET
|
||||
totalPings = excluded.totalPings,
|
||||
successfulPings = excluded.successfulPings,
|
||||
avgResponseTime = excluded.avgResponseTime,
|
||||
minResponseTime = excluded.minResponseTime,
|
||||
maxResponseTime = excluded.maxResponseTime
|
||||
`);
|
||||
|
||||
insertStmt.run(
|
||||
targetId,
|
||||
today,
|
||||
stats.totalPings || 0,
|
||||
stats.successfulPings || 0,
|
||||
stats.avgResponseTime || 0,
|
||||
stats.minResponseTime || null,
|
||||
stats.maxResponseTime || null
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error updating daily stats:'), error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Get uptime percentage for a target
|
||||
function getUptimePercentage(targetId, days = 30) {
|
||||
const database = getDatabase();
|
||||
|
||||
try {
|
||||
const stmt = database.prepare(`
|
||||
SELECT
|
||||
COUNT(*) as totalPings,
|
||||
SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successfulPings
|
||||
FROM ping_results
|
||||
WHERE targetId = ? AND timestamp >= datetime('now', '-' || ? || ' days')
|
||||
`);
|
||||
|
||||
const result = stmt.get(targetId, days);
|
||||
|
||||
if (result.totalPings === 0) {
|
||||
return 100;
|
||||
}
|
||||
|
||||
return ((result.successfulPings / result.totalPings) * 100).toFixed(2);
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error calculating uptime:'), error.message);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Clean old ping results (keep only last 90 days)
|
||||
function cleanupOldData() {
|
||||
const database = getDatabase();
|
||||
|
||||
try {
|
||||
const stmt = database.prepare(`
|
||||
DELETE FROM ping_results
|
||||
WHERE timestamp < datetime('now', '-90 days')
|
||||
`);
|
||||
|
||||
const changes = stmt.run().changes;
|
||||
|
||||
if (changes > 0) {
|
||||
console.log(chalk.yellow(`⊘ Cleaned up ${changes} old ping records`));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error cleaning up old data:'), error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Clear all ping data
|
||||
function clearAllPingData() {
|
||||
const database = getDatabase();
|
||||
|
||||
try {
|
||||
// Clear ping_results table
|
||||
const pingStmt = database.prepare('DELETE FROM ping_results');
|
||||
const pingChanges = pingStmt.run().changes;
|
||||
|
||||
// Clear daily_stats table
|
||||
const statsStmt = database.prepare('DELETE FROM daily_stats');
|
||||
const statsChanges = statsStmt.run().changes;
|
||||
|
||||
console.log(chalk.yellow(`⊘ Cleared ${pingChanges} ping records and ${statsChanges} daily stats`));
|
||||
|
||||
return {
|
||||
pingRecordsDeleted: pingChanges,
|
||||
dailyStatsDeleted: statsChanges
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Error clearing ping data:'), error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Close database connection
|
||||
function closeDatabase() {
|
||||
if (db) {
|
||||
db.close();
|
||||
db = null;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
initializeDatabase,
|
||||
getDatabase,
|
||||
storePingResult,
|
||||
getPingResults,
|
||||
getDailyStats,
|
||||
updateDailyStats,
|
||||
getUptimePercentage,
|
||||
cleanupOldData,
|
||||
clearAllPingData,
|
||||
closeDatabase,
|
||||
};
|
||||
@@ -0,0 +1,259 @@
|
||||
const { parentPort } = require('worker_threads');
|
||||
const { exec } = require('child_process');
|
||||
const { promisify } = require('util');
|
||||
const axios = require('axios');
|
||||
const tcpPing = require('tcp-ping');
|
||||
const dgram = require('dgram');
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
/**
|
||||
* Ping worker - handles ping operations in a separate thread
|
||||
*/
|
||||
class PingWorker {
|
||||
constructor() {
|
||||
this.timeout = 5000; // 5 seconds default timeout
|
||||
}
|
||||
|
||||
async pingICMP(host, timeout) {
|
||||
try {
|
||||
const isWindows = process.platform === 'win32';
|
||||
const cmd = isWindows
|
||||
? `ping -n 1 -w ${timeout} ${host}`
|
||||
: `ping -c 1 -W ${timeout / 1000} ${host}`;
|
||||
|
||||
const { stdout } = await execAsync(cmd, { timeout: timeout + 1000 });
|
||||
return { success: true, protocol: 'ICMP' };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'ICMP ping failed: ' + error.message,
|
||||
protocol: 'ICMP'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async pingTCP(host, port) {
|
||||
return new Promise((resolve) => {
|
||||
const startTime = Date.now();
|
||||
tcpPing.probe(host, port, (err, available) => {
|
||||
const responseTime = Date.now() - startTime;
|
||||
if (err || !available) {
|
||||
resolve({
|
||||
success: false,
|
||||
responseTime,
|
||||
error: err ? err.message : 'Connection refused',
|
||||
protocol: 'TCP',
|
||||
});
|
||||
} else {
|
||||
resolve({
|
||||
success: true,
|
||||
responseTime,
|
||||
protocol: 'TCP',
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async pingUDP(host, port, timeout) {
|
||||
return new Promise((resolve) => {
|
||||
const start = Date.now();
|
||||
const client = dgram.createSocket('udp4');
|
||||
const message = Buffer.from('ping');
|
||||
let resolved = false;
|
||||
|
||||
const timeoutHandle = setTimeout(() => {
|
||||
if (!resolved) {
|
||||
resolved = true;
|
||||
client.close();
|
||||
resolve({
|
||||
success: false,
|
||||
responseTime: Date.now() - start,
|
||||
error: 'UDP ping timeout',
|
||||
protocol: 'UDP',
|
||||
});
|
||||
}
|
||||
}, timeout);
|
||||
|
||||
client.send(message, 0, message.length, port, host, (err) => {
|
||||
if (err && !resolved) {
|
||||
resolved = true;
|
||||
clearTimeout(timeoutHandle);
|
||||
client.close();
|
||||
resolve({
|
||||
success: false,
|
||||
responseTime: Date.now() - start,
|
||||
error: 'UDP send failed: ' + err.message,
|
||||
protocol: 'UDP',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
client.on('message', () => {
|
||||
if (!resolved) {
|
||||
resolved = true;
|
||||
clearTimeout(timeoutHandle);
|
||||
client.close();
|
||||
resolve({
|
||||
success: true,
|
||||
responseTime: Date.now() - start,
|
||||
protocol: 'UDP',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
client.on('error', (err) => {
|
||||
if (!resolved) {
|
||||
resolved = true;
|
||||
clearTimeout(timeoutHandle);
|
||||
client.close();
|
||||
resolve({
|
||||
success: false,
|
||||
responseTime: Date.now() - start,
|
||||
error: 'UDP error: ' + err.message,
|
||||
protocol: 'UDP',
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async pingHTTP(url, target = {}) {
|
||||
try {
|
||||
const timeout = (target.timeout || 30) * 1000;
|
||||
const axiosConfig = {
|
||||
timeout,
|
||||
validateStatus: () => true,
|
||||
maxRedirects: target.maxRedirects !== undefined ? target.maxRedirects : 5,
|
||||
method: (target.httpMethod || 'GET').toUpperCase(),
|
||||
};
|
||||
|
||||
if (target.ignoreSsl === true || target.ignoreSsl === 1) {
|
||||
const httpsAgent = require('https').Agent({ rejectUnauthorized: false });
|
||||
const httpAgent = require('http').Agent({ rejectUnauthorized: false });
|
||||
axiosConfig.httpsAgent = httpsAgent;
|
||||
axiosConfig.httpAgent = httpAgent;
|
||||
}
|
||||
|
||||
let auth = target.auth;
|
||||
if (auth && typeof auth === 'string') {
|
||||
try {
|
||||
auth = JSON.parse(auth);
|
||||
} catch (e) {
|
||||
auth = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (auth) {
|
||||
if (auth.type === 'basic') {
|
||||
axiosConfig.auth = {
|
||||
username: auth.username,
|
||||
password: auth.password,
|
||||
};
|
||||
} else if (auth.type === 'bearer') {
|
||||
axiosConfig.headers = {
|
||||
'Authorization': `Bearer ${auth.token}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const response = await axios(url, axiosConfig);
|
||||
const statusCodes = target.statusCodes || '200-299';
|
||||
const success = this.isStatusCodeAccepted(response.status, statusCodes);
|
||||
|
||||
return {
|
||||
success,
|
||||
statusCode: response.status,
|
||||
protocol: url.startsWith('https') ? 'HTTPS' : 'HTTP',
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.message,
|
||||
protocol: url.startsWith('https') ? 'HTTPS' : 'HTTP',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
isStatusCodeAccepted(statusCode, statusCodes) {
|
||||
if (!statusCodes) return statusCode >= 200 && statusCode < 300;
|
||||
const parts = statusCodes.split(',').map(s => s.trim());
|
||||
for (const part of parts) {
|
||||
if (part.includes('-')) {
|
||||
const [start, end] = part.split('-').map(s => parseInt(s.trim()));
|
||||
if (statusCode >= start && statusCode <= end) {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
if (parseInt(part) === statusCode) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async executePing(target) {
|
||||
const start = Date.now();
|
||||
const timeout = target.timeout ? target.timeout * 1000 : this.timeout;
|
||||
|
||||
try {
|
||||
let result;
|
||||
switch (target.protocol?.toUpperCase()) {
|
||||
case 'ICMP':
|
||||
result = await this.pingICMP(target.host, timeout);
|
||||
break;
|
||||
case 'TCP':
|
||||
result = await this.pingTCP(target.host, target.port || 80);
|
||||
break;
|
||||
case 'UDP':
|
||||
result = await this.pingUDP(target.host, target.port || 53, timeout);
|
||||
break;
|
||||
case 'HTTP':
|
||||
result = await this.pingHTTP(`http://${target.host}:${target.port || 80}${target.path || '/'}`, target);
|
||||
break;
|
||||
case 'HTTPS':
|
||||
result = await this.pingHTTP(`https://${target.host}:${target.port || 443}${target.path || '/'}`, target);
|
||||
break;
|
||||
default:
|
||||
result = {
|
||||
success: false,
|
||||
error: 'Unknown protocol: ' + target.protocol,
|
||||
};
|
||||
}
|
||||
|
||||
result.responseTime = result.responseTime || (Date.now() - start);
|
||||
return result;
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
responseTime: Date.now() - start,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle messages from main thread
|
||||
const worker = new PingWorker();
|
||||
|
||||
parentPort.on('message', async (message) => {
|
||||
try {
|
||||
const result = await worker.executePing(message.target);
|
||||
parentPort.postMessage({
|
||||
id: message.id,
|
||||
result,
|
||||
});
|
||||
} catch (error) {
|
||||
parentPort.postMessage({
|
||||
id: message.id,
|
||||
result: {
|
||||
success: false,
|
||||
responseTime: 0,
|
||||
error: error.message,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
const { Worker } = require('worker_threads');
|
||||
const path = require('path');
|
||||
|
||||
/**
|
||||
* Worker Pool Manager - manages a pool of worker threads for ping operations
|
||||
*/
|
||||
class WorkerPool {
|
||||
constructor(size = 4) {
|
||||
this.size = size;
|
||||
this.workers = [];
|
||||
this.queue = [];
|
||||
this.activeTasks = new Map();
|
||||
this.taskIdCounter = 0;
|
||||
this.initialized = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the worker pool
|
||||
*/
|
||||
initialize() {
|
||||
if (this.initialized) return;
|
||||
|
||||
const workerPath = path.join(__dirname, 'pingWorker.js');
|
||||
const fs = require('fs');
|
||||
|
||||
// Verify worker file exists
|
||||
if (!fs.existsSync(workerPath)) {
|
||||
console.error(`Worker file not found: ${workerPath}`);
|
||||
throw new Error(`Worker file not found: ${workerPath}`);
|
||||
}
|
||||
|
||||
for (let i = 0; i < this.size; i++) {
|
||||
let worker;
|
||||
try {
|
||||
worker = new Worker(workerPath);
|
||||
} catch (error) {
|
||||
console.error(`Failed to create worker ${i}:`, error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
worker.on('message', (message) => {
|
||||
const { id, result } = message;
|
||||
const task = this.activeTasks.get(id);
|
||||
|
||||
if (task) {
|
||||
task.resolve(result);
|
||||
this.activeTasks.delete(id);
|
||||
}
|
||||
|
||||
// Mark worker as not busy
|
||||
const workerInfo = this.workers.find(w => w.worker === worker);
|
||||
if (workerInfo) {
|
||||
workerInfo.busy = false;
|
||||
}
|
||||
|
||||
this.processQueue();
|
||||
});
|
||||
|
||||
worker.on('error', (error) => {
|
||||
console.error(`Worker error:`, error);
|
||||
// Remove failed worker and create a new one
|
||||
const index = this.workers.indexOf(worker);
|
||||
if (index > -1) {
|
||||
this.workers.splice(index, 1);
|
||||
this.createWorker();
|
||||
}
|
||||
});
|
||||
|
||||
worker.on('exit', (code) => {
|
||||
if (code !== 0) {
|
||||
console.error(`Worker exited with code ${code}`);
|
||||
const index = this.workers.indexOf(worker);
|
||||
if (index > -1) {
|
||||
this.workers.splice(index, 1);
|
||||
this.createWorker();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.workers.push({
|
||||
worker,
|
||||
busy: false,
|
||||
});
|
||||
}
|
||||
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new worker to replace a failed one
|
||||
*/
|
||||
createWorker() {
|
||||
const workerPath = path.join(__dirname, 'pingWorker.js');
|
||||
const worker = new Worker(workerPath);
|
||||
|
||||
worker.on('message', (message) => {
|
||||
const { id, result } = message;
|
||||
const task = this.activeTasks.get(id);
|
||||
|
||||
if (task) {
|
||||
task.resolve(result);
|
||||
this.activeTasks.delete(id);
|
||||
}
|
||||
|
||||
// Mark worker as not busy
|
||||
const workerInfo = this.workers.find(w => w.worker === worker);
|
||||
if (workerInfo) {
|
||||
workerInfo.busy = false;
|
||||
}
|
||||
|
||||
this.processQueue();
|
||||
});
|
||||
|
||||
worker.on('error', (error) => {
|
||||
console.error(`Worker error:`, error);
|
||||
const index = this.workers.findIndex(w => w.worker === worker);
|
||||
if (index > -1) {
|
||||
this.workers[index].worker.terminate();
|
||||
this.workers.splice(index, 1);
|
||||
}
|
||||
});
|
||||
|
||||
worker.on('exit', (code) => {
|
||||
if (code !== 0) {
|
||||
const index = this.workers.findIndex(w => w.worker === worker);
|
||||
if (index > -1) {
|
||||
this.workers.splice(index, 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.workers.push({
|
||||
worker,
|
||||
busy: false,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an available worker
|
||||
*/
|
||||
getAvailableWorker() {
|
||||
return this.workers.find(w => !w.busy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the queue of pending tasks
|
||||
*/
|
||||
processQueue() {
|
||||
if (this.queue.length === 0) return;
|
||||
|
||||
const availableWorker = this.getAvailableWorker();
|
||||
if (!availableWorker) return;
|
||||
|
||||
const task = this.queue.shift();
|
||||
|
||||
// Check if task has already timed out
|
||||
if (!this.activeTasks.has(task.id)) {
|
||||
// Task was removed due to timeout, skip it
|
||||
this.processQueue();
|
||||
return;
|
||||
}
|
||||
|
||||
availableWorker.busy = true;
|
||||
|
||||
availableWorker.worker.postMessage({
|
||||
id: task.id,
|
||||
target: task.target,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a ping task using the worker pool
|
||||
*/
|
||||
async execute(target) {
|
||||
if (!this.initialized) {
|
||||
this.initialize();
|
||||
}
|
||||
|
||||
// Get timeout from target config or use default (60 seconds)
|
||||
const timeout = (target.timeout || 60) * 1000;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const taskId = ++this.taskIdCounter;
|
||||
|
||||
// Set up timeout for the task
|
||||
let assignedWorker = null;
|
||||
const timeoutHandle = setTimeout(() => {
|
||||
const task = this.activeTasks.get(taskId);
|
||||
if (task) {
|
||||
this.activeTasks.delete(taskId);
|
||||
|
||||
// Remove from queue if it's still queued
|
||||
const queueIndex = this.queue.findIndex(t => t.id === taskId);
|
||||
if (queueIndex !== -1) {
|
||||
this.queue.splice(queueIndex, 1);
|
||||
}
|
||||
|
||||
// Mark assigned worker as not busy if it was assigned
|
||||
if (assignedWorker) {
|
||||
assignedWorker.busy = false;
|
||||
}
|
||||
|
||||
task.reject(new Error(`Ping timeout after ${timeout}ms`));
|
||||
this.processQueue();
|
||||
}
|
||||
}, timeout);
|
||||
|
||||
const task = {
|
||||
id: taskId,
|
||||
target,
|
||||
timeoutHandle,
|
||||
resolve: (result) => {
|
||||
clearTimeout(timeoutHandle);
|
||||
resolve(result);
|
||||
},
|
||||
reject: (error) => {
|
||||
clearTimeout(timeoutHandle);
|
||||
reject(error);
|
||||
},
|
||||
};
|
||||
|
||||
const availableWorker = this.getAvailableWorker();
|
||||
|
||||
if (availableWorker) {
|
||||
availableWorker.busy = true;
|
||||
assignedWorker = availableWorker;
|
||||
this.activeTasks.set(taskId, task);
|
||||
|
||||
availableWorker.worker.postMessage({
|
||||
id: taskId,
|
||||
target,
|
||||
});
|
||||
} else {
|
||||
// No available worker, add to queue
|
||||
this.queue.push(task);
|
||||
// Store task in activeTasks so timeout can remove it from queue
|
||||
this.activeTasks.set(taskId, task);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute multiple pings concurrently
|
||||
*/
|
||||
async executeBatch(targets) {
|
||||
const promises = targets.map(target => this.execute(target));
|
||||
return Promise.all(promises);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shutdown all workers
|
||||
*/
|
||||
async shutdown() {
|
||||
const shutdownPromises = this.workers.map(({ worker }) => {
|
||||
return worker.terminate();
|
||||
});
|
||||
|
||||
await Promise.all(shutdownPromises);
|
||||
this.workers = [];
|
||||
this.queue = [];
|
||||
this.activeTasks.clear();
|
||||
this.initialized = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get pool statistics
|
||||
*/
|
||||
getStats() {
|
||||
return {
|
||||
totalWorkers: this.workers.length,
|
||||
busyWorkers: this.workers.filter(w => w.busy).length,
|
||||
queueLength: this.queue.length,
|
||||
activeTasks: this.activeTasks.size,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Create a singleton instance
|
||||
// Use optimal pool size based on CPU cores, but cap at 8 to avoid overhead
|
||||
const optimalSize = Math.min(Math.max(require('os').cpus().length, 2), 8);
|
||||
const workerPool = new WorkerPool(optimalSize);
|
||||
|
||||
module.exports = workerPool;
|
||||
|
||||
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 62 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#7db4ff"/><stop offset="1" stop-color="#3b6cf0"/></linearGradient></defs><rect width="512" height="512" rx="112" fill="#0b0d12"/><circle cx="256" cy="256" r="176" fill="none" stroke="url(#g)" stroke-width="28" opacity=".28"/><circle cx="256" cy="256" r="118" fill="none" stroke="url(#g)" stroke-width="28" opacity=".6"/><path d="M96 262h88l36-84 62 170 42-86h92" fill="none" stroke="url(#g)" stroke-width="30" stroke-linecap="round" stroke-linejoin="round"/><circle cx="400" cy="262" r="0" fill="#3ddc97"/></svg>
|
||||
|
After Width: | Height: | Size: 661 B |
@@ -0,0 +1,37 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Status</title>
|
||||
<meta name="description" content="Live status, incident history, news and small tools for the services on example.com.">
|
||||
<meta name="theme-color" content="#0b0d12">
|
||||
<link rel="icon" href="/brand/icon-32.png"><link rel="apple-touch-icon" href="/brand/icon-180.png"><link rel="manifest" href="/manifest.webmanifest">
|
||||
<link rel="alternate" type="application/rss+xml" title="News" href="/api/site/news.rss">
|
||||
<link rel="stylesheet" href="/s/site.css">
|
||||
<link rel="modulepreload" href="/s/site.js">
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip" href="#main">Skip to content</a>
|
||||
<header class="top">
|
||||
<a class="brand" href="/" data-link><span class="dot" id="brand-dot"></span><span id="brand-name">Status</span></a>
|
||||
<nav id="nav" aria-label="Main">
|
||||
<a href="/" data-link>Overview</a>
|
||||
<a href="/status" data-link>Status</a>
|
||||
<a href="/news" data-link>News</a>
|
||||
<a href="/tools" data-link>Tools</a>
|
||||
<a href="/about" data-link>About</a>
|
||||
</nav>
|
||||
</header>
|
||||
<main id="main" tabindex="-1"><div class="wrap"><div class="skeleton"></div></div></main>
|
||||
<footer class="foot">
|
||||
<div class="wrap">
|
||||
<span>© <span id="yr"></span> <span class="site-owner">Your Name</span></span>
|
||||
<span><a href="mailto:[email protected]">[email protected]</a> · <a href="/api/site/news.rss">RSS</a></span>
|
||||
<span>Powered by <a href="https://github.com/YOUR-ORG/localping">LocalPing</a></span>
|
||||
</div>
|
||||
</footer>
|
||||
<script type="module" src="/s/site.js"></script>
|
||||
<noscript><div class="wrap"><p>This site needs JavaScript to show live data. Contact: [email protected]</p></div></noscript>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,64 @@
|
||||
:root{--bg:#0b0d12;--panel:#12151c;--panel2:#171b24;--line:#232836;--text:#e8ebf2;--muted:#8a93a6;--acc:#6ea8ff;--ok:#3ddc97;--warn:#f5b942;--bad:#ff5d6c;--r:14px;color-scheme:dark}
|
||||
*{box-sizing:border-box}
|
||||
html{-webkit-text-size-adjust:100%}
|
||||
body{margin:0;background:var(--bg);color:var(--text);font:15px/1.55 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;min-height:100vh;display:flex;flex-direction:column}
|
||||
a{color:var(--acc);text-decoration:none}a:hover{text-decoration:underline}
|
||||
.skip{position:absolute;left:-999px}.skip:focus{left:8px;top:8px;background:#000;padding:8px;z-index:9}
|
||||
.wrap{max-width:1040px;margin:0 auto;padding:0 20px}
|
||||
.top{position:sticky;top:0;z-index:5;display:flex;align-items:center;justify-content:space-between;gap:16px;padding:12px 20px;background:rgba(11,13,18,.85);backdrop-filter:blur(10px);border-bottom:1px solid var(--line)}
|
||||
.brand{font-weight:700;font-size:17px;color:var(--text);display:flex;align-items:center;gap:9px;white-space:nowrap}.brand:hover{text-decoration:none}
|
||||
.muted{color:var(--muted)}
|
||||
.dot{width:10px;height:10px;border-radius:50%;background:var(--muted);box-shadow:0 0 0 0 transparent}
|
||||
.dot.operational{background:var(--ok);box-shadow:0 0 10px var(--ok)}.dot.degraded{background:var(--warn);box-shadow:0 0 10px var(--warn)}.dot.down{background:var(--bad);box-shadow:0 0 10px var(--bad)}
|
||||
nav{display:flex;gap:2px;overflow-x:auto;scrollbar-width:none}nav::-webkit-scrollbar{display:none}
|
||||
nav a{color:var(--muted);padding:7px 12px;border-radius:9px;font-weight:500;white-space:nowrap}
|
||||
nav a:hover{color:var(--text);background:var(--panel);text-decoration:none}nav a.on{color:var(--text);background:var(--panel2)}
|
||||
main{flex:1;padding:28px 0 56px;outline:none}
|
||||
h1{font-size:clamp(26px,4vw,38px);line-height:1.15;margin:0 0 8px;letter-spacing:-.02em}
|
||||
h2{font-size:18px;margin:34px 0 12px}
|
||||
.lead{color:var(--muted);max-width:60ch;margin:0 0 22px}
|
||||
.banner{display:flex;align-items:center;gap:14px;padding:18px 20px;border-radius:var(--r);border:1px solid var(--line);background:var(--panel)}
|
||||
.banner .big{font-size:20px;font-weight:650}.banner small{color:var(--muted)}
|
||||
.banner.operational{border-color:#1f4d3a;background:linear-gradient(90deg,#10231c,var(--panel))}
|
||||
.banner.degraded{border-color:#5a4513;background:linear-gradient(90deg,#261f0e,var(--panel))}
|
||||
.banner.down{border-color:#5c1f27;background:linear-gradient(90deg,#2a1216,var(--panel))}
|
||||
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin:14px 0}
|
||||
.stat{background:var(--panel);border:1px solid var(--line);border-radius:var(--r);padding:14px 16px}
|
||||
.stat b{display:block;font-size:24px;letter-spacing:-.02em}.stat span{color:var(--muted);font-size:13px}
|
||||
.list{background:var(--panel);border:1px solid var(--line);border-radius:var(--r);overflow:hidden}
|
||||
.row{display:grid;grid-template-columns:minmax(0,1.3fr) auto minmax(0,1fr) 64px;gap:14px;align-items:center;padding:12px 16px;border-top:1px solid var(--line)}
|
||||
.row:first-child{border-top:0}
|
||||
.svc{display:flex;align-items:center;gap:11px;min-width:0}
|
||||
.svc img{width:24px;height:24px;border-radius:6px;object-fit:contain;background:var(--panel2);flex:none}
|
||||
.svc .ph{width:24px;height:24px;border-radius:6px;background:var(--panel2);flex:none}
|
||||
.svc span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:550}
|
||||
.pill{font-size:12px;font-weight:600;padding:3px 9px;border-radius:99px;border:1px solid var(--line);white-space:nowrap}
|
||||
.pill.up{color:var(--ok);border-color:#1f4d3a;background:#10231c}.pill.down{color:var(--bad);border-color:#5c1f27;background:#2a1216}.pill.unknown{color:var(--muted)}
|
||||
.bars{display:flex;gap:2px;height:22px;align-items:stretch}
|
||||
.bars i{flex:1;border-radius:2px;background:var(--line);min-width:2px}
|
||||
.bars i.b1{background:var(--ok)}.bars i.b2{background:var(--warn)}.bars i.b3{background:var(--bad)}
|
||||
.pc{text-align:right;color:var(--muted);font-variant-numeric:tabular-nums;font-size:13px}
|
||||
.card{background:var(--panel);border:1px solid var(--line);border-radius:var(--r);padding:18px 20px;margin-bottom:12px}
|
||||
.card h3{margin:0 0 4px;font-size:16px}.card time,.meta{color:var(--muted);font-size:13px}
|
||||
.card p{margin:8px 0 0;white-space:pre-wrap}
|
||||
.tag{display:inline-block;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;padding:2px 8px;border-radius:6px;margin-right:6px;background:var(--panel2);color:var(--muted)}
|
||||
.tag.critical,.tag.major{color:var(--bad)}.tag.minor{color:var(--warn)}.tag.resolved{color:var(--ok)}.tag.scheduled{color:var(--acc)}
|
||||
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:12px}
|
||||
input,textarea,select,button{font:inherit;color:var(--text);background:var(--panel2);border:1px solid var(--line);border-radius:10px;padding:9px 12px}
|
||||
textarea{width:100%;min-height:90px;resize:vertical;font-family:ui-monospace,Menlo,monospace;font-size:13px}
|
||||
input{width:100%}button{cursor:pointer;background:var(--acc);color:#07101f;border:0;font-weight:650}button.ghost{background:var(--panel2);color:var(--text);border:1px solid var(--line)}
|
||||
.btns{display:flex;gap:8px;flex-wrap:wrap;margin:8px 0}
|
||||
.out{font-family:ui-monospace,Menlo,monospace;font-size:13px;word-break:break-all;background:var(--bg);border:1px solid var(--line);border-radius:10px;padding:10px;min-height:40px;margin-top:8px}
|
||||
.stale{background:#261f0e;border:1px solid #5a4513;color:var(--warn);padding:10px 14px;border-radius:10px;margin-bottom:14px}
|
||||
.skeleton{height:220px;border-radius:var(--r);background:linear-gradient(90deg,var(--panel),var(--panel2),var(--panel));background-size:200% 100%;animation:sh 1.2s infinite}
|
||||
@keyframes sh{to{background-position:-200% 0}}
|
||||
.foot{border-top:1px solid var(--line);padding:22px 0;color:var(--muted);font-size:13px}
|
||||
.foot .wrap{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap}
|
||||
@media(max-width:680px){
|
||||
.top{padding:10px 14px;flex-wrap:wrap}.wrap{padding:0 14px}
|
||||
.row{grid-template-columns:1fr auto;row-gap:8px}.row .bars{grid-column:1/-1;order:3}.row .pc{order:2;display:none}
|
||||
}
|
||||
@media(prefers-reduced-motion:reduce){*{animation:none!important}}
|
||||
.svc{position:relative}.info{flex:none;width:18px;height:18px;padding:0;border-radius:50%;background:var(--panel2);color:var(--muted);border:1px solid var(--line);font:italic 700 11px/1 Georgia,serif;display:inline-grid;place-items:center}
|
||||
.info:hover,.info[aria-expanded=true]{color:var(--acc);border-color:var(--acc)}
|
||||
.tip{position:absolute;left:0;top:100%;margin-top:6px;z-index:6;width:min(320px,80vw);background:#1b2030;border:1px solid var(--line);border-radius:10px;padding:10px 12px;font-size:13px;line-height:1.45;box-shadow:0 8px 30px rgba(0,0,0,.5)}
|
||||
@@ -0,0 +1,125 @@
|
||||
const $ = (s, r = document) => r.querySelector(s);
|
||||
const main = $('#main');
|
||||
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const LABEL = { operational: 'All systems operational', degraded: 'Some services are down', down: 'Major outage', unknown: 'Status unknown' };
|
||||
const ago = (d) => { const s = (Date.now() - new Date(d)) / 1e3; return s < 90 ? 'just now' : s < 5400 ? Math.round(s / 60) + ' min ago' : s < 129600 ? Math.round(s / 3600) + ' h ago' : new Date(d).toLocaleDateString(); };
|
||||
const fmt = (d) => new Date(d).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' });
|
||||
|
||||
let summary = null, lastOk = 0;
|
||||
async function load() {
|
||||
try {
|
||||
const r = await fetch('/api/site/summary');
|
||||
if (!r.ok) throw 0;
|
||||
summary = await r.json(); lastOk = Date.now();
|
||||
localStorage.setItem('summary', JSON.stringify(summary));
|
||||
} catch { if (!summary) try { summary = JSON.parse(localStorage.getItem('summary')); } catch {} }
|
||||
$('#brand-dot').className = 'dot ' + (summary?.overall || '');
|
||||
return summary;
|
||||
}
|
||||
const stale = () => (!lastOk || Date.now() - lastOk > 120e3) ? '<div class="stale">Live data is unavailable right now. Showing the last known state.</div>' : '';
|
||||
|
||||
const icon = (s) => s.icon ? `<img loading="lazy" decoding="async" width="24" height="24" alt="" src="/api/proxy-icon?url=${encodeURIComponent(s.icon)}">` : '<div class="ph"></div>';
|
||||
const row = (s) => `<div class="row">
|
||||
<div class="svc">${icon(s)}<span>${s.url ? `<a href="${esc(s.url)}" rel="noopener">${esc(s.name)}</a>` : esc(s.name)}</span>${s.description ? `<button class="info" type="button" aria-label="About ${esc(s.name)}" aria-expanded="false" data-info="${esc(s.description)}">i</button>` : ''}</div>
|
||||
<span class="pill ${esc(s.status)}">${s.status === 'up' ? 'Operational' : s.status === 'down' ? 'Down' : 'Unknown'}</span>
|
||||
<div class="bars" title="Last 24 hours, hourly">${s.bars.map((b) => `<i class="b${b}"></i>`).join('')}</div>
|
||||
<div class="pc">${s.up30 == null ? '–' : s.up30.toFixed(1) + '%'}</div></div>`;
|
||||
const TIERS = [['featured', 'Popular services'], ['normal', 'Other services'], ['background', 'Infrastructure & background services']];
|
||||
const groups = (list) => TIERS.map(([t, h]) => { const l = list.filter((s) => (s.tier || 'normal') === t); return l.length ? `<h2>${h}</h2><div class="list">${l.map(row).join('')}</div>` : ''; }).join('');
|
||||
|
||||
function banner(d) {
|
||||
return `<div class="banner ${d.overall}"><span class="dot ${d.overall}"></span><div><div class="big">${LABEL[d.overall]}</div><small>${d.up} of ${d.total} services up · updated ${ago(d.generatedAt)}</small></div></div>`;
|
||||
}
|
||||
const incCard = (i) => `<div class="card"><h3><span class="tag ${i.scheduled ? 'scheduled' : esc(i.severity)}">${i.scheduled ? 'scheduled' : esc(i.severity)}</span><span class="tag ${esc(i.status)}">${esc(i.status)}</span>${esc(i.title)}</h3>
|
||||
<div class="meta">${fmt(i.scheduled && i.start ? i.start : i.createdAt)}${i.resolvedAt ? ' · resolved ' + fmt(i.resolvedAt) : ''}</div>${i.description ? `<p>${esc(i.description)}</p>` : ''}</div>`;
|
||||
|
||||
const views = {
|
||||
async '/'() {
|
||||
const d = await load(); const news = await (await fetch('/api/site/news').catch(() => null))?.json?.().catch(() => null);
|
||||
const active = d?.incidents.filter((i) => i.status !== 'resolved' && (!i.scheduled || new Date(i.start) <= Date.now() + 864e5)) || [];
|
||||
return `<div class="wrap">${stale()}<h1>Service status</h1><p class="lead">Live health, incidents and news.</p>
|
||||
${d ? banner(d) : ''}
|
||||
${active.length ? `<h2>Active & upcoming</h2>${active.map(incCard).join('')}` : ''}
|
||||
${groups(d?.services || [])}
|
||||
<p class="meta">Bars show the last 24 hours. Percentage is 30-day uptime. <a href="/status" data-link>Full status & history →</a></p>
|
||||
${news?.posts?.length ? `<h2>Latest news</h2>${news.posts.slice(0, 2).map(post).join('')}<a href="/news" data-link>All news →</a>` : ''}</div>`;
|
||||
},
|
||||
async '/status'() {
|
||||
const d = await load(); if (!d) return `<div class="wrap">${stale()}<h1>Status</h1></div>`;
|
||||
const avg = d.services.filter((s) => s.up30 != null);
|
||||
const u = avg.length ? (avg.reduce((a, s) => a + s.up30, 0) / avg.length).toFixed(2) : '–';
|
||||
const rts = d.services.filter((s) => s.rt); const rt = rts.length ? Math.round(rts.reduce((a, s) => a + s.rt, 0) / rts.length) : '–';
|
||||
return `<div class="wrap">${stale()}<h1>Status</h1><p class="lead">Checked every minute from a monitor on a separate host.</p>${banner(d)}
|
||||
<div class="stats"><div class="stat"><b>${d.up}/${d.total}</b><span>services up</span></div><div class="stat"><b>${u}%</b><span>avg 30-day uptime</span></div><div class="stat"><b>${rt}${rt === '–' ? '' : ' ms'}</b><span>avg response (24h)</span></div></div>
|
||||
${groups(d.services)}
|
||||
<h2>Incident history</h2>${d.incidents.length ? d.incidents.map(incCard).join('') : '<p class="muted">No incidents recorded.</p>'}</div>`;
|
||||
},
|
||||
async '/news'() {
|
||||
const r = await fetch('/api/site/news').then((x) => x.json()).catch(() => null);
|
||||
return `<div class="wrap"><h1>News</h1><p class="lead">Announcements, changes and maintenance notes. <a href="/api/site/news.rss">RSS feed</a></p>${r?.posts?.length ? r.posts.map(post).join('') : '<p class="muted">Nothing yet.</p>'}</div>`;
|
||||
},
|
||||
async '/tools'() { return toolsView(); },
|
||||
async '/about'() {
|
||||
return `<div class="wrap"><h1>About</h1><p class="lead">Edit this page in src/site/site.js (or point SITE_DIR at your own theme).</p>
|
||||
<div class="card"><h3>Contact</h3><p><a href="mailto:you@example.com">you@example.com</a></p></div></div>`;
|
||||
},
|
||||
};
|
||||
const post = (p) => `<article class="card" id="${esc(p.id)}"><h3>${esc(p.title)}</h3><time>${fmt(p.createdAt)}</time><p>${esc(p.content)}</p></article>`;
|
||||
|
||||
// ---- Tools: small, client-side only ----
|
||||
const tools = [
|
||||
{ id: 'ip', name: 'My IP address', desc: 'The address the internet sees for you.', run: async (o) => { const r = await fetch('/api/site/tools/ip').then((x) => x.json()); o.textContent = r.ip; } },
|
||||
{ id: 'dns', name: 'DNS lookup', desc: 'Resolve a hostname via Cloudflare DNS-over-HTTPS.', input: 'Status',
|
||||
run: async (o, v) => { const r = await fetch(`https://cloudflare-dns.com/dns-query?name=${encodeURIComponent(v)}&type=A`, { headers: { accept: 'application/dns-json' } }).then((x) => x.json()); o.textContent = (r.Answer || []).map((a) => a.data).join('\n') || 'No records'; } },
|
||||
{ id: 'b64', name: 'Base64', desc: 'Encode or decode text.', area: true,
|
||||
run: (o, v, m) => { try { o.textContent = m === 'dec' ? new TextDecoder().decode(Uint8Array.from(atob(v), (c) => c.charCodeAt(0))) : btoa(String.fromCharCode(...new TextEncoder().encode(v))); } catch { o.textContent = 'Invalid input'; } }, modes: [['enc', 'Encode'], ['dec', 'Decode']] },
|
||||
{ id: 'hash', name: 'SHA-256', desc: 'Hash text in your browser.', area: true, modes: [['go', 'Hash']],
|
||||
run: async (o, v) => { const h = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(v)); o.textContent = [...new Uint8Array(h)].map((b) => b.toString(16).padStart(2, '0')).join(''); } },
|
||||
{ id: 'pw', name: 'Password generator', desc: 'Random 20-character password.', modes: [['go', 'Generate']],
|
||||
run: (o) => { const c = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789!@#$%^&*-_'; const a = crypto.getRandomValues(new Uint32Array(20)); o.textContent = [...a].map((n) => c[n % c.length]).join(''); } },
|
||||
{ id: 'time', name: 'Unix time', desc: 'Convert between timestamps and dates.', input: String(Math.floor(Date.now() / 1e3)), modes: [['go', 'Convert']],
|
||||
run: (o, v) => { const n = Number(v); o.textContent = isNaN(n) ? new Date(v).getTime() / 1e3 + ' (unix)' : new Date(n * (n < 1e12 ? 1e3 : 1)).toISOString(); } },
|
||||
];
|
||||
function toolsView() {
|
||||
setTimeout(() => tools.forEach((t) => {
|
||||
const el = $('#t-' + t.id); if (!el) return; const out = $('.out', el), inp = $('input,textarea', el);
|
||||
const go = async (m) => { out.textContent = '…'; try { await t.run(out, inp?.value ?? '', m); } catch { out.textContent = 'Failed'; } };
|
||||
el.querySelectorAll('button[data-m]').forEach((b) => b.addEventListener('click', () => go(b.dataset.m)));
|
||||
if (!t.modes) go();
|
||||
}));
|
||||
return `<div class="wrap"><h1>Tools</h1><p class="lead">Small utilities. Everything except the IP check runs in your browser.</p><div class="grid">${tools.map((t) => `<div class="card" id="t-${t.id}"><h3>${t.name}</h3><div class="meta">${t.desc}</div>
|
||||
${t.area ? '<textarea placeholder="Input"></textarea>' : t.input ? `<input value="${esc(t.input)}" placeholder="${esc(t.input)}">` : ''}
|
||||
${t.modes ? `<div class="btns">${t.modes.map(([m, l]) => `<button data-m="${m}">${l}</button>`).join('')}</div>` : ''}<div class="out"></div></div>`).join('')}</div></div>`;
|
||||
}
|
||||
|
||||
// ---- router ----
|
||||
async function render(path, push) {
|
||||
const p = views[path] ? path : '/';
|
||||
if (push) history.pushState({}, '', path);
|
||||
document.querySelectorAll('#nav a').forEach((a) => a.classList.toggle('on', a.getAttribute('href') === p));
|
||||
const titles = { '/': 'Overview', '/status': 'Status', '/news': 'News', '/tools': 'Tools', '/about': 'About' };
|
||||
document.title = (p === '/' ? '' : titles[p] + ' · ') + 'Status';
|
||||
main.innerHTML = await views[p]();
|
||||
if (push) window.scrollTo(0, 0);
|
||||
}
|
||||
document.addEventListener('click', (e) => {
|
||||
const a = e.target.closest('a[data-link]'); if (!a || e.metaKey || e.ctrlKey) return;
|
||||
e.preventDefault(); render(a.getAttribute('href'), true);
|
||||
});
|
||||
addEventListener('popstate', () => render(location.pathname));
|
||||
document.addEventListener('click', (e) => {
|
||||
const b = e.target.closest('.info'); document.querySelectorAll('.tip').forEach((t) => t.remove());
|
||||
document.querySelectorAll('.info[aria-expanded=true]').forEach((x) => x !== b && x.setAttribute('aria-expanded', 'false'));
|
||||
if (!b) return;
|
||||
if (b.getAttribute('aria-expanded') === 'true') return b.setAttribute('aria-expanded', 'false');
|
||||
b.setAttribute('aria-expanded', 'true');
|
||||
const t = document.createElement('div'); t.className = 'tip'; t.setAttribute('role', 'tooltip'); t.textContent = b.dataset.info; b.parentElement.appendChild(t);
|
||||
});
|
||||
document.addEventListener('keydown', (e) => { if (e.key === 'Escape') document.querySelectorAll('.tip').forEach((t) => t.remove()); });
|
||||
$('#yr').textContent = new Date().getFullYear();
|
||||
render(location.pathname.replace(/\/$/, '') || '/');
|
||||
setInterval(() => { if (!document.hidden && ['/', '/status'].includes(location.pathname)) render(location.pathname); }, 60e3);
|
||||
// Broken icon -> neutral placeholder
|
||||
document.addEventListener('error', (e) => { const i = e.target; if (i.tagName === 'IMG' && i.closest('.svc')) { const d = document.createElement('div'); d.className = 'ph'; i.replaceWith(d); } }, true);
|
||||
// Branding from Admin → Site
|
||||
fetch('/api/site/brand').then((r) => r.json()).then((b) => { const n = document.getElementById('brand-name'); if (n && b.name) n.textContent = b.name; if (b.accent) document.documentElement.style.setProperty('--acc', b.accent); }).catch(() => {});
|
||||
@@ -0,0 +1,11 @@
|
||||
// Simple color output utility (alternative to chalk for compatibility)
|
||||
module.exports = {
|
||||
green: (str) => `\x1b[32m${str}\x1b[39m`,
|
||||
cyan: (str) => `\x1b[36m${str}\x1b[39m`,
|
||||
yellow: (str) => `\x1b[33m${str}\x1b[39m`,
|
||||
red: (str) => `\x1b[31m${str}\x1b[39m`,
|
||||
blue: (str) => `\x1b[34m${str}\x1b[39m`,
|
||||
magenta: (str) => `\x1b[35m${str}\x1b[39m`,
|
||||
gray: (str) => `\x1b[90m${str}\x1b[39m`,
|
||||
bold: (str) => `\x1b[1m${str}\x1b[22m`,
|
||||
};
|
||||
@@ -0,0 +1,144 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Admin Login - LocalPing</title>
|
||||
<script src="/vendor/tailwindcss.js"></script>
|
||||
<style>
|
||||
body {
|
||||
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
|
||||
min-height: 100vh;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
}
|
||||
.form-input {
|
||||
background-color: #0f1419;
|
||||
border-color: #2a2a4e;
|
||||
}
|
||||
.form-input:focus {
|
||||
border-color: #4f46e5;
|
||||
box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
|
||||
}
|
||||
.btn-primary {
|
||||
background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%);
|
||||
}
|
||||
.btn-primary:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="min-h-screen flex items-center justify-center p-4">
|
||||
<div class="w-full max-w-md">
|
||||
<!-- Header -->
|
||||
<div class="text-center mb-8">
|
||||
<h1 class="text-4xl font-bold text-white mb-2">LocalPing</h1>
|
||||
<p class="text-gray-400">Admin Panel</p>
|
||||
</div>
|
||||
|
||||
<!-- Login Card -->
|
||||
<div class="bg-[#0f1419] border border-[#2a2a4e] rounded-lg p-8">
|
||||
<h2 class="text-2xl font-bold text-white mb-6">Admin Login</h2>
|
||||
|
||||
<div id="error-message" class="mb-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg hidden">
|
||||
<p class="text-red-400 text-sm" id="error-text"></p>
|
||||
</div>
|
||||
|
||||
<form id="loginForm" class="space-y-6">
|
||||
<div>
|
||||
<label for="username" class="block text-sm font-medium text-gray-300 mb-2">
|
||||
Username
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="username"
|
||||
name="username"
|
||||
class="form-input w-full px-4 py-2 border rounded-lg text-white placeholder-gray-500"
|
||||
placeholder="Enter admin username"
|
||||
required
|
||||
autofocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label for="password" class="block text-sm font-medium text-gray-300 mb-2">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
id="password"
|
||||
name="password"
|
||||
class="form-input w-full px-4 py-2 border rounded-lg text-white placeholder-gray-500"
|
||||
placeholder="Enter admin password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
class="btn-primary w-full py-3 rounded-lg font-semibold text-white transition"
|
||||
id="submitBtn"
|
||||
>
|
||||
Login
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div class="mt-6 pt-6 border-t border-[#2a2a4e]">
|
||||
<p class="text-gray-400 text-sm text-center">
|
||||
Forgot your password? <a href="/setup" class="text-indigo-400 hover:text-indigo-300">Reset setup</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<p class="text-center text-gray-500 text-xs mt-8">
|
||||
LocalPing • Homelab Dashboard & System Monitor
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.getElementById('loginForm').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
const username = document.getElementById('username').value;
|
||||
const password = document.getElementById('password').value;
|
||||
const errorDiv = document.getElementById('error-message');
|
||||
const errorText = document.getElementById('error-text');
|
||||
const submitBtn = document.getElementById('submitBtn');
|
||||
|
||||
try {
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = 'Logging in...';
|
||||
|
||||
const response = await fetch('/admin/login', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok && data.success) {
|
||||
// Redirect to admin panel
|
||||
window.location.href = '/admin';
|
||||
} else {
|
||||
// Show error
|
||||
errorText.textContent = data.error || 'Invalid username or password';
|
||||
errorDiv.classList.remove('hidden');
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = 'Login';
|
||||
document.getElementById('username').focus();
|
||||
}
|
||||
} catch (err) {
|
||||
errorText.textContent = 'An error occurred. Please try again.';
|
||||
errorDiv.classList.remove('hidden');
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = 'Login';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,21 @@
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Site settings · LocalPing</title>
|
||||
<link rel="stylesheet" href="/s/site.css"><style>td,th{padding:8px;text-align:left;border-top:1px solid var(--line);vertical-align:top}table{width:100%;border-collapse:collapse}select{width:auto}input[type=text],input[type=color]{width:100%}.sv{font-size:12px;color:var(--ok)}</style></head>
|
||||
<body><header class="top"><a class="brand" href="/admin"><span>← Admin</span></a><nav><a class="on" href="/admin/site">Public site</a></nav></header>
|
||||
<main><div class="wrap"><h1>Public site</h1>
|
||||
<div class="card"><h3>Branding & app icon</h3><p class="meta">Used for the header, favicon and when installed as an app (PWA). PNG/WebP/JPEG/SVG, max 2 MB, square works best.</p>
|
||||
<div class="grid"><div><label>Name</label><input type="text" id="b-name"></div><div><label>Tagline</label><input type="text" id="b-tag"></div><div><label>Accent colour</label><input type="color" id="b-acc" value="#6ea8ff"></div><div><label>Icon</label><input type="file" id="b-file" accept="image/png,image/jpeg,image/webp,image/svg+xml"></div></div>
|
||||
<div class="btns"><button id="b-save">Save branding</button><button class="ghost" id="b-reset">Reset icon to default</button><img id="b-prev" src="/brand/icon-192.png" width="48" height="48" alt="" style="border-radius:10px"><span class="sv" id="b-msg"></span></div></div>
|
||||
<div class="card"><h3>Services: explainers, tiers & links</h3><p class="meta">Tier decides placement (featured = shown first). Untick “Link” for private services so no link to them is shown publicly.</p>
|
||||
<div style="overflow-x:auto"><table><thead><tr><th>Service</th><th>Tier</th><th>Link</th><th>Explainer (shown in ⓘ)</th><th></th></tr></thead><tbody id="rows"></tbody></table></div></div></div></main>
|
||||
<script>
|
||||
const $=s=>document.querySelector(s),j=(u,o)=>fetch(u,o).then(r=>r.json());
|
||||
const H={'content-type':'application/json'};
|
||||
async function load(){const d=await j('/admin/api/site/meta');$('#b-name').value=d.brand.name;$('#b-tag').value=d.brand.tagline;if(d.brand.accent)$('#b-acc').value=d.brand.accent;
|
||||
$('#rows').innerHTML=d.targets.map(t=>`<tr data-id="${t.id}"><td><b></b></td><td><select data-k="tier">${['featured','normal','background'].map(x=>`<option ${x===t.tier?'selected':''}>${x}</option>`).join('')}</select></td><td><input type="checkbox" data-k="linkPublic" ${t.linkPublic?'checked':''}></td><td><input type="text" data-k="description" maxlength="400"></td><td class="sv"></td></tr>`).join('');
|
||||
[...$('#rows').children].forEach((tr,i)=>{const t=d.targets[i];tr.querySelector('b').textContent=t.name+(t.publicVisible?'':' (hidden)');tr.querySelector('[data-k=description]').value=t.description||'';
|
||||
tr.addEventListener('change',async()=>{const b={tier:tr.querySelector('[data-k=tier]').value,linkPublic:tr.querySelector('[data-k=linkPublic]').checked,description:tr.querySelector('[data-k=description]').value};
|
||||
const r=await j('/admin/api/site/meta/'+t.id,{method:'PUT',headers:H,body:JSON.stringify(b)});tr.querySelector('.sv').textContent=r.success?'saved':'error';});});}
|
||||
const file=()=>new Promise(r=>{const f=$('#b-file').files[0];if(!f)return r(null);const fr=new FileReader();fr.onload=()=>r(fr.result);fr.readAsDataURL(f)});
|
||||
async function save(reset){const r=await j('/admin/api/site/brand',{method:'PUT',headers:H,body:JSON.stringify({name:$('#b-name').value,tagline:$('#b-tag').value,accent:$('#b-acc').value,iconBase64:reset?null:await file(),resetIcon:!!reset})});$('#b-msg').textContent=r.success?'saved':r.error;$('#b-prev').src='/brand/icon-192.png?'+Date.now();}
|
||||
$('#b-save').onclick=()=>save(false);$('#b-reset').onclick=()=>save(true);load();
|
||||
</script></body></html>
|
||||
@@ -0,0 +1,37 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title><%= typeof title !== 'undefined' ? title : 'LocalPing' %></title>
|
||||
<link rel="icon" type="image/x-icon" href="/favicon.ico">
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
|
||||
<link rel="manifest" href="/manifest.json">
|
||||
<meta name="msapplication-config" content="/browserconfig.xml">
|
||||
|
||||
<!-- TailwindCSS (Local) -->
|
||||
<script src="/vendor/tailwindcss.js"></script>
|
||||
<script>
|
||||
tailwind.config = {
|
||||
darkMode: 'class',
|
||||
theme: {
|
||||
extend: {}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Charts Library (Chart.js) (Local) -->
|
||||
<script src="/vendor/chart.js"></script>
|
||||
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="dark bg-slate-900 text-slate-100">
|
||||
<%- body %>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,185 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>LocalPing Setup</title>
|
||||
<script src="/vendor/tailwindcss.js"></script>
|
||||
<style>
|
||||
body {
|
||||
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
|
||||
min-height: 100vh;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
}
|
||||
.form-input {
|
||||
background-color: #0f1419;
|
||||
border-color: #2a2a4e;
|
||||
}
|
||||
.form-input:focus {
|
||||
border-color: #4f46e5;
|
||||
box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
|
||||
}
|
||||
.btn-primary {
|
||||
background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%);
|
||||
}
|
||||
.btn-primary:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="min-h-screen flex items-center justify-center p-4">
|
||||
<div class="w-full max-w-md">
|
||||
<!-- Header -->
|
||||
<div class="text-center mb-8">
|
||||
<h1 class="text-4xl font-bold text-white mb-2">LocalPing</h1>
|
||||
<p class="text-gray-400">Initial Setup Wizard</p>
|
||||
</div>
|
||||
|
||||
<!-- Setup Card -->
|
||||
<div class="bg-[#0f1419] border border-[#2a2a4e] rounded-lg p-8">
|
||||
<% if (error) { %>
|
||||
<div class="mb-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
|
||||
<p class="text-red-400 text-sm"><strong>Error:</strong> <%= error %></p>
|
||||
</div>
|
||||
<% } %>
|
||||
|
||||
<form method="POST" class="space-y-6">
|
||||
<!-- Step 1: Admin Credentials -->
|
||||
<div>
|
||||
<h2 class="text-lg font-semibold text-white mb-4">Admin Credentials</h2>
|
||||
|
||||
<div class="mb-4">
|
||||
<label for="adminUsername" class="block text-sm font-medium text-gray-300 mb-2">
|
||||
Admin Username
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="adminUsername"
|
||||
name="adminUsername"
|
||||
value="admin"
|
||||
class="form-input w-full px-4 py-2 border rounded-lg text-white placeholder-gray-500"
|
||||
required
|
||||
/>
|
||||
<p class="text-gray-400 text-xs mt-1">Used to log in to the admin panel</p>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<label for="adminPassword" class="block text-sm font-medium text-gray-300 mb-2">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
id="adminPassword"
|
||||
name="adminPassword"
|
||||
class="form-input w-full px-4 py-2 border rounded-lg text-white placeholder-gray-500"
|
||||
placeholder="At least 6 characters"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<label for="passwordConfirm" class="block text-sm font-medium text-gray-300 mb-2">
|
||||
Confirm Password
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
id="passwordConfirm"
|
||||
name="passwordConfirm"
|
||||
class="form-input w-full px-4 py-2 border rounded-lg text-white placeholder-gray-500"
|
||||
placeholder="Re-enter your password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 2: Network Configuration -->
|
||||
<div class="pt-4 border-t border-[#2a2a4e]">
|
||||
<h2 class="text-lg font-semibold text-white mb-4">Network Configuration</h2>
|
||||
|
||||
<div>
|
||||
<label for="gatewayIp" class="block text-sm font-medium text-gray-300 mb-2">
|
||||
Gateway IP Address
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="gatewayIp"
|
||||
name="gatewayIp"
|
||||
value="<%= detectedGateway %>"
|
||||
class="form-input w-full px-4 py-2 border rounded-lg text-white placeholder-gray-500"
|
||||
placeholder="e.g., 192.168.1.1"
|
||||
required
|
||||
/>
|
||||
<p class="text-gray-400 text-xs mt-1">
|
||||
<% if (detectedGateway) { %>
|
||||
✓ Auto-detected: <%= detectedGateway %> (you can change this)
|
||||
<% } else { %>
|
||||
Enter your network gateway IP address
|
||||
<% } %>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Info -->
|
||||
<div class="pt-4 border-t border-[#2a2a4e]">
|
||||
<p class="text-gray-400 text-sm mb-2">
|
||||
<strong>Default monitors will be created for:</strong>
|
||||
</p>
|
||||
<ul class="text-gray-400 text-sm space-y-1 ml-4">
|
||||
<li>✓ Gateway monitoring (ICMP ping)</li>
|
||||
<li>✓ Cloudflare DNS at 1.1.1.1 (ICMP ping)</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<!-- Submit -->
|
||||
<div class="pt-4">
|
||||
<button
|
||||
type="submit"
|
||||
class="btn-primary w-full py-3 rounded-lg font-semibold text-white transition"
|
||||
>
|
||||
Complete Setup
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p class="text-center text-gray-400 text-xs mt-4">
|
||||
By completing setup, you agree that LocalPing will monitor your network
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<p class="text-center text-gray-500 text-xs mt-8">
|
||||
LocalPing • Homelab Dashboard & System Monitor
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Form validation on client side
|
||||
document.querySelector('form').addEventListener('submit', function(e) {
|
||||
const password = document.getElementById('adminPassword').value;
|
||||
const passwordConfirm = document.getElementById('passwordConfirm').value;
|
||||
const gateway = document.getElementById('gatewayIp').value;
|
||||
|
||||
if (password.length < 6) {
|
||||
e.preventDefault();
|
||||
alert('Password must be at least 6 characters');
|
||||
return;
|
||||
}
|
||||
|
||||
if (password !== passwordConfirm) {
|
||||
e.preventDefault();
|
||||
alert('Passwords do not match');
|
||||
return;
|
||||
}
|
||||
|
||||
const ipRegex = /^(\d{1,3}\.){3}\d{1,3}$/;
|
||||
if (!ipRegex.test(gateway)) {
|
||||
e.preventDefault();
|
||||
alert('Invalid IP address format');
|
||||
return;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,606 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* API Test Suite for LocalPing
|
||||
*
|
||||
* Tests CRUD operations on:
|
||||
* - Monitors/Targets (via /api/* - requires API key)
|
||||
* - Incidents (via /admin/api/* - requires session auth)
|
||||
* - Blog Posts (via /admin/api/* - requires session auth)
|
||||
* - Admin Settings (via /admin/api/* - requires session auth)
|
||||
*
|
||||
* Uses credentials from .env file for admin authentication.
|
||||
*
|
||||
* Usage: node test-api.js [baseUrl] [apiKey]
|
||||
* Example: node test-api.js http://localhost:8000 your-api-key
|
||||
*/
|
||||
|
||||
const axios = require('axios');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// Simple color functions
|
||||
const colors = {
|
||||
blue: (s) => `\x1b[34m${s}\x1b[0m`,
|
||||
green: (s) => `\x1b[32m${s}\x1b[0m`,
|
||||
red: (s) => `\x1b[31m${s}\x1b[0m`,
|
||||
yellow: (s) => `\x1b[33m${s}\x1b[0m`,
|
||||
cyan: (s) => `\x1b[36m${s}\x1b[0m`,
|
||||
white: (s) => s,
|
||||
};
|
||||
|
||||
// Load .env file
|
||||
function loadEnv() {
|
||||
const envPath = path.join(process.cwd(), '.env');
|
||||
const env = {};
|
||||
if (fs.existsSync(envPath)) {
|
||||
const content = fs.readFileSync(envPath, 'utf8');
|
||||
content.split('\n').forEach(line => {
|
||||
const match = line.match(/^([^#=]+)=(.*)$/);
|
||||
if (match) {
|
||||
env[match[1].trim()] = match[2].trim();
|
||||
}
|
||||
});
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
const env = loadEnv();
|
||||
|
||||
// Configuration
|
||||
const BASE_URL = process.argv[2] || 'http://localhost:8000';
|
||||
const API_KEY = process.argv[3] || env.ADMIN_API_KEY || 'test-key';
|
||||
const ADMIN_USERNAME = env.ADMIN_USERNAME;
|
||||
const ADMIN_PASSWORD = env.ADMIN_PASSWORD;
|
||||
|
||||
// Test results
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
const errors = [];
|
||||
|
||||
// Helper functions
|
||||
function log(message, type = 'info') {
|
||||
const colorMap = {
|
||||
info: colors.blue,
|
||||
success: colors.green,
|
||||
error: colors.red,
|
||||
warning: colors.yellow,
|
||||
test: colors.cyan,
|
||||
};
|
||||
const colorFn = colorMap[type] || colors.white;
|
||||
console.log(colorFn(message));
|
||||
}
|
||||
|
||||
function test(name, fn) {
|
||||
return async () => {
|
||||
try {
|
||||
log(`\n🧪 Testing: ${name}`, 'test');
|
||||
await fn();
|
||||
passed++;
|
||||
log(`✅ PASSED: ${name}`, 'success');
|
||||
} catch (error) {
|
||||
failed++;
|
||||
const errorMsg = error.response
|
||||
? `Status ${error.response.status}: ${error.response.data?.error || error.message}`
|
||||
: error.message;
|
||||
errors.push({ test: name, error: errorMsg });
|
||||
log(`❌ FAILED: ${name} - ${errorMsg}`, 'error');
|
||||
if (error.response?.data && error.response.status !== 401) {
|
||||
console.log('Response:', JSON.stringify(error.response.data, null, 2));
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Cookie storage for session
|
||||
let sessionCookie = null;
|
||||
|
||||
// API client for /api/* routes (uses API key)
|
||||
const api = axios.create({
|
||||
baseURL: BASE_URL,
|
||||
headers: {
|
||||
'X-API-Key': API_KEY,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
validateStatus: () => true,
|
||||
});
|
||||
|
||||
// Admin API client for /admin/api/* routes (uses session cookies)
|
||||
const adminApi = axios.create({
|
||||
baseURL: BASE_URL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
validateStatus: () => true,
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
// Add cookie to admin requests
|
||||
adminApi.interceptors.request.use(config => {
|
||||
if (sessionCookie) {
|
||||
config.headers.Cookie = sessionCookie;
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
// Extract cookie from admin responses
|
||||
adminApi.interceptors.response.use(response => {
|
||||
const setCookie = response.headers['set-cookie'];
|
||||
if (setCookie && setCookie.length > 0) {
|
||||
// Extract session cookie (usually the first one)
|
||||
const cookie = setCookie.find(c => c.startsWith('connect.sid')) || setCookie[0];
|
||||
if (cookie) {
|
||||
sessionCookie = cookie.split(';')[0]; // Get just the cookie name=value part
|
||||
}
|
||||
}
|
||||
return response;
|
||||
});
|
||||
|
||||
// Login to admin
|
||||
async function loginAdmin() {
|
||||
if (!ADMIN_USERNAME || !ADMIN_PASSWORD) {
|
||||
throw new Error('ADMIN_USERNAME and ADMIN_PASSWORD must be set in .env file');
|
||||
}
|
||||
|
||||
log('🔐 Logging in to admin...', 'info');
|
||||
const response = await adminApi.post('/admin/login', {
|
||||
username: ADMIN_USERNAME,
|
||||
password: ADMIN_PASSWORD,
|
||||
});
|
||||
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Login failed: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
|
||||
// Extract cookie from response
|
||||
const setCookie = response.headers['set-cookie'];
|
||||
if (setCookie && setCookie.length > 0) {
|
||||
const cookie = setCookie.find(c => c.startsWith('connect.sid')) || setCookie[0];
|
||||
if (cookie) {
|
||||
sessionCookie = cookie.split(';')[0];
|
||||
log(` ✅ Logged in successfully`, 'success');
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('Login succeeded but no session cookie received');
|
||||
}
|
||||
|
||||
// Test data storage
|
||||
const testData = {
|
||||
targetId: null,
|
||||
incidentId: null,
|
||||
postId: null,
|
||||
notificationDelayMinutes: 5,
|
||||
};
|
||||
|
||||
// ==================== TARGETS/MONITORS TESTS ====================
|
||||
|
||||
const testTargets = {
|
||||
create: test('Create Target', async () => {
|
||||
const target = {
|
||||
name: `test-target-${Date.now()}`,
|
||||
host: 'example.com',
|
||||
protocol: 'HTTPS',
|
||||
port: 443,
|
||||
interval: 60,
|
||||
enabled: true,
|
||||
publicVisible: true,
|
||||
publicShowDetails: false,
|
||||
publicShowStatus: true,
|
||||
publicShowAppLink: true,
|
||||
important: false,
|
||||
};
|
||||
|
||||
const response = await api.post('/api/targets', target);
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to create target: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
testData.targetId = response.data.targetId;
|
||||
log(` Created target with ID: ${testData.targetId}`);
|
||||
}),
|
||||
|
||||
getAll: test('Get All Targets', async () => {
|
||||
const response = await api.get('/api/targets');
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to get targets: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
if (!Array.isArray(response.data.targets)) {
|
||||
throw new Error('Targets is not an array');
|
||||
}
|
||||
log(` Found ${response.data.targets.length} targets`);
|
||||
}),
|
||||
|
||||
getOne: test('Get Target by ID', async () => {
|
||||
if (!testData.targetId) {
|
||||
throw new Error('No target ID available (create test must run first)');
|
||||
}
|
||||
const response = await api.get(`/api/targets/${testData.targetId}`);
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to get target: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
if (response.data.target._id !== testData.targetId) {
|
||||
throw new Error('Target ID mismatch');
|
||||
}
|
||||
log(` Retrieved target: ${response.data.target.name}`);
|
||||
}),
|
||||
|
||||
update: test('Update Target', async () => {
|
||||
if (!testData.targetId) {
|
||||
throw new Error('No target ID available');
|
||||
}
|
||||
const updates = {
|
||||
name: `updated-target-${Date.now()}`,
|
||||
interval: 120,
|
||||
publicShowDetails: true,
|
||||
publicVisible: false,
|
||||
publicShowStatus: false,
|
||||
};
|
||||
const response = await api.put(`/api/targets/${testData.targetId}`, updates);
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to update target: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
const verify = await api.get(`/api/targets/${testData.targetId}`);
|
||||
if (verify.status !== 200 || verify.data.target.publicVisible !== false || verify.data.target.publicShowStatus !== false) {
|
||||
throw new Error(`Target visibility settings were not persisted: ${JSON.stringify(verify.data)}`);
|
||||
}
|
||||
log(` Updated target: ${updates.name}`);
|
||||
}),
|
||||
|
||||
getStatistics: test('Get Target Statistics', async () => {
|
||||
if (!testData.targetId) {
|
||||
throw new Error('No target ID available');
|
||||
}
|
||||
const response = await api.get(`/api/targets/${testData.targetId}/statistics?days=30`);
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to get statistics: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
log(` Retrieved statistics (${response.data.statistics?.length || 0} data points)`);
|
||||
}),
|
||||
|
||||
delete: test('Delete Target', async () => {
|
||||
if (!testData.targetId) {
|
||||
throw new Error('No target ID available');
|
||||
}
|
||||
const response = await api.delete(`/api/targets/${testData.targetId}`);
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to delete target: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
log(` Deleted target: ${testData.targetId}`);
|
||||
testData.targetId = null;
|
||||
}),
|
||||
};
|
||||
|
||||
// ==================== INCIDENTS TESTS ====================
|
||||
|
||||
const testIncidents = {
|
||||
create: test('Create Incident', async () => {
|
||||
const incident = {
|
||||
title: `Test Incident ${Date.now()}`,
|
||||
description: 'This is a test incident created by the API test suite',
|
||||
severity: 'major',
|
||||
status: 'investigating',
|
||||
};
|
||||
|
||||
const response = await adminApi.post('/admin/api/incidents', incident);
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to create incident: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
testData.incidentId = response.data.incident?._id || response.data.incidentId;
|
||||
log(` Created incident with ID: ${testData.incidentId}`);
|
||||
}),
|
||||
|
||||
getAll: test('Get All Incidents', async () => {
|
||||
const response = await adminApi.get('/admin/api/incidents');
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to get incidents: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
if (!Array.isArray(response.data.incidents)) {
|
||||
throw new Error('Incidents is not an array');
|
||||
}
|
||||
log(` Found ${response.data.incidents.length} incidents`);
|
||||
}),
|
||||
|
||||
getOne: test('Get Incident by ID', async () => {
|
||||
if (!testData.incidentId) {
|
||||
throw new Error('No incident ID available');
|
||||
}
|
||||
const response = await adminApi.get(`/admin/api/incidents/${testData.incidentId}`);
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to get incident: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
if (response.data.incident._id !== testData.incidentId) {
|
||||
throw new Error('Incident ID mismatch');
|
||||
}
|
||||
log(` Retrieved incident: ${response.data.incident.title}`);
|
||||
}),
|
||||
|
||||
update: test('Update Incident', async () => {
|
||||
if (!testData.incidentId) {
|
||||
throw new Error('No incident ID available');
|
||||
}
|
||||
const updates = {
|
||||
status: 'resolved',
|
||||
description: 'Updated description',
|
||||
};
|
||||
const response = await adminApi.put(`/admin/api/incidents/${testData.incidentId}`, updates);
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to update incident: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
log(` Updated incident status to: ${updates.status}`);
|
||||
}),
|
||||
|
||||
delete: test('Delete Incident', async () => {
|
||||
if (!testData.incidentId) {
|
||||
throw new Error('No incident ID available');
|
||||
}
|
||||
const response = await adminApi.delete(`/admin/api/incidents/${testData.incidentId}`);
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to delete incident: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
log(` Deleted incident: ${testData.incidentId}`);
|
||||
testData.incidentId = null;
|
||||
}),
|
||||
};
|
||||
|
||||
// ==================== BLOG POSTS TESTS ====================
|
||||
|
||||
const testPosts = {
|
||||
create: test('Create Blog Post', async () => {
|
||||
const post = {
|
||||
title: `Test Post ${Date.now()}`,
|
||||
content: 'This is a test blog post created by the API test suite.\n\nIt has multiple paragraphs.',
|
||||
published: true,
|
||||
};
|
||||
|
||||
const response = await adminApi.post('/admin/api/posts', post);
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to create post: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
testData.postId = response.data.post?._id || response.data.postId;
|
||||
log(` Created post with ID: ${testData.postId}`);
|
||||
}),
|
||||
|
||||
getAll: test('Get All Posts', async () => {
|
||||
const response = await adminApi.get('/admin/api/posts');
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to get posts: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
if (!Array.isArray(response.data.posts)) {
|
||||
throw new Error('Posts is not an array');
|
||||
}
|
||||
log(` Found ${response.data.posts.length} posts`);
|
||||
}),
|
||||
|
||||
getOne: test('Get Post by ID', async () => {
|
||||
if (!testData.postId) {
|
||||
throw new Error('No post ID available');
|
||||
}
|
||||
const response = await adminApi.get(`/admin/api/posts/${testData.postId}`);
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to get post: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
if (response.data.post._id !== testData.postId) {
|
||||
throw new Error('Post ID mismatch');
|
||||
}
|
||||
log(` Retrieved post: ${response.data.post.title}`);
|
||||
}),
|
||||
|
||||
update: test('Update Post', async () => {
|
||||
if (!testData.postId) {
|
||||
throw new Error('No post ID available');
|
||||
}
|
||||
const updates = {
|
||||
title: `Updated Post ${Date.now()}`,
|
||||
content: 'Updated content',
|
||||
published: false,
|
||||
};
|
||||
const response = await adminApi.put(`/admin/api/posts/${testData.postId}`, updates);
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to update post: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
log(` Updated post: ${updates.title}`);
|
||||
}),
|
||||
|
||||
delete: test('Delete Post', async () => {
|
||||
if (!testData.postId) {
|
||||
throw new Error('No post ID available');
|
||||
}
|
||||
const response = await adminApi.delete(`/admin/api/posts/${testData.postId}`);
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to delete post: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
log(` Deleted post: ${testData.postId}`);
|
||||
testData.postId = null;
|
||||
}),
|
||||
};
|
||||
|
||||
// ==================== OTHER API TESTS ====================
|
||||
|
||||
const testOther = {
|
||||
healthCheck: test('Health Check', async () => {
|
||||
const response = await api.get('/health');
|
||||
if (response.status !== 200) {
|
||||
throw new Error(`Health check failed: ${response.status}`);
|
||||
}
|
||||
log(` Health check passed: ${response.data.status}`);
|
||||
}),
|
||||
|
||||
getAlerts: test('Get Alerts', async () => {
|
||||
const response = await api.get('/api/alerts');
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to get alerts: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
if (!Array.isArray(response.data.alerts)) {
|
||||
throw new Error('Alerts is not an array');
|
||||
}
|
||||
log(` Found ${response.data.alerts.length} alerts`);
|
||||
}),
|
||||
|
||||
getPublicStatus: test('Get Public Status (no auth)', async () => {
|
||||
const response = await axios.get(`${BASE_URL}/api/status`);
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to get public status: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
log(` Public status: ${response.data.status?.overallStatus || 'unknown'}`);
|
||||
}),
|
||||
|
||||
getPublicPages: test('Get Public Apps, Uptime, and Blog Pages', async () => {
|
||||
for (const page of ['/', '/uptime', '/blog']) {
|
||||
const response = await axios.get(`${BASE_URL}${page}`);
|
||||
if (response.status !== 200 || !response.data.includes('LocalPing')) {
|
||||
throw new Error(`Public page ${page} failed: ${response.status}`);
|
||||
}
|
||||
}
|
||||
log(' Public routes returned the shared shell');
|
||||
}),
|
||||
|
||||
getNotificationSettings: test('Get Notification Settings', async () => {
|
||||
const response = await adminApi.get('/admin/api/notification-settings');
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to get notification settings: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
const delay = response.data.settings?.monitorDownDelayMinutes;
|
||||
if (!Number.isInteger(delay) || delay < 1 || delay > 1440) {
|
||||
throw new Error(`Invalid monitor notification delay: ${delay}`);
|
||||
}
|
||||
testData.notificationDelayMinutes = delay;
|
||||
log(` Current outage notification delay: ${delay} minute(s)`);
|
||||
}),
|
||||
|
||||
updateNotificationSettings: test('Update Notification Settings', async () => {
|
||||
const delay = testData.notificationDelayMinutes || 5;
|
||||
const response = await adminApi.put('/admin/api/notification-settings', {
|
||||
monitorDownDelayMinutes: delay,
|
||||
});
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to update notification settings: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
log(` Notification delay accepted: ${delay} minute(s)`);
|
||||
}),
|
||||
|
||||
getSettings: test('Get Admin Settings', async () => {
|
||||
const response = await adminApi.get('/admin/api/admin-settings');
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to get settings: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
log(` Retrieved admin settings`);
|
||||
}),
|
||||
|
||||
updateSettings: test('Update Admin Settings', async () => {
|
||||
const settings = {
|
||||
sessionDurationDays: 30,
|
||||
dataRetentionDays: 60,
|
||||
};
|
||||
const response = await adminApi.put('/admin/api/admin-settings', settings);
|
||||
if (response.status !== 200 || !response.data.success) {
|
||||
throw new Error(`Failed to update settings: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
log(` Updated settings`);
|
||||
}),
|
||||
|
||||
invalidApiKey: test('Test Invalid API Key', async () => {
|
||||
const response = await axios.get(`${BASE_URL}/api/targets`, {
|
||||
headers: { 'X-API-Key': 'invalid-key' },
|
||||
validateStatus: () => true,
|
||||
});
|
||||
// API might return 200 with empty data or 401/403
|
||||
if (response.status === 200 && response.data?.success === false) {
|
||||
log(` Correctly rejected invalid API key (status: ${response.status})`);
|
||||
} else if (response.status >= 400) {
|
||||
log(` Correctly rejected invalid API key (status: ${response.status})`);
|
||||
} else {
|
||||
log(` API accepted request (may not require auth for GET) - status: ${response.status}`);
|
||||
}
|
||||
}),
|
||||
};
|
||||
|
||||
// ==================== RUN ALL TESTS ====================
|
||||
|
||||
async function runAllTests() {
|
||||
log('\n' + '='.repeat(60), 'info');
|
||||
log('🚀 Starting API Test Suite', 'info');
|
||||
log(`Base URL: ${BASE_URL}`, 'info');
|
||||
log(`API Key: ${API_KEY.substring(0, 8)}...`, 'info');
|
||||
if (ADMIN_USERNAME) {
|
||||
log(`Admin Username: ${ADMIN_USERNAME}`, 'info');
|
||||
} else {
|
||||
log(`⚠️ ADMIN_USERNAME not found in .env`, 'warning');
|
||||
}
|
||||
log('='.repeat(60), 'info');
|
||||
|
||||
// Login to admin first
|
||||
try {
|
||||
await loginAdmin();
|
||||
} catch (error) {
|
||||
log(`\n❌ Failed to login to admin: ${error.message}`, 'error');
|
||||
log(' Admin API tests will be skipped', 'warning');
|
||||
}
|
||||
|
||||
// Test order matters - create before read, read before update, etc.
|
||||
const testSuites = [
|
||||
{ name: 'Health & Basic', tests: [testOther.healthCheck, testOther.invalidApiKey] },
|
||||
{ name: 'Targets/Monitors', tests: [
|
||||
testTargets.create,
|
||||
testTargets.getAll,
|
||||
testTargets.getOne,
|
||||
testTargets.getStatistics,
|
||||
testTargets.update,
|
||||
testTargets.delete,
|
||||
]},
|
||||
{ name: 'Incidents', tests: [
|
||||
testIncidents.create,
|
||||
testIncidents.getAll,
|
||||
testIncidents.getOne,
|
||||
testIncidents.update,
|
||||
testIncidents.delete,
|
||||
]},
|
||||
{ name: 'Blog Posts', tests: [
|
||||
testPosts.create,
|
||||
testPosts.getAll,
|
||||
testPosts.getOne,
|
||||
testPosts.update,
|
||||
testPosts.delete,
|
||||
]},
|
||||
{ name: 'Other Endpoints', tests: [
|
||||
testOther.getAlerts,
|
||||
testOther.getPublicStatus,
|
||||
testOther.getPublicPages,
|
||||
testOther.getSettings,
|
||||
testOther.updateSettings,
|
||||
testOther.getNotificationSettings,
|
||||
testOther.updateNotificationSettings,
|
||||
]},
|
||||
];
|
||||
|
||||
for (const suite of testSuites) {
|
||||
log(`\n📦 Test Suite: ${suite.name}`, 'test');
|
||||
for (const testFn of suite.tests) {
|
||||
await testFn();
|
||||
}
|
||||
}
|
||||
|
||||
// Summary
|
||||
log('\n' + '='.repeat(60), 'info');
|
||||
log('📊 Test Summary', 'info');
|
||||
log('='.repeat(60), 'info');
|
||||
log(`✅ Passed: ${passed}`, 'success');
|
||||
log(`❌ Failed: ${failed}`, failed > 0 ? 'error' : 'success');
|
||||
log(`📈 Total: ${passed + failed}`, 'info');
|
||||
|
||||
if (errors.length > 0) {
|
||||
log('\n❌ Failed Tests:', 'error');
|
||||
errors.forEach(({ test, error }) => {
|
||||
log(` • ${test}: ${error}`, 'error');
|
||||
});
|
||||
}
|
||||
|
||||
log('\n' + '='.repeat(60), 'info');
|
||||
process.exit(failed > 0 ? 1 : 0);
|
||||
}
|
||||
|
||||
// Run tests
|
||||
runAllTests().catch(error => {
|
||||
log(`\n💥 Fatal error: ${error.message}`, 'error');
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||