diff --git a/dashcaddy-api/__tests__/monitoring-journald-reader.test.js b/dashcaddy-api/__tests__/monitoring-journald-reader.test.js new file mode 100644 index 0000000..9f57b82 --- /dev/null +++ b/dashcaddy-api/__tests__/monitoring-journald-reader.test.js @@ -0,0 +1,326 @@ +/** + * DC-055: Host journald reader unit tests + * + * The reader is a security-sensitive shell-out — every test below exists + * to prevent a regression that would let a caller pass a tainted unit + * name or since/until/search string to journalctl. We never call the real + * binary; every spawn is mocked by injecting an `exec` function (the + * module accepts exec as the second argument specifically for testability). + */ + +const path = require('path'); +const { EventEmitter } = require('events'); + +const MODULE_PATH = path.join(__dirname, '..', 'src', 'monitoring', 'journald-reader.js'); + +// Construct a fake child process that matches the interface journald-reader +// uses: stdout/stderr EventEmitters, kill(), and emits 'exit' on demand. +function makeFakeChild({ stdout = '', stderr = '', code = 0, signal = null, failOnSpawn = null, killFn = null } = {}) { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.kill = killFn || (() => {}); + process.nextTick(() => { + if (failOnSpawn) { + const err = new Error('spawn fail'); + err.code = failOnSpawn; + child.emit('error', err); + return; + } + if (stdout) child.stdout.emit('data', Buffer.from(stdout)); + if (stderr) child.stderr.emit('data', Buffer.from(stderr)); + child.emit('exit', code, signal); + }); + return child; +} + +// Factory for an `exec` function that returns the given fake child. +function fakeExec(child) { + return jest.fn().mockReturnValue(child); +} + +describe('journald-reader', () => { + describe('assertUnitAllowed', () => { + const { assertUnitAllowed } = require(MODULE_PATH); + + test('accepts allow-listed bare names', () => { + expect(assertUnitAllowed('caddy')).toBe('caddy'); + expect(assertUnitAllowed('docker')).toBe('docker'); + expect(assertUnitAllowed('dashcaddy-api')).toBe('dashcaddy-api'); + }); + + test('strips .service suffix', () => { + expect(assertUnitAllowed('caddy.service')).toBe('caddy'); + expect(assertUnitAllowed('docker.service')).toBe('docker'); + }); + + test('rejects units not on the allow-list', () => { + expect(() => assertUnitAllowed('sshd')).toThrow(/not in allow-list/); + expect(() => assertUnitAllowed('nginx')).toThrow(/not in allow-list/); + expect(() => assertUnitAllowed('root')).toThrow(/not in allow-list/); + }); + + test('rejects shell metacharacters and path traversal', () => { + expect(() => assertUnitAllowed('caddy; rm -rf /')).toThrow(/invalid characters/); + expect(() => assertUnitAllowed('caddy && touch /tmp/pwn')).toThrow(/invalid characters/); + expect(() => assertUnitAllowed('caddy|tee /etc/passwd')).toThrow(/invalid characters/); + expect(() => assertUnitAllowed('../etc/passwd')).toThrow(/invalid characters/); + expect(() => assertUnitAllowed('caddy\nfoo')).toThrow(/invalid characters/); + }); + + test('rejects empty / non-string', () => { + expect(() => assertUnitAllowed('')).toThrow(/unit is required/); + expect(() => assertUnitAllowed(null)).toThrow(/unit is required/); + expect(() => assertUnitAllowed(undefined)).toThrow(/unit is required/); + expect(() => assertUnitAllowed(42)).toThrow(/unit is required/); + }); + + test('throws ValidationError specifically (route layer keys on .name)', () => { + try { assertUnitAllowed('nginx'); } + catch (e) { expect(e.name).toBe('ValidationError'); } + }); + }); + + describe('parseTail', () => { + const { parseTail, MAX_TAIL_LINES } = require(MODULE_PATH); + + test('returns fallback on undefined', () => { + expect(parseTail(undefined)).toBe(200); + expect(parseTail(undefined, 50)).toBe(50); + }); + + test('clamps to MAX_TAIL_LINES', () => { + expect(parseTail('999999999999')).toBe(MAX_TAIL_LINES); + expect(parseTail(999999999999)).toBe(MAX_TAIL_LINES); + }); + + test('rejects non-positive and non-integer', () => { + expect(() => parseTail('0')).toThrow(/positive integer/); + expect(() => parseTail('-5')).toThrow(/positive integer/); + expect(() => parseTail('abc')).toThrow(/positive integer/); + expect(() => parseTail('1.5')).toThrow(/positive integer/); + expect(() => parseTail(NaN)).toThrow(/positive integer/); + }); + + test('accepts valid integers', () => { + expect(parseTail('1')).toBe(1); + expect(parseTail('500')).toBe(500); + expect(parseTail(200)).toBe(200); + }); + }); + + describe('parseTimestamp', () => { + const { parseTimestamp } = require(MODULE_PATH); + + test('returns null on undefined/empty', () => { + expect(parseTimestamp(undefined, 'since')).toBeNull(); + expect(parseTimestamp('', 'since')).toBeNull(); + expect(parseTimestamp(null, 'since')).toBeNull(); + }); + + test('parses ISO 8601 timestamps', () => { + const out = parseTimestamp('2026-08-18T07:00:00Z', 'since'); + expect(out).toBe('2026-08-18T07:00:00.000Z'); + }); + + test('parses ISO date-only', () => { + const out = parseTimestamp('2026-08-18', 'since'); + expect(out).toMatch(/^2026-08-18/); + }); + + test('parses unix epoch in seconds and ms', () => { + // Use a known epoch so the test isn't sensitive to "now". The + // expected ISO output is computed at runtime so this stays correct. + const epochSec = 1787038846; // 2026-08-18T07:00:46Z + const expected = new Date(epochSec * 1000).toISOString(); + expect(parseTimestamp(String(epochSec), 'since')).toBe(expected); + expect(parseTimestamp(String(epochSec * 1000), 'since')).toBe(expected); + }); + + test('passes through journalctl relative syntax', () => { + expect(parseTimestamp('30 min ago', 'since')).toBe('30 min ago'); + expect(parseTimestamp('today', 'until')).toBe('today'); + }); + + test('rejects shell metacharacters in relative syntax', () => { + expect(() => parseTimestamp('30 min ago; touch /tmp/pwn', 'since')).toThrow(/forbidden/); + expect(() => parseTimestamp('today && rm -rf /', 'until')).toThrow(/forbidden/); + }); + + test('rejects strings >1024 chars', () => { + const huge = 'a'.repeat(1025); + expect(() => parseTimestamp(huge, 'since')).toThrow(/forbidden/); + }); + + test('rejects invalid ISO', () => { + // 'not-a-date' doesn't match the ISO_PATTERN and isn't numeric or + // safe relative-syntax — falls through to the relative branch but + // doesn't contain forbidden chars either, so it would pass through + // to journalctl. Use a string with shell metacharacters instead + // to prove the path actually rejects. + expect(() => parseTimestamp('yesterday | nc evil 1234', 'since')).toThrow(); + // Numbers that overflow Date.parse + expect(() => parseTimestamp('99999999999999999999', 'since')).toThrow(); + }); + }); + + describe('buildArgv', () => { + const { buildArgv } = require(MODULE_PATH); + + test('always emits --directory + unit + --no-pager', () => { + const argv = buildArgv({ unit: 'caddy', tail: 100 }); + expect(argv).toContain('--directory'); + expect(argv[argv.indexOf('--directory') + 1]).toBe('/var/log/journal'); + expect(argv).toContain('--no-pager'); + expect(argv).toContain('-u'); + expect(argv[argv.indexOf('-u') + 1]).toBe('caddy'); + expect(argv).not.toContain('--follow'); + }); + + test('follow flag is set when requested', () => { + const argv = buildArgv({ unit: 'caddy', follow: true }); + expect(argv).toContain('--follow'); + }); + + test('emits -n for numeric tail', () => { + const argv = buildArgv({ unit: 'caddy', tail: 500 }); + const idx = argv.indexOf('-n'); + expect(idx).toBeGreaterThan(-1); + expect(argv[idx + 1]).toBe('500'); + }); + + test('emits --since/--until/search when provided', () => { + const argv = buildArgv({ + unit: 'caddy', tail: 100, + since: '2026-08-18T00:00:00Z', + until: '2026-08-18T23:59:59Z', + search: 'health', + }); + expect(argv).toContain('--since'); + expect(argv).toContain('--until'); + expect(argv).toContain('-S'); + expect(argv[argv.indexOf('-S') + 1]).toBe('health'); + }); + + test('emits argv as a flat string array (no shell)', () => { + const argv = buildArgv({ unit: 'caddy', tail: 1 }); + expect(argv.every(a => typeof a === 'string')).toBe(true); + }); + }); + + describe('readEntries', () => { + const reader = require(MODULE_PATH); + + test('parses short-output lines into structured entries', async () => { + const child = makeFakeChild({ + stdout: [ + 'Aug 18 00:42:46 vmi3080415 caddy[3620580]: {"level":"info","msg":"hello"}', + 'Aug 18 00:42:56 vmi3080415 caddy[3620580]: {"level":"warn","msg":"oops"}', + '', + ].join('\n'), + }); + const entries = await reader.readEntries({ unit: 'caddy', tail: 50 }, { exec: fakeExec(child) }); + expect(entries).toHaveLength(2); + expect(entries[0].timestamp).toBe('Aug 18 00:42:46'); + expect(entries[0].hostname).toBe('vmi3080415'); + expect(entries[0].unit).toBe('caddy'); + expect(entries[0].text).toBe('{"level":"info","msg":"hello"}'); + }); + + test('throws on ValidationError for bad unit', async () => { + await expect(reader.readEntries({ unit: 'nginx' })).rejects.toMatchObject({ + name: 'ValidationError', + }); + }); + + test('throws on ValidationError for bad tail', async () => { + await expect(reader.readEntries({ unit: 'caddy', tail: -1 })).rejects.toMatchObject({ + name: 'ValidationError', + }); + }); + + test('throws on ValidationError for shell-meta since', async () => { + await expect(reader.readEntries({ unit: 'caddy', since: 'yesterday; touch /tmp/pwn' })) + .rejects.toMatchObject({ name: 'ValidationError' }); + }); + + test('surfaces ENOENT as Error("journalctl unavailable")', async () => { + const child = makeFakeChild({ failOnSpawn: 'ENOENT' }); + const err = await reader.readEntries({ unit: 'caddy' }, { exec: fakeExec(child) }) + .then(() => null, e => e); + expect(err.message).toBe('journalctl unavailable'); + }); + + test('surfaces non-zero exit with stderr snippet', async () => { + const child = makeFakeChild({ + stdout: '', + stderr: 'Failed to open directory: /var/log/journal/foo\n', + code: 1, + }); + const err = await reader.readEntries({ unit: 'caddy' }, { exec: fakeExec(child) }) + .then(() => null, e => e); + expect(err.message).toMatch(/exited 1/); + expect(err.message).toMatch(/Failed to open directory/); + }); + + test('clamps stdout at MAX_OUTPUT_BUFFER and rejects with overflow', async () => { + // Use smaller chunks: 800KB then another 800KB = 1.6MB > 2MB cap. + // Wait, that's <2MB. Need: total > 2MB. Use 1MB + 1.2MB. + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.kill = jest.fn(); + const cap = require(MODULE_PATH).MAX_OUTPUT_BUFFER; + const first = Math.floor(cap * 0.4); // 40% + const second = Math.floor(cap * 0.7); // 70% more — total 110% + process.nextTick(() => { + child.stdout.emit('data', Buffer.alloc(first, 'x')); + child.stdout.emit('data', Buffer.alloc(second, 'x')); + // Don't emit exit — the overflow rejection doesn't depend on it. + // Kill the child eventually so Jest can exit cleanly. + setTimeout(() => child.emit('exit', null, 'SIGKILL'), 50); + }); + const execSpy = jest.fn().mockReturnValue(child); + const err = await reader.readEntries({ unit: 'caddy' }, { exec: execSpy }) + .then(() => null, e => e); + expect(err).not.toBeNull(); + expect(err.message).toMatch(/exceeded/); + expect(child.kill).toHaveBeenCalledWith('SIGKILL'); + }); + }); + + describe('streamEntries', () => { + const reader = require(MODULE_PATH); + + test('emits parsed data + completes on exit', async () => { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.kill = jest.fn(); + + process.nextTick(() => { + child.stdout.emit('data', Buffer.from('Aug 18 00:42:46 host caddy[1]: hello\n')); + child.emit('exit', 0, null); + }); + + const seen = []; + const execSpy = jest.fn().mockReturnValue(child); + reader.streamEntries({ unit: 'caddy' }, { + exec: execSpy, + onData: (e) => seen.push(e), + onError: () => {}, + }); + // Drain microtasks so the nextTick callback fires. + await new Promise((r) => setTimeout(r, 30)); + expect(execSpy).toHaveBeenCalledTimes(1); + expect(seen.length).toBeGreaterThanOrEqual(1); + expect(seen[0].unit).toBe('caddy'); + expect(seen[0].text).toBe('hello'); + }); + + test('rejects bad unit before opening stream', () => { + expect(() => reader.streamEntries({ unit: 'nginx' }, { onError: () => {} })) + .toThrow(/not in allow-list/); + }); + }); +}); \ No newline at end of file diff --git a/dashcaddy-api/__tests__/routes/logs-journal.routes.test.js b/dashcaddy-api/__tests__/routes/logs-journal.routes.test.js new file mode 100644 index 0000000..024f004 --- /dev/null +++ b/dashcaddy-api/__tests__/routes/logs-journal.routes.test.js @@ -0,0 +1,196 @@ +/** + * DC-055: Host journald route smoke tests. + * + * Mounts the routes/logs.js journald endpoints into a tiny express app + * with a mocked journald reader. The mock mirrors the real module's + * validation pipeline (assertUnitAllowed, parseTail, parseTimestamp) so + * bad inputs still throw ValidationError -> 400 at the route boundary, + * but the actual journalctl spawn is short-circuited. + */ + +const express = require('express'); +const request = require('supertest'); +const path = require('path'); + +const realJournaldPath = require.resolve('../../src/monitoring/journald-reader.js'); + +// Pull the real module's validators so the mock's readEntries can +// reproduce the same 400-on-bad-input behaviour as production. +const realReader = jest.requireActual(realJournaldPath); + +// Mocked journald reader. Variable name MUST start with "mock" so +// jest.mock hoisting doesn't reject the factory closure. +const mockJournald = { + ALLOWED_UNITS: realReader.ALLOWED_UNITS, + MAX_TAIL_LINES: realReader.MAX_TAIL_LINES, + MAX_OUTPUT_BUFFER: realReader.MAX_OUTPUT_BUFFER, + isAvailable: jest.fn().mockResolvedValue(true), + // Validation pipeline runs through the real assert/parse functions so + // bad unit/tail/since/until still surface as ValidationError. The + // journalctl spawn itself is short-circuited — return canned entries. + readEntries: jest.fn(async (opts) => { + const unit = realReader.assertUnitAllowed(opts.unit); + realReader.parseTail(opts.tail); // throws on bad tail + realReader.parseTimestamp(opts.since, 'since'); + realReader.parseTimestamp(opts.until, 'until'); + return [ + { timestamp: 'Aug 18 00:42:46', hostname: 'host', unit, text: 'mock-line-1' }, + ]; + }), + // Default stream mock: invokes onData with one synthetic entry then + // returns a no-op handle. Tests override per-case. + streamEntries: jest.fn((opts, hooks = {}) => { + if (hooks.onData) { + hooks.onData({ timestamp: 'Aug 18 00:42:46', unit: opts.unit, text: 'stream-line-1' }); + } + return { kill: jest.fn(), child: {} }; + }), + listUnits: jest.fn(async () => [ + { unit: 'caddy', hasEntries: true }, + { unit: 'docker', hasEntries: true }, + ]), + assertUnitAllowed: realReader.assertUnitAllowed, + parseTail: realReader.parseTail, + parseTimestamp: realReader.parseTimestamp, + parseShortLine: realReader.parseShortLine, + buildArgv: realReader.buildArgv, +}; + +jest.mock('../../src/monitoring/journald-reader.js', () => mockJournald); + +// Force journaldAvailable = true in routes/logs.js. The route checks +// /var/log/journal + /usr/bin/journalctl at module-load time, so we stub +// fs.existsSync to lie about those paths. +const realFs = require('fs'); +const realExists = realFs.existsSync; +realFs.existsSync = function(p) { + if (p === '/var/log/journal' || p === '/usr/bin/journalctl') return true; + return realExists.apply(this, arguments); +}; + +const logsRoutes = require('../../routes/logs.js'); + +function buildApp() { + const app = express(); + const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next); + const ok = (res, data) => res.json({ success: true, ...data }); + const errorHandler = (err, req, res, next) => { + const status = err.statusCode || (err.name === 'ValidationError' ? 400 : 500); + res.status(status).json({ success: false, error: err.message }); + }; + app.use('/api/v1', logsRoutes({ asyncHandler, ok })); + app.use(errorHandler); + return app; +} + +describe('routes /logs/journal', () => { + let app; + + beforeEach(async () => { + mockJournald.readEntries.mockClear(); + mockJournald.streamEntries.mockClear(); + mockJournald.listUnits.mockClear(); + app = buildApp(); + // Let any keep-alive socket from the prior test close before we + // bind a new express app. + await new Promise(r => setTimeout(r, 10)); + }); + + describe('GET /logs/journal/units', () => { + test('returns unit list when journald is mounted', async () => { + const res = await request(app).get('/api/v1/logs/journal/units'); + expect(res.status).toBe(200); + expect(res.body.success).toBe(true); + expect(res.body.available).toBe(true); + expect(res.body.units.length).toBeGreaterThanOrEqual(1); + }); + }); + + describe('GET /logs/journal', () => { + test('returns entries for caddy', async () => { + const res = await request(app) + .get('/api/v1/logs/journal') + .query({ unit: 'caddy', tail: 50 }); + expect(res.status).toBe(200); + expect(res.body.entries.length).toBeGreaterThanOrEqual(1); + expect(res.body.entries[0].unit).toBe('caddy'); + expect(mockJournald.readEntries).toHaveBeenCalled(); + const call = mockJournald.readEntries.mock.calls[0][0]; + expect(call.unit).toBe('caddy'); + expect(call.tail).toBe('50'); + }); + + test('forwards since/until/search verbatim', async () => { + await request(app).get('/api/v1/logs/journal').query({ + unit: 'caddy', tail: 100, + since: '2026-08-18T00:00:00Z', + until: '2026-08-18T23:59:59Z', + search: 'health', + }); + const call = mockJournald.readEntries.mock.calls[0][0]; + expect(call.since).toBe('2026-08-18T00:00:00Z'); + expect(call.until).toBe('2026-08-18T23:59:59Z'); + expect(call.search).toBe('health'); + }); + + test('returns 400 when unit not in allow-list', async () => { + const res = await request(app).get('/api/v1/logs/journal').query({ unit: 'nginx' }); + expect(res.status).toBe(400); + expect(res.body.error).toMatch(/not in allow-list/); + // The reader is called and rejects; the route layer maps the + // ValidationError to 400 without doing any spawn. + expect(mockJournald.readEntries).toHaveBeenCalled(); + }); + + test('returns 400 when unit contains shell metacharacters', async () => { + const res = await request(app).get('/api/v1/logs/journal').query({ unit: 'caddy; rm -rf /' }); + expect(res.status).toBe(400); + expect(mockJournald.readEntries).toHaveBeenCalled(); + }); + + test('returns 400 when tail is invalid', async () => { + const res = await request(app).get('/api/v1/logs/journal').query({ unit: 'caddy', tail: 'oops' }); + expect(res.status).toBe(400); + }); + + test('returns 500 when reader throws non-validation error', async () => { + mockJournald.readEntries.mockRejectedValueOnce(new Error('journalctl exited 1: bad dir')); + const res = await request(app).get('/api/v1/logs/journal').query({ unit: 'caddy' }); + expect(res.status).toBe(500); + expect(res.body.error).toMatch(/journalctl exited 1/); + }); + }); + + describe('GET /logs/journal/stream', () => { + test('opens SSE with correct content-type for a valid unit', async () => { + // Stub the mock to immediately call onError so the route ends + // the response and supertest can collect it. Production SSE + // streams stay open until the client disconnects — covered by + // the journald-reader.streamEntries unit tests. + mockJournald.streamEntries.mockImplementationOnce((opts, hooks) => { + setTimeout(() => hooks.onError && hooks.onError(new Error('synthetic-EOF')), 5); + return { kill: jest.fn(), child: {} }; + }); + + const res = await request(app) + .get('/api/v1/logs/journal/stream') + .query({ unit: 'caddy' }) + .timeout(2000); + expect(res.status).toBe(200); + expect(res.headers['content-type']).toMatch(/text\/event-stream/); + }); + + test('400 when unit not in allow-list', async () => { + // The route pre-validates with journald.assertUnitAllowed BEFORE + // opening SSE — invalid unit returns a 400 JSON response without + // touching the stream. + const res = await request(app) + .get('/api/v1/logs/journal/stream') + .query({ unit: 'nginx' }); + expect(res.status).toBe(400); + expect(res.body.error).toMatch(/not in allow-list/); + // streamEntries must NOT have been called for a bad unit. + expect(mockJournald.streamEntries).not.toHaveBeenCalled(); + }); + }); +}); \ No newline at end of file diff --git a/dashcaddy-api/routes/logs.js b/dashcaddy-api/routes/logs.js index 7ed867b..92af6c8 100644 --- a/dashcaddy-api/routes/logs.js +++ b/dashcaddy-api/routes/logs.js @@ -6,6 +6,15 @@ const { exists } = require('../src/utilities/fs-helpers'); const { paginate, parsePaginationParams } = require('../src/utilities/pagination'); const { NotFoundError, ValidationError, ForbiddenError } = require('../src/utilities/errors'); const { ok } = require('../src/utils/responses'); +const journald = require('../src/monitoring/journald-reader'); + +const journaldAvailable = (() => { + try { + return fs.existsSync('/var/log/journal') && fs.existsSync('/usr/bin/journalctl'); + } catch (_) { + return false; + } +})(); /** * Logs route factory @@ -218,6 +227,99 @@ module.exports = function({ asyncHandler, ok, docker, logDigest, dockerMaintenan ok(res, { result }); }, 'logs-docker-maintenance')); + // ===== DC-055: Host journald log viewer ===== + // Reads from the host's /var/log/journal via bind-mount in start.sh. + // Returns 503 if the bind-mount isn't present (dev containers, Windows). + + // Allow-list of units the dashboard can stream. Exposed to the client so + // the dropdown stays in sync with the server-side allow-list. + router.get('/logs/journal/units', asyncHandler(async (req, res) => { + if (!journaldAvailable) { + return ok(res, { available: false, units: [] }); + } + const units = await journald.listUnits(); + ok(res, { available: true, units }); + }, 'logs-journal-units')); + + // Read a bounded tail of entries for a unit. + router.get('/logs/journal', asyncHandler(async (req, res) => { + if (!journaldAvailable) { + throw new Error('journald not mounted in this container (host /var/log/journal + /usr/bin/journalctl required)'); + } + const entries = await journald.readEntries({ + unit: req.query.unit, + tail: req.query.tail, + since: req.query.since, + until: req.query.until, + search: req.query.search, + }); + ok(res, { entries, count: entries.length }); + }, 'logs-journal-read')); + + // Stream entries as they arrive (Server-Sent Events). + router.get('/logs/journal/stream', asyncHandler(async (req, res) => { + if (!journaldAvailable) { + res.statusCode = 503; + res.setHeader('Content-Type', 'text/event-stream'); + res.write(`data: ${JSON.stringify({ error: 'journald not mounted in this container' })}\n\n`); + res.end(); + return; + } + + // Validate BEFORE writing SSE headers — once headers go out we + // can't change statusCode. The reader does the same validation but + // we want to short-circuit here so the response status reflects the + // right category (400 for validation, 503 for bind-mount missing). + try { + journald.assertUnitAllowed(req.query.unit); + if (req.query.since) journald.parseTimestamp(req.query.since, 'since'); + } catch (err) { + // Pass through the global error middleware so the response status + // + shape matches every other validation error in the API. + throw err; + } + + // SSE headers — same convention as /logs/stream/:id. + res.setHeader('Content-Type', 'text/event-stream'); + res.setHeader('Cache-Control', 'no-cache'); + res.setHeader('Connection', 'keep-alive'); + res.setHeader('X-Accel-Buffering', 'no'); + + let settled = false; + const cleanup = (handle) => { + if (settled) return; + settled = true; + try { handle && handle.kill(); } catch (_) { /* already dead */ } + try { res.end(); } catch (_) { /* already closed */ } + }; + + let handle; + try { + handle = journald.streamEntries( + { unit: req.query.unit, since: req.query.since, search: req.query.search }, + { + onData(entry) { + if (settled) return; + res.write(`data: ${JSON.stringify(entry)}\n\n`); + }, + onError(err) { + if (settled) return; + res.write(`data: ${JSON.stringify({ error: err.message || String(err) })}\n\n`); + cleanup(handle); + }, + } + ); + } catch (err) { + res.write(`data: ${JSON.stringify({ error: (err && err.message) || 'stream failed' })}\n\n`); + try { res.end(); } catch (_) { /* ignore */ } + return; + } + + // Modern Node fires 'close' for both clean disconnects and aborts; + // the separate 'aborted' listener is deprecated as of Node 18. + req.on('close', () => cleanup(handle)); + }, 'logs-journal-stream')); + // Get logs from a file path (for native applications) router.get('/logs/file', asyncHandler(async (req, res) => { const { path: logPath, tail = 100 } = req.query; diff --git a/dashcaddy-api/src/monitoring/journald-reader.js b/dashcaddy-api/src/monitoring/journald-reader.js new file mode 100644 index 0000000..d2d7353 --- /dev/null +++ b/dashcaddy-api/src/monitoring/journald-reader.js @@ -0,0 +1,417 @@ +/** + * DC-055: Host journald reader + * + * Wraps the host's `journalctl` binary so the API can stream host service + * logs (caddy, dashcaddy-api, docker, ...) without exposing the binary + * directly to the web layer. The CLI is invoked with --directory pointed at + * the bind-mounted /var/log/journal from start.sh so we don't need the + * systemd-journal remote protocol or a privileged socket. + * + * Security contract: + * - `unit` MUST be in the allow-list `ALLOWED_UNITS`. We never accept a + * raw unit name from the caller and pass it to the shell, even with + * shell:false — because an attacker who can set unit=caddy.service; + * touch /tmp/x could use the CLI itself as a confused-deputy vector. + * - All journalctl invocations use `spawn` (not `exec`) and pass arguments + * as an array (`shell:false`). No shell metacharacters can be smuggled + * in through any field — the unit, since/until, search, tail numbers + * are validated separately before being added to argv. + * - Streams (SSE) cap to MAX_STREAM_BYTES and kill the child on overflow + * so a `tail=999999999999` request can't OOM the process. + * + * Failure modes that surface to the route layer: + * - journalctl missing in the container (DN container, dev container): + * every call throws Error('journalctl unavailable'). Route 503s. + * - unit not in allow-list: throws ValidationError. Route 400s. + * - non-zero exit code: child stderr is captured and surfaced verbatim + * up to LOG_PREVIEW_BYTES so the operator can see "Failed to open + * directory" instead of a generic 500. + */ + +const { spawn } = require('child_process'); +const path = require('path'); +const fs = require('fs'); + +const JOURNAL_DIR = '/var/log/journal'; +const ALLOWED_UNITS = Object.freeze([ + // Core reverse proxy + DNS host services + 'caddy', + 'dashcaddy-api', + 'docker', + 'systemd-journald', + 'networkd-dispatcher', + 'tailscaled', + 'ssh', + // Permit the unit with and without the .service suffix. The CLI accepts + // both; we store the bare name and append nothing — journalctl treats + // "caddy" and "caddy.service" identically. +]); + +// Cap how much a single request can read — prevents `tail=999999999` from +// piping half the journal into memory. The dashboard doesn't have a UI for +// "load 100MB of logs" and journalctl itself caps at 2GB anyway. +const MAX_TAIL_LINES = 5000; +// Streaming cap: how many journal entries we hand to the SSE consumer +// before killing the child. The dashboard shouldn't accumulate more than +// this in memory — pair with MAX_OUTPUT_BUFFER for a defense-in-depth +// bound on what the route layer will hold. +const MAX_STREAM_LINES = 5000; +const MAX_OUTPUT_BUFFER = 2 * 1024 * 1024; // 2MB hard cap on total stdout +const LOG_PREVIEW_BYTES = 4096; + +const UNIT_PATTERN = /^[a-zA-Z0-9_.@-]+$/; +const ISO_PATTERN = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/; + +/** + * Validate a unit name against the allow-list. Returns the canonical name + * or throws ValidationError. + */ +function assertUnitAllowed(unit) { + if (typeof unit !== 'string' || !unit) { + const err = new Error('unit is required'); + err.name = 'ValidationError'; + throw err; + } + // Strip the .service suffix defensively so callers don't have to remember + // which form journalctl prefers for a given unit. + const normalised = unit.endsWith('.service') ? unit.slice(0, -8) : unit; + if (!UNIT_PATTERN.test(normalised)) { + const err = new Error(`unit contains invalid characters: ${unit}`); + err.name = 'ValidationError'; + throw err; + } + if (!ALLOWED_UNITS.includes(normalised)) { + const err = new Error(`unit not in allow-list: ${normalised}`); + err.name = 'ValidationError'; + throw err; + } + return normalised; +} + +/** + * Parse tail to a bounded positive integer. + */ +function parseTail(raw, fallback = 200) { + if (raw === undefined || raw === null || raw === '') return fallback; + const n = Number(raw); + if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) { + const err = new Error(`tail must be a positive integer (got ${raw})`); + err.name = 'ValidationError'; + throw err; + } + return Math.min(n, MAX_TAIL_LINES); +} + +/** + * Parse since/until — accept either an ISO timestamp, a unix epoch in ms, or + * journalctl's relative syntax ("30 min ago", "today", "yesterday"). The + * dashboard uses ISO timestamps from ``; the + * relative syntax is for power users typing into the search bar. + */ +function parseTimestamp(raw, fieldName) { + if (raw === undefined || raw === null || raw === '') return null; + if (typeof raw !== 'string') { + const err = new Error(`${fieldName} must be a string`); + err.name = 'ValidationError'; + throw err; + } + // ISO 8601 + if (ISO_PATTERN.test(raw)) { + const ms = Date.parse(raw); + if (!Number.isFinite(ms)) { + const err = new Error(`${fieldName} is not a valid ISO timestamp: ${raw}`); + err.name = 'ValidationError'; + throw err; + } + return new Date(ms).toISOString(); + } + // Numeric (unix epoch seconds OR ms — journalctl accepts seconds) + if (/^-?\d+$/.test(raw)) { + const n = Number(raw); + const ms = n > 1e12 ? n : n * 1000; + if (!Number.isFinite(ms)) { + const err = new Error(`${fieldName} is not a valid epoch: ${raw}`); + err.name = 'ValidationError'; + throw err; + } + return new Date(ms).toISOString(); + } + // Relative syntax: pass through to journalctl, but cap to 1024 chars and + // disallow shell metacharacters. + if (raw.length > 1024 || /[`$;&|><\\\n\r]/.test(raw)) { + const err = new Error(`${fieldName} contains forbidden characters: ${raw}`); + err.name = 'ValidationError'; + throw err; + } + return raw; +} + +/** + * Detect whether journalctl is reachable. Cheap probe (no-op flag) so we + * don't shell out on every request when the binary is missing (dev + * container, Windows host, etc.). + */ +function isAvailable({ journalDir = JOURNAL_DIR, exec = spawn } = {}) { + if (!fs.existsSync(journalDir)) return false; + return new Promise((resolve) => { + const child = exec('journalctl', ['--no-pager', '--version'], { stdio: 'ignore' }); + child.on('error', () => resolve(false)); + child.on('exit', (code) => resolve(code === 0)); + }); +} + +/** + * Build argv for journalctl. Exposed so tests can assert exactly what we + * shell out — never build the arg array inline anywhere else. + */ +function buildArgv({ unit, since, until, tail, search, follow = false }) { + const argv = [ + '--directory', JOURNAL_DIR, + '--no-pager', + '--output=short', + '-u', unit, + ]; + if (since) argv.push('--since', since); + if (until) argv.push('--until', until); + if (typeof tail === 'number') argv.push('-n', String(tail)); + if (search) { + // journalctl -S matches the searchable text fields (MESSAGE + others). + // Quote-enforcing isn't needed because spawn argv doesn't touch a shell. + argv.push('-S', search); + } + if (follow) argv.push('--follow'); + return argv; +} + +/** + * Read a bounded tail of journal entries for a unit. Resolves to an array + * of {timestamp, text} lines, oldest first. Throws ValidationError on bad + * input, Error('journalctl unavailable') if the binary or journal dir is + * missing, and Error('journalctl exited N: ') for CLI failures. + */ +/** + * Spawn journalctl with the given argv and collect stdout/stderr up to + * the configured caps. Resolves to a Buffer of stdout on success, rejects + * with Error('journalctl unavailable') on ENOENT or + * Error('journalctl exited N: ') on non-zero exit. Exceeding the + * output cap rejects with an explicit overflow message. + * + * Kept as a free function (not inside `readEntries`) so the same plumbing + * can be reused for streaming without code duplication. + */ +function runJournalctl({ exec, argv }) { + return new Promise((resolve, reject) => { + const child = exec('journalctl', argv, { stdio: ['ignore', 'pipe', 'pipe'] }); + + let stdout = Buffer.alloc(0); + let stderr = ''; + + child.stdout.on('data', (chunk) => { + if (stdout.length + chunk.length > MAX_OUTPUT_BUFFER) { + child.kill('SIGKILL'); + reject(new Error(`output exceeded ${MAX_OUTPUT_BUFFER} bytes`)); + return; + } + stdout = Buffer.concat([stdout, chunk]); + }); + child.stderr.on('data', (chunk) => { + if (stderr.length < LOG_PREVIEW_BYTES) { + stderr += chunk.toString('utf8'); + if (stderr.length > LOG_PREVIEW_BYTES) { + stderr = stderr.slice(0, LOG_PREVIEW_BYTES) + '…'; + } + } + }); + + child.on('error', (err) => { + if (err.code === 'ENOENT') { + reject(new Error('journalctl unavailable')); + } else { + reject(err); + } + }); + child.on('exit', (code, signal) => { + if (signal === 'SIGKILL' && stdout.length >= MAX_OUTPUT_BUFFER) return; // already rejected + if (code !== 0) { + reject(new Error(`journalctl exited ${code}${stderr ? ': ' + stderr.trim() : ''}`)); + return; + } + resolve({ stdout, stderr }); + }); + }); +} + +/** + * Parse a journalctl --output=short line into a structured entry. + * Lines look like: "Aug 18 00:42:46 vmi3080415 caddy[3620580]: {...}" + */ +function parseShortLine(line, fallbackUnit) { + const tsMatch = line.match(/^([A-Z][a-z]{2} \d{2} \d{2}:\d{2}:\d{2}) (\S+) (.+?)\[\d+\]: (.*)$/); + if (tsMatch) { + return { + timestamp: tsMatch[1], + hostname: tsMatch[2], + unit: tsMatch[3], + text: tsMatch[4], + }; + } + return { timestamp: null, hostname: null, unit: fallbackUnit, text: line }; +} + +function readEntries(opts, { exec = spawn } = {}) { + return Promise.resolve().then(async () => { + const unit = assertUnitAllowed(opts.unit); + const tail = parseTail(opts.tail); + const since = parseTimestamp(opts.since, 'since'); + const until = parseTimestamp(opts.until, 'until'); + const search = typeof opts.search === 'string' && opts.search.length > 0 + ? opts.search.slice(0, 1024) + : null; + + const argv = buildArgv({ unit, tail, since, until, search, follow: false }); + const { stdout } = await runJournalctl({ exec, argv }); + const lines = stdout.toString('utf8').split('\n').filter(Boolean); + return lines.map((line) => parseShortLine(line, unit)); + }); +} + +/** + * Stream journal entries as they arrive. Returns { child, onData, onError, + * kill } — the route wires `onData`/`onError` to the SSE socket and calls + * `kill()` on disconnect. + * + * The child is spawned with --follow and we cap total bytes received; on + * overflow we kill the child and emit a synthetic 'overflow' message so the + * client knows to reconnect with a narrower window. + */ +function streamEntries(opts, { exec = spawn, onData, onError } = {}) { + const unit = assertUnitAllowed(opts.unit); + const since = parseTimestamp(opts.since, 'since'); + const search = typeof opts.search === 'string' && opts.search.length > 0 + ? opts.search.slice(0, 1024) + : null; + + const argv = buildArgv({ unit, since, search, follow: true }); + + let child; + try { + child = exec('journalctl', argv, { stdio: ['ignore', 'pipe', 'pipe'] }); + } catch (err) { + if (err.code === 'ENOENT') { + const e = new Error('journalctl unavailable'); + onError && onError(e); + return { kill: () => {}, child: null }; + } + throw err; + } + + // Closure-scoped stream bookkeeping: the previous version attached a + // counter to the onData function itself, which made the 5000-line cap + // unreachable (a function has its own properties — the count was never + // incremented). Closure scope is the right place. + let stdout = Buffer.alloc(0); + let lineCount = 0; + let overflowEmitted = false; + + child.stdout.on('data', (chunk) => { + if (stdout.length + chunk.length > MAX_OUTPUT_BUFFER) { + child.kill('SIGKILL'); + onError && onError(new Error(`stream exceeded ${MAX_OUTPUT_BUFFER} bytes`)); + return; + } + stdout = Buffer.concat([stdout, chunk]); + if (onData) { + const text = stdout.toString('utf8'); + const lines = text.split('\n'); + // Hold back the last partial line; flush on the next chunk or exit. + stdout = Buffer.from(lines.pop(), 'utf8'); + for (const line of lines) { + if (!line) continue; + lineCount++; + if (lineCount > MAX_STREAM_LINES && !overflowEmitted) { + overflowEmitted = true; + child.kill('SIGKILL'); + onError && onError(new Error(`stream exceeded ${MAX_STREAM_LINES} lines`)); + return; + } + const tsMatch = line.match(/^([A-Z][a-z]{2} \d{2} \d{2}:\d{2}:\d{2}) (\S+) (.+?)\[\d+\]: (.*)$/); + onData({ + timestamp: tsMatch ? tsMatch[1] : null, + hostname: tsMatch ? tsMatch[2] : null, + unit: tsMatch ? tsMatch[3] : unit, + text: tsMatch ? tsMatch[4] : line, + }); + } + } + }); + + let stderr = ''; + child.stderr.on('data', (chunk) => { + if (stderr.length < LOG_PREVIEW_BYTES) { + stderr += chunk.toString('utf8'); + if (stderr.length > LOG_PREVIEW_BYTES) { + stderr = stderr.slice(0, LOG_PREVIEW_BYTES) + '…'; + } + } + }); + + child.on('error', (err) => { + onError && onError(err); + }); + child.on('exit', (code) => { + if (code !== 0 && stderr) { + onError && onError(new Error(`journalctl exited ${code}: ${stderr.trim()}`)); + } + }); + + return { + child, + kill() { + try { child.kill('SIGTERM'); } catch (_) { /* already dead */ } + }, + }; +} + +/** + * List units that currently have journal entries (for the dashboard + * dropdown). Walks the allow-list and asks journalctl for the most recent + * entry per unit. Units with no entries are omitted. + */ +async function listUnits({ exec = spawn } = {}) { + if (!fs.existsSync(JOURNAL_DIR)) return []; + const out = []; + for (const unit of ALLOWED_UNITS) { + const lines = await new Promise((resolve) => { + const child = exec('journalctl', [ + '--directory', JOURNAL_DIR, + '--no-pager', '-q', + '-u', unit, + '-n', '1', + '--output=short', + ], { stdio: ['ignore', 'pipe', 'ignore'] }); + let buf = ''; + child.stdout.on('data', (c) => { buf += c.toString('utf8'); }); + child.on('error', () => resolve('')); + child.on('exit', () => resolve(buf)); + }); + if (lines.trim()) { + out.push({ unit, hasEntries: true }); + } + } + return out; +} + +module.exports = { + ALLOWED_UNITS, + MAX_TAIL_LINES, + MAX_OUTPUT_BUFFER, + isAvailable, + readEntries, + streamEntries, + listUnits, + assertUnitAllowed, + parseTail, + parseTimestamp, + parseShortLine, + buildArgv, +}; \ No newline at end of file diff --git a/start.sh b/start.sh index 599ec43..8316d7d 100755 --- a/start.sh +++ b/start.sh @@ -167,6 +167,8 @@ docker run -d --restart unless-stopped --name ${CONTAINER_NAME} \ -v /usr/bin/tailscale:/usr/bin/tailscale:ro \ -v /var/run/tailscale:/var/run/tailscale:ro \ -v /etc/ssl/sami-ca:/etc/ssl/sami-ca:ro \ + -v /var/log/journal:/var/log/journal:ro \ + -v /usr/bin/journalctl:/usr/bin/journalctl:ro \ -e NODE_ENV=production \ -e SERVICES_FILE=/app/data/services.json \ -e CONFIG_FILE=/app/data/config.json \ diff --git a/status/build.js b/status/build.js index 352a9da..240a9d7 100644 --- a/status/build.js +++ b/status/build.js @@ -54,6 +54,10 @@ const bundles = { JS('import-export.js'), JS('error-logs.js'), JS('container-logs.js'), + // DC-055: Host journald log viewer — reads /var/log/journal via the + // bind-mount added in start.sh. Self-contained modal with SSE stream + // + bounded tail read. Exposes window.openJournaldModal(). + JS('journald.js'), JS('snapshot.js'), JS('smart-arr-connect.js'), JS('notification-settings.js'), diff --git a/status/dist/features.js b/status/dist/features.js index c0244ed..9c5a22d 100644 --- a/status/dist/features.js +++ b/status/dist/features.js @@ -90,44 +90,44 @@ - `);const x=document.getElementById("logo-modal"),B=document.getElementById("logo-preview-dark"),A=document.getElementById("logo-preview-light"),C=document.getElementById("logo-status"),M=document.getElementById("logo-same-both"),P=document.getElementById("logo-dual-uploads"),z=document.getElementById("logo-single-upload"),N=document.getElementById("logo-upload-dark"),f=document.getElementById("logo-upload-light"),L=document.getElementById("logo-upload-single"),w=document.querySelector("#brand .brand-logo-dark"),$=document.querySelector("#brand .brand-logo-light"),k=document.querySelector(".top-row"),T=document.getElementById("dashboard-title"),E=DC.NAME;let I=null,j=null,H=null,R="left",D=E;M?.addEventListener("change",()=>{M.checked?(P.style.display="none",z.style.display="",I=null,j=null):(P.style.display="flex",z.style.display="none",H=null)});function O(t,e){if(!t||!t.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const a=new FileReader;a.onload=o=>e(o.target.result),a.readAsDataURL(t)}N?.addEventListener("change",t=>{O(t.target.files[0],e=>{I=e,B.src=e,C.textContent="New dark logo ready to save"})}),f?.addEventListener("change",t=>{O(t.target.files[0],e=>{j=e,A.src=e,C.textContent="New light logo ready to save"})}),L?.addEventListener("change",t=>{O(t.target.files[0],e=>{H=e,B.src=e,A.src=e,C.textContent="New logo ready to save (both themes)"})});function p(t){k.setAttribute("data-logo-pos",t),document.querySelectorAll(".logo-pos-btn").forEach(e=>{e.style.background=e.dataset.pos===t?"var(--accent)":"var(--card-bg)",e.style.color=e.dataset.pos===t?"white":"var(--fg)"})}function v(t){D=t||E,document.title=D;const e=document.querySelector(".dashboard-title");e&&(e.textContent=D)}async function b(){try{const t=await fetch("/api/v1/logo");if(t.ok){const e=await t.json();e.customLogoDark&&(w.src=e.customLogoDark,B.src=e.customLogoDark),e.customLogoLight&&($.src=e.customLogoLight,A.src=e.customLogoLight),!e.customLogoDark&&!e.customLogoLight&&e.customLogo&&(w.src=e.customLogo,$.src=e.customLogo,B.src=e.customLogo,A.src=e.customLogo),e.isDefault||(C.textContent="Using custom logo"),e.position&&(R=e.position,p(e.position)),e.dashboardTitle&&v(e.dashboardTitle)}}catch(t){console.warn("Could not load custom logo:",t.message)}}document.querySelectorAll(".logo-pos-btn").forEach(t=>{t.addEventListener("click",()=>{R=t.dataset.pos,p(R)})}),document.getElementById("brand")?.addEventListener("click",()=>{I=null,j=null,H=null,N&&(N.value=""),f&&(f.value=""),L&&(L.value=""),M&&(M.checked=!1),P.style.display="flex",z.style.display="none",B.src=w.src,A.src=$.src;const t=w.src.includes("custom-logo")||$.src.includes("custom-logo");C.textContent=t?"Using custom logo":"Using default logos",p(R),T.value=D,x.classList.add("show")}),document.getElementById("logo-save")?.addEventListener("click",async()=>{try{const t=T.value.trim()||E,e={position:R,dashboardTitle:t};M?.checked&&H?(e.dataDark=H,e.dataLight=H):(I&&(e.dataDark=I),j&&(e.dataLight=j));const a=await secureFetch("/api/v1/logo",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(a.ok){const o=await a.json(),r="?t="+Date.now();o.pathDark&&(w.src=o.pathDark+r,B.src=o.pathDark+r),o.pathLight&&($.src=o.pathLight+r,A.src=o.pathLight+r),p(R),v(t),x.classList.remove("show")}else{const o=await a.json();showNotification("Failed to save: "+o.error,"error")}}catch(t){showNotification("Error saving: "+t.message,"error")}}),document.getElementById("logo-reset")?.addEventListener("click",async()=>{if(confirm(`Reset all branding to DashCaddy defaults? + `);const w=document.getElementById("logo-modal"),B=document.getElementById("logo-preview-dark"),A=document.getElementById("logo-preview-light"),S=document.getElementById("logo-status"),z=document.getElementById("logo-same-both"),P=document.getElementById("logo-dual-uploads"),M=document.getElementById("logo-single-upload"),D=document.getElementById("logo-upload-dark"),h=document.getElementById("logo-upload-light"),T=document.getElementById("logo-upload-single"),f=document.querySelector("#brand .brand-logo-dark"),H=document.querySelector("#brand .brand-logo-light"),k=document.querySelector(".top-row"),$=document.getElementById("dashboard-title"),E=DC.NAME;let I=null,O=null,C=null,j="left",N=E;z?.addEventListener("change",()=>{z.checked?(P.style.display="none",M.style.display="",I=null,O=null):(P.style.display="flex",M.style.display="none",C=null)});function R(t,e){if(!t||!t.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const a=new FileReader;a.onload=o=>e(o.target.result),a.readAsDataURL(t)}D?.addEventListener("change",t=>{R(t.target.files[0],e=>{I=e,B.src=e,S.textContent="New dark logo ready to save"})}),h?.addEventListener("change",t=>{R(t.target.files[0],e=>{O=e,A.src=e,S.textContent="New light logo ready to save"})}),T?.addEventListener("change",t=>{R(t.target.files[0],e=>{C=e,B.src=e,A.src=e,S.textContent="New logo ready to save (both themes)"})});function u(t){k.setAttribute("data-logo-pos",t),document.querySelectorAll(".logo-pos-btn").forEach(e=>{e.style.background=e.dataset.pos===t?"var(--accent)":"var(--card-bg)",e.style.color=e.dataset.pos===t?"white":"var(--fg)"})}function v(t){N=t||E,document.title=N;const e=document.querySelector(".dashboard-title");e&&(e.textContent=N)}async function x(){try{const t=await fetch("/api/v1/logo");if(t.ok){const e=await t.json();e.customLogoDark&&(f.src=e.customLogoDark,B.src=e.customLogoDark),e.customLogoLight&&(H.src=e.customLogoLight,A.src=e.customLogoLight),!e.customLogoDark&&!e.customLogoLight&&e.customLogo&&(f.src=e.customLogo,H.src=e.customLogo,B.src=e.customLogo,A.src=e.customLogo),e.isDefault||(S.textContent="Using custom logo"),e.position&&(j=e.position,u(e.position)),e.dashboardTitle&&v(e.dashboardTitle)}}catch(t){console.warn("Could not load custom logo:",t.message)}}document.querySelectorAll(".logo-pos-btn").forEach(t=>{t.addEventListener("click",()=>{j=t.dataset.pos,u(j)})}),document.getElementById("brand")?.addEventListener("click",()=>{I=null,O=null,C=null,D&&(D.value=""),h&&(h.value=""),T&&(T.value=""),z&&(z.checked=!1),P.style.display="flex",M.style.display="none",B.src=f.src,A.src=H.src;const t=f.src.includes("custom-logo")||H.src.includes("custom-logo");S.textContent=t?"Using custom logo":"Using default logos",u(j),$.value=N,w.classList.add("show")}),document.getElementById("logo-save")?.addEventListener("click",async()=>{try{const t=$.value.trim()||E,e={position:j,dashboardTitle:t};z?.checked&&C?(e.dataDark=C,e.dataLight=C):(I&&(e.dataDark=I),O&&(e.dataLight=O));const a=await secureFetch("/api/v1/logo",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(a.ok){const o=await a.json(),i="?t="+Date.now();o.pathDark&&(f.src=o.pathDark+i,B.src=o.pathDark+i),o.pathLight&&(H.src=o.pathLight+i,A.src=o.pathLight+i),u(j),v(t),w.classList.remove("show")}else{const o=await a.json();showNotification("Failed to save: "+o.error,"error")}}catch(t){showNotification("Error saving: "+t.message,"error")}}),document.getElementById("logo-reset")?.addEventListener("click",async()=>{if(confirm(`Reset all branding to DashCaddy defaults? -This will reset the logo, favicon, title, and position.`))try{if((await secureFetch("/api/v1/logo",{method:"DELETE"})).ok&&(w.src="/assets/dashcaddy-logo-dark.png",$.src="/assets/dashcaddy-logo-light.png",B.src="/assets/dashcaddy-logo-dark.png",A.src="/assets/dashcaddy-logo-light.png",C.textContent="Using default logos",I=null,j=null,H=null,T.value=E,v(E),R="left",p("left")),(await secureFetch("/api/v1/favicon",{method:"DELETE"})).ok){const a=document.querySelector('link[rel="icon"]'),o=document.getElementById("favicon-preview"),r=document.getElementById("favicon-status");a&&(a.href="/assets/dashcaddy-favicon.ico?t="+Date.now()),o&&(o.src="/assets/dashcaddy-favicon.ico?t="+Date.now()),r&&(r.textContent="Using DashCaddy favicon"),l=null}}catch(t){showNotification("Error resetting branding: "+t.message,"error")}}),wireModal(x,document.getElementById("logo-cancel"));const y=document.getElementById("favicon-preview"),h=document.getElementById("favicon-status"),s=document.getElementById("favicon-upload"),c=document.querySelector('link[rel="icon"]')||document.createElement("link");let l=null;document.querySelector('link[rel="icon"]')||(c.rel="icon",c.href="/assets/dashcaddy-favicon.ico",document.head.appendChild(c));async function m(){try{const t=await fetch("/api/v1/favicon");if(t.ok){const e=await t.json();e.customFavicon&&(c.href=e.customFavicon+"?t="+Date.now(),y.src=e.customFavicon+"?t="+Date.now(),h.textContent="Using custom favicon")}}catch(t){console.warn("Could not load custom favicon:",t.message)}}s?.addEventListener("change",t=>{const e=t.target.files[0];if(!e)return;if(!e.type.match(/^image\/(png|svg\+xml)$/)){showNotification("Please select a PNG or SVG file","warning"),s.value="";return}const a=new FileReader;a.onload=o=>{l=o.target.result,y.src=l,h.textContent="New favicon ready to save"},a.readAsDataURL(e)}),document.getElementById("logo-save")?.addEventListener("click",async()=>{if(l)try{const t=await secureFetch("/api/v1/favicon",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:l})});if(t.ok){const e=await t.json();c.href=e.path+"?t="+Date.now(),y.src=e.path+"?t="+Date.now(),h.textContent="Using custom favicon",l=null}else{const e=await t.json();showNotification("Failed to save favicon: "+e.error,"error")}}catch(t){showNotification("Error saving favicon: "+t.message,"error")}}),m(),b();const u=document.getElementById("settings-timezone");u&&(new MutationObserver(()=>{x.classList.contains("show")&&u.options.length===0&&(async()=>{let e;try{const a=await fetch("/api/v1/config");a.ok&&(e=(await a.json()).timezone)}catch{}window.populateTimezoneSelect(u,e)})()}).observe(x,{attributes:!0,attributeFilter:["class"]}),document.getElementById("logo-save")?.addEventListener("click",async()=>{const e=u.value;if(e)try{const a=await fetch("/api/v1/config");if(!a.ok)return;const o=await a.json();o.timezone=e,o.updatedAt=new Date().toISOString(),await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})}catch(a){console.warn("Failed to save timezone:",a.message)}}))})(),window.populateTimezoneSelect=function(x,B){const A=Intl.supportedValuesOf("timeZone"),C=B||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";x.innerHTML="";for(const M of A){const P=document.createElement("option");P.value=M,P.textContent=M.replace(/_/g," "),M===C&&(P.selected=!0),x.appendChild(P)}},(function(){let x="homelab",B=null;async function A(){try{const v=await fetch("/api/v1/config");if(v.ok&&(B=await v.json(),B&&B.setupComplete))return document.getElementById("setup-wizard").style.display="none",!0}catch(v){console.warn("Could not fetch server config, checking localStorage fallback:",v.message)}return safeGet("dashcaddy-setup")?(document.getElementById("setup-wizard").style.display="none",!0):(document.getElementById("setup-wizard").style.display="flex",!1)}A();const C=document.getElementById("setup-timezone");C&&window.populateTimezoneSelect(C);function M(p){document.querySelectorAll(".setup-step").forEach(b=>{b.style.display="none"});const v=document.getElementById(p);v&&(v.style.display="block")}function P(){const p=document.getElementById("setup-summary-content");if(!p)return;let v='
';if(x==="homelab"){const y=document.getElementById("setup-tld")?.value?.trim()||".home",h=document.getElementById("setup-ca-name")?.value?.trim()||"",s=document.getElementById("setup-dns-ip")?.value?.trim()||"",c=document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT;v+=` +This will reset the logo, favicon, title, and position.`))try{if((await secureFetch("/api/v1/logo",{method:"DELETE"})).ok&&(f.src="/assets/dashcaddy-logo-dark.png",H.src="/assets/dashcaddy-logo-light.png",B.src="/assets/dashcaddy-logo-dark.png",A.src="/assets/dashcaddy-logo-light.png",S.textContent="Using default logos",I=null,O=null,C=null,$.value=E,v(E),j="left",u("left")),(await secureFetch("/api/v1/favicon",{method:"DELETE"})).ok){const a=document.querySelector('link[rel="icon"]'),o=document.getElementById("favicon-preview"),i=document.getElementById("favicon-status");a&&(a.href="/assets/dashcaddy-favicon.ico?t="+Date.now()),o&&(o.src="/assets/dashcaddy-favicon.ico?t="+Date.now()),i&&(i.textContent="Using DashCaddy favicon"),l=null}}catch(t){showNotification("Error resetting branding: "+t.message,"error")}}),wireModal(w,document.getElementById("logo-cancel"));const g=document.getElementById("favicon-preview"),b=document.getElementById("favicon-status"),s=document.getElementById("favicon-upload"),p=document.querySelector('link[rel="icon"]')||document.createElement("link");let l=null;document.querySelector('link[rel="icon"]')||(p.rel="icon",p.href="/assets/dashcaddy-favicon.ico",document.head.appendChild(p));async function m(){try{const t=await fetch("/api/v1/favicon");if(t.ok){const e=await t.json();e.customFavicon&&(p.href=e.customFavicon+"?t="+Date.now(),g.src=e.customFavicon+"?t="+Date.now(),b.textContent="Using custom favicon")}}catch(t){console.warn("Could not load custom favicon:",t.message)}}s?.addEventListener("change",t=>{const e=t.target.files[0];if(!e)return;if(!e.type.match(/^image\/(png|svg\+xml)$/)){showNotification("Please select a PNG or SVG file","warning"),s.value="";return}const a=new FileReader;a.onload=o=>{l=o.target.result,g.src=l,b.textContent="New favicon ready to save"},a.readAsDataURL(e)}),document.getElementById("logo-save")?.addEventListener("click",async()=>{if(l)try{const t=await secureFetch("/api/v1/favicon",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:l})});if(t.ok){const e=await t.json();p.href=e.path+"?t="+Date.now(),g.src=e.path+"?t="+Date.now(),b.textContent="Using custom favicon",l=null}else{const e=await t.json();showNotification("Failed to save favicon: "+e.error,"error")}}catch(t){showNotification("Error saving favicon: "+t.message,"error")}}),m(),x();const c=document.getElementById("settings-timezone");c&&(new MutationObserver(()=>{w.classList.contains("show")&&c.options.length===0&&(async()=>{let e;try{const a=await fetch("/api/v1/config");a.ok&&(e=(await a.json()).timezone)}catch{}window.populateTimezoneSelect(c,e)})()}).observe(w,{attributes:!0,attributeFilter:["class"]}),document.getElementById("logo-save")?.addEventListener("click",async()=>{const e=c.value;if(e)try{const a=await fetch("/api/v1/config");if(!a.ok)return;const o=await a.json();o.timezone=e,o.updatedAt=new Date().toISOString(),await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})}catch(a){console.warn("Failed to save timezone:",a.message)}}))})(),window.populateTimezoneSelect=function(w,B){const A=Intl.supportedValuesOf("timeZone"),S=B||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";w.innerHTML="";for(const z of A){const P=document.createElement("option");P.value=z,P.textContent=z.replace(/_/g," "),z===S&&(P.selected=!0),w.appendChild(P)}},(function(){let w="homelab",B=null;async function A(){try{const v=await fetch("/api/v1/config");if(v.ok&&(B=await v.json(),B&&B.setupComplete))return document.getElementById("setup-wizard").style.display="none",!0}catch(v){console.warn("Could not fetch server config, checking localStorage fallback:",v.message)}return safeGet("dashcaddy-setup")?(document.getElementById("setup-wizard").style.display="none",!0):(document.getElementById("setup-wizard").style.display="flex",!1)}A();const S=document.getElementById("setup-timezone");S&&window.populateTimezoneSelect(S);function z(u){document.querySelectorAll(".setup-step").forEach(x=>{x.style.display="none"});const v=document.getElementById(u);v&&(v.style.display="block")}function P(){const u=document.getElementById("setup-summary-content");if(!u)return;let v='
';if(w==="homelab"){const g=document.getElementById("setup-tld")?.value?.trim()||".home",b=document.getElementById("setup-ca-name")?.value?.trim()||"",s=document.getElementById("setup-dns-ip")?.value?.trim()||"",p=document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT;v+=`

Home Lab Configuration

-
TLD: ${y}
-
Certificate Authority: ${h}
-
DNS Server: ${s}:${c}
-
Example URLs: https://uptime${y}, https://nextcloud${y}
+
TLD: ${g}
+
Certificate Authority: ${b}
+
DNS Server: ${s}:${p}
+
Example URLs: https://uptime${g}, https://nextcloud${g}
- `}else if(x==="simple"){const y=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost";v+=` + `}else if(w==="simple"){const g=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost";v+=`

Simple Setup

Access Method: IP:Port only
-
Default IP: ${y}
+
Default IP: ${g}
SSL: None (HTTP only)
-
Example URLs: http://${y}:8080, http://${y}:3000
+
Example URLs: http://${g}:8080, http://${g}:3000
- `}else if(x==="public"){const y=document.getElementById("setup-public-domain")?.value?.trim()||"",h=document.getElementById("setup-public-email")?.value?.trim()||"",s=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",c=s==="subdirectory"?`https://${y}/sonarr, https://${y}/grafana`:`https://sonarr.${y}, https://grafana.${y}`;v+=` + `}else if(w==="public"){const g=document.getElementById("setup-public-domain")?.value?.trim()||"",b=document.getElementById("setup-public-email")?.value?.trim()||"",s=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",p=s==="subdirectory"?`https://${g}/sonarr, https://${g}/grafana`:`https://sonarr.${g}, https://grafana.${g}`;v+=`

Public Server

-
Domain: ${y}
+
Domain: ${g}
SSL: Let's Encrypt
-
Email: ${h}
+
Email: ${b}
Routing: ${s==="subdirectory"?"Subdirectory (domain.com/app)":"Subdomain (app.domain.com)"}
-
Example URLs: ${c}
+
Example URLs: ${p}
- `}const b=document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";v+=` + `}const x=document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";v+=`
-
Timezone: ${b.replace(/_/g," ")}
+
Timezone: ${x.replace(/_/g," ")}
- `,v+="
",p.innerHTML=v,M("setup-step-summary")}async function z(p){try{const v=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)});return v.ok?(await v.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${v.status}`),{function:"saveConfigToServer"}),!1)}catch(v){return errorHandler.logError("[SetupWizard] Save Config",v,{function:"saveConfigToServer"}),!1}}async function N(){const p={setupComplete:!0,configurationType:x,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};if(x==="homelab"){p.tld=document.getElementById("setup-tld")?.value?.trim()||".home",p.caName=document.getElementById("setup-ca-name")?.value?.trim()||"";const h=document.getElementById("setup-dns-provider")?.value||"technitium";p.dns={provider:h,ip:document.getElementById("setup-dns-ip")?.value?.trim()||"",port:document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT,token:document.getElementById("setup-dns-token")?.value?.trim()||""},p.defaults={dnsType:"private",sslType:"internal",targetIP:"localhost"}}else x==="simple"?(p.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",p.defaults={dnsType:"none",sslType:"none",targetIP:p.defaultIP}):x==="public"&&(p.domain=document.getElementById("setup-public-domain")?.value?.trim()||"",p.email=document.getElementById("setup-public-email")?.value?.trim()||"",p.routingMode=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",p.defaults={dnsType:p.routingMode==="subdirectory"?"none":"public",sslType:"letsencrypt",targetIP:"localhost"});const v=await z(p);safeSet("dashcaddy-config",JSON.stringify(p)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const b=x==="homelab"?"Professional Home Lab":x==="simple"?"Simple Setup":"Public Server",y=v?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${b}. Settings saved to: ${y}`,"success",5e3),setTimeout(()=>location.reload(),500)}const f=document.getElementById("setup-step-1-next");f&&(f.onclick=function(p){p.preventDefault();const v=document.querySelector('input[name="config-type"]:checked');v&&(x=v.value),M(x==="homelab"?"setup-step-homelab":x==="simple"?"setup-step-simple":x==="public"?"setup-step-public":"setup-step-homelab")});const L=document.getElementById("setup-skip");L&&(L.onclick=async function(p){p.preventDefault(),confirm("Skip setup? You can run it later from Settings.")&&(await z({setupComplete:!0,skipped:!0,timestamp:new Date().toISOString()}),safeSet("dashcaddy-setup","skipped"),document.getElementById("setup-wizard").style.display="none")});const w=document.getElementById("setup-tld");w&&(w.oninput=function(p){const v=p.target.value||".home",b=document.getElementById("tld-preview"),y=document.getElementById("tld-preview-2");b&&(b.textContent=v),y&&(y.textContent=v)});const $=document.getElementById("setup-homelab-back");$&&($.onclick=function(p){p.preventDefault(),M("setup-step-1")});const k=document.getElementById("setup-homelab-next");k&&(k.onclick=function(p){p.preventDefault();const v=document.getElementById("setup-tld")?.value?.trim()||"",b=document.getElementById("setup-ca-name")?.value?.trim()||"",y=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!v||!v.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!b){showNotification("Please enter a Certificate Authority name","warning");return}if(!y){showNotification("Please enter your DNS server IP address","warning");return}P()});const T=document.getElementById("setup-simple-back");T&&(T.onclick=function(p){p.preventDefault(),M("setup-step-1")});const E=document.getElementById("setup-simple-next");E&&(E.onclick=function(p){p.preventDefault(),P()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(p){p.onchange=function(){var v=document.getElementById("dns-requirement-note");v&&(v.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const I=document.getElementById("setup-public-back");I&&(I.onclick=function(p){p.preventDefault(),M("setup-step-1")});const j=document.getElementById("setup-public-next");j&&(j.onclick=function(p){p.preventDefault();const v=document.getElementById("setup-public-domain")?.value?.trim()||"",b=document.getElementById("setup-public-email")?.value?.trim()||"";if(!v){showNotification("Please enter your domain name","warning");return}if(!b||!b.includes("@")){showNotification("Please enter a valid email address","warning");return}P()});const H=document.getElementById("setup-summary-back");H&&(H.onclick=function(p){p.preventDefault(),x==="homelab"?M("setup-step-homelab"):x==="simple"?M("setup-step-simple"):x==="public"&&M("setup-step-public")});const R=document.getElementById("setup-summary-next");R&&(R.onclick=function(p){p.preventDefault(),M("setup-step-disk-safety")});const D=document.getElementById("setup-disk-safety-back");D&&(D.onclick=function(p){p.preventDefault(),M("setup-step-summary")});const O=document.getElementById("setup-disk-safety-finish");O&&(O.onclick=function(p){p.preventDefault(),N()}),window.getGlobalConfig=async function(){try{const v=await fetch("/api/v1/config");if(v.ok){const b=await v.json();if(b&&b.setupComplete)return b}}catch{console.warn("Could not fetch config from server")}const p=safeGet("dashcaddy-config");return p?JSON.parse(p):{setupComplete:!1,configurationType:"homelab",tld:".home",caName:"",defaults:{dnsType:"private",sslType:"internal",targetIP:"localhost"}}},window.resetSetupWizard=async function(){if(confirm("Reset DashCaddy configuration? This will show the setup wizard again.")){try{await secureFetch("/api/v1/config",{method:"DELETE"})}catch{console.warn("Could not delete server config")}safeRemove("dashcaddy-setup"),safeRemove("dashcaddy-config"),location.reload()}}})(),(function(){const x=new ErrorHandler;injectModal("app-selector-modal",`
+ `,v+="
",u.innerHTML=v,z("setup-step-summary")}async function M(u){try{const v=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return v.ok?(await v.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${v.status}`),{function:"saveConfigToServer"}),!1)}catch(v){return errorHandler.logError("[SetupWizard] Save Config",v,{function:"saveConfigToServer"}),!1}}async function D(){const u={setupComplete:!0,configurationType:w,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};if(w==="homelab"){u.tld=document.getElementById("setup-tld")?.value?.trim()||".home",u.caName=document.getElementById("setup-ca-name")?.value?.trim()||"";const b=document.getElementById("setup-dns-provider")?.value||"technitium";u.dns={provider:b,ip:document.getElementById("setup-dns-ip")?.value?.trim()||"",port:document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT,token:document.getElementById("setup-dns-token")?.value?.trim()||""},u.defaults={dnsType:"private",sslType:"internal",targetIP:"localhost"}}else w==="simple"?(u.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",u.defaults={dnsType:"none",sslType:"none",targetIP:u.defaultIP}):w==="public"&&(u.domain=document.getElementById("setup-public-domain")?.value?.trim()||"",u.email=document.getElementById("setup-public-email")?.value?.trim()||"",u.routingMode=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",u.defaults={dnsType:u.routingMode==="subdirectory"?"none":"public",sslType:"letsencrypt",targetIP:"localhost"});const v=await M(u);safeSet("dashcaddy-config",JSON.stringify(u)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const x=w==="homelab"?"Professional Home Lab":w==="simple"?"Simple Setup":"Public Server",g=v?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${x}. Settings saved to: ${g}`,"success",5e3),setTimeout(()=>location.reload(),500)}const h=document.getElementById("setup-step-1-next");h&&(h.onclick=function(u){u.preventDefault();const v=document.querySelector('input[name="config-type"]:checked');v&&(w=v.value),z(w==="homelab"?"setup-step-homelab":w==="simple"?"setup-step-simple":w==="public"?"setup-step-public":"setup-step-homelab")});const T=document.getElementById("setup-skip");T&&(T.onclick=async function(u){u.preventDefault(),confirm("Skip setup? You can run it later from Settings.")&&(await M({setupComplete:!0,skipped:!0,timestamp:new Date().toISOString()}),safeSet("dashcaddy-setup","skipped"),document.getElementById("setup-wizard").style.display="none")});const f=document.getElementById("setup-tld");f&&(f.oninput=function(u){const v=u.target.value||".home",x=document.getElementById("tld-preview"),g=document.getElementById("tld-preview-2");x&&(x.textContent=v),g&&(g.textContent=v)});const H=document.getElementById("setup-homelab-back");H&&(H.onclick=function(u){u.preventDefault(),z("setup-step-1")});const k=document.getElementById("setup-homelab-next");k&&(k.onclick=function(u){u.preventDefault();const v=document.getElementById("setup-tld")?.value?.trim()||"",x=document.getElementById("setup-ca-name")?.value?.trim()||"",g=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!v||!v.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!x){showNotification("Please enter a Certificate Authority name","warning");return}if(!g){showNotification("Please enter your DNS server IP address","warning");return}P()});const $=document.getElementById("setup-simple-back");$&&($.onclick=function(u){u.preventDefault(),z("setup-step-1")});const E=document.getElementById("setup-simple-next");E&&(E.onclick=function(u){u.preventDefault(),P()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(u){u.onchange=function(){var v=document.getElementById("dns-requirement-note");v&&(v.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const I=document.getElementById("setup-public-back");I&&(I.onclick=function(u){u.preventDefault(),z("setup-step-1")});const O=document.getElementById("setup-public-next");O&&(O.onclick=function(u){u.preventDefault();const v=document.getElementById("setup-public-domain")?.value?.trim()||"",x=document.getElementById("setup-public-email")?.value?.trim()||"";if(!v){showNotification("Please enter your domain name","warning");return}if(!x||!x.includes("@")){showNotification("Please enter a valid email address","warning");return}P()});const C=document.getElementById("setup-summary-back");C&&(C.onclick=function(u){u.preventDefault(),w==="homelab"?z("setup-step-homelab"):w==="simple"?z("setup-step-simple"):w==="public"&&z("setup-step-public")});const j=document.getElementById("setup-summary-next");j&&(j.onclick=function(u){u.preventDefault(),z("setup-step-disk-safety")});const N=document.getElementById("setup-disk-safety-back");N&&(N.onclick=function(u){u.preventDefault(),z("setup-step-summary")});const R=document.getElementById("setup-disk-safety-finish");R&&(R.onclick=function(u){u.preventDefault(),D()}),window.getGlobalConfig=async function(){try{const v=await fetch("/api/v1/config");if(v.ok){const x=await v.json();if(x&&x.setupComplete)return x}}catch{console.warn("Could not fetch config from server")}const u=safeGet("dashcaddy-config");return u?JSON.parse(u):{setupComplete:!1,configurationType:"homelab",tld:".home",caName:"",defaults:{dnsType:"private",sslType:"internal",targetIP:"localhost"}}},window.resetSetupWizard=async function(){if(confirm("Reset DashCaddy configuration? This will show the setup wizard again.")){try{await secureFetch("/api/v1/config",{method:"DELETE"})}catch{console.warn("Could not delete server config")}safeRemove("dashcaddy-setup"),safeRemove("dashcaddy-config"),location.reload()}}})(),(function(){const w=new ErrorHandler;injectModal("app-selector-modal",`

Choose an App

@@ -333,12 +333,12 @@ This will reset the logo, favicon, title, and position.`))try{if((await secureFe
-
`);const B="custom-apps";let A=null,C=null;const M=document.getElementById("app-selector-modal"),P=document.getElementById("app-selector-grid");async function z(){try{const c=await(await fetch("/api/v1/apps/templates")).json();if(c.success)return A=c.templates,C=c.categories,!0}catch(s){x.logError("[AppSelector] Fetch Templates",s,{function:"fetchApiTemplates"})}return!1}async function N(s){try{return await(await fetch(`/api/v1/apps/ports/${s}/check`)).json()}catch(c){return x.logError("[AppSelector] Check Port",c,{function:"checkPortAvailability"}),{available:!0}}}async function f(s){try{const l=await(await fetch(`/api/v1/apps/ports/${s}/suggest`)).json();if(l.success)return l.suggestedPort}catch(c){x.logError("[AppSelector] Get Suggested Port",c,{function:"getSuggestedPort"})}return s}async function L(){if(P.innerHTML='
Loading app templates...
',!A&&!await z()){P.innerHTML='
Failed to load app templates. Please try again.
';return}P.innerHTML="";const s={};for(const[l,m]of Object.entries(A)){const u=m.category||"Other";s[u]||(s[u]=[]),s[u].push({id:l,...m})}const c=C?Object.keys(C):Object.keys(s).sort();for(const l of c){const m=s[l];if(!m||m.length===0)continue;m.sort((e,a)=>(a.popularity||0)-(e.popularity||0));const u=document.createElement("div");u.className="app-category-header";const t=C?.[l]||{};u.innerHTML=`${escapeHtml(t.icon||"")} ${escapeHtml(l)}`,t.color&&(u.style.borderBottomColor=t.color),P.appendChild(u),m.forEach(e=>{const a=document.createElement("div");a.className="app-option";const o=e.isDashboardWidget,r=o&&safeGet("widget-"+e.id+"-enabled")!=="false",n=o?`
${r?"ON":"OFF"}
`:"",i=!o&&e.difficulty?`
${escapeHtml(e.difficulty)}
`:"";a.innerHTML=` + `);const B="custom-apps";let A=null,S=null;const z=document.getElementById("app-selector-modal"),P=document.getElementById("app-selector-grid");async function M(){try{const p=await(await fetch("/api/v1/apps/templates")).json();if(p.success)return A=p.templates,S=p.categories,!0}catch(s){w.logError("[AppSelector] Fetch Templates",s,{function:"fetchApiTemplates"})}return!1}async function D(s){try{return await(await fetch(`/api/v1/apps/ports/${s}/check`)).json()}catch(p){return w.logError("[AppSelector] Check Port",p,{function:"checkPortAvailability"}),{available:!0}}}async function h(s){try{const l=await(await fetch(`/api/v1/apps/ports/${s}/suggest`)).json();if(l.success)return l.suggestedPort}catch(p){w.logError("[AppSelector] Get Suggested Port",p,{function:"getSuggestedPort"})}return s}async function T(){if(P.innerHTML='
Loading app templates...
',!A&&!await M()){P.innerHTML='
Failed to load app templates. Please try again.
';return}P.innerHTML="";const s={};for(const[l,m]of Object.entries(A)){const c=m.category||"Other";s[c]||(s[c]=[]),s[c].push({id:l,...m})}const p=S?Object.keys(S):Object.keys(s).sort();for(const l of p){const m=s[l];if(!m||m.length===0)continue;m.sort((e,a)=>(a.popularity||0)-(e.popularity||0));const c=document.createElement("div");c.className="app-category-header";const t=S?.[l]||{};c.innerHTML=`${escapeHtml(t.icon||"")} ${escapeHtml(l)}`,t.color&&(c.style.borderBottomColor=t.color),P.appendChild(c),m.forEach(e=>{const a=document.createElement("div");a.className="app-option";const o=e.isDashboardWidget,i=o&&safeGet("widget-"+e.id+"-enabled")!=="false",n=o?`
${i?"ON":"OFF"}
`:"",r=!o&&e.difficulty?`
${escapeHtml(e.difficulty)}
`:"";a.innerHTML=`
${escapeHtml(e.icon||"\u{1F4E6}")}
${escapeHtml(e.name)}
${escapeHtml(e.description||"")}
- ${n}${i} - `,o?a.onclick=()=>w(e,a):a.onclick=()=>$(e),P.appendChild(a)})}window.renderRecipeCards&&await window.renderRecipeCards(P)}function w(s,c){const l="widget-"+s.id+"-enabled",u=!(safeGet(l)!=="false");safeSet(l,String(u));const t=s.widgetSelector;if(t){const a=document.querySelector(t);a&&(a.style.display=u?"":"none")}const e=c.querySelector('div[style*="border-radius: 4px"]');e&&(e.textContent=u?"ON":"OFF",e.style.background=u?"#2ecc7130":"#e74c3c30",e.style.color=u?"#2ecc71":"#e74c3c"),showNotification(`${s.name} widget ${u?"enabled":"disabled"}`,"success",2e3)}async function $(s){const c=document.getElementById("app-deploy-modal"),l=document.getElementById("app-deploy-title"),m=document.getElementById("deploy-subdomain"),u=document.getElementById("deploy-url-preview"),t=document.getElementById("deploy-ip"),e=document.getElementById("deploy-port"),a=document.getElementById("deploy-tailscale-only"),o=document.getElementById("tailscale-status");try{const G=await(await secureFetch("/api/v1/apps/check-existing",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:s.id})})).json();if(G.success&&G.exists){const V=G.container;confirm(`Found existing ${s.name} container: + ${n}${r} + `,o?a.onclick=()=>f(e,a):a.onclick=()=>H(e),P.appendChild(a)})}window.renderRecipeCards&&await window.renderRecipeCards(P)}function f(s,p){const l="widget-"+s.id+"-enabled",c=!(safeGet(l)!=="false");safeSet(l,String(c));const t=s.widgetSelector;if(t){const a=document.querySelector(t);a&&(a.style.display=c?"":"none")}const e=p.querySelector('div[style*="border-radius: 4px"]');e&&(e.textContent=c?"ON":"OFF",e.style.background=c?"#2ecc7130":"#e74c3c30",e.style.color=c?"#2ecc71":"#e74c3c"),showNotification(`${s.name} widget ${c?"enabled":"disabled"}`,"success",2e3)}async function H(s){const p=document.getElementById("app-deploy-modal"),l=document.getElementById("app-deploy-title"),m=document.getElementById("deploy-subdomain"),c=document.getElementById("deploy-url-preview"),t=document.getElementById("deploy-ip"),e=document.getElementById("deploy-port"),a=document.getElementById("deploy-tailscale-only"),o=document.getElementById("tailscale-status");try{const G=await(await secureFetch("/api/v1/apps/check-existing",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:s.id})})).json();if(G.success&&G.exists){const V=G.container;confirm(`Found existing ${s.name} container: Container: ${V.name} Status: ${V.status} @@ -347,38 +347,38 @@ Port: ${V.primaryPort||"N/A"} Would you like to use this existing container? Click OK to configure DNS/Caddy for the existing container. -Click Cancel to deploy a new container.`)&&(s._useExisting=!0,s._existingContainer=V)}}catch{}l.textContent=`Deploy ${s.name}`;const r=s.subdomain||s.id.replace(/-/g,"");m.value=r;const n=document.getElementById("subpath-compat-warning");if(n)if(SITE.routingMode==="subdirectory"){const W=s.subpathSupport||"strip";W==="none"?(n.style.display="block",n.innerHTML=''+s.name+" does not support subdirectory mode. It may not work correctly at a subpath."):W==="strip"?(n.style.display="block",n.innerHTML='ⓘ '+s.name+" has unverified subdirectory support. It may require additional configuration."):n.style.display="none"}else n.style.display="none";const i=SITE.defaults.dnsType||(SITE.configurationType==="public"?"public":"private"),d=SITE.defaults.sslType||(SITE.configurationType==="public"?"letsencrypt":"internal"),g=document.querySelector(`input[name="dns-type"][value="${i}"]`),S=document.querySelector(`input[name="ssl-type"][value="${d}"]`);g?g.checked=!0:document.querySelector('input[name="dns-type"][value="private"]').checked=!0,S?S.checked=!0:document.querySelector('input[name="ssl-type"][value="internal"]').checked=!0,t.value=SITE.defaults.targetIP||"localhost",a.checked=!1;const U=document.querySelector("#app-deploy-modal .flex-col-gap")?.closest("div"),q=document.querySelector("#app-deploy-modal details"),F=q?.querySelector("div");if(q&&F&&(SITE.configurationType==="public"||SITE.configurationType==="homelab")){const W=document.querySelectorAll('#app-deploy-modal input[name="dns-type"]')[0]?.closest("div.flex-col-gap")?.parentElement,G=document.querySelectorAll('#app-deploy-modal input[name="ssl-type"]')[0]?.closest("div.flex-col-gap")?.parentElement;W&&!W.dataset.moved&&(F.appendChild(W),W.dataset.moved="1"),G&&!G.dataset.moved&&(F.appendChild(G),G.dataset.moved="1")}const _=document.getElementById("media-path-section"),J=document.getElementById("deploy-media-path"),X=document.getElementById("media-path-description");if(s.mediaMount){_.style.display="block",J.value="",J.placeholder="/media/Movies, /media/TVShows or click Browse";const W=document.getElementById("detected-mounts-container"),G=document.getElementById("detected-mounts-list");try{const K=await(await fetch("/api/v1/media/detected-mounts")).json();if(K.success&&K.mounts.length>0){W.style.display="block",G.innerHTML="";const te=[...new Set(K.mounts.map(ee=>ee.hostPath))];J.value=te.join(", "),K.mounts.forEach(ee=>{const Z=document.createElement("button");Z.type="button";const de=te.includes(ee.hostPath);Z.style.cssText=`padding: 8px 14px; font-size: 0.85rem; background: color-mix(in srgb, var(--success) ${de?"40%":"15%"}, var(--card-bg)); border: 1px solid var(--success); border-radius: 6px; cursor: pointer; color: var(--fg);`,Z.innerHTML=`${escapeHtml(ee.folderName)}
from ${escapeHtml(ee.sourceImage)}`,Z.title=`${ee.hostPath} (from ${ee.sourceContainer})`,Z.onclick=()=>{const le=J.value.split(",").map(ce=>ce.trim()).filter(ce=>ce),pe=le.indexOf(ee.hostPath);pe>=0?(le.splice(pe,1),Z.style.background="color-mix(in srgb, var(--success) 15%, var(--card-bg))"):(le.push(ee.hostPath),Z.style.background="color-mix(in srgb, var(--success) 40%, var(--card-bg))"),J.value=le.join(", ")},G.appendChild(Z)})}else W.style.display="none"}catch{W.style.display="none"}document.getElementById("browse-media-btn").onclick=()=>{openFolderBrowser(J)}}else _.style.display="none",J.value="",document.getElementById("detected-mounts-container").style.display="none";const Q=document.getElementById("plex-claim-section");Q&&(s.id==="plex"||s.claimToken?(Q.style.display="block",document.getElementById("deploy-plex-claim").value=""):Q.style.display="none");const ne=document.getElementById("volume-mounts-section"),oe=document.getElementById("volume-mounts-list");if(oe.innerHTML="",s.docker?.volumes?.length){const W=s.mediaMount?.containerPath,G=s.docker.volumes.filter(V=>!V.includes("{{MEDIA_PATH}}")&&!(W&&V.endsWith(":"+W)));G.length>0?(ne.style.display="block",G.forEach((V,K)=>{const[te,ee]=V.split(":"),Z=document.createElement("div");Z.style.cssText="display: flex; gap: 6px; align-items: center;",Z.innerHTML=` +Click Cancel to deploy a new container.`)&&(s._useExisting=!0,s._existingContainer=V)}}catch{}l.textContent=`Deploy ${s.name}`;const i=s.subdomain||s.id.replace(/-/g,"");m.value=i;const n=document.getElementById("subpath-compat-warning");if(n)if(SITE.routingMode==="subdirectory"){const W=s.subpathSupport||"strip";W==="none"?(n.style.display="block",n.innerHTML=''+s.name+" does not support subdirectory mode. It may not work correctly at a subpath."):W==="strip"?(n.style.display="block",n.innerHTML='ⓘ '+s.name+" has unverified subdirectory support. It may require additional configuration."):n.style.display="none"}else n.style.display="none";const r=SITE.defaults.dnsType||(SITE.configurationType==="public"?"public":"private"),d=SITE.defaults.sslType||(SITE.configurationType==="public"?"letsencrypt":"internal"),y=document.querySelector(`input[name="dns-type"][value="${r}"]`),L=document.querySelector(`input[name="ssl-type"][value="${d}"]`);y?y.checked=!0:document.querySelector('input[name="dns-type"][value="private"]').checked=!0,L?L.checked=!0:document.querySelector('input[name="ssl-type"][value="internal"]').checked=!0,t.value=SITE.defaults.targetIP||"localhost",a.checked=!1;const U=document.querySelector("#app-deploy-modal .flex-col-gap")?.closest("div"),q=document.querySelector("#app-deploy-modal details"),F=q?.querySelector("div");if(q&&F&&(SITE.configurationType==="public"||SITE.configurationType==="homelab")){const W=document.querySelectorAll('#app-deploy-modal input[name="dns-type"]')[0]?.closest("div.flex-col-gap")?.parentElement,G=document.querySelectorAll('#app-deploy-modal input[name="ssl-type"]')[0]?.closest("div.flex-col-gap")?.parentElement;W&&!W.dataset.moved&&(F.appendChild(W),W.dataset.moved="1"),G&&!G.dataset.moved&&(F.appendChild(G),G.dataset.moved="1")}const _=document.getElementById("media-path-section"),J=document.getElementById("deploy-media-path"),X=document.getElementById("media-path-description");if(s.mediaMount){_.style.display="block",J.value="",J.placeholder="/media/Movies, /media/TVShows or click Browse";const W=document.getElementById("detected-mounts-container"),G=document.getElementById("detected-mounts-list");try{const K=await(await fetch("/api/v1/media/detected-mounts")).json();if(K.success&&K.mounts.length>0){W.style.display="block",G.innerHTML="";const te=[...new Set(K.mounts.map(ee=>ee.hostPath))];J.value=te.join(", "),K.mounts.forEach(ee=>{const Z=document.createElement("button");Z.type="button";const de=te.includes(ee.hostPath);Z.style.cssText=`padding: 8px 14px; font-size: 0.85rem; background: color-mix(in srgb, var(--success) ${de?"40%":"15%"}, var(--card-bg)); border: 1px solid var(--success); border-radius: 6px; cursor: pointer; color: var(--fg);`,Z.innerHTML=`${escapeHtml(ee.folderName)}
from ${escapeHtml(ee.sourceImage)}`,Z.title=`${ee.hostPath} (from ${ee.sourceContainer})`,Z.onclick=()=>{const le=J.value.split(",").map(ce=>ce.trim()).filter(ce=>ce),pe=le.indexOf(ee.hostPath);pe>=0?(le.splice(pe,1),Z.style.background="color-mix(in srgb, var(--success) 15%, var(--card-bg))"):(le.push(ee.hostPath),Z.style.background="color-mix(in srgb, var(--success) 40%, var(--card-bg))"),J.value=le.join(", ")},G.appendChild(Z)})}else W.style.display="none"}catch{W.style.display="none"}document.getElementById("browse-media-btn").onclick=()=>{openFolderBrowser(J)}}else _.style.display="none",J.value="",document.getElementById("detected-mounts-container").style.display="none";const Q=document.getElementById("plex-claim-section");Q&&(s.id==="plex"||s.claimToken?(Q.style.display="block",document.getElementById("deploy-plex-claim").value=""):Q.style.display="none");const ne=document.getElementById("volume-mounts-section"),oe=document.getElementById("volume-mounts-list");if(oe.innerHTML="",s.docker?.volumes?.length){const W=s.mediaMount?.containerPath,G=s.docker.volumes.filter(V=>!V.includes("{{MEDIA_PATH}}")&&!(W&&V.endsWith(":"+W)));G.length>0?(ne.style.display="block",G.forEach((V,K)=>{const[te,ee]=V.split(":"),Z=document.createElement("div");Z.style.cssText="display: flex; gap: 6px; align-items: center;",Z.innerHTML=` \u2192 ${ee} - `,oe.appendChild(Z),Z.querySelector(".vol-browse-btn").onclick=()=>{const de=Z.querySelector(".vol-host-path");openFolderBrowser(de)}})):ne.style.display="none"}else ne.style.display="none";const se=s.defaultPort||8080;e.value="",e.placeholder=`Default: ${se}`;let Y=document.getElementById("deploy-port-status");Y||(Y=document.createElement("div"),Y.id="deploy-port-status",Y.style.cssText="font-size: 0.8rem; margin-top: 4px;",e.parentNode.appendChild(Y));async function ie(){const W=e.value||se;Y.innerHTML='Checking port...';const G=await N(W);if(G.available)Y.innerHTML=`Port ${escapeHtml(String(W))} is available`;else{const V=await f(se);Y.innerHTML=` + `,oe.appendChild(Z),Z.querySelector(".vol-browse-btn").onclick=()=>{const de=Z.querySelector(".vol-host-path");openFolderBrowser(de)}})):ne.style.display="none"}else ne.style.display="none";const se=s.defaultPort||8080;e.value="",e.placeholder=`Default: ${se}`;let Y=document.getElementById("deploy-port-status");Y||(Y=document.createElement("div"),Y.id="deploy-port-status",Y.style.cssText="font-size: 0.8rem; margin-top: 4px;",e.parentNode.appendChild(Y));async function ie(){const W=e.value||se;Y.innerHTML='Checking port...';const G=await D(W);if(G.available)Y.innerHTML=`Port ${escapeHtml(String(W))} is available`;else{const V=await h(se);Y.innerHTML=` Port ${escapeHtml(W)} in use by ${escapeHtml(G.conflict?.usedBy||"unknown")} `;const K=document.createElement("button");K.type="button",K.textContent=`Use ${V}`,K.style.cssText="margin-left: 8px; padding: 2px 8px; font-size: 0.75rem; cursor: pointer;",K.onclick=()=>{document.getElementById("deploy-port").value=V,Y.innerHTML=`Using suggested port ${escapeHtml(String(V))}`},Y.appendChild(K)}}let re;e.oninput=function(){clearTimeout(re),re=setTimeout(ie,500)},ie();try{const G=await(await fetch("/api/v1/tailscale/status")).json();G.success&&G.installed&&G.connected?o.innerHTML=` Connected ${G.self?.hostname} (${G.self?.ip}) | ${G.deviceCount} devices - `:G.installed?o.innerHTML='Not connected':(o.innerHTML='Not available',a.disabled=!0)}catch{o.innerHTML='Could not check status'}function ae(){const W=m.value||"subdomain",G=document.querySelector('input[name="dns-type"]:checked').value,V=document.querySelector('input[name="ssl-type"]:checked').value;let K="";if(SITE.routingMode==="subdirectory"&&SITE.domain)K=`https://${SITE.domain}/${W}`;else if(G==="private")K=`${V==="none"?"http":"https"}://${buildDomain(W)}`;else if(G==="public"){const te=V==="none"?"http":"https",ee=SITE.domain||W;K=SITE.domain?`${te}://${W}.${SITE.domain}`:`${te}://${W}`}else{const te=e.value||s.defaultPort||DC.DEFAULTS.SERVICE_PORT;K=`http://${t.value}:${te}`}u.textContent=K}m.oninput=ae,t.oninput=ae,e.oninput=ae,document.querySelectorAll('input[name="dns-type"]').forEach(W=>{W.onchange=ae}),document.querySelectorAll('input[name="ssl-type"]').forEach(W=>{W.onchange=ae}),ae(),M.classList.remove("show"),c.classList.add("show"),c.dataset.appTemplate=JSON.stringify(s)}async function k(s){const c=s.appTemplate,l=safeGetJSON(B,[]),m=c._useExisting&&c._existingContainer,u=l.find(t=>t.id===s.subdomain);if(!(u&&!m&&!confirm(`An app with subdomain "${s.subdomain}" already exists. Redeploy?`))){if(u){const t=l.indexOf(u);l.splice(t,1),safeSet(B,JSON.stringify(l))}if(m)s.port=c._existingContainer.primaryPort;else{const t=s.port||c.defaultPort||8080;showNotification(`Checking port ${t} availability...`,"info",0);const e=await N(t);if(!e.available){const a=await f(c.defaultPort||8080);if(confirm(`Port ${t} is already in use by ${e.conflict?.usedBy||"another container"}. + `:G.installed?o.innerHTML='Not connected':(o.innerHTML='Not available',a.disabled=!0)}catch{o.innerHTML='Could not check status'}function ae(){const W=m.value||"subdomain",G=document.querySelector('input[name="dns-type"]:checked').value,V=document.querySelector('input[name="ssl-type"]:checked').value;let K="";if(SITE.routingMode==="subdirectory"&&SITE.domain)K=`https://${SITE.domain}/${W}`;else if(G==="private")K=`${V==="none"?"http":"https"}://${buildDomain(W)}`;else if(G==="public"){const te=V==="none"?"http":"https",ee=SITE.domain||W;K=SITE.domain?`${te}://${W}.${SITE.domain}`:`${te}://${W}`}else{const te=e.value||s.defaultPort||DC.DEFAULTS.SERVICE_PORT;K=`http://${t.value}:${te}`}c.textContent=K}m.oninput=ae,t.oninput=ae,e.oninput=ae,document.querySelectorAll('input[name="dns-type"]').forEach(W=>{W.onchange=ae}),document.querySelectorAll('input[name="ssl-type"]').forEach(W=>{W.onchange=ae}),ae(),z.classList.remove("show"),p.classList.add("show"),p.dataset.appTemplate=JSON.stringify(s)}async function k(s){const p=s.appTemplate,l=safeGetJSON(B,[]),m=p._useExisting&&p._existingContainer,c=l.find(t=>t.id===s.subdomain);if(!(c&&!m&&!confirm(`An app with subdomain "${s.subdomain}" already exists. Redeploy?`))){if(c){const t=l.indexOf(c);l.splice(t,1),safeSet(B,JSON.stringify(l))}if(m)s.port=p._existingContainer.primaryPort;else{const t=s.port||p.defaultPort||8080;showNotification(`Checking port ${t} availability...`,"info",0);const e=await D(t);if(!e.available){const a=await h(p.defaultPort||8080);if(confirm(`Port ${t} is already in use by ${e.conflict?.usedBy||"another container"}. -Would you like to use port ${a} instead?`))s.port=a;else{showNotification("Deployment cancelled - port conflict","error",5e3);return}}}showNotification(m?`Configuring ${c.name} with existing container...`:`Deploying ${c.name}...`,"info",0);try{const t={appId:c.id,config:{subdomain:s.subdomain,ip:s.ip,createDns:s.dnsType==="private",port:s.port||c.defaultPort||null,sslType:s.sslType,dnsType:s.dnsType,tailscaleOnly:s.tailscaleOnly||!1,mediaPath:s.mediaPath||null,plexClaimToken:s.plexClaimToken||null,customVolumes:s.customVolumes||null}};m&&(t.config.useExisting=!0,t.config.existingContainerId=c._existingContainer.id,t.config.existingPort=c._existingContainer.primaryPort,!s.port&&c._existingContainer.primaryPort&&(t.config.port=c._existingContainer.primaryPort));const a=await(await secureFetch("/api/v1/apps/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(a.success){const o={id:s.subdomain,name:c.name,logo:`/assets/${c.id}.png`,containerId:a.containerId,url:a.url,ip:s.ip,appTemplate:c.id,tailscaleOnly:s.tailscaleOnly||!1};l.push(o),safeSet(B,JSON.stringify(l)),window.APPS&&!window.APPS.some(n=>n.id===c.id)&&(window.APPS.push(o),typeof window.buildGrid=="function"&&window.buildGrid(),typeof window.refreshAll=="function"&&setTimeout(()=>window.refreshAll(),500));let r=a.usedExisting?`${c.name} configured with existing container! -URL: ${a.url}`:`${c.name} deployed successfully! -URL: ${a.url}`;a.warning&&(r+=` +Would you like to use port ${a} instead?`))s.port=a;else{showNotification("Deployment cancelled - port conflict","error",5e3);return}}}showNotification(m?`Configuring ${p.name} with existing container...`:`Deploying ${p.name}...`,"info",0);try{const t={appId:p.id,config:{subdomain:s.subdomain,ip:s.ip,createDns:s.dnsType==="private",port:s.port||p.defaultPort||null,sslType:s.sslType,dnsType:s.dnsType,tailscaleOnly:s.tailscaleOnly||!1,mediaPath:s.mediaPath||null,plexClaimToken:s.plexClaimToken||null,customVolumes:s.customVolumes||null}};m&&(t.config.useExisting=!0,t.config.existingContainerId=p._existingContainer.id,t.config.existingPort=p._existingContainer.primaryPort,!s.port&&p._existingContainer.primaryPort&&(t.config.port=p._existingContainer.primaryPort));const a=await(await secureFetch("/api/v1/apps/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(a.success){const o={id:s.subdomain,name:p.name,logo:`/assets/${p.id}.png`,containerId:a.containerId,url:a.url,ip:s.ip,appTemplate:p.id,tailscaleOnly:s.tailscaleOnly||!1};l.push(o),safeSet(B,JSON.stringify(l)),window.APPS&&!window.APPS.some(n=>n.id===p.id)&&(window.APPS.push(o),typeof window.buildGrid=="function"&&window.buildGrid(),typeof window.refreshAll=="function"&&setTimeout(()=>window.refreshAll(),500));let i=a.usedExisting?`${p.name} configured with existing container! +URL: ${a.url}`:`${p.name} deployed successfully! +URL: ${a.url}`;a.warning&&(i+=` -\u26A0 Warning: ${a.warning}`),showNotification(r,"success",8e3),delete c._useExisting,delete c._existingContainer,a.url&&a.url.startsWith("https://")&&T(a.url,c.name),a.setupInstructions&&a.setupInstructions.length>0&&setTimeout(()=>{const n=a.setupInstructions.join(` -`);showNotification(`Setup Instructions for ${c.name}: ${n}`,"info",1e4)},1e3)}else throw new Error(a.error||"Deployment failed")}catch(t){x.logError("[AppSelector] Deployment",t,{function:"deploy"}),showNotification(`Failed to deploy ${c.name}: ${t.message}`,"error",8e3)}}}async function T(s,c){showNotification(`\u23F3 Generating SSL certificate for ${c}...`,"warning",6e4);let l=0;const m=12,u=async()=>{l++;try{const t=await fetch(s,{method:"HEAD",mode:"no-cors"});return showNotification(`\u2705 ${c} is ready! SSL certificate generated.`,"success",5e3),!0}catch{return l{window.APPS.some(l=>l.id===c.id)||window.APPS.push(c)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{L(),M.classList.add("show")}),wireModal(M,document.getElementById("app-selector-cancel"));const I=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{I.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const s=JSON.parse(I.dataset.appTemplate),c=document.getElementById("deploy-media-path").value.trim(),l=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(u=>{l.push({hostPath:u.value.trim(),containerPath:u.dataset.containerPath})});const m={appTemplate:s,subdomain:document.getElementById("deploy-subdomain").value.trim(),dnsType:document.querySelector('input[name="dns-type"]:checked').value,sslType:document.querySelector('input[name="ssl-type"]:checked').value,ip:document.getElementById("deploy-ip").value.trim(),port:document.getElementById("deploy-port").value.trim(),tailscaleOnly:document.getElementById("deploy-tailscale-only").checked,mediaPath:c||null,plexClaimToken:document.getElementById("deploy-plex-claim")?.value.trim()||null,customVolumes:l.length>0?l:null,resources:{cpus:parseFloat(document.getElementById("deploy-cpu-limit").value)||0,memory:parseFloat(document.getElementById("deploy-memory-limit").value)||0}};if(!m.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(s.mediaMount?.required&&!c){showNotification("Please enter a media library path for this application","warning");return}I.classList.remove("show"),k(m)}),wireModal(I);const j=document.getElementById("folder-browser-modal"),H=document.getElementById("folder-browser-path"),R=document.getElementById("folder-browser-list"),D=document.getElementById("folder-browser-selected"),O=document.getElementById("folder-browser-selected-list");let p="",v=[],b=null;window.openFolderBrowser=function(s){b=s,v=s.value.split(",").map(c=>c.trim()).filter(c=>c),p="",h(),y(""),j.classList.add("show")};async function y(s){H.textContent=s||"Select a drive...",R.innerHTML='
Loading...
';try{const l=await(await fetch(`/api/v1/browse/directories?path=${encodeURIComponent(s)}`)).json();if(!l.success){R.innerHTML=`
Error: ${escapeHtml(l.error)}
`;return}p=l.path||"",H.textContent=p||"Select a drive...";let m="";l.parent&&l.parent!==l.path&&(m+=`
+\u26A0 Warning: ${a.warning}`),showNotification(i,"success",8e3),delete p._useExisting,delete p._existingContainer,a.url&&a.url.startsWith("https://")&&$(a.url,p.name),a.setupInstructions&&a.setupInstructions.length>0&&setTimeout(()=>{const n=a.setupInstructions.join(` +`);showNotification(`Setup Instructions for ${p.name}: ${n}`,"info",1e4)},1e3)}else throw new Error(a.error||"Deployment failed")}catch(t){w.logError("[AppSelector] Deployment",t,{function:"deploy"}),showNotification(`Failed to deploy ${p.name}: ${t.message}`,"error",8e3)}}}async function $(s,p){showNotification(`\u23F3 Generating SSL certificate for ${p}...`,"warning",6e4);let l=0;const m=12,c=async()=>{l++;try{const t=await fetch(s,{method:"HEAD",mode:"no-cors"});return showNotification(`\u2705 ${p} is ready! SSL certificate generated.`,"success",5e3),!0}catch{return l{window.APPS.some(l=>l.id===p.id)||window.APPS.push(p)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{T(),z.classList.add("show")}),wireModal(z,document.getElementById("app-selector-cancel"));const I=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{I.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const s=JSON.parse(I.dataset.appTemplate),p=document.getElementById("deploy-media-path").value.trim(),l=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(c=>{l.push({hostPath:c.value.trim(),containerPath:c.dataset.containerPath})});const m={appTemplate:s,subdomain:document.getElementById("deploy-subdomain").value.trim(),dnsType:document.querySelector('input[name="dns-type"]:checked').value,sslType:document.querySelector('input[name="ssl-type"]:checked').value,ip:document.getElementById("deploy-ip").value.trim(),port:document.getElementById("deploy-port").value.trim(),tailscaleOnly:document.getElementById("deploy-tailscale-only").checked,mediaPath:p||null,plexClaimToken:document.getElementById("deploy-plex-claim")?.value.trim()||null,customVolumes:l.length>0?l:null,resources:{cpus:parseFloat(document.getElementById("deploy-cpu-limit").value)||0,memory:parseFloat(document.getElementById("deploy-memory-limit").value)||0}};if(!m.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(s.mediaMount?.required&&!p){showNotification("Please enter a media library path for this application","warning");return}I.classList.remove("show"),k(m)}),wireModal(I);const O=document.getElementById("folder-browser-modal"),C=document.getElementById("folder-browser-path"),j=document.getElementById("folder-browser-list"),N=document.getElementById("folder-browser-selected"),R=document.getElementById("folder-browser-selected-list");let u="",v=[],x=null;window.openFolderBrowser=function(s){x=s,v=s.value.split(",").map(p=>p.trim()).filter(p=>p),u="",b(),g(""),O.classList.add("show")};async function g(s){C.textContent=s||"Select a drive...",j.innerHTML='
Loading...
';try{const l=await(await fetch(`/api/v1/browse/directories?path=${encodeURIComponent(s)}`)).json();if(!l.success){j.innerHTML=`
Error: ${escapeHtml(l.error)}
`;return}u=l.path||"",C.textContent=u||"Select a drive...";let m="";l.parent&&l.parent!==l.path&&(m+=`
\u2B06\uFE0F .. Parent Directory -
`),l.items.length===0&&!l.parent?m+='
No browseable drives configured. Check your docker-compose.yml volume mounts.
':l.items.length===0?m+='
No subfolders found
':l.items.forEach(u=>{const t=u.type==="drive"?"\u{1F4BE}":"\u{1F4C1}",e=v.includes(u.path),a=e?"background: color-mix(in srgb, var(--success) 20%, transparent);":"";m+=`
+
`),l.items.length===0&&!l.parent?m+='
No browseable drives configured. Check your docker-compose.yml volume mounts.
':l.items.length===0?m+='
No subfolders found
':l.items.forEach(c=>{const t=c.type==="drive"?"\u{1F4BE}":"\u{1F4C1}",e=v.includes(c.path),a=e?"background: color-mix(in srgb, var(--success) 20%, transparent);":"";m+=`
${t} - ${escapeHtml(u.name)} + ${escapeHtml(c.name)} ${e?'\u2713':""} -
`}),R.innerHTML=m,R.querySelectorAll(".folder-item").forEach(u=>{u.addEventListener("click",()=>{y(u.dataset.path)}),u.addEventListener("mouseenter",()=>{u.style.background="var(--card-bg)"}),u.addEventListener("mouseleave",()=>{const t=v.includes(u.dataset.path);u.style.background=t?"color-mix(in srgb, var(--success) 20%, transparent)":""})})}catch(c){R.innerHTML=`
Failed to load: ${escapeHtml(c.message)}
`}}function h(){if(v.length===0){D.style.display="none";return}D.style.display="block",O.innerHTML=v.map(s=>` +
`}),j.innerHTML=m,j.querySelectorAll(".folder-item").forEach(c=>{c.addEventListener("click",()=>{g(c.dataset.path)}),c.addEventListener("mouseenter",()=>{c.style.background="var(--card-bg)"}),c.addEventListener("mouseleave",()=>{const t=v.includes(c.dataset.path);c.style.background=t?"color-mix(in srgb, var(--success) 20%, transparent)":""})})}catch(p){j.innerHTML=`
Failed to load: ${escapeHtml(p.message)}
`}}function b(){if(v.length===0){N.style.display="none";return}N.style.display="block",R.innerHTML=v.map(s=>` ${escapeHtml(s)} - `).join("")}window.removeSelectedFolder=function(s){v=v.filter(c=>c!==s),h(),y(p)},document.getElementById("folder-browser-select-current").addEventListener("click",()=>{p&&!v.includes(p)&&(v.push(p),h(),y(p))}),wireModal(j,document.getElementById("folder-browser-cancel")),document.getElementById("folder-browser-done").addEventListener("click",()=>{b&&(b.value=v.join(", ")),j.classList.remove("show")}),E()})(),(function(){injectModal("recipe-deploy-modal",`
+ `).join("")}window.removeSelectedFolder=function(s){v=v.filter(p=>p!==s),b(),g(u)},document.getElementById("folder-browser-select-current").addEventListener("click",()=>{u&&!v.includes(u)&&(v.push(u),b(),g(u))}),wireModal(O,document.getElementById("folder-browser-cancel")),document.getElementById("folder-browser-done").addEventListener("click",()=>{x&&(x.value=v.join(", ")),O.classList.remove("show")}),E()})(),(function(){injectModal("recipe-deploy-modal",`

Deploy Recipe

@@ -445,31 +445,31 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
-
`);let x=null,B=null,A=null,C=1,M=!1;const P=document.getElementById("recipe-deploy-modal"),z=document.getElementById("recipe-cancel"),N=document.getElementById("recipe-prev"),f=document.getElementById("recipe-next");wireModal(P,z);async function L(){try{const p=await fetch("/api/v1/recipes/templates"),v=await p.json();if(v.success)return x=v.templates,B=v.categories,!0;if(p.status===403)return M=!1,!1}catch(p){console.warn("Failed to fetch recipe templates:",p.message)}return!1}async function w(){try{M=(await(await fetch("/api/v1/license/feature/recipes")).json()).available}catch{M=!1}return M}window.renderRecipeCards=async function(p){await w();let v;if(M&&x?v=x:v=$(),!v||v.length===0)return;const b=document.createElement("div");b.className="app-category-header",b.innerHTML="\u{1F9EA} Recipes",b.style.borderBottomColor="#8e44ad",p.appendChild(b);const y=Array.isArray(v)?v:Object.values(v);y.sort((h,s)=>(s.popularity||0)-(h.popularity||0));for(const h of y){const s=document.createElement("div");s.className="app-option",s.style.position="relative";const c=`
${h.componentCount||h.components?.length||"?"} apps
`,l=M?"":'
PREMIUM
';s.innerHTML=` + `);let w=null,B=null,A=null,S=1,z=!1;const P=document.getElementById("recipe-deploy-modal"),M=document.getElementById("recipe-cancel"),D=document.getElementById("recipe-prev"),h=document.getElementById("recipe-next");wireModal(P,M);async function T(){try{const u=await fetch("/api/v1/recipes/templates"),v=await u.json();if(v.success)return w=v.templates,B=v.categories,!0;if(u.status===403)return z=!1,!1}catch(u){console.warn("Failed to fetch recipe templates:",u.message)}return!1}async function f(){try{z=(await(await fetch("/api/v1/license/feature/recipes")).json()).available}catch{z=!1}return z}window.renderRecipeCards=async function(u){await f();let v;if(z&&w?v=w:v=H(),!v||v.length===0)return;const x=document.createElement("div");x.className="app-category-header",x.innerHTML="\u{1F9EA} Recipes",x.style.borderBottomColor="#8e44ad",u.appendChild(x);const g=Array.isArray(v)?v:Object.values(v);g.sort((b,s)=>(s.popularity||0)-(b.popularity||0));for(const b of g){const s=document.createElement("div");s.className="app-option",s.style.position="relative";const p=`
${b.componentCount||b.components?.length||"?"} apps
`,l=z?"":'
PREMIUM
';s.innerHTML=` ${l} -
${escapeHtml(h.icon||"\u{1F9EA}")}
-
${escapeHtml(h.name)}
-
${escapeHtml(h.description||"")}
- ${c} - `,s.onclick=()=>{if(!M){showNotification("Recipes require a DashCaddy Premium license. Click the License button to activate.","warning",5e3),window.openLicenseModal&&window.openLicenseModal();return}k(h)},p.appendChild(s)}};function $(){return[{id:"htpc-suite",name:"HTPC Suite",icon:"\u{1F3AC}",description:"Complete media automation: find, download, organize, and stream",componentCount:6,popularity:98},{id:"nextcloud-complete",name:"Nextcloud Complete",icon:"\u2601\uFE0F",description:"Full productivity suite: cloud storage, office editing, and collaboration",componentCount:4,popularity:90},{id:"smart-home",name:"Smart Home Hub",icon:"\u{1F3E0}",description:"Home automation: control, automate, and monitor IoT devices",componentCount:4,popularity:88},{id:"dev-environment",name:"Dev Environment",icon:"\u{1F4BB}",description:"Self-hosted development workflow: Git, CI/CD, IDE, and database",componentCount:4,popularity:82}]}function k(p){A=p,C=1;const v=document.getElementById("app-selector-modal");v&&v.classList.remove("show"),document.getElementById("recipe-deploy-title").textContent=`Deploy ${p.name}`,T(),E(),P.classList.add("show")}function T(){document.querySelectorAll("#recipe-steps .recipe-step").forEach(p=>{const v=parseInt(p.dataset.step);p.classList.toggle("active",v===C),p.classList.toggle("completed",v1&&C<4?"":"none",C===4?(f.style.display="none",z.textContent="Close"):C===3?(f.textContent="\u{1F680} Deploy",f.style.display="",z.textContent="Cancel"):(f.textContent="Next",f.style.display="",z.textContent="Cancel")}function E(){const p=document.getElementById("recipe-component-list");p.innerHTML="";const v=A.components||[];for(const b of v){const y=document.createElement("div");y.style.cssText="display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: 8px; background: var(--card-bg); border: 1px solid var(--border);";const h=b.required,s=b.internal;y.innerHTML=` - ${escapeHtml(b.icon||"\u{1F9EA}")} +
${escapeHtml(b.name)}
+
${escapeHtml(b.description||"")}
+ ${p} + `,s.onclick=()=>{if(!z){showNotification("Recipes require a DashCaddy Premium license. Click the License button to activate.","warning",5e3),window.openLicenseModal&&window.openLicenseModal();return}k(b)},u.appendChild(s)}};function H(){return[{id:"htpc-suite",name:"HTPC Suite",icon:"\u{1F3AC}",description:"Complete media automation: find, download, organize, and stream",componentCount:6,popularity:98},{id:"nextcloud-complete",name:"Nextcloud Complete",icon:"\u2601\uFE0F",description:"Full productivity suite: cloud storage, office editing, and collaboration",componentCount:4,popularity:90},{id:"smart-home",name:"Smart Home Hub",icon:"\u{1F3E0}",description:"Home automation: control, automate, and monitor IoT devices",componentCount:4,popularity:88},{id:"dev-environment",name:"Dev Environment",icon:"\u{1F4BB}",description:"Self-hosted development workflow: Git, CI/CD, IDE, and database",componentCount:4,popularity:82}]}function k(u){A=u,S=1;const v=document.getElementById("app-selector-modal");v&&v.classList.remove("show"),document.getElementById("recipe-deploy-title").textContent=`Deploy ${u.name}`,$(),E(),P.classList.add("show")}function $(){document.querySelectorAll("#recipe-steps .recipe-step").forEach(u=>{const v=parseInt(u.dataset.step);u.classList.toggle("active",v===S),u.classList.toggle("completed",v1&&S<4?"":"none",S===4?(h.style.display="none",M.textContent="Close"):S===3?(h.textContent="\u{1F680} Deploy",h.style.display="",M.textContent="Cancel"):(h.textContent="Next",h.style.display="",M.textContent="Cancel")}function E(){const u=document.getElementById("recipe-component-list");u.innerHTML="";const v=A.components||[];for(const x of v){const g=document.createElement("div");g.style.cssText="display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: 8px; background: var(--card-bg); border: 1px solid var(--border);";const b=x.required,s=x.internal;g.innerHTML=` +
-
${escapeHtml(b.role||b.id)}
+
${escapeHtml(x.role||x.id)}
- ${b.templateRef?escapeHtml(b.templateRef):"Built-in"} - ${h?'Required':'Optional'} + ${x.templateRef?escapeHtml(x.templateRef):"Built-in"} + ${b?'Required':'Optional'} ${s?'(Internal)':""}
- ${b.note?`
\u26A0 ${escapeHtml(b.note)}
`:""} + ${x.note?`
\u26A0 ${escapeHtml(x.note)}
`:""}
- `,p.appendChild(y)}}function I(){const p=document.getElementById("recipe-volumes-section"),v=document.getElementById("recipe-volume-list"),b=A.sharedVolumes;if(b&&Object.keys(b).length>0){p.style.display="",v.innerHTML="";for(const[y,h]of Object.entries(b)){const s=document.createElement("div");s.style.cssText="display: grid; gap: 4px;",s.innerHTML=` - - 0){u.style.display="",v.innerHTML="";for(const[g,b]of Object.entries(x)){const s=document.createElement("div");s.style.cssText="display: grid; gap: 4px;",s.innerHTML=` + + -
${escapeHtml(h.description||"")}
- `,v.appendChild(s)}}else p.style.display="none"}function j(){const p=document.getElementById("recipe-review-content"),v=H(),b=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),y={};b.forEach(l=>{y[l.dataset.volumeKey]=l.value});const h=document.getElementById("recipe-timezone").value||"UTC",s=document.getElementById("recipe-ip").value||"host.docker.internal",c=document.getElementById("recipe-tailscale").checked;p.innerHTML=` +
${escapeHtml(b.description||"")}
+ `,v.appendChild(s)}}else u.style.display="none"}function O(){const u=document.getElementById("recipe-review-content"),v=C(),x=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),g={};x.forEach(l=>{g[l.dataset.volumeKey]=l.value});const b=document.getElementById("recipe-timezone").value||"UTC",s=document.getElementById("recipe-ip").value||"host.docker.internal",p=document.getElementById("recipe-tailscale").checked;u.innerHTML=`
${escapeHtml(A.name)}
${escapeHtml(A.description||"")}
@@ -482,21 +482,21 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}}; - ${Object.keys(y).length>0?`
+ ${Object.keys(g).length>0?`
Volumes: - ${Object.entries(y).map(([l,m])=>`
${l}: ${escapeHtml(m)}
`).join("")} + ${Object.entries(g).map(([l,m])=>`
${l}: ${escapeHtml(m)}
`).join("")}
`:""}
- Timezone: ${escapeHtml(h)} • IP: ${escapeHtml(s)} ${c?"• Tailscale only":""} + Timezone: ${escapeHtml(b)} • IP: ${escapeHtml(s)} ${p?"• Tailscale only":""}
${A.network?`
Docker network: ${escapeHtml(A.network.name)}
`:""} - `}function H(){const p=document.querySelectorAll("#recipe-component-list input[data-component-id]"),v=new Set;p.forEach(y=>{y.checked&&v.add(y.dataset.componentId)});const b=A.components||[];return b.filter(y=>y.required).forEach(y=>v.add(y.id)),b.filter(y=>v.has(y.id))}async function R(){const p=document.getElementById("recipe-progress-list"),v=document.getElementById("recipe-deploy-result");v.style.display="none",p.innerHTML="";const b=H();for(const c of b){const l=document.createElement("div");l.id=`recipe-progress-${c.id}`,l.style.cssText="display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border); font-size: 0.85rem;",l.innerHTML=` + `}function C(){const u=document.querySelectorAll("#recipe-component-list input[data-component-id]"),v=new Set;u.forEach(g=>{g.checked&&v.add(g.dataset.componentId)});const x=A.components||[];return x.filter(g=>g.required).forEach(g=>v.add(g.id)),x.filter(g=>v.has(g.id))}async function j(){const u=document.getElementById("recipe-progress-list"),v=document.getElementById("recipe-deploy-result");v.style.display="none",u.innerHTML="";const x=C();for(const p of x){const l=document.createElement("div");l.id=`recipe-progress-${p.id}`,l.style.cssText="display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border); font-size: 0.85rem;",l.innerHTML=` \u23F3 - ${escapeHtml(c.role||c.id)} + ${escapeHtml(p.role||p.id)} Queued - `,p.appendChild(l)}const y=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),h={};y.forEach(c=>{h[c.dataset.volumeKey]=c.value});const s={selectedComponents:b.map(c=>c.id),sharedConfig:{ip:document.getElementById("recipe-ip").value||"host.docker.internal",timezone:document.getElementById("recipe-timezone").value||"UTC",tailscaleOnly:document.getElementById("recipe-tailscale").checked,volumes:h},componentOverrides:{}};for(const c of b)D(c.id,"deploying","Deploying...");try{const l=await(await secureFetch("/api/v1/recipes/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recipeId:A.id,config:s})})).json();if(l.success){for(const m of l.deployed||[])D(m.id,"success",m.url?`Running \u2192 ${m.url}`:"Running");for(const m of l.errors||[])D(m.componentId,"error",m.error);v.style.display="",v.innerHTML=` + `,u.appendChild(l)}const g=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),b={};g.forEach(p=>{b[p.dataset.volumeKey]=p.value});const s={selectedComponents:x.map(p=>p.id),sharedConfig:{ip:document.getElementById("recipe-ip").value||"host.docker.internal",timezone:document.getElementById("recipe-timezone").value||"UTC",tailscaleOnly:document.getElementById("recipe-tailscale").checked,volumes:b},componentOverrides:{}};for(const p of x)N(p.id,"deploying","Deploying...");try{const l=await(await secureFetch("/api/v1/recipes/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recipeId:A.id,config:s})})).json();if(l.success){for(const m of l.deployed||[])N(m.id,"success",m.url?`Running \u2192 ${m.url}`:"Running");for(const m of l.errors||[])N(m.componentId,"error",m.error);v.style.display="",v.innerHTML=`
${escapeHtml(l.message||"Deployed!")}
${l.setupInstructions?`
@@ -506,9 +506,9 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
`,showNotification(`${A.name} recipe deployed successfully!`,"success",5e3),window.loadServices&&window.loadServices()}else v.style.display="",v.innerHTML=`
Deployment failed: ${escapeHtml(l.error||"Unknown error")} -
`,showNotification(`Recipe deployment failed: ${l.error}`,"error",5e3)}catch(c){v.style.display="",v.innerHTML=`
- Network error: ${escapeHtml(c.message)} -
`}}function D(p,v,b){const y=document.getElementById(`recipe-progress-${p}`);if(!y)return;const h=y.querySelector(".recipe-progress-icon"),s=y.querySelector(".recipe-progress-status");v==="deploying"?(h.textContent="\u23F3",s.style.color="var(--accent)"):v==="success"?(h.textContent="\u2705",s.style.color="var(--ok-fg)"):v==="error"&&(h.textContent="\u274C",s.style.color="var(--bad-fg)"),s.textContent=b}f.addEventListener("click",()=>{if(C===3){C=4,T(),R();return}C<3&&(C++,T(),C===2&&I(),C===3&&j())}),N.addEventListener("click",()=>{C>1&&C<4&&(C--,T())}),window.groupRecipeCards=function(){const p=document.querySelectorAll(".service-card[data-recipe-id]");if(p.length===0)return;const v={};p.forEach(b=>{const y=b.dataset.recipeId;v[y]||(v[y]=[]),v[y].push(b)});for(const[b,y]of Object.entries(v))y.length<2||y.forEach((h,s)=>{if(h.style.borderLeft="3px solid rgba(142,68,173,0.5)",s===0){let c=h.querySelector(".recipe-group-label");c||(c=document.createElement("div"),c.className="recipe-group-label",c.style.cssText="position: absolute; top: -8px; left: 12px; font-size: 0.6rem; padding: 1px 8px; border-radius: 8px; background: rgba(142,68,173,0.3); color: #d4a5ff; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;",c.textContent=b.replace(/-/g," "),h.style.position="relative",h.appendChild(c))}})},window.manageRecipe=async function(p,v){const b=`/api/v1/recipes/${p}/${v}`,y=v==="remove"?"DELETE":"POST",h=v==="remove"?`/api/v1/recipes/${p}`:b;if(!(v==="remove"&&!confirm(`Remove the entire ${p} recipe? This will delete all containers and configuration.`)))try{const c=await(await secureFetch(h,{method:y})).json();c.success?(showNotification(`Recipe ${v}: ${c.results?.filter(l=>l.status!=="failed").length||0} components processed`,"success",4e3),window.loadServices&&window.loadServices()):showNotification(`Recipe ${v} failed: ${c.error}`,"error",5e3)}catch(s){showNotification(`Network error: ${s.message}`,"error",5e3)}};const O=document.createElement("style");O.textContent=` +
`,showNotification(`Recipe deployment failed: ${l.error}`,"error",5e3)}catch(p){v.style.display="",v.innerHTML=`
+ Network error: ${escapeHtml(p.message)} +
`}}function N(u,v,x){const g=document.getElementById(`recipe-progress-${u}`);if(!g)return;const b=g.querySelector(".recipe-progress-icon"),s=g.querySelector(".recipe-progress-status");v==="deploying"?(b.textContent="\u23F3",s.style.color="var(--accent)"):v==="success"?(b.textContent="\u2705",s.style.color="var(--ok-fg)"):v==="error"&&(b.textContent="\u274C",s.style.color="var(--bad-fg)"),s.textContent=x}h.addEventListener("click",()=>{if(S===3){S=4,$(),j();return}S<3&&(S++,$(),S===2&&I(),S===3&&O())}),D.addEventListener("click",()=>{S>1&&S<4&&(S--,$())}),window.groupRecipeCards=function(){const u=document.querySelectorAll(".service-card[data-recipe-id]");if(u.length===0)return;const v={};u.forEach(x=>{const g=x.dataset.recipeId;v[g]||(v[g]=[]),v[g].push(x)});for(const[x,g]of Object.entries(v))g.length<2||g.forEach((b,s)=>{if(b.style.borderLeft="3px solid rgba(142,68,173,0.5)",s===0){let p=b.querySelector(".recipe-group-label");p||(p=document.createElement("div"),p.className="recipe-group-label",p.style.cssText="position: absolute; top: -8px; left: 12px; font-size: 0.6rem; padding: 1px 8px; border-radius: 8px; background: rgba(142,68,173,0.3); color: #d4a5ff; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;",p.textContent=x.replace(/-/g," "),b.style.position="relative",b.appendChild(p))}})},window.manageRecipe=async function(u,v){const x=`/api/v1/recipes/${u}/${v}`,g=v==="remove"?"DELETE":"POST",b=v==="remove"?`/api/v1/recipes/${u}`:x;if(!(v==="remove"&&!confirm(`Remove the entire ${u} recipe? This will delete all containers and configuration.`)))try{const p=await(await secureFetch(b,{method:g})).json();p.success?(showNotification(`Recipe ${v}: ${p.results?.filter(l=>l.status!=="failed").length||0} components processed`,"success",4e3),window.loadServices&&window.loadServices()):showNotification(`Recipe ${v} failed: ${p.error}`,"error",5e3)}catch(s){showNotification(`Network error: ${s.message}`,"error",5e3)}};const R=document.createElement("style");R.textContent=` .recipe-step { flex: 1; text-align: center; @@ -550,7 +550,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}}; .recipe-step-panel { min-height: 180px; } - `,document.head.appendChild(O),w()})(),(function(){document.getElementById("reload-caddy-top")?.addEventListener("click",async()=>{const x=document.getElementById("reload-caddy-top"),B=x.textContent;try{x.textContent="\u23F3 Reloading...",x.disabled=!0;const A=await secureFetch("/api/v1/caddy/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),C=await A.json();if(A.ok&&C.success)x.textContent="\u2705 Reloaded!",setTimeout(()=>{x.textContent=B,x.disabled=!1},2e3);else throw new Error(C.error||"Reload failed")}catch(A){x.textContent="\u274C Failed",showNotification(`Failed to reload Caddy: ${A.message}`,"error"),setTimeout(()=>{x.textContent=B,x.disabled=!1},2e3)}})})(),(function(){injectModal("error-log-modal",`
+ `,document.head.appendChild(R),f()})(),(function(){document.getElementById("reload-caddy-top")?.addEventListener("click",async()=>{const w=document.getElementById("reload-caddy-top"),B=w.textContent;try{w.textContent="\u23F3 Reloading...",w.disabled=!0;const A=await secureFetch("/api/v1/caddy/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),S=await A.json();if(A.ok&&S.success)w.textContent="\u2705 Reloaded!",setTimeout(()=>{w.textContent=B,w.disabled=!1},2e3);else throw new Error(S.error||"Reload failed")}catch(A){w.textContent="\u274C Failed",showNotification(`Failed to reload Caddy: ${A.message}`,"error"),setTimeout(()=>{w.textContent=B,w.disabled=!1},2e3)}})})(),(function(){injectModal("error-log-modal",`

\u{1F4CB} Error Logs

-
`);const x=document.getElementById("error-log-modal"),B=document.getElementById("view-error-logs"),A=document.getElementById("error-log-refresh"),C=document.getElementById("error-log-clear"),M=document.getElementById("error-log-close"),P=document.getElementById("error-log-level"),z=document.getElementById("error-log-context"),N=document.getElementById("error-log-search"),f=document.getElementById("error-log-since"),L=document.getElementById("error-log-until"),w=document.getElementById("error-log-container"),$=document.getElementById("error-log-load-more"),k=document.getElementById("error-log-total"),T=50;let E=0,I=null,j=0,H=[];function R(h){if(!h)return null;const s=new Date(h);return isNaN(s.getTime())?null:s.toISOString()}async function D(){try{const h=await fetch("/api/v1/error-logs/contexts");if(!h.ok)return;const s=await h.json();if(!s.success||!Array.isArray(s.contexts))return;H=s.contexts;const c=z.value;z.innerHTML='';for(const l of s.contexts){const m=document.createElement("option");m.value=l.name,m.textContent=`${l.name} (${l.count})`,z.appendChild(m)}c&&s.contexts.some(l=>l.name===c)&&(z.value=c)}catch{}}function O(){const h=new URLSearchParams;h.set("limit",String(T)),h.set("offset",String(E)),P.value&&h.set("level",P.value),z.value&&h.set("context",z.value);const s=R(f.value),c=R(L.value);s&&h.set("since",s),c&&h.set("until",c);const l=(N.value||"").trim();return l&&h.set("search",l),h}async function p(h){try{h?(I&&I.abort(),I=new AbortController):(I&&I.abort(),I=new AbortController,E=0,j++,w.innerHTML='
Loading...
');const s=j,c=O(),l=await fetch("/api/v1/error-logs?"+c.toString(),{signal:I.signal});if(!l.ok){w.innerHTML=`
Failed: HTTP ${l.status}
`,$.style.display="none",k.textContent="";return}const m=await l.json();if(!m.success){w.innerHTML=`
Failed: ${escapeHtml(m.error||"unknown")}
`,$.style.display="none",k.textContent="";return}if(!h&&s!==j)return;const u=Array.isArray(m.logs)?m.logs:[];if(u.length===0&&!h){const e=m.filters&&(m.filters.level||m.filters.context||m.filters.search||m.filters.since||m.filters.until)?"No error log entries match your filters.":"\u2705 No errors logged! Everything is working smoothly.";w.innerHTML=`
\u{1F4CB}${escapeHtml(e)}
`,$.style.display="none",k.textContent=m.total?`${m.total} total`:"";return}let t="";h||(t='',t+='',t+='',t+='',t+='',t+='',t+='',t+="");for(const e of u){const a=(e.level||"?").toUpperCase(),o=a==="ERR"?"var(--bad-fg)":a==="WARN"?"var(--warn-fg, #f0c674)":"var(--muted)",r=e.timestamp?new Date(e.timestamp).toLocaleString():"\u2014",n=e.context||"\u2014",i=(e.error||"").split(` -`)[0],d=e.request&&e.request.ip||"";t+='',t+=``,t+=``,t+=``,t+=``,t+=``,t+="",e.detail&&(t+=``)}if(!h)t+="
WhenLevelContextMessageIP
${escapeHtml(r)}${escapeHtml(a)}${escapeHtml(n)}${escapeHtml(i)}${escapeHtml(d)}
",w.innerHTML=t;else{const e=w.querySelector("table");e&&e.insertAdjacentHTML("beforeend",t)}E+=u.length,$.style.display=m.hasMore?"":"none",k.textContent=`${m.total} total${m.hasMore?" (showing "+E+")":""}`,w.querySelectorAll(".error-log-row").forEach(e=>{e.dataset.wired||(e.dataset.wired="true",e.addEventListener("click",()=>{const a=e.nextElementSibling;a&&a.classList.contains("error-log-detail")&&(a.style.display=a.style.display==="none"?"":"none")}))})}catch(s){if(s&&s.name==="AbortError")return;w.innerHTML=`
Failed: ${escapeHtml(s.message)}
`,k.textContent=""}}async function v(){if(confirm("Clear the entire error log? This cannot be undone."))try{const s=await(await secureFetch("/api/v1/error-logs",{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:"CLEAR"})})).json();s.success?(await D(),p(!1),showNotification("\u2705 Error logs cleared","success",3e3)):showNotification("\u274C "+(s.error||"Clear failed"),"error",4e3)}catch(h){showNotification("\u274C "+h.message,"error",4e3)}}let b;function y(){P?.addEventListener("change",()=>p(!1)),z?.addEventListener("change",()=>p(!1)),N?.addEventListener("input",()=>{clearTimeout(b),b=setTimeout(()=>p(!1),250)});let h;[f,L].forEach(s=>{s?.addEventListener("change",()=>{clearTimeout(h),h=setTimeout(()=>p(!1),250)})}),A?.addEventListener("click",()=>p(!1)),$?.addEventListener("click",()=>p(!0)),C?.addEventListener("click",v),wireModal(x,M)}B?.addEventListener("click",async()=>{x?.classList.add("show"),await D(),p(!1)}),y()})(),(function(){injectModal("container-logs-modal",`
+
`);const w=document.getElementById("error-log-modal"),B=document.getElementById("view-error-logs"),A=document.getElementById("error-log-refresh"),S=document.getElementById("error-log-clear"),z=document.getElementById("error-log-close"),P=document.getElementById("error-log-level"),M=document.getElementById("error-log-context"),D=document.getElementById("error-log-search"),h=document.getElementById("error-log-since"),T=document.getElementById("error-log-until"),f=document.getElementById("error-log-container"),H=document.getElementById("error-log-load-more"),k=document.getElementById("error-log-total"),$=50;let E=0,I=null,O=0,C=[];function j(b){if(!b)return null;const s=new Date(b);return isNaN(s.getTime())?null:s.toISOString()}async function N(){try{const b=await fetch("/api/v1/error-logs/contexts");if(!b.ok)return;const s=await b.json();if(!s.success||!Array.isArray(s.contexts))return;C=s.contexts;const p=M.value;M.innerHTML='';for(const l of s.contexts){const m=document.createElement("option");m.value=l.name,m.textContent=`${l.name} (${l.count})`,M.appendChild(m)}p&&s.contexts.some(l=>l.name===p)&&(M.value=p)}catch{}}function R(){const b=new URLSearchParams;b.set("limit",String($)),b.set("offset",String(E)),P.value&&b.set("level",P.value),M.value&&b.set("context",M.value);const s=j(h.value),p=j(T.value);s&&b.set("since",s),p&&b.set("until",p);const l=(D.value||"").trim();return l&&b.set("search",l),b}async function u(b){try{b?(I&&I.abort(),I=new AbortController):(I&&I.abort(),I=new AbortController,E=0,O++,f.innerHTML='
Loading...
');const s=O,p=R(),l=await fetch("/api/v1/error-logs?"+p.toString(),{signal:I.signal});if(!l.ok){f.innerHTML=`
Failed: HTTP ${l.status}
`,H.style.display="none",k.textContent="";return}const m=await l.json();if(!m.success){f.innerHTML=`
Failed: ${escapeHtml(m.error||"unknown")}
`,H.style.display="none",k.textContent="";return}if(!b&&s!==O)return;const c=Array.isArray(m.logs)?m.logs:[];if(c.length===0&&!b){const e=m.filters&&(m.filters.level||m.filters.context||m.filters.search||m.filters.since||m.filters.until)?"No error log entries match your filters.":"\u2705 No errors logged! Everything is working smoothly.";f.innerHTML=`
\u{1F4CB}${escapeHtml(e)}
`,H.style.display="none",k.textContent=m.total?`${m.total} total`:"";return}let t="";b||(t='',t+='',t+='',t+='',t+='',t+='',t+='',t+="");for(const e of c){const a=(e.level||"?").toUpperCase(),o=a==="ERR"?"var(--bad-fg)":a==="WARN"?"var(--warn-fg, #f0c674)":"var(--muted)",i=e.timestamp?new Date(e.timestamp).toLocaleString():"\u2014",n=e.context||"\u2014",r=(e.error||"").split(` +`)[0],d=e.request&&e.request.ip||"";t+='',t+=``,t+=``,t+=``,t+=``,t+=``,t+="",e.detail&&(t+=``)}if(!b)t+="
WhenLevelContextMessageIP
${escapeHtml(i)}${escapeHtml(a)}${escapeHtml(n)}${escapeHtml(r)}${escapeHtml(d)}
",f.innerHTML=t;else{const e=f.querySelector("table");e&&e.insertAdjacentHTML("beforeend",t)}E+=c.length,H.style.display=m.hasMore?"":"none",k.textContent=`${m.total} total${m.hasMore?" (showing "+E+")":""}`,f.querySelectorAll(".error-log-row").forEach(e=>{e.dataset.wired||(e.dataset.wired="true",e.addEventListener("click",()=>{const a=e.nextElementSibling;a&&a.classList.contains("error-log-detail")&&(a.style.display=a.style.display==="none"?"":"none")}))})}catch(s){if(s&&s.name==="AbortError")return;f.innerHTML=`
Failed: ${escapeHtml(s.message)}
`,k.textContent=""}}async function v(){if(confirm("Clear the entire error log? This cannot be undone."))try{const s=await(await secureFetch("/api/v1/error-logs",{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:"CLEAR"})})).json();s.success?(await N(),u(!1),showNotification("\u2705 Error logs cleared","success",3e3)):showNotification("\u274C "+(s.error||"Clear failed"),"error",4e3)}catch(b){showNotification("\u274C "+b.message,"error",4e3)}}let x;function g(){P?.addEventListener("change",()=>u(!1)),M?.addEventListener("change",()=>u(!1)),D?.addEventListener("input",()=>{clearTimeout(x),x=setTimeout(()=>u(!1),250)});let b;[h,T].forEach(s=>{s?.addEventListener("change",()=>{clearTimeout(b),b=setTimeout(()=>u(!1),250)})}),A?.addEventListener("click",()=>u(!1)),H?.addEventListener("click",()=>u(!0)),S?.addEventListener("click",v),wireModal(w,z)}B?.addEventListener("click",async()=>{w?.classList.add("show"),await N(),u(!1)}),g()})(),(function(){injectModal("container-logs-modal",`
@@ -648,14 +648,57 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
-
`);const x=document.getElementById("container-logs-modal"),B=document.getElementById("cl-container-select"),A=document.getElementById("cl-log-content"),C=document.getElementById("cl-log-search"),M=document.getElementById("cl-log-tail"),P=document.getElementById("cl-refresh"),z=document.getElementById("cl-stream"),N=document.getElementById("cl-download"),f=document.getElementById("cl-clear-search"),L=document.getElementById("cl-close"),w=document.getElementById("cl-close-btn"),$=document.getElementById("cl-stream-status"),k=document.getElementById("cl-stream-indicator"),T=document.getElementById("cl-stream-text"),E=document.getElementById("cl-line-count"),I=document.getElementById("cl-filter-count"),j=document.getElementById("cl-image"),H=document.getElementById("cl-status"),R=document.getElementById("cl-created");let D=null,O=[],p=[],v=null,b=!1,y=null;function h(i){if(!i)return"-";const d=new Date(i);return isNaN(d.getTime())?i:d.toLocaleString()}function s(i){if(!i)return"";const d=document.createElement("div");return d.textContent=i,d.innerHTML}function c(i,d){const g=i.stream==="stderr"?"log-stderr":"log-stdout",S=i.stream==="stderr"?"\u26A0\uFE0F":"\u{1F4E4}";return` -
+
`);const w=document.getElementById("container-logs-modal"),B=document.getElementById("cl-container-select"),A=document.getElementById("cl-log-content"),S=document.getElementById("cl-log-search"),z=document.getElementById("cl-log-tail"),P=document.getElementById("cl-refresh"),M=document.getElementById("cl-stream"),D=document.getElementById("cl-download"),h=document.getElementById("cl-clear-search"),T=document.getElementById("cl-close"),f=document.getElementById("cl-close-btn"),H=document.getElementById("cl-stream-status"),k=document.getElementById("cl-stream-indicator"),$=document.getElementById("cl-stream-text"),E=document.getElementById("cl-line-count"),I=document.getElementById("cl-filter-count"),O=document.getElementById("cl-image"),C=document.getElementById("cl-status"),j=document.getElementById("cl-created");let N=null,R=[],u=[],v=null,x=!1,g=null;function b(r){if(!r)return"-";const d=new Date(r);return isNaN(d.getTime())?r:d.toLocaleString()}function s(r){if(!r)return"";const d=document.createElement("div");return d.textContent=r,d.innerHTML}function p(r,d){const y=r.stream==="stderr"?"log-stderr":"log-stdout",L=r.stream==="stderr"?"\u26A0\uFE0F":"\u{1F4E4}";return` +
${d+1} - ${S} - ${s(i.text)} + ${L} + ${s(r.text)}
- `}function l(i,d=""){if(!i||i.length===0){A.innerHTML='
No logs available
',E.textContent="0 lines",I.textContent="0 filtered";return}if(O=i,p=d?i.filter(g=>g.text&&g.text.toLowerCase().includes(d.toLowerCase())):i,E.textContent=`${i.length} lines`,I.textContent=d?`${p.length} of ${i.length} shown`:`${i.length} shown`,p.length===0){A.innerHTML=`
No logs match "${s(d)}"
`;return}A.innerHTML=p.map((g,S)=>c(g,S)).join(""),A.scrollTop=A.scrollHeight}async function m(){try{const d=(await getJSON("/api/v1/logs/containers")).containers||[],g=B.value;B.innerHTML='',d.forEach(S=>{const U=document.createElement("option");U.value=S.id,U.textContent=`${S.name} (${S.image.split(":")[0]}) - ${S.status}`,U.dataset.name=S.name,U.dataset.image=S.image,U.dataset.status=S.status,U.dataset.created=S.created,B.appendChild(U)}),g&&B.querySelector(`option[value="${g}"]`)&&(B.value=g,u(g))}catch(i){console.error("Failed to load containers:",i)}}function u(i){const d=B.querySelector(`option[value="${i}"]`);d&&(j.textContent=d.dataset.image||"-",H.textContent=d.dataset.status||"-",H.style.color=d.dataset.status==="running"?"var(--ok-fg, #4ade80)":"var(--bad-fg, #ef4444)",R.textContent=h(d.dataset.created))}async function t(){const i=B.value;if(!i){A.innerHTML='
Select a container to view logs
';return}a(),D=i,u(i);const d=M.value,g=C.value.trim();A.innerHTML='
Loading logs...
';try{const S=`/api/v1/logs/container/${i}${d!=="all"?`?tail=${d}`:""}`,U=await getJSON(S);U.logs&&U.logs.length>0?l(U.logs,g):(A.innerHTML='
No logs found for this container
',E.textContent="0 lines",I.textContent="0 filtered")}catch(S){A.innerHTML=`
Error loading logs: ${s(S.message)}
`}}function e(){const i=B.value;if(!i)return;a(),b=!0,z.textContent="\u23F9 Stop",$.style.display="flex",k.textContent="\u{1F7E2}",T.textContent="Connecting...";const d=`/api/v1/logs/stream/${i}`;v=new EventSource(d),v.onopen=()=>{k.textContent="\u{1F7E2}",T.textContent="Connected - streaming logs"},v.onmessage=g=>{try{const S=JSON.parse(g.data);if(S.error){k.textContent="\u{1F534}",T.textContent=`Error: ${S.error}`;return}O.push(S),p.push(S),E.textContent=`${O.length} lines`,I.textContent=`${p.length} shown`;const U=C.value.trim();if(!U||S.text&&S.text.toLowerCase().includes(U.toLowerCase())){const q=document.createElement("div");q.innerHTML=c(S,p.length-1);const F=q.firstElementChild;F.style.background="#1a3a1a",A.appendChild(F),A.scrollTop=A.scrollHeight}}catch(S){console.error("Error parsing log:",S)}},v.onerror=()=>{k.textContent="\u{1F534}",T.textContent="Disconnected",b=!1,z.textContent="\u25B6 Stream"},x._eventSource=v}function a(){v&&(v.close(),v=null),x._eventSource&&(x._eventSource.close(),x._eventSource=null),b=!1,z.textContent="\u25B6 Stream",$.style.display="none"}function o(){if(!O||O.length===0){showNotification("No logs to download","error");return}const i=B.querySelector(`option[value="${D}"]`)?.dataset.name||D,d=new Date().toISOString().replace(/[:.]/g,"-"),g=`${i}-logs-${d}.txt`,S=O.map(_=>{const J=_.timestamp||"",X=_.stream==="stderr"?"[ERR]":"[OUT]";return`${J?J+" ":""}${X} ${_.text}`}).join(` -`),U=new Blob([S],{type:"text/plain"}),q=URL.createObjectURL(U),F=document.createElement("a");F.href=q,F.download=g,document.body.appendChild(F),F.click(),document.body.removeChild(F),URL.revokeObjectURL(q),showNotification(`Downloaded ${O.length} log lines`,"success")}B?.addEventListener("change",()=>{t()}),M?.addEventListener("change",()=>{t()}),P?.addEventListener("click",()=>{t()}),z?.addEventListener("click",()=>{b?a():e()}),N?.addEventListener("click",()=>{o()}),f?.addEventListener("click",()=>{C.value="",l(O,"")}),C?.addEventListener("input",()=>{clearTimeout(y),y=setTimeout(()=>{l(O,C.value.trim())},300)}),C?.addEventListener("keydown",i=>{i.key==="Escape"&&(C.value="",l(O,""))}),document.getElementById("view-container-logs")?.addEventListener("click",()=>{x.classList.add("show"),m()});function n(){a(),x.classList.remove("show")}L?.addEventListener("click",n),w?.addEventListener("click",n),document.addEventListener("keydown",i=>{i.key==="Escape"&&x.classList.contains("show")&&n()}),x.addEventListener("click",i=>{i.target===x&&n()}),window.openContainerLogsModal=function(i,d){x.classList.add("show"),m().then(()=>{const g=Array.from(B.options).find(S=>S.value===i||S.dataset.name===d);g?(B.value=g.value,u(g.value),t()):i?(D=i,j.textContent=d||i,H.textContent="-",R.textContent="-",t()):A.innerHTML='
Select a container to view logs
'})}})(),(function(){injectModal("snapshot-modal",`
+ `}function l(r,d=""){if(!r||r.length===0){A.innerHTML='
No logs available
',E.textContent="0 lines",I.textContent="0 filtered";return}if(R=r,u=d?r.filter(y=>y.text&&y.text.toLowerCase().includes(d.toLowerCase())):r,E.textContent=`${r.length} lines`,I.textContent=d?`${u.length} of ${r.length} shown`:`${r.length} shown`,u.length===0){A.innerHTML=`
No logs match "${s(d)}"
`;return}A.innerHTML=u.map((y,L)=>p(y,L)).join(""),A.scrollTop=A.scrollHeight}async function m(){try{const d=(await getJSON("/api/v1/logs/containers")).containers||[],y=B.value;B.innerHTML='',d.forEach(L=>{const U=document.createElement("option");U.value=L.id,U.textContent=`${L.name} (${L.image.split(":")[0]}) - ${L.status}`,U.dataset.name=L.name,U.dataset.image=L.image,U.dataset.status=L.status,U.dataset.created=L.created,B.appendChild(U)}),y&&B.querySelector(`option[value="${y}"]`)&&(B.value=y,c(y))}catch(r){console.error("Failed to load containers:",r)}}function c(r){const d=B.querySelector(`option[value="${r}"]`);d&&(O.textContent=d.dataset.image||"-",C.textContent=d.dataset.status||"-",C.style.color=d.dataset.status==="running"?"var(--ok-fg, #4ade80)":"var(--bad-fg, #ef4444)",j.textContent=b(d.dataset.created))}async function t(){const r=B.value;if(!r){A.innerHTML='
Select a container to view logs
';return}a(),N=r,c(r);const d=z.value,y=S.value.trim();A.innerHTML='
Loading logs...
';try{const L=`/api/v1/logs/container/${r}${d!=="all"?`?tail=${d}`:""}`,U=await getJSON(L);U.logs&&U.logs.length>0?l(U.logs,y):(A.innerHTML='
No logs found for this container
',E.textContent="0 lines",I.textContent="0 filtered")}catch(L){A.innerHTML=`
Error loading logs: ${s(L.message)}
`}}function e(){const r=B.value;if(!r)return;a(),x=!0,M.textContent="\u23F9 Stop",H.style.display="flex",k.textContent="\u{1F7E2}",$.textContent="Connecting...";const d=`/api/v1/logs/stream/${r}`;v=new EventSource(d),v.onopen=()=>{k.textContent="\u{1F7E2}",$.textContent="Connected - streaming logs"},v.onmessage=y=>{try{const L=JSON.parse(y.data);if(L.error){k.textContent="\u{1F534}",$.textContent=`Error: ${L.error}`;return}R.push(L),u.push(L),E.textContent=`${R.length} lines`,I.textContent=`${u.length} shown`;const U=S.value.trim();if(!U||L.text&&L.text.toLowerCase().includes(U.toLowerCase())){const q=document.createElement("div");q.innerHTML=p(L,u.length-1);const F=q.firstElementChild;F.style.background="#1a3a1a",A.appendChild(F),A.scrollTop=A.scrollHeight}}catch(L){console.error("Error parsing log:",L)}},v.onerror=()=>{k.textContent="\u{1F534}",$.textContent="Disconnected",x=!1,M.textContent="\u25B6 Stream"},w._eventSource=v}function a(){v&&(v.close(),v=null),w._eventSource&&(w._eventSource.close(),w._eventSource=null),x=!1,M.textContent="\u25B6 Stream",H.style.display="none"}function o(){if(!R||R.length===0){showNotification("No logs to download","error");return}const r=B.querySelector(`option[value="${N}"]`)?.dataset.name||N,d=new Date().toISOString().replace(/[:.]/g,"-"),y=`${r}-logs-${d}.txt`,L=R.map(_=>{const J=_.timestamp||"",X=_.stream==="stderr"?"[ERR]":"[OUT]";return`${J?J+" ":""}${X} ${_.text}`}).join(` +`),U=new Blob([L],{type:"text/plain"}),q=URL.createObjectURL(U),F=document.createElement("a");F.href=q,F.download=y,document.body.appendChild(F),F.click(),document.body.removeChild(F),URL.revokeObjectURL(q),showNotification(`Downloaded ${R.length} log lines`,"success")}B?.addEventListener("change",()=>{t()}),z?.addEventListener("change",()=>{t()}),P?.addEventListener("click",()=>{t()}),M?.addEventListener("click",()=>{x?a():e()}),D?.addEventListener("click",()=>{o()}),h?.addEventListener("click",()=>{S.value="",l(R,"")}),S?.addEventListener("input",()=>{clearTimeout(g),g=setTimeout(()=>{l(R,S.value.trim())},300)}),S?.addEventListener("keydown",r=>{r.key==="Escape"&&(S.value="",l(R,""))}),document.getElementById("view-container-logs")?.addEventListener("click",()=>{w.classList.add("show"),m()});function n(){a(),w.classList.remove("show")}T?.addEventListener("click",n),f?.addEventListener("click",n),document.addEventListener("keydown",r=>{r.key==="Escape"&&w.classList.contains("show")&&n()}),w.addEventListener("click",r=>{r.target===w&&n()}),window.openContainerLogsModal=function(r,d){w.classList.add("show"),m().then(()=>{const y=Array.from(B.options).find(L=>L.value===r||L.dataset.name===d);y?(B.value=y.value,c(y.value),t()):r?(N=r,O.textContent=d||r,C.textContent="-",j.textContent="-",t()):A.innerHTML='
Select a container to view logs
'})}})(),(function(){"use strict";const w=[{unit:"caddy",label:"Caddy (reverse proxy)"},{unit:"dashcaddy-api",label:"DashCaddy API (host systemd unit, not this container)"},{unit:"docker",label:"Docker daemon"},{unit:"ssh",label:"SSH server"},{unit:"systemd-journald",label:"systemd-journald"},{unit:"tailscaled",label:"Tailscale"},{unit:"networkd-dispatcher",label:"Networkd dispatcher"}];injectModal("journald-modal",` +
+
+
+
+

\u{1F6F0}\uFE0F Host Logs (journald)

+ +
+
+ + + + + + + +
+
+ +
+ Source: journald + Unit: - + Stream: disconnected +
+ +
+
Select a unit and click Load tail or Stream.
+
+ + +
+
+ `);const B=document.getElementById("journald-modal"),A=document.getElementById("jd-unit-select"),S=document.getElementById("jd-search"),z=document.getElementById("jd-tail"),P=document.getElementById("jd-refresh"),M=document.getElementById("jd-stream"),D=document.getElementById("jd-clear-search"),h=document.getElementById("jd-close"),T=document.getElementById("jd-close-btn"),f=document.getElementById("jd-content"),H=document.getElementById("jd-line-count"),k=document.getElementById("jd-filter-count"),$=document.getElementById("jd-overflow"),E=document.getElementById("jd-unit-display"),I=document.getElementById("jd-stream-state");let O=!1,C=[],j=!1,N=null,R=null;function u(c){const t=document.createElement("div");return t.textContent=String(c),t.innerHTML}function v(c){O=c,A.innerHTML="",w.forEach(t=>{const e=document.createElement("option");e.value=t.unit,e.textContent=t.label+" ("+t.unit+")",A.appendChild(e)}),A.disabled=!c,c?(P.disabled=!1,M.disabled=!1):(f.innerHTML='
journald bind-mount not available in this container.
Requires /var/log/journal + /usr/bin/journalctl mounted (start.sh).
',P.disabled=!0,M.disabled=!0)}async function x(){try{const c=await fetch("/api/v1/logs/journal/units");if(!c.ok){v(!1);return}const t=await c.json();v(!!t.available)}catch{v(!1)}}function g(){const c=(S.value||"").trim().toLowerCase(),t=c?C.filter(e=>(e.textContent||"").toLowerCase().includes(c)):C;if(t.length===0)f.innerHTML='
No entries'+(c?` matching "${u(c)}"`:"")+"
";else{const e=t.map(o=>{const i=o.timestamp?u(o.timestamp):"\u2014",n=u(o.textContent);return`
${i}${n}
`}).join("");f.innerHTML=e,f.scrollHeight-f.scrollTop-f.clientHeight<80&&(f.scrollTop=f.scrollHeight)}H.textContent=`${C.length} entries`,k.textContent=c?`${t.length} of ${C.length} shown`:`${C.length} shown`}async function b(){if(!O)return;p();const c=A.value;if(!c)return;const t=Math.max(1,Math.min(5e3,Number(z.value)||200)),e=(S.value||"").trim();f.innerHTML='
Loading\u2026
';try{const a=new URL("/api/v1/logs/journal",window.location.origin);a.searchParams.set("unit",c),a.searchParams.set("tail",String(t)),e&&a.searchParams.set("search",e);const o=await fetch(a.toString()),i=await o.json();if(!o.ok||!i.success){f.innerHTML='
Failed: '+u(i&&i.error||"HTTP "+o.status)+"
";return}E.textContent=c,C=(i.entries||[]).map(n=>({timestamp:n.timestamp,unit:n.unit,textContent:n.text||""})),$.style.display="none",g()}catch(a){f.innerHTML='
Error: '+u(a.message)+"
"}}function s(){if(!O)return;p();const c=A.value;if(!c)return;const t=(S.value||"").trim();E.textContent=c,M.textContent="\u23F8 Stop",M.classList.add("streaming"),I.textContent="streaming",I.style.color="var(--ok-fg, #4ade80)",C=[],g(),$.style.display="none";const e=new URL("/api/v1/logs/journal/stream",window.location.origin);e.searchParams.set("unit",c),t&&e.searchParams.set("search",t),N=new EventSource(e.toString()),N.onmessage=a=>{try{const o=JSON.parse(a.data);if(o.error){/stream (exceeded|line cap)/.test(o.error)&&($.style.display="",p()),f.innerHTML+='
\u26A0 '+u(o.error)+"
",f.scrollTop=f.scrollHeight;return}C.push({timestamp:o.timestamp,unit:o.unit||c,textContent:o.text||""}),C.length>5e3&&(C=C.slice(C.length-5e3),$.style.display=""),g()}catch{}},N.onerror=()=>{},j=!0}function p(){if(j=!1,N){try{N.close()}catch{}N=null}M.textContent="\u25B6 Stream",M.classList.remove("streaming"),I.textContent="disconnected",I.style.color="var(--muted)"}function l(){p(),B.classList.remove("show")}P.addEventListener("click",b),M.addEventListener("click",()=>j?p():s()),D.addEventListener("click",()=>{S.value="",g()}),S.addEventListener("input",()=>{clearTimeout(R),R=setTimeout(g,200)}),S.addEventListener("keydown",c=>{c.key==="Escape"&&(S.value="",g())}),h.addEventListener("click",l),T.addEventListener("click",l),B.addEventListener("click",c=>{c.target===B&&l()}),document.addEventListener("keydown",c=>{c.key==="Escape"&&B.classList.contains("show")&&l()}),A.addEventListener("change",()=>{C.length>0&&b()});function m(){B.classList.add("show"),x()}window.openJournaldModal=m,document.getElementById("view-journald-logs")?.addEventListener("click",m)})(),(function(){injectModal("snapshot-modal",`

\u{1F4BE} Container Snapshots

-
`);const x=document.getElementById("snapshot-modal"),B=document.getElementById("snapshot-btn"),A=document.getElementById("snapshot-close"),C=document.getElementById("snapshot-container-select"),M=document.getElementById("snapshot-details"),P=document.getElementById("snapshot-create-btn"),z=document.getElementById("snapshot-create-status");let N=null;async function f(){try{const E=await(await fetch("/api/v1/containers")).json();if(!E.success||!E.containers)return;C.innerHTML='';for(const I of E.containers){const j=document.createElement("option");j.value=I.id,j.textContent=`${I.name||I.id} (${I.image||"unknown"})`,j.dataset.name=I.name,j.dataset.image=I.image,j.dataset.status=I.status,j.dataset.created=I.created,C.appendChild(j)}}catch(T){console.error("Failed to load containers:",T)}}function L(T){if(!T||!T.value){M.style.display="none",N=null;return}N=T.value,document.getElementById("snapshot-image").textContent=T.dataset.image||"-",document.getElementById("snapshot-status").textContent=T.dataset.status||"-",document.getElementById("snapshot-created").textContent=T.dataset.created?new Date(T.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=T.value.substring(0,12),M.style.display=""}async function w(){if(!N){z.textContent="Please select a container first",z.style.color="var(--bad-fg)";return}const T=document.getElementById("snapshot-name").value.trim();if(!T){z.textContent="Please enter a snapshot name",z.style.color="var(--bad-fg)";return}const E=document.getElementById("snapshot-leave-running").checked;P.disabled=!0,P.textContent="Creating...",z.textContent="";try{const j=await(await fetch(`/api/v1/containers/${encodeURIComponent(N)}/checkpoint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:T,leaveRunning:E})})).json();j.success?(z.textContent=`\u2713 Snapshot "${T}" created successfully`,z.style.color="var(--ok-fg)",document.getElementById("snapshot-name").value=""):(z.textContent=`\u2717 Failed: ${j.error||"Unknown error"}`,z.style.color="var(--bad-fg)")}catch(I){z.textContent=`\u2717 Error: ${I.message}`,z.style.color="var(--bad-fg)"}finally{P.disabled=!1,P.textContent="\u{1F4BE} Create Snapshot"}}function $(){x.classList.add("show"),f()}function k(){x.classList.remove("show"),M.style.display="none",N=null,C.selectedIndex=0}B?.addEventListener("click",$),A?.addEventListener("click",k),wireModal(x,A),C?.addEventListener("change",T=>{const E=C.options[C.selectedIndex];L(E)}),P?.addEventListener("click",w),x?.querySelectorAll(".panel-tab").forEach(T=>{T.addEventListener("click",()=>{x.querySelectorAll(".panel-tab").forEach(E=>E.classList.remove("active")),x.querySelectorAll(".panel-section").forEach(E=>E.classList.remove("active")),T.classList.add("active"),x.querySelector(`#${T.dataset.panel}`).classList.add("active")})})})(),(function(){injectModal("arr-setup-modal",`
+
`);const w=document.getElementById("snapshot-modal"),B=document.getElementById("snapshot-btn"),A=document.getElementById("snapshot-close"),S=document.getElementById("snapshot-container-select"),z=document.getElementById("snapshot-details"),P=document.getElementById("snapshot-create-btn"),M=document.getElementById("snapshot-create-status");let D=null;async function h(){try{const E=await(await fetch("/api/v1/containers")).json();if(!E.success||!E.containers)return;S.innerHTML='';for(const I of E.containers){const O=document.createElement("option");O.value=I.id,O.textContent=`${I.name||I.id} (${I.image||"unknown"})`,O.dataset.name=I.name,O.dataset.image=I.image,O.dataset.status=I.status,O.dataset.created=I.created,S.appendChild(O)}}catch($){console.error("Failed to load containers:",$)}}function T($){if(!$||!$.value){z.style.display="none",D=null;return}D=$.value,document.getElementById("snapshot-image").textContent=$.dataset.image||"-",document.getElementById("snapshot-status").textContent=$.dataset.status||"-",document.getElementById("snapshot-created").textContent=$.dataset.created?new Date($.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=$.value.substring(0,12),z.style.display=""}async function f(){if(!D){M.textContent="Please select a container first",M.style.color="var(--bad-fg)";return}const $=document.getElementById("snapshot-name").value.trim();if(!$){M.textContent="Please enter a snapshot name",M.style.color="var(--bad-fg)";return}const E=document.getElementById("snapshot-leave-running").checked;P.disabled=!0,P.textContent="Creating...",M.textContent="";try{const O=await(await fetch(`/api/v1/containers/${encodeURIComponent(D)}/checkpoint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:$,leaveRunning:E})})).json();O.success?(M.textContent=`\u2713 Snapshot "${$}" created successfully`,M.style.color="var(--ok-fg)",document.getElementById("snapshot-name").value=""):(M.textContent=`\u2717 Failed: ${O.error||"Unknown error"}`,M.style.color="var(--bad-fg)")}catch(I){M.textContent=`\u2717 Error: ${I.message}`,M.style.color="var(--bad-fg)"}finally{P.disabled=!1,P.textContent="\u{1F4BE} Create Snapshot"}}function H(){w.classList.add("show"),h()}function k(){w.classList.remove("show"),z.style.display="none",D=null,S.selectedIndex=0}B?.addEventListener("click",H),A?.addEventListener("click",k),wireModal(w,A),S?.addEventListener("change",$=>{const E=S.options[S.selectedIndex];T(E)}),P?.addEventListener("click",f),w?.querySelectorAll(".panel-tab").forEach($=>{$.addEventListener("click",()=>{w.querySelectorAll(".panel-tab").forEach(E=>E.classList.remove("active")),w.querySelectorAll(".panel-section").forEach(E=>E.classList.remove("active")),$.classList.add("active"),w.querySelector(`#${$.dataset.panel}`).classList.add("active")})})})(),(function(){injectModal("arr-setup-modal",`

\u{1F3AC} Smart Arr Connect

@@ -788,73 +831,73 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};

-
`);const x=document.getElementById("arr-setup-modal"),B=document.getElementById("arr-setup-btn"),A=document.getElementById("arr-setup-cancel"),C=document.getElementById("smart-connect-btn"),M=document.getElementById("smart-phase-detect"),P=document.getElementById("smart-phase-credentials"),z=document.getElementById("smart-phase-progress"),N=document.getElementById("smart-phase-results"),f=document.getElementById("smart-detect-results"),L=document.getElementById("smart-credential-inputs"),w=document.getElementById("smart-progress-steps"),$=document.getElementById("smart-results-content"),k=document.getElementById("smart-plex-libraries"),T=document.getElementById("smart-retry-btn");let E=null;const I={plex:"\u{1F3AC}",radarr:"\u{1F3AC}",sonarr:"\u{1F4FA}",prowlarr:"\u{1F50D}",seerr:"\u{1F4CB}"},j={plex:"Plex",radarr:"Radarr (Movies)",sonarr:"Sonarr (TV)",prowlarr:"Prowlarr (Indexers)",seerr:"Seerr"};function H(y){M.style.display=y==="detect"?"block":"none",P.style.display=y==="credentials"?"block":"none",z.style.display=y==="progress"?"block":"none",N.style.display=y==="results"?"block":"none"}function R(y){const h={connected:{bg:"var(--ok-fg)",icon:"✓",text:"Connected"},needs_key:{bg:"#f39c12",icon:"🔑",text:"Needs API Key"},not_found:{bg:"var(--muted)",icon:"—",text:"Not Found"},error:{bg:"var(--bad-fg)",icon:"✗",text:"Error"}},s=h[y]||h.not_found;return`${s.icon} ${s.text}`}async function D(){H("detect"),f.style.display="none";try{if(E=await(await fetch("/api/v1/arr/smart-detect")).json(),!E.success){f.innerHTML=`
Detection failed: ${escapeHtml(E.error)}
`,f.style.display="block";return}let h='
';for(const[c,l]of Object.entries(E.services)){const m=I[c]||"\u{1F4E6}",u=j[c]||c,t=l.source?`${escapeHtml(l.source)}`:"",e=l.version?`v${escapeHtml(l.version)}`:"",a=(l.hasApiKey||l.hasToken)&&l.status==="connected"?'Key saved':"";h+=`
+
`);const w=document.getElementById("arr-setup-modal"),B=document.getElementById("arr-setup-btn"),A=document.getElementById("arr-setup-cancel"),S=document.getElementById("smart-connect-btn"),z=document.getElementById("smart-phase-detect"),P=document.getElementById("smart-phase-credentials"),M=document.getElementById("smart-phase-progress"),D=document.getElementById("smart-phase-results"),h=document.getElementById("smart-detect-results"),T=document.getElementById("smart-credential-inputs"),f=document.getElementById("smart-progress-steps"),H=document.getElementById("smart-results-content"),k=document.getElementById("smart-plex-libraries"),$=document.getElementById("smart-retry-btn");let E=null;const I={plex:"\u{1F3AC}",radarr:"\u{1F3AC}",sonarr:"\u{1F4FA}",prowlarr:"\u{1F50D}",seerr:"\u{1F4CB}"},O={plex:"Plex",radarr:"Radarr (Movies)",sonarr:"Sonarr (TV)",prowlarr:"Prowlarr (Indexers)",seerr:"Seerr"};function C(g){z.style.display=g==="detect"?"block":"none",P.style.display=g==="credentials"?"block":"none",M.style.display=g==="progress"?"block":"none",D.style.display=g==="results"?"block":"none"}function j(g){const b={connected:{bg:"var(--ok-fg)",icon:"✓",text:"Connected"},needs_key:{bg:"#f39c12",icon:"🔑",text:"Needs API Key"},not_found:{bg:"var(--muted)",icon:"—",text:"Not Found"},error:{bg:"var(--bad-fg)",icon:"✗",text:"Error"}},s=b[g]||b.not_found;return`${s.icon} ${s.text}`}async function N(){C("detect"),h.style.display="none";try{if(E=await(await fetch("/api/v1/arr/smart-detect")).json(),!E.success){h.innerHTML=`
Detection failed: ${escapeHtml(E.error)}
`,h.style.display="block";return}let b='
';for(const[p,l]of Object.entries(E.services)){const m=I[p]||"\u{1F4E6}",c=O[p]||p,t=l.source?`${escapeHtml(l.source)}`:"",e=l.version?`v${escapeHtml(l.version)}`:"",a=(l.hasApiKey||l.hasToken)&&l.status==="connected"?'Key saved':"";b+=`
${m}
-
${u}
+
${c}
${t} ${e} ${a}
- ${R(l.status)} -
`}h+="
";const s=E.summary;h+=`
+ ${j(l.status)} +
`}b+="
";const s=E.summary;b+=`
${escapeHtml(String(s.fullyConnected))}/${escapeHtml(String(s.totalDetected+(5-s.totalDetected)))} services detected · ${escapeHtml(String(s.fullyConnected))} connected${s.needsApiKey>0?` · ${escapeHtml(String(s.needsApiKey))} needs API key`:""} -
`,f.innerHTML=h,f.style.display="block",O(E),setTimeout(()=>{H("credentials")},800)}catch(y){f.innerHTML=`
Error: ${escapeHtml(y.message)}
`,f.style.display="block"}}function O(y){let h="";const s=y.services,c=["radarr","sonarr","prowlarr"];for(const u of c){const t=s[u];if(!t||t.status==="not_found"&&!t.url)continue;const e=I[u],a=j[u],o=t.status==="connected";h+=`
+
`,h.innerHTML=b,h.style.display="block",R(E),setTimeout(()=>{C("credentials")},800)}catch(g){h.innerHTML=`
Error: ${escapeHtml(g.message)}
`,h.style.display="block"}}function R(g){let b="";const s=g.services,p=["radarr","sonarr","prowlarr"];for(const c of p){const t=s[c];if(!t||t.status==="not_found"&&!t.url)continue;const e=I[c],a=O[c],o=t.status==="connected";b+=`
${e} ${a} - + ${o?'✓ Connected':""}
-
-
- -
`}const l=s.plex;if(l){const u=l.status==="connected";h+=`
+ +
`}const l=s.plex;if(l){const c=l.status==="connected";b+=`
\u{1F3AC} Plex - ${R(l.status)} + ${j(l.status)} ${escapeHtml(l.source||"")}
-
`}const m=s.seerr;if(m){const u=m.status==="connected";let t="";if(m.configuredServices){const e=m.configuredServices;t=`
+
`}const m=s.seerr;if(m){const c=m.status==="connected";let t="";if(m.configuredServices){const e=m.configuredServices;t=`
Configured: ${e.radarr?"✓ Radarr":"✗ Radarr"} · ${e.sonarr?"✓ Sonarr":"✗ Sonarr"} · ${e.plex?"✓ Plex":"✗ Plex"} -
`}h+=`
+
`}b+=`
\u{1F4CB} Seerr - ${R(m.status)} + ${j(m.status)}
${t} -
`}L.innerHTML=h}window.smartTestConnection=async function(y){const h=document.getElementById(`smart-${y}-url`),s=document.getElementById(`smart-${y}-key`),c=document.getElementById(`smart-${y}-status`),l=h?.value.trim(),m=s?.value.trim();if(!l||!m){c.innerHTML='Enter URL and API key';return}c.innerHTML='';try{const t=await(await secureFetch("/api/v1/arr/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:y,url:l,apiKey:m})})).json();t.success?c.innerHTML=`✓ ${escapeHtml(t.appName||"Connected")} v${escapeHtml(t.version||"")}`:c.innerHTML=`✗ ${escapeHtml(t.error)}`}catch(u){c.innerHTML=`✗ ${escapeHtml(u.message)}`}};async function p(){H("progress"),w.innerHTML='
Connecting services...
';const y={};for(const s of["radarr","sonarr","prowlarr"]){const c=document.getElementById(`smart-${s}-url`)?.value.trim(),l=document.getElementById(`smart-${s}-key`)?.value.trim();l&&c?y[s]={apiKey:l,url:c}:l&&(y[s]={apiKey:l})}const h={services:Object.keys(y).length>0?y:void 0,configurePlex:document.getElementById("smart-opt-plex")?.checked,configureProwlarr:document.getElementById("smart-opt-prowlarr")?.checked,configureSeerr:document.getElementById("smart-opt-seerr")?.checked,saveCredentials:document.getElementById("smart-opt-save")?.checked};try{const c=await(await secureFetch("/api/v1/arr/smart-connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)})).json();let l="";for(const m of c.steps||[]){const u=m.status==="success"?'':'',t=m.status==="success"?"var(--muted)":"var(--bad-fg)";l+=`
- ${u} +
`}T.innerHTML=b}window.smartTestConnection=async function(g){const b=document.getElementById(`smart-${g}-url`),s=document.getElementById(`smart-${g}-key`),p=document.getElementById(`smart-${g}-status`),l=b?.value.trim(),m=s?.value.trim();if(!l||!m){p.innerHTML='Enter URL and API key';return}p.innerHTML='';try{const t=await(await secureFetch("/api/v1/arr/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:g,url:l,apiKey:m})})).json();t.success?p.innerHTML=`✓ ${escapeHtml(t.appName||"Connected")} v${escapeHtml(t.version||"")}`:p.innerHTML=`✗ ${escapeHtml(t.error)}`}catch(c){p.innerHTML=`✗ ${escapeHtml(c.message)}`}};async function u(){C("progress"),f.innerHTML='
Connecting services...
';const g={};for(const s of["radarr","sonarr","prowlarr"]){const p=document.getElementById(`smart-${s}-url`)?.value.trim(),l=document.getElementById(`smart-${s}-key`)?.value.trim();l&&p?g[s]={apiKey:l,url:p}:l&&(g[s]={apiKey:l})}const b={services:Object.keys(g).length>0?g:void 0,configurePlex:document.getElementById("smart-opt-plex")?.checked,configureProwlarr:document.getElementById("smart-opt-prowlarr")?.checked,configureSeerr:document.getElementById("smart-opt-seerr")?.checked,saveCredentials:document.getElementById("smart-opt-save")?.checked};try{const p=await(await secureFetch("/api/v1/arr/smart-connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)})).json();let l="";for(const m of p.steps||[]){const c=m.status==="success"?'':'',t=m.status==="success"?"var(--muted)":"var(--bad-fg)";l+=`
+ ${c} ${escapeHtml(m.step)} ${escapeHtml(m.details||"")} -
`}w.innerHTML=l,setTimeout(()=>v(c),500)}catch(s){w.innerHTML=`
Connection error: ${escapeHtml(s.message)}
`}}function v(y){H("results");const h=y.summary||{},s=h.failed===0&&h.succeeded>0,c=s?"var(--ok-fg)":"#f39c12",l=s?"✓":"⚠",m=s?"All Connected!":`${escapeHtml(String(h.succeeded))}/${escapeHtml(String(h.totalSteps))} Steps Succeeded`;let u=`
-
${l}
-
${m}
-
${escapeHtml(String(h.succeeded))} succeeded, ${escapeHtml(String(h.failed))} failed
-
`;u+='
';for(const t of y.steps||[]){const e=t.status==="success"?'':'';u+=`
+
`}f.innerHTML=l,setTimeout(()=>v(p),500)}catch(s){f.innerHTML=`
Connection error: ${escapeHtml(s.message)}
`}}function v(g){C("results");const b=g.summary||{},s=b.failed===0&&b.succeeded>0,p=s?"var(--ok-fg)":"#f39c12",l=s?"✓":"⚠",m=s?"All Connected!":`${escapeHtml(String(b.succeeded))}/${escapeHtml(String(b.totalSteps))} Steps Succeeded`;let c=`
+
${l}
+
${m}
+
${escapeHtml(String(b.succeeded))} succeeded, ${escapeHtml(String(b.failed))} failed
+
`;c+='
';for(const t of g.steps||[]){const e=t.status==="success"?'':'';c+=`
${e} ${escapeHtml(t.step)} ${escapeHtml(t.details||"")} -
`}u+="
",$.innerHTML=u,T.style.display=h.failed>0?"block":"none",y.steps?.some(t=>t.step.includes("Plex")&&t.status==="success")&&b()}async function b(){try{const h=await(await fetch("/api/v1/plex/libraries")).json();if(h.success&&h.libraries?.length>0){let s=`
-

\u{1F3AC} ${escapeHtml(h.serverName)} Libraries

-
`;for(const c of h.libraries){const l=c.type==="movie"?"\u{1F3AC}":c.type==="show"?"\u{1F4FA}":"\u{1F3B5}";s+=`
- ${l} ${escapeHtml(c.title)} - ${escapeHtml(String(c.count))} items -
`}s+="
",k.innerHTML=s,k.style.display="block"}}catch{}}B?.addEventListener("click",()=>{x.classList.add("show"),k.style.display="none",D()}),wireModal(x,A),C?.addEventListener("click",p),T?.addEventListener("click",p)})(),(function(){const x=new ErrorHandler;injectModal("notifications-modal",`
+
`}c+="
",H.innerHTML=c,$.style.display=b.failed>0?"block":"none",g.steps?.some(t=>t.step.includes("Plex")&&t.status==="success")&&x()}async function x(){try{const b=await(await fetch("/api/v1/plex/libraries")).json();if(b.success&&b.libraries?.length>0){let s=`
+

\u{1F3AC} ${escapeHtml(b.serverName)} Libraries

+
`;for(const p of b.libraries){const l=p.type==="movie"?"\u{1F3AC}":p.type==="show"?"\u{1F4FA}":"\u{1F3B5}";s+=`
+ ${l} ${escapeHtml(p.title)} + ${escapeHtml(String(p.count))} items +
`}s+="
",k.innerHTML=s,k.style.display="block"}}catch{}}B?.addEventListener("click",()=>{w.classList.add("show"),k.style.display="none",N()}),wireModal(w,A),S?.addEventListener("click",u),$?.addEventListener("click",u)})(),(function(){const w=new ErrorHandler;injectModal("notifications-modal",`

\u{1F514} Notification Settings

@@ -1039,15 +1082,15 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
-
`);const B=document.getElementById("notifications-modal"),A=document.getElementById("manage-notifications"),C=document.getElementById("notifications-save"),M=document.getElementById("notifications-cancel");["discord","telegram","ntfy","email"].forEach(k=>{const T=document.getElementById(`${k}-enabled`),E=document.getElementById(`${k}-config`);T?.addEventListener("change",()=>{E.style.display=T.checked?"block":"none"})});const P=document.getElementById("health-check-enabled"),z=document.getElementById("health-check-config");P?.addEventListener("change",()=>{z.style.opacity=P.checked?"1":"0.5"});async function N(){try{const T=await(await fetch("/api/v1/notifications/config")).json();if(T.success){const E=T.config;document.getElementById("notifications-enabled").checked=E.enabled,document.getElementById("discord-enabled").checked=E.providers?.discord?.enabled||!1,document.getElementById("telegram-enabled").checked=E.providers?.telegram?.enabled||!1,document.getElementById("ntfy-enabled").checked=E.providers?.ntfy?.enabled||!1,document.getElementById("email-enabled").checked=E.providers?.email?.enabled||!1,document.getElementById("discord-config").style.display=E.providers?.discord?.enabled?"block":"none",document.getElementById("telegram-config").style.display=E.providers?.telegram?.enabled?"block":"none",document.getElementById("ntfy-config").style.display=E.providers?.ntfy?.enabled?"block":"none",document.getElementById("email-config").style.display=E.providers?.email?.enabled?"block":"none",E.providers?.ntfy?.serverUrl&&(document.getElementById("ntfy-server").value=E.providers.ntfy.serverUrl),E.providers?.email?.host&&(document.getElementById("email-host").value=E.providers.email.host),E.providers?.email?.from&&(document.getElementById("email-from").value=E.providers.email.from),document.getElementById("health-check-enabled").checked=E.healthCheck?.enabled||!1,E.healthCheck?.intervalMinutes&&(document.getElementById("health-check-interval").value=E.healthCheck.intervalMinutes),E.healthCheck?.lastCheck&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(E.healthCheck.lastCheck).toLocaleString()}`),document.getElementById("event-container-down").checked=E.events?.containerDown!==!1,document.getElementById("event-container-up").checked=E.events?.containerUp!==!1,document.getElementById("event-deploy-success").checked=E.events?.deploymentSuccess!==!1,document.getElementById("event-deploy-failed").checked=E.events?.deploymentFailed!==!1,document.getElementById("event-resource-alert").checked=E.events?.resourceAlert!==!1}}catch(k){x.logError("[Notifications] Load Config",k,{function:"loadConfig"})}}async function f(){try{const T=await(await fetch("/api/v1/notifications/history?limit=10")).json(),E=document.getElementById("notification-history");T.success&&T.history?.length>0?E.innerHTML=T.history.map(I=>{const j=new Date(I.timestamp).toLocaleString();return` + `);const B=document.getElementById("notifications-modal"),A=document.getElementById("manage-notifications"),S=document.getElementById("notifications-save"),z=document.getElementById("notifications-cancel");["discord","telegram","ntfy","email"].forEach(k=>{const $=document.getElementById(`${k}-enabled`),E=document.getElementById(`${k}-config`);$?.addEventListener("change",()=>{E.style.display=$.checked?"block":"none"})});const P=document.getElementById("health-check-enabled"),M=document.getElementById("health-check-config");P?.addEventListener("change",()=>{M.style.opacity=P.checked?"1":"0.5"});async function D(){try{const $=await(await fetch("/api/v1/notifications/config")).json();if($.success){const E=$.config;document.getElementById("notifications-enabled").checked=E.enabled,document.getElementById("discord-enabled").checked=E.providers?.discord?.enabled||!1,document.getElementById("telegram-enabled").checked=E.providers?.telegram?.enabled||!1,document.getElementById("ntfy-enabled").checked=E.providers?.ntfy?.enabled||!1,document.getElementById("email-enabled").checked=E.providers?.email?.enabled||!1,document.getElementById("discord-config").style.display=E.providers?.discord?.enabled?"block":"none",document.getElementById("telegram-config").style.display=E.providers?.telegram?.enabled?"block":"none",document.getElementById("ntfy-config").style.display=E.providers?.ntfy?.enabled?"block":"none",document.getElementById("email-config").style.display=E.providers?.email?.enabled?"block":"none",E.providers?.ntfy?.serverUrl&&(document.getElementById("ntfy-server").value=E.providers.ntfy.serverUrl),E.providers?.email?.host&&(document.getElementById("email-host").value=E.providers.email.host),E.providers?.email?.from&&(document.getElementById("email-from").value=E.providers.email.from),document.getElementById("health-check-enabled").checked=E.healthCheck?.enabled||!1,E.healthCheck?.intervalMinutes&&(document.getElementById("health-check-interval").value=E.healthCheck.intervalMinutes),E.healthCheck?.lastCheck&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(E.healthCheck.lastCheck).toLocaleString()}`),document.getElementById("event-container-down").checked=E.events?.containerDown!==!1,document.getElementById("event-container-up").checked=E.events?.containerUp!==!1,document.getElementById("event-deploy-success").checked=E.events?.deploymentSuccess!==!1,document.getElementById("event-deploy-failed").checked=E.events?.deploymentFailed!==!1,document.getElementById("event-resource-alert").checked=E.events?.resourceAlert!==!1}}catch(k){w.logError("[Notifications] Load Config",k,{function:"loadConfig"})}}async function h(){try{const $=await(await fetch("/api/v1/notifications/history?limit=10")).json(),E=document.getElementById("notification-history");$.success&&$.history?.length>0?E.innerHTML=$.history.map(I=>{const O=new Date(I.timestamp).toLocaleString();return`
${I.type==="success"?"\u2713":I.type==="error"?"\u2717":"\u2139"}
${escapeHtml(I.title)}
-
${j}
+
${O}
- `}).join(""):E.innerHTML='
No notifications yet
'}catch(k){x.logError("[Notifications] Load History",k,{function:"loadHistory"})}}async function L(){try{const k={enabled:document.getElementById("notifications-enabled").checked,providers:{discord:{enabled:document.getElementById("discord-enabled").checked,webhookUrl:document.getElementById("discord-webhook").value.trim()},telegram:{enabled:document.getElementById("telegram-enabled").checked,botToken:document.getElementById("telegram-bot-token").value.trim(),chatId:document.getElementById("telegram-chat-id").value.trim()},ntfy:{enabled:document.getElementById("ntfy-enabled").checked,serverUrl:document.getElementById("ntfy-server").value.trim()||"https://ntfy.sh",topic:document.getElementById("ntfy-topic").value.trim()},email:{enabled:document.getElementById("email-enabled").checked,host:document.getElementById("email-host").value.trim(),port:parseInt(document.getElementById("email-port").value)||587,secure:document.getElementById("email-secure").checked,user:document.getElementById("email-user").value.trim(),pass:document.getElementById("email-pass").value.trim(),from:document.getElementById("email-from").value.trim(),to:document.getElementById("email-to").value.trim()}},events:{containerDown:document.getElementById("event-container-down").checked,containerUp:document.getElementById("event-container-up").checked,deploymentSuccess:document.getElementById("event-deploy-success").checked,deploymentFailed:document.getElementById("event-deploy-failed").checked,resourceAlert:document.getElementById("event-resource-alert").checked},healthCheck:{enabled:document.getElementById("health-check-enabled").checked,intervalMinutes:parseInt(document.getElementById("health-check-interval").value)||5}},E=await(await secureFetch("/api/v1/notifications/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)})).json();E.success?(showNotification("Notification settings saved","success",3e3),B.classList.remove("show")):showNotification(`Failed to save: ${E.error}`,"error",3e3)}catch(k){showNotification(`Error: ${k.message}`,"error",3e3)}}async function w(k){try{const E=await(await secureFetch("/api/v1/notifications/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:k})})).json();E.success?showNotification(`Test ${k} notification sent!`,"success",3e3):showNotification(`Test failed: ${E.error}`,"error",3e3)}catch(T){showNotification(`Error: ${T.message}`,"error",3e3)}}document.getElementById("discord-test")?.addEventListener("click",()=>w("discord")),document.getElementById("telegram-test")?.addEventListener("click",()=>w("telegram")),document.getElementById("ntfy-test")?.addEventListener("click",()=>w("ntfy")),document.getElementById("email-test")?.addEventListener("click",()=>w("email")),document.getElementById("health-check-now")?.addEventListener("click",async()=>{try{const T=await(await secureFetch("/api/v1/notifications/health-check",{method:"POST"})).json();T.success&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(T.lastCheck).toLocaleString()} (${T.containersMonitored} containers)`,showNotification("Health check completed","success",2e3))}catch(k){showNotification(`Error: ${k.message}`,"error",3e3)}}),A?.addEventListener("click",()=>{B.classList.add("show"),N(),f()}),C?.addEventListener("click",L),document.getElementById("notifications-send-test")?.addEventListener("click",async()=>{const k=document.getElementById("notifications-send-test"),T=k.textContent;k.textContent="Sending...",k.disabled=!0;try{const I=await(await secureFetch("/api/v1/notifications/send",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"test",data:{message:"This is a test notification from DashCaddy."},type:"info"})})).json();I.success?(showNotification("Test notification sent!","success",3e3),$()):showNotification(`Test failed: ${I.results?.map(j=>`${j.provider}: ${j.error||"ok"}`).join(", ")}`,"error",5e3)}catch(E){showNotification(`Error: ${E.message}`,"error",3e3)}finally{k.textContent=T,k.disabled=!1}});async function $(){try{const T=await(await fetch("/api/v1/notifications/status")).json();if(T.success&&T.lastSent){const E=document.getElementById("last-notification-sent");E&&(E.textContent=`Last sent: ${new Date(T.lastSent).toLocaleString()}`)}}catch{}}wireModal(B,M)})(),(function(){document.addEventListener("click",x=>{const B=x.target.closest(".panel-tab");if(!B)return;const A=B.dataset.panel;if(!A)return;const C=B.closest(".panel-tabs"),M=C.closest(".weather-modal-content");C.querySelectorAll(".panel-tab").forEach(z=>z.classList.remove("active")),B.classList.add("active"),M.querySelectorAll(".panel-section").forEach(z=>z.classList.remove("active"));const P=M.querySelector("#"+A);P&&P.classList.add("active")})})(),(function(){var x=["dashcaddy_site_config","dashcaddy_onboarding","dashcaddy-encryption-key","dashcaddy-setup","dashcaddy-config","theme","user-themes","custom-theme","custom-apps","custom-services","toolbar-sections","weather-location","weather-zip","weather-geo","weather-unit","clock-style","clock-chimes","clock-chime-volume"];function B(){for(var e={},a=0;a + `}).join(""):E.innerHTML='
No notifications yet
'}catch(k){w.logError("[Notifications] Load History",k,{function:"loadHistory"})}}async function T(){try{const k={enabled:document.getElementById("notifications-enabled").checked,providers:{discord:{enabled:document.getElementById("discord-enabled").checked,webhookUrl:document.getElementById("discord-webhook").value.trim()},telegram:{enabled:document.getElementById("telegram-enabled").checked,botToken:document.getElementById("telegram-bot-token").value.trim(),chatId:document.getElementById("telegram-chat-id").value.trim()},ntfy:{enabled:document.getElementById("ntfy-enabled").checked,serverUrl:document.getElementById("ntfy-server").value.trim()||"https://ntfy.sh",topic:document.getElementById("ntfy-topic").value.trim()},email:{enabled:document.getElementById("email-enabled").checked,host:document.getElementById("email-host").value.trim(),port:parseInt(document.getElementById("email-port").value)||587,secure:document.getElementById("email-secure").checked,user:document.getElementById("email-user").value.trim(),pass:document.getElementById("email-pass").value.trim(),from:document.getElementById("email-from").value.trim(),to:document.getElementById("email-to").value.trim()}},events:{containerDown:document.getElementById("event-container-down").checked,containerUp:document.getElementById("event-container-up").checked,deploymentSuccess:document.getElementById("event-deploy-success").checked,deploymentFailed:document.getElementById("event-deploy-failed").checked,resourceAlert:document.getElementById("event-resource-alert").checked},healthCheck:{enabled:document.getElementById("health-check-enabled").checked,intervalMinutes:parseInt(document.getElementById("health-check-interval").value)||5}},E=await(await secureFetch("/api/v1/notifications/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)})).json();E.success?(showNotification("Notification settings saved","success",3e3),B.classList.remove("show")):showNotification(`Failed to save: ${E.error}`,"error",3e3)}catch(k){showNotification(`Error: ${k.message}`,"error",3e3)}}async function f(k){try{const E=await(await secureFetch("/api/v1/notifications/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:k})})).json();E.success?showNotification(`Test ${k} notification sent!`,"success",3e3):showNotification(`Test failed: ${E.error}`,"error",3e3)}catch($){showNotification(`Error: ${$.message}`,"error",3e3)}}document.getElementById("discord-test")?.addEventListener("click",()=>f("discord")),document.getElementById("telegram-test")?.addEventListener("click",()=>f("telegram")),document.getElementById("ntfy-test")?.addEventListener("click",()=>f("ntfy")),document.getElementById("email-test")?.addEventListener("click",()=>f("email")),document.getElementById("health-check-now")?.addEventListener("click",async()=>{try{const $=await(await secureFetch("/api/v1/notifications/health-check",{method:"POST"})).json();$.success&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date($.lastCheck).toLocaleString()} (${$.containersMonitored} containers)`,showNotification("Health check completed","success",2e3))}catch(k){showNotification(`Error: ${k.message}`,"error",3e3)}}),A?.addEventListener("click",()=>{B.classList.add("show"),D(),h()}),S?.addEventListener("click",T),document.getElementById("notifications-send-test")?.addEventListener("click",async()=>{const k=document.getElementById("notifications-send-test"),$=k.textContent;k.textContent="Sending...",k.disabled=!0;try{const I=await(await secureFetch("/api/v1/notifications/send",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"test",data:{message:"This is a test notification from DashCaddy."},type:"info"})})).json();I.success?(showNotification("Test notification sent!","success",3e3),H()):showNotification(`Test failed: ${I.results?.map(O=>`${O.provider}: ${O.error||"ok"}`).join(", ")}`,"error",5e3)}catch(E){showNotification(`Error: ${E.message}`,"error",3e3)}finally{k.textContent=$,k.disabled=!1}});async function H(){try{const $=await(await fetch("/api/v1/notifications/status")).json();if($.success&&$.lastSent){const E=document.getElementById("last-notification-sent");E&&(E.textContent=`Last sent: ${new Date($.lastSent).toLocaleString()}`)}}catch{}}wireModal(B,z)})(),(function(){document.addEventListener("click",w=>{const B=w.target.closest(".panel-tab");if(!B)return;const A=B.dataset.panel;if(!A)return;const S=B.closest(".panel-tabs"),z=S.closest(".weather-modal-content");S.querySelectorAll(".panel-tab").forEach(M=>M.classList.remove("active")),B.classList.add("active"),z.querySelectorAll(".panel-section").forEach(M=>M.classList.remove("active"));const P=z.querySelector("#"+A);P&&P.classList.add("active")})})(),(function(){var w=["dashcaddy_site_config","dashcaddy_onboarding","dashcaddy-encryption-key","dashcaddy-setup","dashcaddy-config","theme","user-themes","custom-theme","custom-apps","custom-services","toolbar-sections","weather-location","weather-zip","weather-geo","weather-unit","clock-style","clock-chimes","clock-chime-volume"];function B(){for(var e={},a=0;a

\u{1F4BE} Backup & Restore

- `);var P=document.getElementById("backup-modal"),z=document.getElementById("backup-restore-btn"),N=document.getElementById("backup-cancel"),f=document.getElementById("backup-export-btn"),L=document.getElementById("backup-select-file"),w=document.getElementById("backup-file-input"),$=document.getElementById("backup-file-name"),k=document.getElementById("backup-preview"),T=document.getElementById("backup-preview-content"),E=document.getElementById("backup-do-restore-btn"),I=document.getElementById("backup-result"),j=document.getElementById("backup-schedules-container"),H=document.getElementById("backup-history-container"),R=document.getElementById("backup-disk-container"),D=document.getElementById("pointintime-container"),O=null;z?.addEventListener("click",function(){P.classList.add("show"),I&&(I.style.display="none"),k&&(k.style.display="none"),$&&($.style.display="none"),O=null}),wireModal(P,N),f?.addEventListener("click",async function(){f.disabled=!0,f.innerHTML=' Exporting...';try{var e=await fetch("/api/v1/backup/export"),a=await e.json();a.browserState=B();var o=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),r=URL.createObjectURL(o),n=document.createElement("a");n.href=r,n.download="dashcaddy-backup-"+new Date().toISOString().split("T")[0]+".json",document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r);var i=Object.keys(a.browserState).length,d=a.themes?Object.keys(a.themes).length:0;I.innerHTML="\u2705 Full backup downloaded \u2014 server config + "+i+" browser settings"+(d?" + "+d+" themes":""),I.style.display="block",I.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",I.style.border="1px solid var(--ok-fg)"}catch(g){I.innerHTML="\u274C Export failed: "+escapeHtml(g.message),I.style.display="block",I.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",I.style.border="1px solid var(--bad-fg)"}f.disabled=!1,f.innerHTML="\u2B07\uFE0F Download Full Backup"}),L?.addEventListener("click",function(){w.click()}),w?.addEventListener("change",async function(e){var a=e.target.files[0];if(a){$.textContent="\u{1F4C4} "+a.name,$.style.display="block",I.style.display="none";try{var o=await a.text(),r=JSON.parse(o);if(C(r)){O=r;var n='
Legacy format (v'+escapeHtml(r.version)+")
";n+='
',r.services?.length&&(n+='\u{1F4CB} '+r.services.length+" services"),r.customApps?.length&&(n+='\u{1F4E6} '+r.customApps.length+" custom apps"),r.theme&&(n+='\u{1F3A8} Theme: '+escapeHtml(r.theme)+""),r.userThemes&&(n+='\u{1F3A8} '+Object.keys(r.userThemes).length+" custom themes"),n+="
",T.innerHTML=n,k.style.display="block";return}var i=await secureFetch("/api/v1/backup/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),d=await i.json();if(d.success){O=r;var n='
Exported: '+new Date(r.exportedAt).toLocaleString()+" (v"+escapeHtml(r.version)+")
";n+='
Server Config
',n+='
';for(var g in d.preview.files){var S=d.preview.files[g],U=S.action==="create"?"\u{1F195}":"\u{1F4DD}";n+=''+U+" "+escapeHtml(S.description)+""}n+="
",d.preview.serviceCount&&(n+='
'+d.preview.serviceCount+" services
"),d.preview.themeCount&&(n+='
\u{1F3A8} '+d.preview.themeCount+" custom themes
"),d.preview.browserStateCount&&(n+='
Browser Preferences
',n+='
\u{1F5A5}\uFE0F '+d.preview.browserStateCount+" saved settings (theme, weather, clock, widgets, etc.)
"),T.innerHTML=n,k.style.display="block"}else I.innerHTML="\u26A0\uFE0F Invalid backup file: "+escapeHtml(d.error),I.style.display="block",I.style.background="color-mix(in srgb, #f39c12 15%, transparent)",I.style.border="1px solid #f39c12",k.style.display="none"}catch(q){I.innerHTML="\u274C Could not read file: "+escapeHtml(q.message),I.style.display="block",I.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",I.style.border="1px solid var(--bad-fg)",k.style.display="none"}}}),E?.addEventListener("click",async function(){if(O&&confirm("This will overwrite your current configuration and browser preferences. Continue?")){E.disabled=!0,E.innerHTML=' Restoring...';try{if(C(O)){M(O),I.innerHTML="\u2705 Legacy backup restored \u2014 browser settings and services imported.",I.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",I.style.border="1px solid var(--ok-fg)",I.style.display="block",setTimeout(function(){location.reload()},2e3),E.disabled=!1,E.innerHTML="\u26A1 Restore Everything";return}var e=document.getElementById("backup-reload-caddy")?.checked??!0,a=await secureFetch("/api/v1/backup/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({backup:O,options:{reloadCaddy:e}})}),o=await a.json(),r=0;if(O.browserState&&(r=A(O.browserState)),o.success){var n="\u2705 "+o.message;r>0&&(n+='
'+r+" browser settings restored"),o.results.caddyReloaded&&(n+='
Caddy configuration reloaded'),I.innerHTML=n,I.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",I.style.border="1px solid var(--ok-fg)",setTimeout(function(){location.reload()},2e3)}else I.innerHTML="\u26A0\uFE0F "+escapeHtml(o.message),r>0&&(I.innerHTML+='
'+r+" browser settings were restored"),o.results?.errors?.length>0&&(I.innerHTML+="
"+o.results.errors.map(function(i){return escapeHtml(i.file)+": "+escapeHtml(i.error)}).join(", ")+""),I.style.background="color-mix(in srgb, #f39c12 15%, transparent)",I.style.border="1px solid #f39c12";I.style.display="block"}catch(i){I.innerHTML="\u274C Restore failed: "+escapeHtml(i.message),I.style.display="block",I.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",I.style.border="1px solid var(--bad-fg)"}E.disabled=!1,E.innerHTML="\u26A1 Restore Everything"}});async function p(){if(j){j.innerHTML='
Loading...
';try{var e=await fetch("/api/v1/backups/schedule"),a=await e.json();if(a.premiumRequired){j.innerHTML=`
\u2B50
Premium Feature
Auto-backup scheduling requires a DashCaddy Premium subscription.
`;return}if(!a.success)throw new Error(a.error||"Failed to load schedules");var o=a.schedules||[];if(o.length===0){j.innerHTML='
\u23F0
No backup schedules configured
Select apps below to enable auto-backup
';return}for(var r='
',n=0;n
Schedule:
Keep last:
Next run: '+escapeHtml(d)+"
Last run: "+escapeHtml(g)+'
'}r+="",r+='

\u2795 Add New Schedule

',j.innerHTML=r,j.querySelectorAll(".schedule-toggle").forEach(function(S){S.addEventListener("change",function(){v(S.dataset.appid,{enabled:S.checked})})}),j.querySelectorAll(".schedule-select").forEach(function(S){S.addEventListener("change",function(){v(S.dataset.appid,{schedule:S.value})})}),j.querySelectorAll(".retention-input").forEach(function(S){S.addEventListener("change",function(){v(S.dataset.appid,{retention:{keep:parseInt(S.value)||7}})})}),j.querySelectorAll(".schedule-run-now").forEach(function(S){S.addEventListener("click",function(){b(S.dataset.appid)})}),j.querySelectorAll(".schedule-delete").forEach(function(S){S.addEventListener("click",function(){y(S.dataset.appid)})}),document.getElementById("add-schedule-btn")?.addEventListener("click",h)}catch(S){j.innerHTML='
Failed to load: '+escapeHtml(S.message)+"
"}}}async function v(e,a){try{var o=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e,...a})}),r=await o.json();r.success?showNotification("Schedule updated for "+e,"success"):(showNotification("Update failed: "+(r.error||"Unknown"),"error"),p())}catch(n){showNotification("Error: "+n.message,"error")}}async function b(e){try{var a=await secureFetch("/api/v1/backups/backup/"+encodeURIComponent(e),{method:"POST",headers:{"Content-Type":"application/json"}}),o=await a.json();o.success?showNotification("Backup started for "+e+"!","success"):showNotification("Backup failed: "+(o.error||"Unknown"),"error")}catch(r){showNotification("Error: "+r.message,"error")}}async function y(e){if(confirm("Remove backup schedule for "+e+"?"))try{var a=await secureFetch("/api/v1/backups/schedule/"+encodeURIComponent(e),{method:"DELETE"}),o=await a.json();o.success?(showNotification("Schedule removed for "+e,"success"),p()):showNotification("Delete failed: "+(o.error||"Unknown"),"error")}catch(r){showNotification("Error: "+r.message,"error")}}async function h(){var e=document.getElementById("new-schedule-appid")?.value?.trim(),a=document.getElementById("new-schedule-interval")?.value||"daily",o=parseInt(document.getElementById("new-schedule-retention")?.value)||7;if(!e){showNotification("Please enter an App ID","warning");return}try{var r=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e,schedule:a,retention:{keep:o},enabled:!0})}),n=await r.json();if(n.success){showNotification("Schedule created for "+e,"success"),p();var i=document.getElementById("new-schedule-appid");i&&(i.value="")}else showNotification("Failed: "+(n.error||"Unknown"),"error")}catch(d){showNotification("Error: "+d.message,"error")}}async function s(){if(R){R.innerHTML='
Loading...
';try{var e=await fetch("/api/v1/backups/files"),a=await e.json();if(!a.success)throw new Error(a.error||"Failed to load");var o=a.files||[];if(o.length===0){R.innerHTML='
\u{1F4BE}
No backup files on disk
Run a backup to create backup files
';return}for(var r={},n=0;n";g+='
';for(var S=Object.keys(r).sort(),U=0;U
'+escapeHtml(d)+' ('+q.length+" backup(s))
";for(var F=0;F
'+i.sizeFormatted+'
'+_+'
'}g+=""}g+="",R.innerHTML=g,R.querySelectorAll(".disk-compare-btn").forEach(function(J){J.addEventListener("click",function(){u(J.dataset.appid,J.dataset.filename)})}),R.querySelectorAll(".disk-restore-btn").forEach(function(J){J.addEventListener("click",function(){t(J.dataset.appid,J.dataset.filename)})})}catch(J){R.innerHTML='
Failed: '+escapeHtml(J.message)+"
"}}}async function c(){if(H){H.innerHTML='
Loading...
';try{var e=await fetch("/api/v1/backups/history?limit=50"),a=await e.json();if(!a.success||!a.history?.length){H.innerHTML='
\u{1F4CB} No backup history yet
';return}for(var o='
',r=0;r',o+='
',o+=' '+escapeHtml(n.name||"backup")+"",o+='
',o+=' '+escapeHtml(n.status)+"",n.status==="success"&&(o+=' '),o+="
",o+="
",o+='
',o+=" "+new Date(n.timestamp).toLocaleString()+" | "+i+" MB | "+(n.duration?(n.duration/1e3).toFixed(1)+"s":"--"),n.encrypted&&(o+=" | \u{1F512}"),o+="
",o+="
"}o+="",H.innerHTML=o,H.querySelectorAll(".backup-restore-btn").forEach(function(d){d.addEventListener("click",function(){window.__restoreServerBackup(d.dataset.backupId)})})}catch(d){H.innerHTML='
Failed: '+escapeHtml(d.message)+"
"}}}window.__restoreServerBackup=async function(e){if(confirm("Restore from this server backup? This will overwrite current configuration."))try{var a=await secureFetch("/api/v1/backups/restore/"+e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restoreServices:!0,restoreConfig:!0})}),o=await a.json();o.success?(showNotification("Restore completed successfully!","success"),location.reload()):showNotification("Restore failed: "+(o.error||"Unknown error"),"error")}catch(r){showNotification("Restore error: "+r.message,"error")}},document.querySelector('[data-panel="backup-schedules-tab"]')?.addEventListener("click",p),document.querySelector('[data-panel="backup-disk-tab"]')?.addEventListener("click",s),document.querySelector('[data-panel="backup-pointintime-tab"]')?.addEventListener("click",l),document.querySelector('[data-panel="backup-history-tab"]')?.addEventListener("click",c);async function l(){if(D){try{var e=await fetch("/api/v1/license/status"),a=await e.json();if(a.tier!=="premium"){D.innerHTML=`
\u2B50
Premium Feature
Point-in-time restore requires DashCaddy Premium with auto-backup enabled.
`;return}}catch{}D.innerHTML='
Loading...
';try{var o=await fetch("/api/v1/services"),r=await o.json(),n=r.services||[];if(n.length===0){D.innerHTML='
\u{1F4E6} No apps deployed yet
';return}for(var i='
',D.innerHTML=i,document.getElementById("pit-load-btn")?.addEventListener("click",function(){var g=document.getElementById("pit-app-select")?.value;g&&m(g)})}catch(g){D.innerHTML='
Failed: '+escapeHtml(g.message)+"
"}}}async function m(e){var a=document.getElementById("pit-backups-list");if(a){a.innerHTML='
Loading backups...
';try{var o=await fetch("/api/v1/backups/files/"+encodeURIComponent(e)),r=await o.json();if(!r.success||!r.files||r.files.length===0){a.innerHTML='
\u{1F4BE} No backup files for '+escapeHtml(e)+"
";return}for(var n='
'+r.files.length+' backup(s)
',i=0;i
'+d.sizeFormatted+'
'+g+'
'}n+="",a.innerHTML=n,a.querySelectorAll(".pit-compare-btn").forEach(function(S){S.addEventListener("click",function(){u(S.dataset.appid,S.dataset.filename)})}),a.querySelectorAll(".pit-restore-btn").forEach(function(S){S.addEventListener("click",function(){t(S.dataset.appid,S.dataset.filename)})})}catch(S){a.innerHTML='
Failed: '+escapeHtml(S.message)+"
"}}}async function u(e,a){try{var o=await secureFetch("/api/v1/backups/compare/"+encodeURIComponent(a),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})}),r=await o.json();if(!r.success){showNotification("Compare failed: "+(r.error||"Unknown"),"error");return}var n=r.diff,i='

\u{1F4CA} Compare: '+escapeHtml(a)+'

Size: '+(n.sizeFormatted||"?")+" | Created: "+new Date(n.timestamp).toLocaleString()+"
";if(n.services){var d=n.services.hasChanges?"\u{1F534}":"\u{1F7E2}";i+='
'+d+' Services (backup vs current)
Backup: '+n.services.backupCount+" services | Current: "+n.services.currentCount+" services
",n.services.hasChanges&&(i+='
Services differ \u2014 restoring will replace current configuration
'),i+="
"}if(n.config){var g=n.config.hasChanges?"\u{1F534}":"\u{1F7E2}";i+='
'+g+" Configuration
",n.config.hasChanges?i+='
Configuration differs \u2014 restoring will replace current settings
':i+='
No changes
',i+="
"}i+='
',document.body.insertAdjacentHTML("beforeend",i),document.getElementById("compare-close-btn")?.addEventListener("click",function(){document.getElementById("compare-overlay")?.remove()}),document.getElementById("compare-overlay")?.addEventListener("click",function(S){S.target===this&&this.remove()})}catch(S){showNotification("Compare error: "+S.message,"error")}}async function t(e,a){if(confirm("Restore "+a+" for "+e+`? + `);var P=document.getElementById("backup-modal"),M=document.getElementById("backup-restore-btn"),D=document.getElementById("backup-cancel"),h=document.getElementById("backup-export-btn"),T=document.getElementById("backup-select-file"),f=document.getElementById("backup-file-input"),H=document.getElementById("backup-file-name"),k=document.getElementById("backup-preview"),$=document.getElementById("backup-preview-content"),E=document.getElementById("backup-do-restore-btn"),I=document.getElementById("backup-result"),O=document.getElementById("backup-schedules-container"),C=document.getElementById("backup-history-container"),j=document.getElementById("backup-disk-container"),N=document.getElementById("pointintime-container"),R=null;M?.addEventListener("click",function(){P.classList.add("show"),I&&(I.style.display="none"),k&&(k.style.display="none"),H&&(H.style.display="none"),R=null}),wireModal(P,D),h?.addEventListener("click",async function(){h.disabled=!0,h.innerHTML=' Exporting...';try{var e=await fetch("/api/v1/backup/export"),a=await e.json();a.browserState=B();var o=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),i=URL.createObjectURL(o),n=document.createElement("a");n.href=i,n.download="dashcaddy-backup-"+new Date().toISOString().split("T")[0]+".json",document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(i);var r=Object.keys(a.browserState).length,d=a.themes?Object.keys(a.themes).length:0;I.innerHTML="\u2705 Full backup downloaded \u2014 server config + "+r+" browser settings"+(d?" + "+d+" themes":""),I.style.display="block",I.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",I.style.border="1px solid var(--ok-fg)"}catch(y){I.innerHTML="\u274C Export failed: "+escapeHtml(y.message),I.style.display="block",I.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",I.style.border="1px solid var(--bad-fg)"}h.disabled=!1,h.innerHTML="\u2B07\uFE0F Download Full Backup"}),T?.addEventListener("click",function(){f.click()}),f?.addEventListener("change",async function(e){var a=e.target.files[0];if(a){H.textContent="\u{1F4C4} "+a.name,H.style.display="block",I.style.display="none";try{var o=await a.text(),i=JSON.parse(o);if(S(i)){R=i;var n='
Legacy format (v'+escapeHtml(i.version)+")
";n+='
',i.services?.length&&(n+='\u{1F4CB} '+i.services.length+" services"),i.customApps?.length&&(n+='\u{1F4E6} '+i.customApps.length+" custom apps"),i.theme&&(n+='\u{1F3A8} Theme: '+escapeHtml(i.theme)+""),i.userThemes&&(n+='\u{1F3A8} '+Object.keys(i.userThemes).length+" custom themes"),n+="
",$.innerHTML=n,k.style.display="block";return}var r=await secureFetch("/api/v1/backup/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),d=await r.json();if(d.success){R=i;var n='
Exported: '+new Date(i.exportedAt).toLocaleString()+" (v"+escapeHtml(i.version)+")
";n+='
Server Config
',n+='
';for(var y in d.preview.files){var L=d.preview.files[y],U=L.action==="create"?"\u{1F195}":"\u{1F4DD}";n+=''+U+" "+escapeHtml(L.description)+""}n+="
",d.preview.serviceCount&&(n+='
'+d.preview.serviceCount+" services
"),d.preview.themeCount&&(n+='
\u{1F3A8} '+d.preview.themeCount+" custom themes
"),d.preview.browserStateCount&&(n+='
Browser Preferences
',n+='
\u{1F5A5}\uFE0F '+d.preview.browserStateCount+" saved settings (theme, weather, clock, widgets, etc.)
"),$.innerHTML=n,k.style.display="block"}else I.innerHTML="\u26A0\uFE0F Invalid backup file: "+escapeHtml(d.error),I.style.display="block",I.style.background="color-mix(in srgb, #f39c12 15%, transparent)",I.style.border="1px solid #f39c12",k.style.display="none"}catch(q){I.innerHTML="\u274C Could not read file: "+escapeHtml(q.message),I.style.display="block",I.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",I.style.border="1px solid var(--bad-fg)",k.style.display="none"}}}),E?.addEventListener("click",async function(){if(R&&confirm("This will overwrite your current configuration and browser preferences. Continue?")){E.disabled=!0,E.innerHTML=' Restoring...';try{if(S(R)){z(R),I.innerHTML="\u2705 Legacy backup restored \u2014 browser settings and services imported.",I.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",I.style.border="1px solid var(--ok-fg)",I.style.display="block",setTimeout(function(){location.reload()},2e3),E.disabled=!1,E.innerHTML="\u26A1 Restore Everything";return}var e=document.getElementById("backup-reload-caddy")?.checked??!0,a=await secureFetch("/api/v1/backup/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({backup:R,options:{reloadCaddy:e}})}),o=await a.json(),i=0;if(R.browserState&&(i=A(R.browserState)),o.success){var n="\u2705 "+o.message;i>0&&(n+='
'+i+" browser settings restored"),o.results.caddyReloaded&&(n+='
Caddy configuration reloaded'),I.innerHTML=n,I.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",I.style.border="1px solid var(--ok-fg)",setTimeout(function(){location.reload()},2e3)}else I.innerHTML="\u26A0\uFE0F "+escapeHtml(o.message),i>0&&(I.innerHTML+='
'+i+" browser settings were restored"),o.results?.errors?.length>0&&(I.innerHTML+="
"+o.results.errors.map(function(r){return escapeHtml(r.file)+": "+escapeHtml(r.error)}).join(", ")+""),I.style.background="color-mix(in srgb, #f39c12 15%, transparent)",I.style.border="1px solid #f39c12";I.style.display="block"}catch(r){I.innerHTML="\u274C Restore failed: "+escapeHtml(r.message),I.style.display="block",I.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",I.style.border="1px solid var(--bad-fg)"}E.disabled=!1,E.innerHTML="\u26A1 Restore Everything"}});async function u(){if(O){O.innerHTML='
Loading...
';try{var e=await fetch("/api/v1/backups/schedule"),a=await e.json();if(a.premiumRequired){O.innerHTML=`
\u2B50
Premium Feature
Auto-backup scheduling requires a DashCaddy Premium subscription.
`;return}if(!a.success)throw new Error(a.error||"Failed to load schedules");var o=a.schedules||[];if(o.length===0){O.innerHTML='
\u23F0
No backup schedules configured
Select apps below to enable auto-backup
';return}for(var i='
',n=0;n
Schedule:
Keep last:
Next run: '+escapeHtml(d)+"
Last run: "+escapeHtml(y)+'
'}i+="",i+='

\u2795 Add New Schedule

',O.innerHTML=i,O.querySelectorAll(".schedule-toggle").forEach(function(L){L.addEventListener("change",function(){v(L.dataset.appid,{enabled:L.checked})})}),O.querySelectorAll(".schedule-select").forEach(function(L){L.addEventListener("change",function(){v(L.dataset.appid,{schedule:L.value})})}),O.querySelectorAll(".retention-input").forEach(function(L){L.addEventListener("change",function(){v(L.dataset.appid,{retention:{keep:parseInt(L.value)||7}})})}),O.querySelectorAll(".schedule-run-now").forEach(function(L){L.addEventListener("click",function(){x(L.dataset.appid)})}),O.querySelectorAll(".schedule-delete").forEach(function(L){L.addEventListener("click",function(){g(L.dataset.appid)})}),document.getElementById("add-schedule-btn")?.addEventListener("click",b)}catch(L){O.innerHTML='
Failed to load: '+escapeHtml(L.message)+"
"}}}async function v(e,a){try{var o=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e,...a})}),i=await o.json();i.success?showNotification("Schedule updated for "+e,"success"):(showNotification("Update failed: "+(i.error||"Unknown"),"error"),u())}catch(n){showNotification("Error: "+n.message,"error")}}async function x(e){try{var a=await secureFetch("/api/v1/backups/backup/"+encodeURIComponent(e),{method:"POST",headers:{"Content-Type":"application/json"}}),o=await a.json();o.success?showNotification("Backup started for "+e+"!","success"):showNotification("Backup failed: "+(o.error||"Unknown"),"error")}catch(i){showNotification("Error: "+i.message,"error")}}async function g(e){if(confirm("Remove backup schedule for "+e+"?"))try{var a=await secureFetch("/api/v1/backups/schedule/"+encodeURIComponent(e),{method:"DELETE"}),o=await a.json();o.success?(showNotification("Schedule removed for "+e,"success"),u()):showNotification("Delete failed: "+(o.error||"Unknown"),"error")}catch(i){showNotification("Error: "+i.message,"error")}}async function b(){var e=document.getElementById("new-schedule-appid")?.value?.trim(),a=document.getElementById("new-schedule-interval")?.value||"daily",o=parseInt(document.getElementById("new-schedule-retention")?.value)||7;if(!e){showNotification("Please enter an App ID","warning");return}try{var i=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e,schedule:a,retention:{keep:o},enabled:!0})}),n=await i.json();if(n.success){showNotification("Schedule created for "+e,"success"),u();var r=document.getElementById("new-schedule-appid");r&&(r.value="")}else showNotification("Failed: "+(n.error||"Unknown"),"error")}catch(d){showNotification("Error: "+d.message,"error")}}async function s(){if(j){j.innerHTML='
Loading...
';try{var e=await fetch("/api/v1/backups/files"),a=await e.json();if(!a.success)throw new Error(a.error||"Failed to load");var o=a.files||[];if(o.length===0){j.innerHTML='
\u{1F4BE}
No backup files on disk
Run a backup to create backup files
';return}for(var i={},n=0;n";y+='
';for(var L=Object.keys(i).sort(),U=0;U
'+escapeHtml(d)+' ('+q.length+" backup(s))
";for(var F=0;F
'+r.sizeFormatted+'
'+_+'
'}y+=""}y+="",j.innerHTML=y,j.querySelectorAll(".disk-compare-btn").forEach(function(J){J.addEventListener("click",function(){c(J.dataset.appid,J.dataset.filename)})}),j.querySelectorAll(".disk-restore-btn").forEach(function(J){J.addEventListener("click",function(){t(J.dataset.appid,J.dataset.filename)})})}catch(J){j.innerHTML='
Failed: '+escapeHtml(J.message)+"
"}}}async function p(){if(C){C.innerHTML='
Loading...
';try{var e=await fetch("/api/v1/backups/history?limit=50"),a=await e.json();if(!a.success||!a.history?.length){C.innerHTML='
\u{1F4CB} No backup history yet
';return}for(var o='
',i=0;i',o+='
',o+=' '+escapeHtml(n.name||"backup")+"",o+='
',o+=' '+escapeHtml(n.status)+"",n.status==="success"&&(o+=' '),o+="
",o+="
",o+='
',o+=" "+new Date(n.timestamp).toLocaleString()+" | "+r+" MB | "+(n.duration?(n.duration/1e3).toFixed(1)+"s":"--"),n.encrypted&&(o+=" | \u{1F512}"),o+="
",o+="
"}o+="",C.innerHTML=o,C.querySelectorAll(".backup-restore-btn").forEach(function(d){d.addEventListener("click",function(){window.__restoreServerBackup(d.dataset.backupId)})})}catch(d){C.innerHTML='
Failed: '+escapeHtml(d.message)+"
"}}}window.__restoreServerBackup=async function(e){if(confirm("Restore from this server backup? This will overwrite current configuration."))try{var a=await secureFetch("/api/v1/backups/restore/"+e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restoreServices:!0,restoreConfig:!0})}),o=await a.json();o.success?(showNotification("Restore completed successfully!","success"),location.reload()):showNotification("Restore failed: "+(o.error||"Unknown error"),"error")}catch(i){showNotification("Restore error: "+i.message,"error")}},document.querySelector('[data-panel="backup-schedules-tab"]')?.addEventListener("click",u),document.querySelector('[data-panel="backup-disk-tab"]')?.addEventListener("click",s),document.querySelector('[data-panel="backup-pointintime-tab"]')?.addEventListener("click",l),document.querySelector('[data-panel="backup-history-tab"]')?.addEventListener("click",p);async function l(){if(N){try{var e=await fetch("/api/v1/license/status"),a=await e.json();if(a.tier!=="premium"){N.innerHTML=`
\u2B50
Premium Feature
Point-in-time restore requires DashCaddy Premium with auto-backup enabled.
`;return}}catch{}N.innerHTML='
Loading...
';try{var o=await fetch("/api/v1/services"),i=await o.json(),n=i.services||[];if(n.length===0){N.innerHTML='
\u{1F4E6} No apps deployed yet
';return}for(var r='
',N.innerHTML=r,document.getElementById("pit-load-btn")?.addEventListener("click",function(){var y=document.getElementById("pit-app-select")?.value;y&&m(y)})}catch(y){N.innerHTML='
Failed: '+escapeHtml(y.message)+"
"}}}async function m(e){var a=document.getElementById("pit-backups-list");if(a){a.innerHTML='
Loading backups...
';try{var o=await fetch("/api/v1/backups/files/"+encodeURIComponent(e)),i=await o.json();if(!i.success||!i.files||i.files.length===0){a.innerHTML='
\u{1F4BE} No backup files for '+escapeHtml(e)+"
";return}for(var n='
'+i.files.length+' backup(s)
',r=0;r
'+d.sizeFormatted+'
'+y+'
'}n+="",a.innerHTML=n,a.querySelectorAll(".pit-compare-btn").forEach(function(L){L.addEventListener("click",function(){c(L.dataset.appid,L.dataset.filename)})}),a.querySelectorAll(".pit-restore-btn").forEach(function(L){L.addEventListener("click",function(){t(L.dataset.appid,L.dataset.filename)})})}catch(L){a.innerHTML='
Failed: '+escapeHtml(L.message)+"
"}}}async function c(e,a){try{var o=await secureFetch("/api/v1/backups/compare/"+encodeURIComponent(a),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})}),i=await o.json();if(!i.success){showNotification("Compare failed: "+(i.error||"Unknown"),"error");return}var n=i.diff,r='

\u{1F4CA} Compare: '+escapeHtml(a)+'

Size: '+(n.sizeFormatted||"?")+" | Created: "+new Date(n.timestamp).toLocaleString()+"
";if(n.services){var d=n.services.hasChanges?"\u{1F534}":"\u{1F7E2}";r+='
'+d+' Services (backup vs current)
Backup: '+n.services.backupCount+" services | Current: "+n.services.currentCount+" services
",n.services.hasChanges&&(r+='
Services differ \u2014 restoring will replace current configuration
'),r+="
"}if(n.config){var y=n.config.hasChanges?"\u{1F534}":"\u{1F7E2}";r+='
'+y+" Configuration
",n.config.hasChanges?r+='
Configuration differs \u2014 restoring will replace current settings
':r+='
No changes
',r+="
"}r+='
',document.body.insertAdjacentHTML("beforeend",r),document.getElementById("compare-close-btn")?.addEventListener("click",function(){document.getElementById("compare-overlay")?.remove()}),document.getElementById("compare-overlay")?.addEventListener("click",function(L){L.target===this&&this.remove()})}catch(L){showNotification("Compare error: "+L.message,"error")}}async function t(e,a){if(confirm("Restore "+a+" for "+e+`? -This will replace current configuration, credentials, and data. Containers will be restarted.`))try{var o=await secureFetch("/api/v1/apps/"+encodeURIComponent(e)+"/revert/"+encodeURIComponent(a),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restartContainers:!0})}),r=await o.json();r.success?(showNotification(e+" restored to "+a,"success"),setTimeout(function(){location.reload()},1500)):showNotification("Restore failed: "+(r.error||"Unknown"),"error")}catch(n){showNotification("Restore error: "+n.message,"error")}}})(),(function(){injectModal("stats-modal",`
+This will replace current configuration, credentials, and data. Containers will be restarted.`))try{var o=await secureFetch("/api/v1/apps/"+encodeURIComponent(e)+"/revert/"+encodeURIComponent(a),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restartContainers:!0})}),i=await o.json();i.success?(showNotification(e+" restored to "+a,"success"),setTimeout(function(){location.reload()},1500)):showNotification("Restore failed: "+(i.error||"Unknown"),"error")}catch(n){showNotification("Restore error: "+n.message,"error")}}})(),(function(){injectModal("stats-modal",`

\u{1F4CA} Resource Monitor

-
`);const x=document.getElementById("stats-modal"),B=document.getElementById("container-stats-btn"),A=document.getElementById("stats-cancel"),C=document.getElementById("stats-refresh-btn"),M=document.getElementById("stats-auto-refresh"),P=document.getElementById("stats-container"),z=document.getElementById("stats-aggregated-container"),N=document.getElementById("stats-alerts-container"),f=document.getElementById("stats-last-update");let L=null,w=null;function $(l){if(l===0||!l)return"0 B";const m=1024,u=["B","KB","MB","GB"],t=Math.floor(Math.log(l)/Math.log(m));return parseFloat((l/Math.pow(m,t)).toFixed(1))+" "+u[t]}function k(l){return l<30?"#2ecc71":l<70?"#f39c12":"#e74c3c"}function T(l){return l<50?"#2ecc71":l<80?"#f39c12":"#e74c3c"}async function E(){try{let l=null,m=!1;try{const e=await(await fetch("/api/v1/monitoring/stats")).json();e.success&&e.stats&&(l=e.stats,m=!0,w=e.stats)}catch{}if(!m){const e=await(await fetch("/api/v1/stats/containers")).json();if(e.success&&e.stats){l={};for(const a of e.stats)l[a.name]={name:a.name,current:{cpu:a.cpu,memory:{percent:a.memory.percent,usage:a.memory.used,limit:a.memory.limit,usageMB:Math.round(a.memory.used/1048576),limitMB:Math.round(a.memory.limit/1048576)},network:{rxBytes:a.network.rx,txBytes:a.network.tx,rxMB:(a.network.rx/1048576).toFixed(1),txMB:(a.network.tx/1048576).toFixed(1)},disk:{readMB:0,writeMB:0}},status:a.status};w=l}}if(!l||Object.keys(l).length===0){P.innerHTML='
No running containers found
';return}let u='
';for(const[t,e]of Object.entries(l)){const a=e.current||e,o=a.cpu?.percent||0,r=a.memory?.percent||0,n=k(o),i=T(r),d=a.memory?.usage||a.memory?.used||0,g=a.memory?.limit||0,S=a.network?.rxBytes||a.network?.rx||0,U=a.network?.txBytes||a.network?.tx||0,q=e.aggregated;u+=` +
`);const w=document.getElementById("stats-modal"),B=document.getElementById("container-stats-btn"),A=document.getElementById("stats-cancel"),S=document.getElementById("stats-refresh-btn"),z=document.getElementById("stats-auto-refresh"),P=document.getElementById("stats-container"),M=document.getElementById("stats-aggregated-container"),D=document.getElementById("stats-alerts-container"),h=document.getElementById("stats-last-update");let T=null,f=null;function H(l){if(l===0||!l)return"0 B";const m=1024,c=["B","KB","MB","GB"],t=Math.floor(Math.log(l)/Math.log(m));return parseFloat((l/Math.pow(m,t)).toFixed(1))+" "+c[t]}function k(l){return l<30?"#2ecc71":l<70?"#f39c12":"#e74c3c"}function $(l){return l<50?"#2ecc71":l<80?"#f39c12":"#e74c3c"}async function E(){try{let l=null,m=!1;try{const e=await(await fetch("/api/v1/monitoring/stats")).json();e.success&&e.stats&&(l=e.stats,m=!0,f=e.stats)}catch{}if(!m){const e=await(await fetch("/api/v1/stats/containers")).json();if(e.success&&e.stats){l={};for(const a of e.stats)l[a.name]={name:a.name,current:{cpu:a.cpu,memory:{percent:a.memory.percent,usage:a.memory.used,limit:a.memory.limit,usageMB:Math.round(a.memory.used/1048576),limitMB:Math.round(a.memory.limit/1048576)},network:{rxBytes:a.network.rx,txBytes:a.network.tx,rxMB:(a.network.rx/1048576).toFixed(1),txMB:(a.network.tx/1048576).toFixed(1)},disk:{readMB:0,writeMB:0}},status:a.status};f=l}}if(!l||Object.keys(l).length===0){P.innerHTML='
No running containers found
';return}let c='
';for(const[t,e]of Object.entries(l)){const a=e.current||e,o=a.cpu?.percent||0,i=a.memory?.percent||0,n=k(o),r=$(i),d=a.memory?.usage||a.memory?.used||0,y=a.memory?.limit||0,L=a.network?.rxBytes||a.network?.rx||0,U=a.network?.txBytes||a.network?.tx||0,q=e.aggregated;c+=`
${e.name||t} @@ -1256,23 +1299,23 @@ This will replace current configuration, credentials, and data. Containers will
Memory
-
+
- ${r.toFixed(1)}% + ${i.toFixed(1)}%
-
${$(d)} / ${$(g)}
+
${H(d)} / ${H(y)}
Network
- \u2193 ${$(S)} + \u2193 ${H(L)} / - \u2191 ${$(U)} + \u2191 ${H(U)}
-
`}u+="",P.innerHTML=u,f.textContent="Updated: "+new Date().toLocaleTimeString()}catch(l){P.innerHTML=`
\u274C Failed to load stats: ${escapeHtml(l.message)}
`}}async function I(){if(!z)return;const l=w;if(!l||Object.keys(l).length===0){z.innerHTML='
\u{1F4C8}No monitoring data available. Open the Live Stats tab first.
';return}let m='
';for(const[u,t]of Object.entries(l)){const e=t.aggregated;e&&(m+=`
-
${t.name||u}
+
`}c+="
",P.innerHTML=c,h.textContent="Updated: "+new Date().toLocaleTimeString()}catch(l){P.innerHTML=`
\u274C Failed to load stats: ${escapeHtml(l.message)}
`}}async function I(){if(!M)return;const l=f;if(!l||Object.keys(l).length===0){M.innerHTML='
\u{1F4C8}No monitoring data available. Open the Live Stats tab first.
';return}let m='
';for(const[c,t]of Object.entries(l)){const e=t.aggregated;e&&(m+=`
+
${t.name||c}
${e.cpu?.avg?.toFixed(1)||0}%Avg CPU
${e.cpu?.max?.toFixed(1)||0}%Max CPU
@@ -1280,27 +1323,27 @@ This will replace current configuration, credentials, and data. Containers will
${e.memory?.max?.toFixed(1)||0}%Max Mem
${e.dataPoints?`
${e.dataPoints} data points over ${e.timeRange||24}h
`:""} -
`)}m+="
",z.innerHTML=m}async function j(){if(!N)return;N.innerHTML='
Loading alerts...
';const l=w;if(!l||Object.keys(l).length===0){N.innerHTML='
\u{1F514}No containers found. Open the Live Stats tab first.
';return}let m=!1;try{m=(await(await fetch("/api/v1/license/feature/resource-alerts")).json()).available}catch{m=!1}let u=[];try{const i=await(await fetch("/api/v1/monitoring/alerts?limit=50")).json();i.success&&(u=i.history||[])}catch{}let t={};try{const i=await(await fetch("/api/v1/monitoring/alerts/config")).json();i.success&&(t=i.configs||{})}catch{}const a=Object.entries(l).map(([n,i])=>{const d=t[n]||{cpuThreshold:80,memoryThreshold:90,diskIOThreshold:50,autoRestart:!1,enabled:!1};return` + `)}m+="",M.innerHTML=m}async function O(){if(!D)return;D.innerHTML='
Loading alerts...
';const l=f;if(!l||Object.keys(l).length===0){D.innerHTML='
\u{1F514}No containers found. Open the Live Stats tab first.
';return}let m=!1;try{m=(await(await fetch("/api/v1/license/feature/resource-alerts")).json()).available}catch{m=!1}let c=[];try{const r=await(await fetch("/api/v1/monitoring/alerts?limit=50")).json();r.success&&(c=r.history||[])}catch{}let t={};try{const r=await(await fetch("/api/v1/monitoring/alerts/config")).json();r.success&&(t=r.configs||{})}catch{}const a=Object.entries(l).map(([n,r])=>{const d=t[n]||{cpuThreshold:80,memoryThreshold:90,diskIOThreshold:50,autoRestart:!1,enabled:!1};return` - ${i.name||n} + ${r.name||n} - + - `}).join(""),o=u.map(n=>{const i=new Date(n.timestamp).toLocaleString(),d=n.notified?"\u2713":"\u2014";return` + `}).join(""),o=c.map(n=>{const r=new Date(n.timestamp).toLocaleString(),d=n.notified?"\u2713":"\u2014";return` - ${i} + ${r} ${n.containerName||n.containerId} ${n.metric||n.type} ${typeof n.value=="number"?n.value.toFixed(1):n.value}${n.metric==="disk"?" MB/s":"%"} ${d} ${n.autoRestartTriggered?"\u21BB":""} - `}).join(""),r=m?` + `}).join(""),i=m?`

\u2699\uFE0F Alert Configuration

@@ -1331,8 +1374,8 @@ This will replace current configuration, credentials, and data. Containers will

Upgrade to configure resource alert thresholds per container.

- `;N.innerHTML=` - ${r} + `;D.innerHTML=` + ${i}

\u{1F4CB} Recent Alerts

${o?` @@ -1353,21 +1396,21 @@ This will replace current configuration, credentials, and data. Containers will
`:'
No alerts recorded yet.
'}
- `,document.getElementById("save-all-alerts")?.addEventListener("click",async()=>{const n={};document.querySelectorAll("#stats-alerts-container tr[data-container]").forEach(i=>{const d=i.dataset.container;n[d]={cpuThreshold:parseInt(i.querySelector(".alert-cpu")?.value)||80,memoryThreshold:parseInt(i.querySelector(".alert-mem")?.value)||90,diskIOThreshold:parseInt(i.querySelector(".alert-disk")?.value)||50,autoRestart:!!i.querySelector(".alert-autorestart")?.checked,enabled:!0}});try{const d=await(await secureFetch("/api/v1/monitoring/alerts/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:n})})).json(),g=document.getElementById("save-all-alerts");g.textContent=d.success?"\u2705 Saved":"\u274C Failed",setTimeout(()=>{g.textContent="Save All"},2e3)}catch{const d=document.getElementById("save-all-alerts");d.textContent="\u274C Error",setTimeout(()=>{d.textContent="Save All"},2e3)}}),document.getElementById("go-to-notifications")?.addEventListener("click",n=>{n.preventDefault(),x.classList.remove("show"),R(),document.getElementById("manage-notifications")?.click()}),document.querySelectorAll(".alert-test-btn").forEach(n=>{n.addEventListener("click",async()=>{const i=n.textContent;n.textContent="...";try{await secureFetch(`/api/v1/monitoring/alerts/${n.dataset.container}/test`,{method:"POST"}),n.textContent="\u2705",showNotification("Test alert sent for "+n.dataset.name,"success",3e3)}catch{n.textContent="\u274C"}setTimeout(()=>{n.textContent=i},2e3)})}),document.getElementById("upgrade-for-alerts")?.addEventListener("click",()=>{x.classList.remove("show"),R(),typeof openLicenseModal=="function"&&openLicenseModal()})}function H(){L&&clearInterval(L),M?.checked&&(L=setInterval(E,DC.POLL.STATS))}function R(){L&&(clearInterval(L),L=null)}B?.addEventListener("click",()=>{x.classList.add("show"),E(),H()}),A?.addEventListener("click",()=>{x.classList.remove("show"),R()}),x?.addEventListener("click",l=>{l.target===x&&(x.classList.remove("show"),R())}),C?.addEventListener("click",E),M?.addEventListener("change",()=>{M.checked?H():R()}),document.querySelector('[data-panel="stats-aggregated"]')?.addEventListener("click",I),document.querySelector('[data-panel="stats-alerts"]')?.addEventListener("click",j);const D=document.getElementById("stats-history-container"),O=document.getElementById("stats-history-container-area"),p=document.querySelectorAll(".stats-range-btn");let v="1h";function b(l){switch(l){case"1h":return 3600*1e3;case"24h":return 1440*60*1e3;case"7d":return 10080*60*1e3;case"30d":return 720*60*60*1e3;case"1y":return 365*24*60*60*1e3;default:return 3600*1e3}}function y(l){return l==="raw"?"live (10s samples)":l==="hourly"?"hourly average":l==="daily"?"daily average":l}function h(l,m,u,t,e){if(!l||l.length===0)return`
No data for ${escapeHtml(t)}
`;const a=l.map(m).filter(_=>_!=null);if(a.length===0)return`
No data for ${escapeHtml(t)}
`;const o=Math.max(...a,1),r=Math.min(...a,0),n=o-r||1,i=600,d=80,g=4,S=(i-g*2)/Math.max(a.length-1,1),U=a.map((_,J)=>{const X=g+J*S,Q=d-g-(_-r)/n*(d-g*2);return`${X.toFixed(1)},${Q.toFixed(1)}`}).join(" "),q=a[a.length-1],F=a.reduce((_,J)=>_+J,0)/a.length;return` + `,document.getElementById("save-all-alerts")?.addEventListener("click",async()=>{const n={};document.querySelectorAll("#stats-alerts-container tr[data-container]").forEach(r=>{const d=r.dataset.container;n[d]={cpuThreshold:parseInt(r.querySelector(".alert-cpu")?.value)||80,memoryThreshold:parseInt(r.querySelector(".alert-mem")?.value)||90,diskIOThreshold:parseInt(r.querySelector(".alert-disk")?.value)||50,autoRestart:!!r.querySelector(".alert-autorestart")?.checked,enabled:!0}});try{const d=await(await secureFetch("/api/v1/monitoring/alerts/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:n})})).json(),y=document.getElementById("save-all-alerts");y.textContent=d.success?"\u2705 Saved":"\u274C Failed",setTimeout(()=>{y.textContent="Save All"},2e3)}catch{const d=document.getElementById("save-all-alerts");d.textContent="\u274C Error",setTimeout(()=>{d.textContent="Save All"},2e3)}}),document.getElementById("go-to-notifications")?.addEventListener("click",n=>{n.preventDefault(),w.classList.remove("show"),j(),document.getElementById("manage-notifications")?.click()}),document.querySelectorAll(".alert-test-btn").forEach(n=>{n.addEventListener("click",async()=>{const r=n.textContent;n.textContent="...";try{await secureFetch(`/api/v1/monitoring/alerts/${n.dataset.container}/test`,{method:"POST"}),n.textContent="\u2705",showNotification("Test alert sent for "+n.dataset.name,"success",3e3)}catch{n.textContent="\u274C"}setTimeout(()=>{n.textContent=r},2e3)})}),document.getElementById("upgrade-for-alerts")?.addEventListener("click",()=>{w.classList.remove("show"),j(),typeof openLicenseModal=="function"&&openLicenseModal()})}function C(){T&&clearInterval(T),z?.checked&&(T=setInterval(E,DC.POLL.STATS))}function j(){T&&(clearInterval(T),T=null)}B?.addEventListener("click",()=>{w.classList.add("show"),E(),C()}),A?.addEventListener("click",()=>{w.classList.remove("show"),j()}),w?.addEventListener("click",l=>{l.target===w&&(w.classList.remove("show"),j())}),S?.addEventListener("click",E),z?.addEventListener("change",()=>{z.checked?C():j()}),document.querySelector('[data-panel="stats-aggregated"]')?.addEventListener("click",I),document.querySelector('[data-panel="stats-alerts"]')?.addEventListener("click",O);const N=document.getElementById("stats-history-container"),R=document.getElementById("stats-history-container-area"),u=document.querySelectorAll(".stats-range-btn");let v="1h";function x(l){switch(l){case"1h":return 3600*1e3;case"24h":return 1440*60*1e3;case"7d":return 10080*60*1e3;case"30d":return 720*60*60*1e3;case"1y":return 365*24*60*60*1e3;default:return 3600*1e3}}function g(l){return l==="raw"?"live (10s samples)":l==="hourly"?"hourly average":l==="daily"?"daily average":l}function b(l,m,c,t,e){if(!l||l.length===0)return`
No data for ${escapeHtml(t)}
`;const a=l.map(m).filter(_=>_!=null);if(a.length===0)return`
No data for ${escapeHtml(t)}
`;const o=Math.max(...a,1),i=Math.min(...a,0),n=o-i||1,r=600,d=80,y=4,L=(r-y*2)/Math.max(a.length-1,1),U=a.map((_,J)=>{const X=y+J*L,Q=d-y-(_-i)/n*(d-y*2);return`${X.toFixed(1)},${Q.toFixed(1)}`}).join(" "),q=a[a.length-1],F=a.reduce((_,J)=>_+J,0)/a.length;return`
${escapeHtml(t)} last ${q.toFixed(1)}${e} \xB7 avg ${F.toFixed(1)}${e} \xB7 max ${o.toFixed(1)}${e}
- - + +
- `}function s(){if(!D)return;const l=w||{},m=D.value,u=Object.entries(l);if(u.length===0){D.innerHTML='';return}D.innerHTML=u.map(([t,e])=>``).join(""),m&&l[m]&&(D.value=m)}async function c(){if(!O||!D)return;const l=D.value;if(!l){O.innerHTML='
\u{1F4CA}No container selected.
';return}const m=Date.now(),u=m-b(v);O.innerHTML='
Loading history...
';try{const e=await(await fetch(`/api/v1/monitoring/history/${encodeURIComponent(l)}?startTime=${u}&endTime=${m}`)).json();if(!e.success)throw new Error(e.error||"Failed to load history");const a=e.samples||[],o=e.tier||"raw";if(a.length===0){O.innerHTML=`
\u{1F4CA}No data for the last ${v}. Tier: ${y(o)}.
`;return}const r=o==="raw",n=r?U=>U.cpu?.percent:U=>U.cpu?.avg,i=r?U=>U.memory?.percent:U=>U.memory?.avgPercent,d=r?U=>U.network?.rxMB||0:U=>U.network?.rxMB||0,g=r?U=>U.network?.txMB||0:U=>U.network?.txMB||0;let S=` + `}function s(){if(!N)return;const l=f||{},m=N.value,c=Object.entries(l);if(c.length===0){N.innerHTML='';return}N.innerHTML=c.map(([t,e])=>``).join(""),m&&l[m]&&(N.value=m)}async function p(){if(!R||!N)return;const l=N.value;if(!l){R.innerHTML='
\u{1F4CA}No container selected.
';return}const m=Date.now(),c=m-x(v);R.innerHTML='
Loading history...
';try{const e=await(await fetch(`/api/v1/monitoring/history/${encodeURIComponent(l)}?startTime=${c}&endTime=${m}`)).json();if(!e.success)throw new Error(e.error||"Failed to load history");const a=e.samples||[],o=e.tier||"raw";if(a.length===0){R.innerHTML=`
\u{1F4CA}No data for the last ${v}. Tier: ${g(o)}.
`;return}const i=o==="raw",n=i?U=>U.cpu?.percent:U=>U.cpu?.avg,r=i?U=>U.memory?.percent:U=>U.memory?.avgPercent,d=i?U=>U.network?.rxMB||0:U=>U.network?.rxMB||0,y=i?U=>U.network?.txMB||0:U=>U.network?.txMB||0;let L=`
- ${a.length} samples \xB7 ${escapeHtml(y(o))} \xB7 ${new Date(u).toLocaleString()} \u2192 ${new Date(m).toLocaleString()} + ${a.length} samples \xB7 ${escapeHtml(g(o))} \xB7 ${new Date(c).toLocaleString()} \u2192 ${new Date(m).toLocaleString()}
- `;S+=h(a,n,"#2ecc71","CPU","%"),S+=h(a,i,"#3498db","Memory","%"),S+=h(a,d,"#9b59b6","Network RX"," MB"),S+=h(a,g,"#e67e22","Network TX"," MB"),O.innerHTML=S}catch(t){O.innerHTML=`
\u26A0\uFE0FFailed to load history: ${escapeHtml(t.message)}
`}}p.forEach(l=>{l.addEventListener("click",()=>{p.forEach(m=>m.classList.remove("active")),l.classList.add("active"),v=l.dataset.range,c()})}),D?.addEventListener("change",c),document.querySelector('[data-panel="stats-history"]')?.addEventListener("click",()=>{s(),c()})})(),(function(){injectModal("health-modal",`
+ `;L+=b(a,n,"#2ecc71","CPU","%"),L+=b(a,r,"#3498db","Memory","%"),L+=b(a,d,"#9b59b6","Network RX"," MB"),L+=b(a,y,"#e67e22","Network TX"," MB"),R.innerHTML=L}catch(t){R.innerHTML=`
\u26A0\uFE0FFailed to load history: ${escapeHtml(t.message)}
`}}u.forEach(l=>{l.addEventListener("click",()=>{u.forEach(m=>m.classList.remove("active")),l.classList.add("active"),v=l.dataset.range,p()})}),N?.addEventListener("change",p),document.querySelector('[data-panel="stats-history"]')?.addEventListener("click",()=>{s(),p()})})(),(function(){injectModal("health-modal",`

\u{1F3E5} Health Check Dashboard

-
`);const x=document.getElementById("health-modal"),B=document.getElementById("health-check-btn"),A=document.getElementById("health-cancel"),C=document.getElementById("health-refresh-btn"),M=document.getElementById("health-status-container"),P=document.getElementById("health-incidents-container"),z=document.getElementById("health-config-container"),N=document.getElementById("health-last-update"),f=document.getElementById("health-add-btn"),L=document.getElementById("health-config-form"),w=document.getElementById("health-form-title"),$=document.getElementById("health-form-cancel"),k=document.getElementById("health-form-save"),T="dashcaddy-health-settings",E={retentionDays:30,pollingInterval:60,statsPollingInterval:30,maxEntriesPerService:500,diskUsageThreshold:80},I=document.getElementById("health-global-save"),j=document.getElementById("health-global-reset"),H=document.getElementById("health-global-status"),R=document.getElementById("health-setting-retention"),D=document.getElementById("health-setting-interval"),O=document.getElementById("health-setting-stats-interval"),p=document.getElementById("health-setting-max-entries"),v=document.getElementById("health-setting-disk-threshold");function b(){try{const r=safeGet(T),n=r?JSON.parse(r):{};return Object.assign({},E,n)}catch{return Object.assign({},E)}}function y(){const r=b();R&&(R.value=r.retentionDays),D&&(D.value=r.pollingInterval),O&&(O.value=r.statsPollingInterval),p&&(p.value=r.maxEntriesPerService),v&&(v.value=r.diskUsageThreshold)}function h(){const r={retentionDays:Math.max(1,Math.min(3650,parseInt(R?.value)||E.retentionDays)),pollingInterval:Math.max(5,Math.min(3600,parseInt(D?.value)||E.pollingInterval)),statsPollingInterval:Math.max(5,Math.min(3600,parseInt(O?.value)||E.statsPollingInterval)),maxEntriesPerService:Math.max(10,Math.min(1e5,parseInt(p?.value)||E.maxEntriesPerService)),diskUsageThreshold:Math.max(50,Math.min(99,parseInt(v?.value)||E.diskUsageThreshold))};try{safeSet(T,JSON.stringify(r)),y(),H&&(H.textContent="Saved \u2713",H.style.color="var(--ok-fg)",setTimeout(()=>{H&&(H.textContent="")},2500)),typeof showNotification=="function"&&showNotification("Global health settings saved","success")}catch(n){H&&(H.textContent="Save failed",H.style.color="var(--bad-fg)"),typeof showNotification=="function"&&showNotification("Failed to save settings: "+n.message,"error")}}function s(){try{safeSet(T,JSON.stringify(E))}catch{}y(),H&&(H.textContent="Reset to defaults \u2713",H.style.color="var(--ok-fg)",setTimeout(()=>{H&&(H.textContent="")},2500))}y(),I?.addEventListener("click",h),j?.addEventListener("click",s);let c=null;function l(r){return r>=99.9?"var(--ok-fg)":r>=95?"#f39c12":"var(--bad-fg)"}function m(r){const n={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`${r}`}async function u(){try{const n=await(await fetch("/api/v1/health-checks/status")).json();if(!n.success||!n.status||Object.keys(n.status).length===0){M.innerHTML='
\u{1F3E5}No health checks configured. Go to the Configure tab to add services.
';return}const i=Object.values(n.status);let d='';d+='',d+='',d+='',d+='';for(const g of i){const S=g.status==="up",U=S?"var(--dot-ok)":"var(--dot-bad)",q=g.uptime?.["24h"]??"-",F=g.uptime?.["7d"]??"-",_=g.avgResponseTime!=null?Math.round(g.avgResponseTime)+"ms":"-",J=g.timestamp?timeAgo(g.timestamp):"-";d+=``,d+=``,d+=``,d+=``,d+=``,d+=``,d+=``,d+="",d+=``}d+="
ServiceStatusUptime 24hUptime 7dAvg ResponseLast Check
${escapeHtml(g.name||g.serviceId)}${S?"Up":"Down"}${typeof q=="number"?q.toFixed(1)+"%":q}${typeof F=="number"?F.toFixed(1)+"%":F}${_}${J}
",M.innerHTML=d,N.textContent="Updated "+new Date().toLocaleTimeString(),M.querySelectorAll("tr[data-health-id]").forEach(g=>{g.addEventListener("click",async()=>{const S=g.dataset.healthId,U=document.getElementById("health-detail-"+S);if(U){if(U.style.display!=="none"){U.style.display="none";return}U.style.display="";try{const F=await(await fetch(`/api/v1/health-checks/${S}/stats?hours=24`)).json();if(F.success&&F.stats){const _=F.stats,J=_.responseTime||{};U.querySelector("td").innerHTML=` + `);const w=document.getElementById("health-modal"),B=document.getElementById("health-check-btn"),A=document.getElementById("health-cancel"),S=document.getElementById("health-refresh-btn"),z=document.getElementById("health-status-container"),P=document.getElementById("health-incidents-container"),M=document.getElementById("health-config-container"),D=document.getElementById("health-last-update"),h=document.getElementById("health-add-btn"),T=document.getElementById("health-config-form"),f=document.getElementById("health-form-title"),H=document.getElementById("health-form-cancel"),k=document.getElementById("health-form-save"),$="dashcaddy-health-settings",E={retentionDays:30,pollingInterval:60,statsPollingInterval:30,maxEntriesPerService:500,diskUsageThreshold:80},I=document.getElementById("health-global-save"),O=document.getElementById("health-global-reset"),C=document.getElementById("health-global-status"),j=document.getElementById("health-setting-retention"),N=document.getElementById("health-setting-interval"),R=document.getElementById("health-setting-stats-interval"),u=document.getElementById("health-setting-max-entries"),v=document.getElementById("health-setting-disk-threshold");function x(){try{const i=safeGet($),n=i?JSON.parse(i):{};return Object.assign({},E,n)}catch{return Object.assign({},E)}}function g(){const i=x();j&&(j.value=i.retentionDays),N&&(N.value=i.pollingInterval),R&&(R.value=i.statsPollingInterval),u&&(u.value=i.maxEntriesPerService),v&&(v.value=i.diskUsageThreshold)}function b(){const i={retentionDays:Math.max(1,Math.min(3650,parseInt(j?.value)||E.retentionDays)),pollingInterval:Math.max(5,Math.min(3600,parseInt(N?.value)||E.pollingInterval)),statsPollingInterval:Math.max(5,Math.min(3600,parseInt(R?.value)||E.statsPollingInterval)),maxEntriesPerService:Math.max(10,Math.min(1e5,parseInt(u?.value)||E.maxEntriesPerService)),diskUsageThreshold:Math.max(50,Math.min(99,parseInt(v?.value)||E.diskUsageThreshold))};try{safeSet($,JSON.stringify(i)),g(),C&&(C.textContent="Saved \u2713",C.style.color="var(--ok-fg)",setTimeout(()=>{C&&(C.textContent="")},2500)),typeof showNotification=="function"&&showNotification("Global health settings saved","success")}catch(n){C&&(C.textContent="Save failed",C.style.color="var(--bad-fg)"),typeof showNotification=="function"&&showNotification("Failed to save settings: "+n.message,"error")}}function s(){try{safeSet($,JSON.stringify(E))}catch{}g(),C&&(C.textContent="Reset to defaults \u2713",C.style.color="var(--ok-fg)",setTimeout(()=>{C&&(C.textContent="")},2500))}g(),I?.addEventListener("click",b),O?.addEventListener("click",s);let p=null;function l(i){return i>=99.9?"var(--ok-fg)":i>=95?"#f39c12":"var(--bad-fg)"}function m(i){const n={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`${i}`}async function c(){try{const n=await(await fetch("/api/v1/health-checks/status")).json();if(!n.success||!n.status||Object.keys(n.status).length===0){z.innerHTML='
\u{1F3E5}No health checks configured. Go to the Configure tab to add services.
';return}const r=Object.values(n.status);let d='';d+='',d+='',d+='',d+='';for(const y of r){const L=y.status==="up",U=L?"var(--dot-ok)":"var(--dot-bad)",q=y.uptime?.["24h"]??"-",F=y.uptime?.["7d"]??"-",_=y.avgResponseTime!=null?Math.round(y.avgResponseTime)+"ms":"-",J=y.timestamp?timeAgo(y.timestamp):"-";d+=``,d+=``,d+=``,d+=``,d+=``,d+=``,d+=``,d+="",d+=``}d+="
ServiceStatusUptime 24hUptime 7dAvg ResponseLast Check
${escapeHtml(y.name||y.serviceId)}${L?"Up":"Down"}${typeof q=="number"?q.toFixed(1)+"%":q}${typeof F=="number"?F.toFixed(1)+"%":F}${_}${J}
",z.innerHTML=d,D.textContent="Updated "+new Date().toLocaleTimeString(),z.querySelectorAll("tr[data-health-id]").forEach(y=>{y.addEventListener("click",async()=>{const L=y.dataset.healthId,U=document.getElementById("health-detail-"+L);if(U){if(U.style.display!=="none"){U.style.display="none";return}U.style.display="";try{const F=await(await fetch(`/api/v1/health-checks/${L}/stats?hours=24`)).json();if(F.success&&F.stats){const _=F.stats,J=_.responseTime||{};U.querySelector("td").innerHTML=`
Total Checks
${_.totalChecks||0}
Uptime
${(_.uptime||0).toFixed(2)}%
@@ -1501,14 +1544,14 @@ This will replace current configuration, credentials, and data. Containers will
Max Response
${Math.round(J.max||0)}ms
Up Checks
${_.upChecks||0}
Down Checks
${_.downChecks||0}
-
`}else U.querySelector("td").innerHTML='
No detailed stats available for this period.
'}catch(q){U.querySelector("td").innerHTML=`
Failed: ${escapeHtml(q.message)}
`}}})})}catch(r){M.innerHTML=`
Failed to load health status: ${escapeHtml(r.message)}
`}}async function t(){try{const[r,n]=await Promise.all([fetch("/api/v1/health-checks/incidents"),fetch("/api/v1/health-checks/incidents/history?limit=50")]),i=await r.json(),d=await n.json();let g="";const S=i.success&&i.incidents?i.incidents:[];if(S.length>0){g+='

Open Incidents ('+S.length+")

";for(const q of S)g+=`
+
`}else U.querySelector("td").innerHTML='
No detailed stats available for this period.
'}catch(q){U.querySelector("td").innerHTML=`
Failed: ${escapeHtml(q.message)}
`}}})})}catch(i){z.innerHTML=`
Failed to load health status: ${escapeHtml(i.message)}
`}}async function t(){try{const[i,n]=await Promise.all([fetch("/api/v1/health-checks/incidents"),fetch("/api/v1/health-checks/incidents/history?limit=50")]),r=await i.json(),d=await n.json();let y="";const L=r.success&&r.incidents?r.incidents:[];if(L.length>0){y+='

Open Incidents ('+L.length+")

";for(const q of L)y+=`
${escapeHtml(q.serviceId)} ${m(q.severity)}
${escapeHtml(q.message)}
Started ${timeAgo(q.createdAt)} \xB7 ${q.occurrences||1} occurrence(s)
-
`;g+="
"}else g+='
All services operational \u2014 no open incidents
';const U=d.success&&d.history?d.history:[];if(U.length>0){g+='

Incident History

',g+='',g+='';for(const q of U){const F=q.status==="resolved",_=F&&q.duration?q.duration<6e4?Math.round(q.duration/1e3)+"s":Math.round(q.duration/6e4)+"m":"-";g+='',g+=``,g+=``,g+=``,g+=``,g+=``,g+=``,g+=""}g+="
ServiceTypeSeverityStatusDurationWhen
${escapeHtml(q.serviceId)}${escapeHtml(q.type)}${m(q.severity)}${q.status}${_}${timeAgo(q.createdAt)}
"}P.innerHTML=g||'
\u{1F6A8}No incidents recorded yet.
'}catch(r){P.innerHTML=`
Failed: ${escapeHtml(r.message)}
`}}async function e(){try{const n=await(await fetch("/api/v1/health-checks/status")).json(),i=n.success&&n.status?Object.values(n.status):[];if(i.length===0){z.innerHTML='
\u2699\uFE0FNo health checks configured yet. Click "Add Health Check" below.
';return}let d='';d+='';for(const g of i){const S=g.status==="up";d+='',d+=``,d+=``,d+=``,d+='"}d+="
ServiceStatusSLA TargetActions
${escapeHtml(g.name||g.serviceId)}${S?"Up":"Down"}${g.sla?.target?g.sla.target+"%":"-"}',d+=``,d+=``,d+="
",z.innerHTML=d}catch(r){z.innerHTML=`
Failed: ${escapeHtml(r.message)}
`}}function a(r,n,i,d,g,S,U){c=r||null,w.textContent=r?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=r||"",document.getElementById("health-form-id").disabled=!!r,document.getElementById("health-form-name").value=n||"",document.getElementById("health-form-url").value=i||"",document.getElementById("health-form-timeout").value=d||1e4,document.getElementById("health-form-codes").value=g||"200",document.getElementById("health-form-sla").value=S||99.9,document.getElementById("health-form-slow").value=U||5e3,L.style.display="",f.style.display="none"}function o(){L.style.display="none",f.style.display="",c=null}f?.addEventListener("click",()=>a("","","",1e4,"200",99.9,5e3)),$?.addEventListener("click",o),k?.addEventListener("click",async()=>{const r=c||document.getElementById("health-form-id").value.trim();if(!r)return showNotification("Service ID is required","warning");const n=document.getElementById("health-form-url").value.trim();if(!n)return showNotification("URL is required","warning");const i=document.getElementById("health-form-codes").value.split(",").map(g=>parseInt(g.trim())).filter(Boolean),d={name:document.getElementById("health-form-name").value.trim()||r,url:n,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:i.length?i:[200],sla:{target:parseFloat(document.getElementById("health-form-sla").value)||99.9},slowResponseThreshold:parseInt(document.getElementById("health-form-slow").value)||5e3};try{k.textContent="Saving...",k.disabled=!0;const S=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(r)}/configure`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)})).json();if(!S.success)throw new Error(S.error||"Save failed");o(),e(),u()}catch(g){showNotification("Error: "+g.message,"error")}finally{k.textContent="Save",k.disabled=!1}}),document.addEventListener("health-edit",async r=>{const n=r.detail;a(n,"","",1e4,"200",99.9,5e3)}),document.addEventListener("health-delete",async r=>{const n=r.detail;if(confirm(`Delete health check for "${n}"?`))try{const d=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(n)}/configure`,{method:"DELETE"})).json();if(!d.success)throw new Error(d.error);e(),u()}catch(i){showNotification("Error: "+i.message,"error")}}),B?.addEventListener("click",()=>{x?.classList.add("show"),u()}),wireModal(x,A),C?.addEventListener("click",u),document.querySelector('[data-panel="health-incidents"]')?.addEventListener("click",t),document.querySelector('[data-panel="health-config"]')?.addEventListener("click",e)})(),(function(){injectModal("updates-modal",`
+
`;y+="
"}else y+='
All services operational \u2014 no open incidents
';const U=d.success&&d.history?d.history:[];if(U.length>0){y+='

Incident History

',y+='',y+='';for(const q of U){const F=q.status==="resolved",_=F&&q.duration?q.duration<6e4?Math.round(q.duration/1e3)+"s":Math.round(q.duration/6e4)+"m":"-";y+='',y+=``,y+=``,y+=``,y+=``,y+=``,y+=``,y+=""}y+="
ServiceTypeSeverityStatusDurationWhen
${escapeHtml(q.serviceId)}${escapeHtml(q.type)}${m(q.severity)}${q.status}${_}${timeAgo(q.createdAt)}
"}P.innerHTML=y||'
\u{1F6A8}No incidents recorded yet.
'}catch(i){P.innerHTML=`
Failed: ${escapeHtml(i.message)}
`}}async function e(){try{const n=await(await fetch("/api/v1/health-checks/status")).json(),r=n.success&&n.status?Object.values(n.status):[];if(r.length===0){M.innerHTML='
\u2699\uFE0FNo health checks configured yet. Click "Add Health Check" below.
';return}let d='';d+='';for(const y of r){const L=y.status==="up";d+='',d+=``,d+=``,d+=``,d+='"}d+="
ServiceStatusSLA TargetActions
${escapeHtml(y.name||y.serviceId)}${L?"Up":"Down"}${y.sla?.target?y.sla.target+"%":"-"}',d+=``,d+=``,d+="
",M.innerHTML=d}catch(i){M.innerHTML=`
Failed: ${escapeHtml(i.message)}
`}}function a(i,n,r,d,y,L,U){p=i||null,f.textContent=i?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=i||"",document.getElementById("health-form-id").disabled=!!i,document.getElementById("health-form-name").value=n||"",document.getElementById("health-form-url").value=r||"",document.getElementById("health-form-timeout").value=d||1e4,document.getElementById("health-form-codes").value=y||"200",document.getElementById("health-form-sla").value=L||99.9,document.getElementById("health-form-slow").value=U||5e3,T.style.display="",h.style.display="none"}function o(){T.style.display="none",h.style.display="",p=null}h?.addEventListener("click",()=>a("","","",1e4,"200",99.9,5e3)),H?.addEventListener("click",o),k?.addEventListener("click",async()=>{const i=p||document.getElementById("health-form-id").value.trim();if(!i)return showNotification("Service ID is required","warning");const n=document.getElementById("health-form-url").value.trim();if(!n)return showNotification("URL is required","warning");const r=document.getElementById("health-form-codes").value.split(",").map(y=>parseInt(y.trim())).filter(Boolean),d={name:document.getElementById("health-form-name").value.trim()||i,url:n,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:r.length?r:[200],sla:{target:parseFloat(document.getElementById("health-form-sla").value)||99.9},slowResponseThreshold:parseInt(document.getElementById("health-form-slow").value)||5e3};try{k.textContent="Saving...",k.disabled=!0;const L=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(i)}/configure`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)})).json();if(!L.success)throw new Error(L.error||"Save failed");o(),e(),c()}catch(y){showNotification("Error: "+y.message,"error")}finally{k.textContent="Save",k.disabled=!1}}),document.addEventListener("health-edit",async i=>{const n=i.detail;a(n,"","",1e4,"200",99.9,5e3)}),document.addEventListener("health-delete",async i=>{const n=i.detail;if(confirm(`Delete health check for "${n}"?`))try{const d=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(n)}/configure`,{method:"DELETE"})).json();if(!d.success)throw new Error(d.error);e(),c()}catch(r){showNotification("Error: "+r.message,"error")}}),B?.addEventListener("click",()=>{w?.classList.add("show"),c()}),wireModal(w,A),S?.addEventListener("click",c),document.querySelector('[data-panel="health-incidents"]')?.addEventListener("click",t),document.querySelector('[data-panel="health-config"]')?.addEventListener("click",e)})(),(function(){injectModal("updates-modal",`

\u2B06\uFE0F Update Management

- `);const x=document.getElementById("updates-modal"),B=document.getElementById("updates-btn"),A=document.getElementById("updates-cancel"),C=document.getElementById("updates-check-btn"),M=document.getElementById("updates-available-container"),P=document.getElementById("updates-history-container"),z=document.getElementById("updates-auto-container"),N=document.getElementById("updates-last-check");async function f(){try{const t=await(await fetch("/api/v1/updates/available")).json();if(!t.success)throw new Error(t.error);const e=t.updates||[];if(e.length===0){M.innerHTML='
\u2705All containers are up to date.
',N.textContent="",document.getElementById("updates-update-all-btn").style.display="none",document.getElementById("updates-count-badge").style.display="none",window._pendingUpdates=[];return}let a='';a+='';for(const n of e){const i=(()=>{const d=window.APPS||[];for(const g of d)if(g.containerId===n.containerId||g.name===n.containerName||g.id===n.containerName)return g.id;return n.containerName})();a+=``,a+=``,a+=``,a+=``,a+=``,a+='"}a+="
ContainerImageCurrentLatestActions
${escapeHtml(n.containerName)}${escapeHtml(n.imageName)}${escapeHtml(n.currentDigest)}${escapeHtml(n.latestDigest)}',a+=``,a+=``,a+="
",M.innerHTML=a,N.textContent=e.length+" update(s) available";const o=document.getElementById("updates-count-badge"),r=document.getElementById("updates-update-all-btn");o&&(o.textContent=e.length+" pending",o.style.display=""),r&&e.length>0&&(r.style.display=""),window._pendingUpdates=e,M.querySelectorAll(".update-now-btn").forEach(n=>{n.addEventListener("click",async()=>{const i=n.dataset.id,d=n.dataset.name;if(confirm(`Update "${d}" to the latest version? The container will restart.`)){n.textContent="Updating...",n.disabled=!0;try{const S=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(i)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if(S.success)n.textContent="Done!",n.style.background="var(--ok-fg)",setTimeout(()=>f(),2e3);else throw new Error(S.error||"Update failed")}catch(g){n.textContent="Failed",n.style.color="var(--bad-fg)",showNotification("Update error: "+g.message,"error"),setTimeout(()=>{n.textContent="Update",n.disabled=!1,n.style.color="",n.style.background=""},3e3)}}})}),M.querySelectorAll(".rollback-btn").forEach(n=>{n.addEventListener("click",async()=>{const i=n.dataset.id,d=n.dataset.name;if(confirm(`Rollback "${d}" to its previous version?`)){n.textContent="Rolling back...",n.disabled=!0;try{const S=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(i)}`,{method:"POST"})).json();if(S.success)n.textContent="Rolled back!",setTimeout(()=>f(),2e3);else throw new Error(S.error||"Rollback failed")}catch(g){n.textContent="Failed",showNotification("Rollback error: "+g.message,"error"),setTimeout(()=>{n.textContent="Rollback",n.disabled=!1},3e3)}}})})}catch(u){M.innerHTML=`
Failed: ${escapeHtml(u.message)}
`}}async function L(){const u=window._pendingUpdates||[];if(!u.length)return;const t=document.getElementById("updates-update-all-btn");if(!confirm(`Update all ${u.length} containers? Each will restart.`))return;t.textContent="\u23F3 Updating...",t.disabled=!0;let e=0,a=0;for(const o of u)try{(await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(o.containerId)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json()).success?e++:a++}catch{a++}t.textContent="\u2705 Done",showNotification(`Update all: ${e} succeeded, ${a} failed.`,e>0&&a===0?"success":"error"),setTimeout(()=>{t.textContent="\u2B06\uFE0F Update All",t.disabled=!1,f()},3e3)}document.getElementById("updates-update-all-btn")?.addEventListener("click",L);async function w(){C.textContent="\u{1F50D} Checking...",C.disabled=!0;try{const t=await(await secureFetch("/api/v1/updates/check",{method:"POST"})).json();if(!t.success)throw new Error(t.error);C.textContent="\u2705 Done!",await f()}catch(u){C.textContent="\u274C Failed",showNotification("Check error: "+u.message,"error")}setTimeout(()=>{C.textContent="\u{1F50D} Check for Updates",C.disabled=!1},3e3)}async function $(){try{P.innerHTML='
Loading...
';const t=await(await fetch("/api/v1/updates/history?limit=50")).json(),e=t.success&&t.history?t.history:[];if(e.length===0){P.innerHTML='
\u{1F4CB}No update history yet.
';return}let a='';a+='';for(const o of e){const r=o.status==="success",n=o.duration?o.duration<1e3?o.duration+"ms":Math.round(o.duration/1e3)+"s":"-";a+='',a+=``,a+=``,a+=``,a+=``,a+=``,a+="",!r&&o.error&&(a+=``)}a+="
WhenContainerImageDurationStatus
${timeAgo(o.timestamp)}${escapeHtml(o.containerName)}${escapeHtml(o.imageName)}${n}${r?"\u2713 success":"\u2717 failed"}
${escapeHtml(o.error)}
",P.innerHTML=a}catch(u){P.innerHTML=`
Failed: ${escapeHtml(u.message)}
`}}async function k(){try{z.innerHTML='
Loading...
';const[u,t]=await Promise.all([fetch("/api/v1/stats/containers"),fetch("/api/v1/updates/auto-update")]),e=await u.json(),a=await t.json(),o=e.success&&e.stats?e.stats:[],r=a.success&&a.config?a.config:{};if(o.length===0){z.innerHTML='
\u{1F916}No running containers found.
';return}let n='
Auto-updates run during maintenance window (default 2AM-4AM). Daily = every day, Weekly = Sundays, Monthly = 1st of month.
';n+='',n+='';for(const i of o){const d=i.name||i.Names?.[0]?.replace(/^\//,"")||i.Id?.substring(0,12),g=i.containerId||i.Id,S=r[g]||{},U=S.enabled?S.schedule||"weekly":"",q=S.autoRollback!==!1,F=S.maintenanceWindow||"",_=S.lastAutoUpdate?timeAgo(S.lastAutoUpdate):"Never";n+=``,n+=``,n+=``,n+=``,n+=``,n+=``,n+=``,n+=""}n+="
ContainerScheduleWindowRollbackLast RunActions
${escapeHtml(d)} - ';a+='';for(const n of e){const r=(()=>{const d=window.APPS||[];for(const y of d)if(y.containerId===n.containerId||y.name===n.containerName||y.id===n.containerName)return y.id;return n.containerName})();a+=``,a+=``,a+=``,a+=``,a+=``,a+='"}a+="
ContainerImageCurrentLatestActions
${escapeHtml(n.containerName)}${escapeHtml(n.imageName)}${escapeHtml(n.currentDigest)}${escapeHtml(n.latestDigest)}',a+=``,a+=``,a+="
",z.innerHTML=a,D.textContent=e.length+" update(s) available";const o=document.getElementById("updates-count-badge"),i=document.getElementById("updates-update-all-btn");o&&(o.textContent=e.length+" pending",o.style.display=""),i&&e.length>0&&(i.style.display=""),window._pendingUpdates=e,z.querySelectorAll(".update-now-btn").forEach(n=>{n.addEventListener("click",async()=>{const r=n.dataset.id,d=n.dataset.name;if(confirm(`Update "${d}" to the latest version? The container will restart.`)){n.textContent="Updating...",n.disabled=!0;try{const L=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(r)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if(L.success)n.textContent="Done!",n.style.background="var(--ok-fg)",setTimeout(()=>h(),2e3);else throw new Error(L.error||"Update failed")}catch(y){n.textContent="Failed",n.style.color="var(--bad-fg)",showNotification("Update error: "+y.message,"error"),setTimeout(()=>{n.textContent="Update",n.disabled=!1,n.style.color="",n.style.background=""},3e3)}}})}),z.querySelectorAll(".rollback-btn").forEach(n=>{n.addEventListener("click",async()=>{const r=n.dataset.id,d=n.dataset.name;if(confirm(`Rollback "${d}" to its previous version?`)){n.textContent="Rolling back...",n.disabled=!0;try{const L=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(r)}`,{method:"POST"})).json();if(L.success)n.textContent="Rolled back!",setTimeout(()=>h(),2e3);else throw new Error(L.error||"Rollback failed")}catch(y){n.textContent="Failed",showNotification("Rollback error: "+y.message,"error"),setTimeout(()=>{n.textContent="Rollback",n.disabled=!1},3e3)}}})})}catch(c){z.innerHTML=`
Failed: ${escapeHtml(c.message)}
`}}async function T(){const c=window._pendingUpdates||[];if(!c.length)return;const t=document.getElementById("updates-update-all-btn");if(!confirm(`Update all ${c.length} containers? Each will restart.`))return;t.textContent="\u23F3 Updating...",t.disabled=!0;let e=0,a=0;for(const o of c)try{(await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(o.containerId)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json()).success?e++:a++}catch{a++}t.textContent="\u2705 Done",showNotification(`Update all: ${e} succeeded, ${a} failed.`,e>0&&a===0?"success":"error"),setTimeout(()=>{t.textContent="\u2B06\uFE0F Update All",t.disabled=!1,h()},3e3)}document.getElementById("updates-update-all-btn")?.addEventListener("click",T);async function f(){S.textContent="\u{1F50D} Checking...",S.disabled=!0;try{const t=await(await secureFetch("/api/v1/updates/check",{method:"POST"})).json();if(!t.success)throw new Error(t.error);S.textContent="\u2705 Done!",await h()}catch(c){S.textContent="\u274C Failed",showNotification("Check error: "+c.message,"error")}setTimeout(()=>{S.textContent="\u{1F50D} Check for Updates",S.disabled=!1},3e3)}async function H(){try{P.innerHTML='
Loading...
';const t=await(await fetch("/api/v1/updates/history?limit=50")).json(),e=t.success&&t.history?t.history:[];if(e.length===0){P.innerHTML='
\u{1F4CB}No update history yet.
';return}let a='';a+='';for(const o of e){const i=o.status==="success",n=o.duration?o.duration<1e3?o.duration+"ms":Math.round(o.duration/1e3)+"s":"-";a+='',a+=``,a+=``,a+=``,a+=``,a+=``,a+="",!i&&o.error&&(a+=``)}a+="
WhenContainerImageDurationStatus
${timeAgo(o.timestamp)}${escapeHtml(o.containerName)}${escapeHtml(o.imageName)}${n}${i?"\u2713 success":"\u2717 failed"}
${escapeHtml(o.error)}
",P.innerHTML=a}catch(c){P.innerHTML=`
Failed: ${escapeHtml(c.message)}
`}}async function k(){try{M.innerHTML='
Loading...
';const[c,t]=await Promise.all([fetch("/api/v1/stats/containers"),fetch("/api/v1/updates/auto-update")]),e=await c.json(),a=await t.json(),o=e.success&&e.stats?e.stats:[],i=a.success&&a.config?a.config:{};if(o.length===0){M.innerHTML='
\u{1F916}No running containers found.
';return}let n='
Auto-updates run during maintenance window (default 2AM-4AM). Daily = every day, Weekly = Sundays, Monthly = 1st of month.
';n+='',n+='';for(const r of o){const d=r.name||r.Names?.[0]?.replace(/^\//,"")||r.Id?.substring(0,12),y=r.containerId||r.Id,L=i[y]||{},U=L.enabled?L.schedule||"weekly":"",q=L.autoRollback!==!1,F=L.maintenanceWindow||"",_=L.lastAutoUpdate?timeAgo(L.lastAutoUpdate):"Never";n+=``,n+=``,n+=``,n+=``,n+=``,n+=``,n+=``,n+=""}n+="
ContainerScheduleWindowRollbackLast RunActions
${escapeHtml(d)} + ${_}
",z.innerHTML=n,z.querySelectorAll(".save-auto-btn").forEach(i=>{i.addEventListener("click",async()=>{const d=i.dataset.id,g=i.closest("tr"),S=g.querySelector(".auto-schedule").value,U=g.querySelector(".auto-rollback").checked,q=g.querySelector(".auto-window").value.trim();i.textContent="Saving...",i.disabled=!0;try{const _=await(await secureFetch(`/api/v1/updates/auto-update/${encodeURIComponent(d)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!!S,schedule:S||"weekly",autoRollback:U,maintenanceWindow:q||void 0})})).json();if(_.success)i.textContent="\u2713 Saved";else throw new Error(_.error)}catch(F){i.textContent="\u2717 Error",showNotification("Save error: "+F.message,"error")}setTimeout(()=>{i.textContent="Save",i.disabled=!1},2e3)})})}catch(u){z.innerHTML=`
Failed: ${escapeHtml(u.message)}
`}}const T=document.getElementById("dashcaddy-current-version"),E=document.getElementById("dashcaddy-update-badge"),I=document.getElementById("dashcaddy-update-details"),j=document.getElementById("dashcaddy-new-version"),H=document.getElementById("dashcaddy-changelog"),R=document.getElementById("dashcaddy-apply-btn"),D=document.getElementById("dashcaddy-check-btn"),O=document.getElementById("dashcaddy-rollback-btn"),p=document.getElementById("dashcaddy-status-bar"),v=document.getElementById("dashcaddy-history-container");let b=null;function y(u,t){p&&(p.style.display="block",p.style.background=t==="error"?"var(--bad-bg)":t==="success"?"var(--ok-bg)":"var(--bg)",p.style.color=t==="error"?"var(--bad-fg)":t==="success"?"var(--ok-fg)":"var(--fg)",p.textContent=u)}async function h(){try{const t=await(await fetch("/api/v1/system/version")).json();if(t.success){const e=t.commit&&t.commit!=="unknown"?t.commit:null;T.textContent="v"+t.version+(e?" ("+e.substring(0,7)+")":"")}}catch{T.textContent="Unable to fetch version"}}async function s(u){u||(D.textContent="Checking...",D.disabled=!0);try{const e=await(await fetch("/api/v1/system/update-check")).json();if(b=e,e.success&&e.available&&e.remote){E.style.display="",I.style.display="",j.textContent="v"+e.remote.version,H.textContent=e.remote.changelog||"No changelog available.";const a=document.getElementById("updates-btn");if(a&&!a.querySelector(".update-dot")){const r=document.createElement("span");r.className="update-dot",r.style.cssText="position:absolute;top:2px;right:2px;width:8px;height:8px;border-radius:50%;background:var(--accent);",a.style.position="relative",a.appendChild(r)}const o=document.getElementById("updates-dashcaddy-tab");if(o&&!o.querySelector(".update-dot")){const r=document.createElement("span");r.className="update-dot",r.style.cssText="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-left:4px;vertical-align:middle;",o.appendChild(r)}}else E.style.display="none",I.style.display="none",await h(),u||y("You are running the latest version.","success");u||(D.textContent="Check for Updates",D.disabled=!1)}catch(t){u||(y("Failed to check: "+t.message,"error"),D.textContent="Check for Updates",D.disabled=!1)}}async function c(){if(!confirm("Apply DashCaddy update? The API container will restart."))return!1;R.textContent="Updating...",R.disabled=!0,y("Downloading and applying update...","info");try{const t=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(t.success)return y("Update initiated: v"+(t.fromVersion||"?")+" \u2192 v"+(t.toVersion||"?")+". The container will restart shortly.","success"),R.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(e=>e.remove()),!0;throw new Error(t.error||"Update failed")}catch(u){throw y("Update failed: "+u.message,"error"),R.textContent="Update Now",R.disabled=!1,u}}async function l(){try{const t=await(await fetch("/api/v1/system/update-history")).json(),e=t.success&&t.history?t.history:[];if(e.length===0){v.innerHTML='
\u{1F4E6}No self-update history.
';return}let a='';a+='';for(const o of e){const r=o.status==="success"?"\u2713 success":o.status==="pending"?"\u23F3 pending":o.status==="partial"?"\u26A0 partial":"\u2717 "+o.status,n=o.status==="success"?"var(--ok-fg)":o.status==="pending"?"var(--muted)":"var(--bad-fg)";a+='',a+='",a+='",a+='",a+='",a+="",o.error&&(a+='"),o.note&&(a+='")}a+="
WhenVersionFromStatus
'+timeAgo(o.timestamp)+"v'+escapeHtml(o.version)+(o.rollback?" (rollback)":"")+"v'+escapeHtml(o.fromVersion||"?")+"'+r+"
'+escapeHtml(o.error)+"
'+escapeHtml(o.note)+"
",v.innerHTML=a}catch(u){v.innerHTML='
Failed: '+escapeHtml(u.message)+"
"}}async function m(){try{const t=await(await fetch("/api/v1/system/rollback-versions")).json(),e=t.success&&t.versions?t.versions:[];if(e.length===0){showNotification("No rollback versions available.","info");return}const a=prompt(`Available rollback versions: +
${_}
",M.innerHTML=n,M.querySelectorAll(".save-auto-btn").forEach(r=>{r.addEventListener("click",async()=>{const d=r.dataset.id,y=r.closest("tr"),L=y.querySelector(".auto-schedule").value,U=y.querySelector(".auto-rollback").checked,q=y.querySelector(".auto-window").value.trim();r.textContent="Saving...",r.disabled=!0;try{const _=await(await secureFetch(`/api/v1/updates/auto-update/${encodeURIComponent(d)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!!L,schedule:L||"weekly",autoRollback:U,maintenanceWindow:q||void 0})})).json();if(_.success)r.textContent="\u2713 Saved";else throw new Error(_.error)}catch(F){r.textContent="\u2717 Error",showNotification("Save error: "+F.message,"error")}setTimeout(()=>{r.textContent="Save",r.disabled=!1},2e3)})})}catch(c){M.innerHTML=`
Failed: ${escapeHtml(c.message)}
`}}const $=document.getElementById("dashcaddy-current-version"),E=document.getElementById("dashcaddy-update-badge"),I=document.getElementById("dashcaddy-update-details"),O=document.getElementById("dashcaddy-new-version"),C=document.getElementById("dashcaddy-changelog"),j=document.getElementById("dashcaddy-apply-btn"),N=document.getElementById("dashcaddy-check-btn"),R=document.getElementById("dashcaddy-rollback-btn"),u=document.getElementById("dashcaddy-status-bar"),v=document.getElementById("dashcaddy-history-container");let x=null;function g(c,t){u&&(u.style.display="block",u.style.background=t==="error"?"var(--bad-bg)":t==="success"?"var(--ok-bg)":"var(--bg)",u.style.color=t==="error"?"var(--bad-fg)":t==="success"?"var(--ok-fg)":"var(--fg)",u.textContent=c)}async function b(){try{const t=await(await fetch("/api/v1/system/version")).json();if(t.success){const e=t.commit&&t.commit!=="unknown"?t.commit:null;$.textContent="v"+t.version+(e?" ("+e.substring(0,7)+")":"")}}catch{$.textContent="Unable to fetch version"}}async function s(c){c||(N.textContent="Checking...",N.disabled=!0);try{const e=await(await fetch("/api/v1/system/update-check")).json();if(x=e,e.success&&e.available&&e.remote){E.style.display="",I.style.display="",O.textContent="v"+e.remote.version,C.textContent=e.remote.changelog||"No changelog available.";const a=document.getElementById("updates-btn");if(a&&!a.querySelector(".update-dot")){const i=document.createElement("span");i.className="update-dot",i.style.cssText="position:absolute;top:2px;right:2px;width:8px;height:8px;border-radius:50%;background:var(--accent);",a.style.position="relative",a.appendChild(i)}const o=document.getElementById("updates-dashcaddy-tab");if(o&&!o.querySelector(".update-dot")){const i=document.createElement("span");i.className="update-dot",i.style.cssText="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-left:4px;vertical-align:middle;",o.appendChild(i)}}else E.style.display="none",I.style.display="none",await b(),c||g("You are running the latest version.","success");c||(N.textContent="Check for Updates",N.disabled=!1)}catch(t){c||(g("Failed to check: "+t.message,"error"),N.textContent="Check for Updates",N.disabled=!1)}}async function p(){if(!confirm("Apply DashCaddy update? The API container will restart."))return!1;j.textContent="Updating...",j.disabled=!0,g("Downloading and applying update...","info");try{const t=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(t.success)return g("Update initiated: v"+(t.fromVersion||"?")+" \u2192 v"+(t.toVersion||"?")+". The container will restart shortly.","success"),j.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(e=>e.remove()),!0;throw new Error(t.error||"Update failed")}catch(c){throw g("Update failed: "+c.message,"error"),j.textContent="Update Now",j.disabled=!1,c}}async function l(){try{const t=await(await fetch("/api/v1/system/update-history")).json(),e=t.success&&t.history?t.history:[];if(e.length===0){v.innerHTML='
\u{1F4E6}No self-update history.
';return}let a='';a+='';for(const o of e){const i=o.status==="success"?"\u2713 success":o.status==="pending"?"\u23F3 pending":o.status==="partial"?"\u26A0 partial":"\u2717 "+o.status,n=o.status==="success"?"var(--ok-fg)":o.status==="pending"?"var(--muted)":"var(--bad-fg)";a+='',a+='",a+='",a+='",a+='",a+="",o.error&&(a+='"),o.note&&(a+='")}a+="
WhenVersionFromStatus
'+timeAgo(o.timestamp)+"v'+escapeHtml(o.version)+(o.rollback?" (rollback)":"")+"v'+escapeHtml(o.fromVersion||"?")+"'+i+"
'+escapeHtml(o.error)+"
'+escapeHtml(o.note)+"
",v.innerHTML=a}catch(c){v.innerHTML='
Failed: '+escapeHtml(c.message)+"
"}}async function m(){try{const t=await(await fetch("/api/v1/system/rollback-versions")).json(),e=t.success&&t.versions?t.versions:[];if(e.length===0){showNotification("No rollback versions available.","info");return}const a=prompt(`Available rollback versions: `+e.join(` `)+` -Enter version to rollback to:`);if(!a)return;if(!e.includes(a)){showNotification("Invalid version: "+a,"error");return}if(!confirm("Rollback DashCaddy to v"+a+"? The container will restart."))return;y("Rolling back to v"+a+"...","info");const r=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:a})})).json();if(r.success)y("Rollback to v"+a+" initiated. Container will restart.","success");else throw new Error(r.error||"Rollback failed")}catch(u){y("Rollback failed: "+u.message,"error")}}D?.addEventListener("click",()=>s(!1)),R?.addEventListener("click",()=>c().catch(()=>{})),O?.addEventListener("click",m),C?.addEventListener("click",w),B?.addEventListener("click",()=>{x?.classList.add("show"),f()}),wireModal(x,A),window.openUpdateModal=function(u){x?.classList.add("show"),f().then(()=>{if(!u)return;const t=M.querySelector(`[data-app-id="${u}"]`);t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.style.background="rgba(249,115,22,0.15)",setTimeout(()=>{t.style.background=""},3e3))})},document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",$),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",k),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{h(),l(),b||s(!0)}),window.dcApplyUpdate=c,window.dcCheckForUpdate=s,setTimeout(()=>s(!0),5e3)})(),(function(){injectModal("docker-resources-modal",`
+Enter version to rollback to:`);if(!a)return;if(!e.includes(a)){showNotification("Invalid version: "+a,"error");return}if(!confirm("Rollback DashCaddy to v"+a+"? The container will restart."))return;g("Rolling back to v"+a+"...","info");const i=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:a})})).json();if(i.success)g("Rollback to v"+a+" initiated. Container will restart.","success");else throw new Error(i.error||"Rollback failed")}catch(c){g("Rollback failed: "+c.message,"error")}}N?.addEventListener("click",()=>s(!1)),j?.addEventListener("click",()=>p().catch(()=>{})),R?.addEventListener("click",m),S?.addEventListener("click",f),B?.addEventListener("click",()=>{w?.classList.add("show"),h()}),wireModal(w,A),window.openUpdateModal=function(c){w?.classList.add("show"),h().then(()=>{if(!c)return;const t=z.querySelector(`[data-app-id="${c}"]`);t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.style.background="rgba(249,115,22,0.15)",setTimeout(()=>{t.style.background=""},3e3))})},document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",H),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",k),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{b(),l(),x||s(!0)}),window.dcApplyUpdate=p,window.dcCheckForUpdate=s,setTimeout(()=>s(!0),5e3)})(),(function(){injectModal("docker-resources-modal",`

\u{1F433} Docker Resources

@@ -1641,7 +1684,7 @@ Enter version to rollback to:`);if(!a)return;if(!e.includes(a)){showNotification
-
`);const x=document.getElementById("docker-resources-modal"),B=document.getElementById("docker-resources-btn"),A=document.getElementById("dr-close");function C(N){if(!N||N===0)return"0 B";const f=["B","KB","MB","GB","TB"],L=Math.floor(Math.log(Math.abs(N))/Math.log(1024));return(N/Math.pow(1024,L)).toFixed(1)+" "+f[L]}async function M(){const N=document.getElementById("dr-vol-list");try{const L=(await getJSON("/api/v1/docker/volumes")).volumes||[];if(L.length===0){N.innerHTML='
\u{1F4E6}No volumes found.
';return}let w='';w+='';for(const $ of L){const k=$.name==="buildkit"||$.name.length===64;w+='',w+=``,w+=``,w+=``,w+='"}w+="
NameDriverScopeActions
${escapeHtml($.name.length>40?$.name.substring(0,37)+"...":$.name)}${escapeHtml($.driver)}${escapeHtml($.scope)}',k||(w+=``),w+="
",N.innerHTML=w,N.querySelectorAll(".dr-vol-del").forEach($=>{$.addEventListener("click",async()=>{if(confirm(`Delete volume "${$.dataset.name}"? Data will be lost.`)){$.textContent="...",$.disabled=!0;try{await deleteAPI(`/api/v1/docker/volumes/${encodeURIComponent($.dataset.name)}?force=true`),M()}catch(k){showNotification("Delete failed: "+k.message,"error"),$.textContent="Delete",$.disabled=!1}}})})}catch(f){N.innerHTML=`
Failed: ${escapeHtml(f.message)}
`}}document.getElementById("dr-vol-create")?.addEventListener("click",async()=>{const N=document.getElementById("dr-vol-name"),f=N.value.trim();if(!f){showNotification("Enter a volume name","warning");return}try{await postJSON("/api/v1/docker/volumes",{name:f}),N.value="",showNotification(`Volume "${f}" created`,"success"),M()}catch(L){showNotification("Create failed: "+L.message,"error")}});async function P(){const N=document.getElementById("dr-net-list");try{const L=(await getJSON("/api/v1/docker/networks")).networks||[];if(L.length===0){N.innerHTML='
\u{1F310}No networks found.
';return}let w='';w+='';for(const $ of L){const k=["bridge","host","none"].includes($.name);w+='',w+=``,w+=``,w+=``,w+=``,w+='"}w+="
NameDriverScopeContainersActions
${escapeHtml($.name)}${escapeHtml($.driver)}${escapeHtml($.scope)}${$.containers}',k||(w+=``),w+="
",N.innerHTML=w,N.querySelectorAll(".dr-net-del").forEach($=>{$.addEventListener("click",async()=>{if(confirm(`Delete network "${$.dataset.name}"?`)){$.textContent="...",$.disabled=!0;try{await deleteAPI(`/api/v1/docker/networks/${encodeURIComponent($.dataset.id)}`),P()}catch(k){showNotification("Delete failed: "+k.message,"error"),$.textContent="Delete",$.disabled=!1}}})})}catch(f){N.innerHTML=`
Failed: ${escapeHtml(f.message)}
`}}document.getElementById("dr-net-create")?.addEventListener("click",async()=>{const N=document.getElementById("dr-net-name"),f=document.getElementById("dr-net-driver"),L=N.value.trim();if(!L){showNotification("Enter a network name","warning");return}try{await postJSON("/api/v1/docker/networks",{name:L,driver:f.value}),N.value="",showNotification(`Network "${L}" created`,"success"),P()}catch(w){showNotification("Create failed: "+w.message,"error")}});async function z(){const N=document.getElementById("dr-disk-content");try{const f=await getJSON("/api/v1/docker/disk-usage"),L=[{label:"Images",icon:"\u{1F4C0}",count:f.images.count,size:f.images.size,reclaimable:f.images.reclaimable},{label:"Containers",icon:"\u{1F4E6}",count:f.containers.count,size:f.containers.size,extra:`${f.containers.running} running`},{label:"Volumes",icon:"\u{1F4BE}",count:f.volumes.count,size:f.volumes.size,reclaimable:f.volumes.reclaimable},{label:"Build Cache",icon:"\u{1F527}",count:f.buildCache.count,size:f.buildCache.size,reclaimable:f.buildCache.reclaimable}];let w=`
Total: ${C(f.totalSize)}
`;w+='
';for(const $ of L)w+='
',w+=`
${$.icon} ${$.label} (${$.count})
`,w+=`
${C($.size)}
`,$.reclaimable>0&&(w+=`
Reclaimable: ${C($.reclaimable)}
`),$.extra&&(w+=`
${$.extra}
`),w+="
";w+="
",N.innerHTML=w}catch(f){N.innerHTML=`
Failed: ${escapeHtml(f.message)}
`}}B?.addEventListener("click",()=>{x?.classList.add("show"),M()}),wireModal(x,A),document.querySelector('[data-panel="dr-networks"]')?.addEventListener("click",P),document.querySelector('[data-panel="dr-disk"]')?.addEventListener("click",z)})(),(function(){injectModal("compose-import-modal",`
+
`);const w=document.getElementById("docker-resources-modal"),B=document.getElementById("docker-resources-btn"),A=document.getElementById("dr-close");function S(D){if(!D||D===0)return"0 B";const h=["B","KB","MB","GB","TB"],T=Math.floor(Math.log(Math.abs(D))/Math.log(1024));return(D/Math.pow(1024,T)).toFixed(1)+" "+h[T]}async function z(){const D=document.getElementById("dr-vol-list");try{const T=(await getJSON("/api/v1/docker/volumes")).volumes||[];if(T.length===0){D.innerHTML='
\u{1F4E6}No volumes found.
';return}let f='';f+='';for(const H of T){const k=H.name==="buildkit"||H.name.length===64;f+='',f+=``,f+=``,f+=``,f+='"}f+="
NameDriverScopeActions
${escapeHtml(H.name.length>40?H.name.substring(0,37)+"...":H.name)}${escapeHtml(H.driver)}${escapeHtml(H.scope)}',k||(f+=``),f+="
",D.innerHTML=f,D.querySelectorAll(".dr-vol-del").forEach(H=>{H.addEventListener("click",async()=>{if(confirm(`Delete volume "${H.dataset.name}"? Data will be lost.`)){H.textContent="...",H.disabled=!0;try{await deleteAPI(`/api/v1/docker/volumes/${encodeURIComponent(H.dataset.name)}?force=true`),z()}catch(k){showNotification("Delete failed: "+k.message,"error"),H.textContent="Delete",H.disabled=!1}}})})}catch(h){D.innerHTML=`
Failed: ${escapeHtml(h.message)}
`}}document.getElementById("dr-vol-create")?.addEventListener("click",async()=>{const D=document.getElementById("dr-vol-name"),h=D.value.trim();if(!h){showNotification("Enter a volume name","warning");return}try{await postJSON("/api/v1/docker/volumes",{name:h}),D.value="",showNotification(`Volume "${h}" created`,"success"),z()}catch(T){showNotification("Create failed: "+T.message,"error")}});async function P(){const D=document.getElementById("dr-net-list");try{const T=(await getJSON("/api/v1/docker/networks")).networks||[];if(T.length===0){D.innerHTML='
\u{1F310}No networks found.
';return}let f='';f+='';for(const H of T){const k=["bridge","host","none"].includes(H.name);f+='',f+=``,f+=``,f+=``,f+=``,f+='"}f+="
NameDriverScopeContainersActions
${escapeHtml(H.name)}${escapeHtml(H.driver)}${escapeHtml(H.scope)}${H.containers}',k||(f+=``),f+="
",D.innerHTML=f,D.querySelectorAll(".dr-net-del").forEach(H=>{H.addEventListener("click",async()=>{if(confirm(`Delete network "${H.dataset.name}"?`)){H.textContent="...",H.disabled=!0;try{await deleteAPI(`/api/v1/docker/networks/${encodeURIComponent(H.dataset.id)}`),P()}catch(k){showNotification("Delete failed: "+k.message,"error"),H.textContent="Delete",H.disabled=!1}}})})}catch(h){D.innerHTML=`
Failed: ${escapeHtml(h.message)}
`}}document.getElementById("dr-net-create")?.addEventListener("click",async()=>{const D=document.getElementById("dr-net-name"),h=document.getElementById("dr-net-driver"),T=D.value.trim();if(!T){showNotification("Enter a network name","warning");return}try{await postJSON("/api/v1/docker/networks",{name:T,driver:h.value}),D.value="",showNotification(`Network "${T}" created`,"success"),P()}catch(f){showNotification("Create failed: "+f.message,"error")}});async function M(){const D=document.getElementById("dr-disk-content");try{const h=await getJSON("/api/v1/docker/disk-usage"),T=[{label:"Images",icon:"\u{1F4C0}",count:h.images.count,size:h.images.size,reclaimable:h.images.reclaimable},{label:"Containers",icon:"\u{1F4E6}",count:h.containers.count,size:h.containers.size,extra:`${h.containers.running} running`},{label:"Volumes",icon:"\u{1F4BE}",count:h.volumes.count,size:h.volumes.size,reclaimable:h.volumes.reclaimable},{label:"Build Cache",icon:"\u{1F527}",count:h.buildCache.count,size:h.buildCache.size,reclaimable:h.buildCache.reclaimable}];let f=`
Total: ${S(h.totalSize)}
`;f+='
';for(const H of T)f+='
',f+=`
${H.icon} ${H.label} (${H.count})
`,f+=`
${S(H.size)}
`,H.reclaimable>0&&(f+=`
Reclaimable: ${S(H.reclaimable)}
`),H.extra&&(f+=`
${H.extra}
`),f+="
";f+="
",D.innerHTML=f}catch(h){D.innerHTML=`
Failed: ${escapeHtml(h.message)}
`}}B?.addEventListener("click",()=>{w?.classList.add("show"),z()}),wireModal(w,A),document.querySelector('[data-panel="dr-networks"]')?.addEventListener("click",P),document.querySelector('[data-panel="dr-disk"]')?.addEventListener("click",M)})(),(function(){injectModal("compose-import-modal",`

\u{1F4E6} Import Docker Compose

@@ -1682,8 +1725,8 @@ Enter version to rollback to:`);if(!a)return;if(!e.includes(a)){showNotification
- `);const x=document.getElementById("compose-import-modal"),B=document.getElementById("compose-import-btn"),A=document.getElementById("compose-cancel");wireModal(x,A);let C=null;function M(z){document.getElementById("compose-step-paste").style.display=z==="paste"?"":"none",document.getElementById("compose-step-preview").style.display=z==="preview"?"":"none",document.getElementById("compose-step-progress").style.display=z==="progress"?"":"none"}B?.addEventListener("click",()=>{M("paste"),C=null,document.getElementById("compose-yaml").value="",document.getElementById("compose-stack-name").value="",x?.classList.add("show")}),document.getElementById("compose-file-upload")?.addEventListener("change",z=>{const N=z.target.files[0];if(!N)return;const f=new FileReader;f.onload=()=>{document.getElementById("compose-yaml").value=f.result},f.readAsText(N)}),document.getElementById("compose-parse-btn")?.addEventListener("click",async()=>{const z=document.getElementById("compose-yaml").value.trim(),N=document.getElementById("compose-stack-name").value.trim()||"stack";if(!z){showNotification("Paste a docker-compose.yml","warning");return}const f=document.getElementById("compose-parse-btn"),L=f.textContent;f.textContent="Parsing...",f.disabled=!0;try{const w=await postJSON("/api/v1/apps/import-compose",{yaml:z,stackName:N});C=w,C.stackName=N,P(w),M("preview")}catch(w){showNotification("Parse failed: "+w.message,"error")}finally{f.textContent=L,f.disabled=!1}});function P(z){const N=document.getElementById("compose-preview-content");let f="";z.networks&&z.networks.length>0&&(f+=`
Networks: ${z.networks.map(L=>`${escapeHtml(L)}`).join(", ")}
`),z.volumes&&z.volumes.length>0&&(f+=`
Volumes: ${z.volumes.map(L=>`${escapeHtml(L)}`).join(", ")}
`),f+=`
${z.services.length} service(s)
`,f+='
';for(const L of z.services){const w=L.skip?"var(--bad-fg)":"var(--border)";if(f+=`
`,f+=`
${escapeHtml(L.name)}`,L.skip&&(f+=` \u2014 skipped: ${escapeHtml(L.reason)}`),f+="
",!L.skip&&(f+=`
Image: ${escapeHtml(L.image)}
`,L.ports?.length&&(f+=`
Ports: ${L.ports.map($=>`${$.host}:${$.container}`).join(", ")}
`),L.volumes?.length&&(f+=`
Volumes: ${L.volumes.length}
`),Object.keys(L.environment||{}).length&&(f+=`
Env vars: ${Object.keys(L.environment).length}
`),L.envFileWarning&&(f+=`
\u26A0 ${escapeHtml(L.envFileWarning)}
`),L.resources?.cpus||L.resources?.memory)){const $=[];L.resources.cpus&&$.push(`CPU: ${L.resources.cpus}`),L.resources.memory&&$.push(`Mem: ${L.resources.memory}MB`),f+=`
Limits: ${$.join(", ")}
`}f+="
"}f+="
",N.innerHTML=f}document.getElementById("compose-back-btn")?.addEventListener("click",()=>M("paste")),document.getElementById("compose-deploy-btn")?.addEventListener("click",async()=>{if(!C)return;const z=document.getElementById("compose-deploy-btn");z.textContent="Deploying...",z.disabled=!0,M("progress");const N=document.getElementById("compose-progress-content");N.innerHTML='
Deploying services...
';try{const f=await postJSON("/api/v1/apps/deploy-compose",{services:C.services,networks:C.networks,stackName:C.stackName});let L=`
Stack "${escapeHtml(f.stackName)}" \u2014 Deployment Complete
`;L+='
';for(const w of f.results){const $=w.status==="deployed"||w.status==="created"?"\u2705":w.status==="exists"?"\u26A1":w.status==="skipped"?"\u23ED":"\u274C";L+='
',L+=`${$} ${escapeHtml(w.name)} (${w.type}) \u2014 ${escapeHtml(w.status)}`,w.error&&(L+=` ${escapeHtml(w.error)}`),w.subdomain&&(L+=` \u2192 ${escapeHtml(w.subdomain)}`),w.reason&&(L+=` (${escapeHtml(w.reason)})`),L+="
"}L+="
",L+='',N.innerHTML=L,document.getElementById("compose-done-btn")?.addEventListener("click",()=>{x?.classList.remove("show"),typeof window.loadServices=="function"&&window.loadServices().then(()=>{typeof window.buildGrid=="function"&&window.buildGrid()})}),showNotification(`Stack "${f.stackName}" deployed`,"success")}catch(f){N.innerHTML=`
Deployment failed: ${escapeHtml(f.message)}
- `,document.getElementById("compose-retry-btn")?.addEventListener("click",()=>M("paste"))}finally{z.textContent="Deploy All",z.disabled=!1}})})(),(function(){injectModal("exec-modal",`
+
`);const w=document.getElementById("compose-import-modal"),B=document.getElementById("compose-import-btn"),A=document.getElementById("compose-cancel");wireModal(w,A);let S=null;function z(M){document.getElementById("compose-step-paste").style.display=M==="paste"?"":"none",document.getElementById("compose-step-preview").style.display=M==="preview"?"":"none",document.getElementById("compose-step-progress").style.display=M==="progress"?"":"none"}B?.addEventListener("click",()=>{z("paste"),S=null,document.getElementById("compose-yaml").value="",document.getElementById("compose-stack-name").value="",w?.classList.add("show")}),document.getElementById("compose-file-upload")?.addEventListener("change",M=>{const D=M.target.files[0];if(!D)return;const h=new FileReader;h.onload=()=>{document.getElementById("compose-yaml").value=h.result},h.readAsText(D)}),document.getElementById("compose-parse-btn")?.addEventListener("click",async()=>{const M=document.getElementById("compose-yaml").value.trim(),D=document.getElementById("compose-stack-name").value.trim()||"stack";if(!M){showNotification("Paste a docker-compose.yml","warning");return}const h=document.getElementById("compose-parse-btn"),T=h.textContent;h.textContent="Parsing...",h.disabled=!0;try{const f=await postJSON("/api/v1/apps/import-compose",{yaml:M,stackName:D});S=f,S.stackName=D,P(f),z("preview")}catch(f){showNotification("Parse failed: "+f.message,"error")}finally{h.textContent=T,h.disabled=!1}});function P(M){const D=document.getElementById("compose-preview-content");let h="";M.networks&&M.networks.length>0&&(h+=`
Networks: ${M.networks.map(T=>`${escapeHtml(T)}`).join(", ")}
`),M.volumes&&M.volumes.length>0&&(h+=`
Volumes: ${M.volumes.map(T=>`${escapeHtml(T)}`).join(", ")}
`),h+=`
${M.services.length} service(s)
`,h+='
';for(const T of M.services){const f=T.skip?"var(--bad-fg)":"var(--border)";if(h+=`
`,h+=`
${escapeHtml(T.name)}`,T.skip&&(h+=` \u2014 skipped: ${escapeHtml(T.reason)}`),h+="
",!T.skip&&(h+=`
Image: ${escapeHtml(T.image)}
`,T.ports?.length&&(h+=`
Ports: ${T.ports.map(H=>`${H.host}:${H.container}`).join(", ")}
`),T.volumes?.length&&(h+=`
Volumes: ${T.volumes.length}
`),Object.keys(T.environment||{}).length&&(h+=`
Env vars: ${Object.keys(T.environment).length}
`),T.envFileWarning&&(h+=`
\u26A0 ${escapeHtml(T.envFileWarning)}
`),T.resources?.cpus||T.resources?.memory)){const H=[];T.resources.cpus&&H.push(`CPU: ${T.resources.cpus}`),T.resources.memory&&H.push(`Mem: ${T.resources.memory}MB`),h+=`
Limits: ${H.join(", ")}
`}h+="
"}h+="
",D.innerHTML=h}document.getElementById("compose-back-btn")?.addEventListener("click",()=>z("paste")),document.getElementById("compose-deploy-btn")?.addEventListener("click",async()=>{if(!S)return;const M=document.getElementById("compose-deploy-btn");M.textContent="Deploying...",M.disabled=!0,z("progress");const D=document.getElementById("compose-progress-content");D.innerHTML='
Deploying services...
';try{const h=await postJSON("/api/v1/apps/deploy-compose",{services:S.services,networks:S.networks,stackName:S.stackName});let T=`
Stack "${escapeHtml(h.stackName)}" \u2014 Deployment Complete
`;T+='
';for(const f of h.results){const H=f.status==="deployed"||f.status==="created"?"\u2705":f.status==="exists"?"\u26A1":f.status==="skipped"?"\u23ED":"\u274C";T+='
',T+=`${H} ${escapeHtml(f.name)} (${f.type}) \u2014 ${escapeHtml(f.status)}`,f.error&&(T+=` ${escapeHtml(f.error)}`),f.subdomain&&(T+=` \u2192 ${escapeHtml(f.subdomain)}`),f.reason&&(T+=` (${escapeHtml(f.reason)})`),T+="
"}T+="
",T+='',D.innerHTML=T,document.getElementById("compose-done-btn")?.addEventListener("click",()=>{w?.classList.remove("show"),typeof window.loadServices=="function"&&window.loadServices().then(()=>{typeof window.buildGrid=="function"&&window.buildGrid()})}),showNotification(`Stack "${h.stackName}" deployed`,"success")}catch(h){D.innerHTML=`
Deployment failed: ${escapeHtml(h.message)}
+ `,document.getElementById("compose-retry-btn")?.addEventListener("click",()=>z("paste"))}finally{M.textContent="Deploy All",M.disabled=!1}})})(),(function(){injectModal("exec-modal",`

Terminal

@@ -1691,11 +1734,11 @@ Enter version to rollback to:`);if(!a)return;if(!e.includes(a)){showNotification
- `);const x=document.getElementById("exec-modal"),B=document.getElementById("exec-terminal"),A=document.getElementById("exec-close");let C=null,M=null,P=null;function z(){if(M){try{M.close()}catch{}M=null}if(C){try{C.dispose()}catch{}C=null}P=null,B.innerHTML=""}function N(f,L){if(z(),document.getElementById("exec-title").textContent=`Terminal \u2014 ${L||f}`,x?.classList.add("show"),typeof Terminal>"u"){B.innerHTML='
xterm.js not loaded
';return}C=new Terminal({cursorBlink:!0,fontSize:14,fontFamily:"'Cascadia Code', 'Fira Code', 'Consolas', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#aeafad",selectionBackground:"#264f78"},scrollback:5e3}),typeof FitAddon<"u"&&(P=new FitAddon.FitAddon,C.loadAddon(P)),C.open(B),P&&setTimeout(()=>P.fit(),50);const w=location.protocol==="https:"?"wss:":"ws:";M=new WebSocket(`${w}//${location.host}/ws/exec/${encodeURIComponent(f)}`),M.binaryType="arraybuffer",M.onopen=()=>{if(C.writeln("\x1B[32mConnecting...\x1B[0m"),P){const k=P.proposeDimensions();k&&M.send(JSON.stringify({type:"resize",cols:k.cols,rows:k.rows}))}},M.onmessage=k=>{if(typeof k.data=="string"){try{const T=JSON.parse(k.data);if(T.type==="connected"){C.writeln(`\x1B[32mConnected (${T.shell})\x1B[0m\r -`);return}if(T.type==="error"){C.writeln(`\x1B[31mError: ${T.message}\x1B[0m`);return}if(T.type==="exit"){C.writeln(`\r -\x1B[33mSession ended.\x1B[0m`);return}}catch{}C.write(k.data)}else C.write(new Uint8Array(k.data))},M.onclose=()=>{C&&C.writeln(`\r -\x1B[33mDisconnected.\x1B[0m`)},M.onerror=()=>{C&&C.writeln(`\r -\x1B[31mConnection error.\x1B[0m`)},C.onData(k=>{M&&M.readyState===WebSocket.OPEN&&M.send(k)}),C.onResize(({cols:k,rows:T})=>{M&&M.readyState===WebSocket.OPEN&&M.send(JSON.stringify({type:"resize",cols:k,rows:T}))});const $=()=>{P&&P.fit()};window.addEventListener("resize",$),x._resizeHandler=$}A?.addEventListener("click",()=>{z(),x._resizeHandler&&window.removeEventListener("resize",x._resizeHandler),x?.classList.remove("show")}),x?.addEventListener("click",f=>{f.target===x&&(z(),x._resizeHandler&&window.removeEventListener("resize",x._resizeHandler),x?.classList.remove("show"))}),window.openExecModal=N})(),(function(){injectModal("audit-modal",`
+
`);const w=document.getElementById("exec-modal"),B=document.getElementById("exec-terminal"),A=document.getElementById("exec-close");let S=null,z=null,P=null;function M(){if(z){try{z.close()}catch{}z=null}if(S){try{S.dispose()}catch{}S=null}P=null,B.innerHTML=""}function D(h,T){if(M(),document.getElementById("exec-title").textContent=`Terminal \u2014 ${T||h}`,w?.classList.add("show"),typeof Terminal>"u"){B.innerHTML='
xterm.js not loaded
';return}S=new Terminal({cursorBlink:!0,fontSize:14,fontFamily:"'Cascadia Code', 'Fira Code', 'Consolas', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#aeafad",selectionBackground:"#264f78"},scrollback:5e3}),typeof FitAddon<"u"&&(P=new FitAddon.FitAddon,S.loadAddon(P)),S.open(B),P&&setTimeout(()=>P.fit(),50);const f=location.protocol==="https:"?"wss:":"ws:";z=new WebSocket(`${f}//${location.host}/ws/exec/${encodeURIComponent(h)}`),z.binaryType="arraybuffer",z.onopen=()=>{if(S.writeln("\x1B[32mConnecting...\x1B[0m"),P){const k=P.proposeDimensions();k&&z.send(JSON.stringify({type:"resize",cols:k.cols,rows:k.rows}))}},z.onmessage=k=>{if(typeof k.data=="string"){try{const $=JSON.parse(k.data);if($.type==="connected"){S.writeln(`\x1B[32mConnected (${$.shell})\x1B[0m\r +`);return}if($.type==="error"){S.writeln(`\x1B[31mError: ${$.message}\x1B[0m`);return}if($.type==="exit"){S.writeln(`\r +\x1B[33mSession ended.\x1B[0m`);return}}catch{}S.write(k.data)}else S.write(new Uint8Array(k.data))},z.onclose=()=>{S&&S.writeln(`\r +\x1B[33mDisconnected.\x1B[0m`)},z.onerror=()=>{S&&S.writeln(`\r +\x1B[31mConnection error.\x1B[0m`)},S.onData(k=>{z&&z.readyState===WebSocket.OPEN&&z.send(k)}),S.onResize(({cols:k,rows:$})=>{z&&z.readyState===WebSocket.OPEN&&z.send(JSON.stringify({type:"resize",cols:k,rows:$}))});const H=()=>{P&&P.fit()};window.addEventListener("resize",H),w._resizeHandler=H}A?.addEventListener("click",()=>{M(),w._resizeHandler&&window.removeEventListener("resize",w._resizeHandler),w?.classList.remove("show")}),w?.addEventListener("click",h=>{h.target===w&&(M(),w._resizeHandler&&window.removeEventListener("resize",w._resizeHandler),w?.classList.remove("show"))}),window.openExecModal=D})(),(function(){injectModal("audit-modal",`

\u{1F4DC} Audit Log

- `);const x=document.getElementById("audit-modal"),B=document.getElementById("audit-log-btn"),A=document.getElementById("audit-cancel"),C=document.getElementById("audit-refresh-btn"),M=document.getElementById("audit-clear-btn"),P=document.getElementById("audit-filter"),z=document.getElementById("audit-outcome-filter"),N=document.getElementById("audit-since"),f=document.getElementById("audit-until"),L=document.getElementById("audit-log-container"),w=document.getElementById("audit-load-more");let $=0,k=null,T=0;const E=50;function I(D){if(!D)return null;const O=new Date(D);return isNaN(O.getTime())?null:O.toISOString()}async function j(D){try{D?(k&&k.abort(),k=new AbortController):(k&&k.abort(),k=new AbortController,$=0,T++,L.innerHTML='
Loading...
');const O=T,p=new URLSearchParams;p.set("limit",String(E)),p.set("offset",String($));const v=P.value,b=z.value,y=I(N.value),h=I(f.value);v&&p.set("action",v),b&&p.set("outcome",b),y&&p.set("since",y),h&&p.set("until",h);const s=await fetch("/api/v1/audit-logs?"+p.toString(),{signal:k.signal});if(!s.ok){L.innerHTML=`
Failed: HTTP ${s.status}
`,w.style.display="none";return}const c=await s.json();if(!c.success){L.innerHTML=`
Failed: ${escapeHtml(c.error||"unknown")}
`,w.style.display="none";return}if(!D&&O!==T)return;const l=Array.isArray(c.entries)?c.entries:[];if(l.length===0&&!D){const u=c.filters&&(c.filters.action||c.filters.outcome||c.filters.since||c.filters.until)?"No entries match your filters.":"No audit log entries yet. Actions will be logged automatically.";L.innerHTML=`
\u{1F4DC}${escapeHtml(u)}
`,w.style.display="none";return}let m="";D||(m='',m+='',m+='',m+='',m+='',m+='',m+='',m+='',m+="");for(const u of l){const t=u.outcome==="success",e=H(u);m+='',m+=``,m+=``,m+=``,m+=``,m+=``,m+=``,m+="",u.details&&Object.keys(u.details).length>0&&(m+=``)}if(!D)m+="
WhenActorIPActionResourceResult
${timeAgo(u.timestamp)}${e}${escapeHtml(u.ip||"-")}${escapeHtml(u.action||"-")}${escapeHtml(u.resource||"-")}${t?"\u2713":"\u2717"} ${escapeHtml(u.outcome||"")}
",L.innerHTML=m;else{const u=L.querySelector("table");u&&u.insertAdjacentHTML("beforeend",m)}$+=l.length,w.style.display=c.hasMore?"":"none",L.querySelectorAll(".audit-row").forEach(u=>{u.dataset.wired||(u.dataset.wired="true",u.addEventListener("click",()=>{const t=u.nextElementSibling;t&&t.classList.contains("audit-detail")&&(t.style.display=t.style.display==="none"?"":"none")}))})}catch(O){if(O&&O.name==="AbortError")return;L.innerHTML=`
Failed: ${escapeHtml(O.message)}
`}}function H(D){const O=D.details||{},p=O.userEmail,v=O.userId,b=O.userRole,y=O.viaProvider;if(p){const h=b?` [${escapeHtml(b)}${y?"/"+escapeHtml(y):""}]`:"";return`${escapeHtml(p)}${h}`}return v?`${escapeHtml(v)}`:D.ip?'anon':'system'}B?.addEventListener("click",()=>{x?.classList.add("show"),j(!1)}),wireModal(x,A),C?.addEventListener("click",()=>j(!1)),P?.addEventListener("change",()=>j(!1)),z?.addEventListener("change",()=>j(!1));let R;[N,f].forEach(D=>{D?.addEventListener("change",()=>{clearTimeout(R),R=setTimeout(()=>j(!1),250)})}),w?.addEventListener("click",()=>j(!0)),M?.addEventListener("click",async()=>{if(confirm("Clear the entire audit log? This cannot be undone."))try{const O=await(await secureFetch("/api/v1/audit-logs",{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:"CLEAR"})})).json();O.success?j(!1):showNotification("Error: "+(O.error||"Clear failed"),"error")}catch(D){showNotification("Error: "+D.message,"error")}})})(),(function(){injectModal("security-modal",`
+
`);const w=document.getElementById("audit-modal"),B=document.getElementById("audit-log-btn"),A=document.getElementById("audit-cancel"),S=document.getElementById("audit-refresh-btn"),z=document.getElementById("audit-clear-btn"),P=document.getElementById("audit-filter"),M=document.getElementById("audit-outcome-filter"),D=document.getElementById("audit-since"),h=document.getElementById("audit-until"),T=document.getElementById("audit-log-container"),f=document.getElementById("audit-load-more");let H=0,k=null,$=0;const E=50;function I(N){if(!N)return null;const R=new Date(N);return isNaN(R.getTime())?null:R.toISOString()}async function O(N){try{N?(k&&k.abort(),k=new AbortController):(k&&k.abort(),k=new AbortController,H=0,$++,T.innerHTML='
Loading...
');const R=$,u=new URLSearchParams;u.set("limit",String(E)),u.set("offset",String(H));const v=P.value,x=M.value,g=I(D.value),b=I(h.value);v&&u.set("action",v),x&&u.set("outcome",x),g&&u.set("since",g),b&&u.set("until",b);const s=await fetch("/api/v1/audit-logs?"+u.toString(),{signal:k.signal});if(!s.ok){T.innerHTML=`
Failed: HTTP ${s.status}
`,f.style.display="none";return}const p=await s.json();if(!p.success){T.innerHTML=`
Failed: ${escapeHtml(p.error||"unknown")}
`,f.style.display="none";return}if(!N&&R!==$)return;const l=Array.isArray(p.entries)?p.entries:[];if(l.length===0&&!N){const c=p.filters&&(p.filters.action||p.filters.outcome||p.filters.since||p.filters.until)?"No entries match your filters.":"No audit log entries yet. Actions will be logged automatically.";T.innerHTML=`
\u{1F4DC}${escapeHtml(c)}
`,f.style.display="none";return}let m="";N||(m='',m+='',m+='',m+='',m+='',m+='',m+='',m+='',m+="");for(const c of l){const t=c.outcome==="success",e=C(c);m+='',m+=``,m+=``,m+=``,m+=``,m+=``,m+=``,m+="",c.details&&Object.keys(c.details).length>0&&(m+=``)}if(!N)m+="
WhenActorIPActionResourceResult
${timeAgo(c.timestamp)}${e}${escapeHtml(c.ip||"-")}${escapeHtml(c.action||"-")}${escapeHtml(c.resource||"-")}${t?"\u2713":"\u2717"} ${escapeHtml(c.outcome||"")}
",T.innerHTML=m;else{const c=T.querySelector("table");c&&c.insertAdjacentHTML("beforeend",m)}H+=l.length,f.style.display=p.hasMore?"":"none",T.querySelectorAll(".audit-row").forEach(c=>{c.dataset.wired||(c.dataset.wired="true",c.addEventListener("click",()=>{const t=c.nextElementSibling;t&&t.classList.contains("audit-detail")&&(t.style.display=t.style.display==="none"?"":"none")}))})}catch(R){if(R&&R.name==="AbortError")return;T.innerHTML=`
Failed: ${escapeHtml(R.message)}
`}}function C(N){const R=N.details||{},u=R.userEmail,v=R.userId,x=R.userRole,g=R.viaProvider;if(u){const b=x?` [${escapeHtml(x)}${g?"/"+escapeHtml(g):""}]`:"";return`${escapeHtml(u)}${b}`}return v?`${escapeHtml(v)}`:N.ip?'anon':'system'}B?.addEventListener("click",()=>{w?.classList.add("show"),O(!1)}),wireModal(w,A),S?.addEventListener("click",()=>O(!1)),P?.addEventListener("change",()=>O(!1)),M?.addEventListener("change",()=>O(!1));let j;[D,h].forEach(N=>{N?.addEventListener("change",()=>{clearTimeout(j),j=setTimeout(()=>O(!1),250)})}),f?.addEventListener("click",()=>O(!0)),z?.addEventListener("click",async()=>{if(confirm("Clear the entire audit log? This cannot be undone."))try{const R=await(await secureFetch("/api/v1/audit-logs",{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:"CLEAR"})})).json();R.success?O(!1):showNotification("Error: "+(R.error||"Clear failed"),"error")}catch(N){showNotification("Error: "+N.message,"error")}})})(),(function(){injectModal("security-modal",`

\u{1F6E1}\uFE0F Security Center

- `);const x=document.getElementById("security-modal"),B=document.getElementById("security-center-btn"),A=document.getElementById("sec-cancel"),C=x.querySelectorAll(".sec-tab"),M=x.querySelectorAll(".sec-panel");let P=[],z=[],N=null;C.forEach(s=>{s.addEventListener("click",()=>{C.forEach(c=>c.classList.toggle("active",c===s)),M.forEach(c=>c.style.display=c.dataset.panel===s.dataset.tab?"":"none"),s.dataset.tab==="overview"&&$(),s.dataset.tab==="events"&&R(),s.dataset.tab==="hosts"&&v()})}),B&&B.addEventListener("click",()=>{x.classList.add("show"),$(),L()}),A.addEventListener("click",f),x.addEventListener("click",s=>{s.target===x&&f()});function f(){x.classList.remove("show"),w()}function L(){if(w(),!!document.getElementById("sec-live-tail").checked&&!(typeof EventSource>"u"))try{N=new EventSource("/api/v1/security/events/stream"),N.addEventListener("init",s=>{try{P=JSON.parse(s.data).events||[],D()}catch{}}),N.addEventListener("security",s=>{try{const c=JSON.parse(s.data);P.unshift(c),P.length>500&&(P.length=500);const l=x.querySelector(".sec-tab.active")?.dataset?.tab;l==="events"?D():l==="overview"&&$()}catch{}}),N.onerror=()=>{}}catch(s){console.warn("[security] SSE failed:",s.message)}}function w(){if(N){try{N.close()}catch{}N=null}}document.getElementById("sec-live-tail").addEventListener("change",()=>{x.classList.contains("show")&&L()});async function $(){try{const s=new Date(Date.now()-864e5).toISOString(),[c,l,m]=await Promise.all([fetch(`/api/v1/security/events/stats?since=${encodeURIComponent(s)}`),fetch("/api/v1/security/hosts"),fetch(`/api/v1/security/events?limit=1&since=${encodeURIComponent(s)}`)]),u=(await c.json()).data||{},t=(await l.json()).data?.hosts||[],e=(await m.json()).data?.total||0;document.querySelector('#sec-stats [data-key="total"]').textContent=`${e} events (24h)`,document.querySelector('#sec-stats [data-key="warn"]').textContent=`${u.by_severity?.warn||0} warnings`,document.querySelector('#sec-stats [data-key="error"]').textContent=`${u.by_severity?.error||0} errors`,document.querySelector('#sec-stats [data-key="denied"]').textContent=`${u.by_outcome?.denied||0} denied`,document.querySelector('#sec-stats [data-key="hosts"]').textContent=`${t.length} hosts`,k("sec-top-actors",u.top_actors||[]),k("sec-top-targets",u.top_targets||[])}catch(s){console.warn("[security] refreshOverview failed:",s.message)}}function k(s,c){const l=document.getElementById(s);if(!c.length){l.innerHTML='
No data
';return}l.innerHTML=''+c.map(m=>``).join("")+"
${y(String(m.key))}${m.count}
"}const T=document.getElementById("sec-filter-source"),E=document.getElementById("sec-filter-severity"),I=document.getElementById("sec-filter-host"),j=document.getElementById("sec-filter-actor"),H=document.getElementById("sec-refresh-btn");[T,E,I].forEach(s=>s.addEventListener("change",R)),j.addEventListener("input",h(R,250)),H.addEventListener("click",R);async function R(){try{const s=new URLSearchParams;s.set("limit","200"),T.value&&s.set("source_type",T.value),E.value&&s.set("severity",E.value),I.value&&s.set("source_host",I.value),j.value&&s.set("actor_prefix",j.value),P=(await(await fetch(`/api/v1/security/events?${s}`)).json()).data.events||[],D(),(!I.options.length||I.options.length===1)&&await p()}catch(s){document.getElementById("sec-events-container").innerHTML='
Load failed: '+y(s.message)+"
"}}function D(){const s=document.getElementById("sec-events-container");if(!P.length){s.innerHTML='
No events
';return}s.innerHTML=P.slice(0,200).map(O).join("")}function O(s){const c=s.severity||"info",l={critical:"#c0392b",error:"#e74c3c",warn:"#f39c12",notice:"#3498db",info:"#7f8c8d"}[c]||"#7f8c8d",m=s.ts?new Date(s.ts).toLocaleTimeString():"",u=s.source_type||"",t=s.actor||"\u2014",e=s.target||"",a=s.action||"",o=s.outcome||"";return`
- ${y(c)} - ${y(u)} - ${y(t)} - ${y(a)} ${y(e)} - ${y(o)} - ${y(m)} -
`}async function p(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[],l=I.value;I.innerHTML=''+c.map(m=>``).join(""),l&&(I.value=l)}catch{}}document.getElementById("sec-host-register-btn").addEventListener("click",b),document.getElementById("sec-hosts-refresh").addEventListener("click",v);async function v(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[];z=c;const l=document.getElementById("sec-hosts-container");if(!c.length){l.innerHTML='
No hosts registered. Click \u2795 Register Host to add one.
';return}l.innerHTML=c.map(m=>{const u=m.enabled?m.last_seen_at?Date.now()-Date.parse(m.last_seen_at)>18e5?"\u{1F7E1} stale":"\u{1F7E2} online":"\u26AA registered":"\u{1F534} disabled";return`
+
`);const w=document.getElementById("security-modal"),B=document.getElementById("security-center-btn"),A=document.getElementById("sec-cancel"),S=w.querySelectorAll(".sec-tab"),z=w.querySelectorAll(".sec-panel");let P=[],M=[],D=null;S.forEach(s=>{s.addEventListener("click",()=>{S.forEach(p=>p.classList.toggle("active",p===s)),z.forEach(p=>p.style.display=p.dataset.panel===s.dataset.tab?"":"none"),s.dataset.tab==="overview"&&H(),s.dataset.tab==="events"&&j(),s.dataset.tab==="hosts"&&v()})}),B&&B.addEventListener("click",()=>{w.classList.add("show"),H(),T()}),A.addEventListener("click",h),w.addEventListener("click",s=>{s.target===w&&h()});function h(){w.classList.remove("show"),f()}function T(){if(f(),!!document.getElementById("sec-live-tail").checked&&!(typeof EventSource>"u"))try{D=new EventSource("/api/v1/security/events/stream"),D.addEventListener("init",s=>{try{P=JSON.parse(s.data).events||[],N()}catch{}}),D.addEventListener("security",s=>{try{const p=JSON.parse(s.data);P.unshift(p),P.length>500&&(P.length=500);const l=w.querySelector(".sec-tab.active")?.dataset?.tab;l==="events"?N():l==="overview"&&H()}catch{}}),D.onerror=()=>{}}catch(s){console.warn("[security] SSE failed:",s.message)}}function f(){if(D){try{D.close()}catch{}D=null}}document.getElementById("sec-live-tail").addEventListener("change",()=>{w.classList.contains("show")&&T()});async function H(){try{const s=new Date(Date.now()-864e5).toISOString(),[p,l,m]=await Promise.all([fetch(`/api/v1/security/events/stats?since=${encodeURIComponent(s)}`),fetch("/api/v1/security/hosts"),fetch(`/api/v1/security/events?limit=1&since=${encodeURIComponent(s)}`)]),c=(await p.json()).data||{},t=(await l.json()).data?.hosts||[],e=(await m.json()).data?.total||0;document.querySelector('#sec-stats [data-key="total"]').textContent=`${e} events (24h)`,document.querySelector('#sec-stats [data-key="warn"]').textContent=`${c.by_severity?.warn||0} warnings`,document.querySelector('#sec-stats [data-key="error"]').textContent=`${c.by_severity?.error||0} errors`,document.querySelector('#sec-stats [data-key="denied"]').textContent=`${c.by_outcome?.denied||0} denied`,document.querySelector('#sec-stats [data-key="hosts"]').textContent=`${t.length} hosts`,k("sec-top-actors",c.top_actors||[]),k("sec-top-targets",c.top_targets||[])}catch(s){console.warn("[security] refreshOverview failed:",s.message)}}function k(s,p){const l=document.getElementById(s);if(!p.length){l.innerHTML='
No data
';return}l.innerHTML=''+p.map(m=>``).join("")+"
${g(String(m.key))}${m.count}
"}const $=document.getElementById("sec-filter-source"),E=document.getElementById("sec-filter-severity"),I=document.getElementById("sec-filter-host"),O=document.getElementById("sec-filter-actor"),C=document.getElementById("sec-refresh-btn");[$,E,I].forEach(s=>s.addEventListener("change",j)),O.addEventListener("input",b(j,250)),C.addEventListener("click",j);async function j(){try{const s=new URLSearchParams;s.set("limit","200"),$.value&&s.set("source_type",$.value),E.value&&s.set("severity",E.value),I.value&&s.set("source_host",I.value),O.value&&s.set("actor_prefix",O.value),P=(await(await fetch(`/api/v1/security/events?${s}`)).json()).data.events||[],N(),(!I.options.length||I.options.length===1)&&await u()}catch(s){document.getElementById("sec-events-container").innerHTML='
Load failed: '+g(s.message)+"
"}}function N(){const s=document.getElementById("sec-events-container");if(!P.length){s.innerHTML='
No events
';return}s.innerHTML=P.slice(0,200).map(R).join("")}function R(s){const p=s.severity||"info",l={critical:"#c0392b",error:"#e74c3c",warn:"#f39c12",notice:"#3498db",info:"#7f8c8d"}[p]||"#7f8c8d",m=s.ts?new Date(s.ts).toLocaleTimeString():"",c=s.source_type||"",t=s.actor||"\u2014",e=s.target||"",a=s.action||"",o=s.outcome||"";return`
+ ${g(p)} + ${g(c)} + ${g(t)} + ${g(a)} ${g(e)} + ${g(o)} + ${g(m)} +
`}async function u(){try{const p=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[],l=I.value;I.innerHTML=''+p.map(m=>``).join(""),l&&(I.value=l)}catch{}}document.getElementById("sec-host-register-btn").addEventListener("click",x),document.getElementById("sec-hosts-refresh").addEventListener("click",v);async function v(){try{const p=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[];M=p;const l=document.getElementById("sec-hosts-container");if(!p.length){l.innerHTML='
No hosts registered. Click \u2795 Register Host to add one.
';return}l.innerHTML=p.map(m=>{const c=m.enabled?m.last_seen_at?Date.now()-Date.parse(m.last_seen_at)>18e5?"\u{1F7E1} stale":"\u{1F7E2} online":"\u26AA registered":"\u{1F534} disabled";return`
- ${y(m.label||m.id)} - ${y(m.type)} + ${g(m.label||m.id)} + ${g(m.type)}
- id: ${y(m.id)} \xB7 + id: ${g(m.id)} \xB7 registered ${new Date(m.registered_at).toLocaleDateString()} \xB7 last seen ${m.last_seen_at?new Date(m.last_seen_at).toLocaleString():"never"}
- ${u} - ${m.id==="self"?"":``} + ${c} + ${m.id==="self"?"":``}
-
`}).join(""),l.querySelectorAll(".sec-host-del").forEach(m=>{m.addEventListener("click",async()=>{confirm(`Remove host ${m.dataset.id}? Events already received will remain in the store.`)&&(await fetch(`/api/v1/security/hosts/${encodeURIComponent(m.dataset.id)}`,{method:"DELETE"}),v())})})}catch(s){document.getElementById("sec-hosts-container").innerHTML='
Load failed: '+y(s.message)+"
"}}async function b(){const s=prompt("Host id (lowercase, no spaces):");if(!s)return;const c=prompt("Display label:",s)||s,l=prompt('Type ("dashcaddy", "service", or "agent"):',"agent")||"agent";try{const m=await fetch("/api/v1/security/hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:s,label:c,type:l})}),u=await m.json();if(!m.ok){alert("Failed: "+(u?.error?.message||m.statusText));return}alert(`\u2705 Host registered! + `}).join(""),l.querySelectorAll(".sec-host-del").forEach(m=>{m.addEventListener("click",async()=>{confirm(`Remove host ${m.dataset.id}? Events already received will remain in the store.`)&&(await fetch(`/api/v1/security/hosts/${encodeURIComponent(m.dataset.id)}`,{method:"DELETE"}),v())})})}catch(s){document.getElementById("sec-hosts-container").innerHTML='
Load failed: '+g(s.message)+"
"}}async function x(){const s=prompt("Host id (lowercase, no spaces):");if(!s)return;const p=prompt("Display label:",s)||s,l=prompt('Type ("dashcaddy", "service", or "agent"):',"agent")||"agent";try{const m=await fetch("/api/v1/security/hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:s,label:p,type:l})}),c=await m.json();if(!m.ok){alert("Failed: "+(c?.error?.message||m.statusText));return}alert(`\u2705 Host registered! -id: ${u.data.host.id} -label: ${u.data.host.label} -type: ${u.data.host.type} +id: ${c.data.host.id} +label: ${c.data.host.label} +type: ${c.data.host.type} \u{1F511} API KEY (save this NOW \u2014 won't be shown again): -${u.data.api_key} +${c.data.api_key} Send this key as: Authorization: Bearer -To endpoint: POST /api/v1/security/events/ingest or /events/batch`),v()}catch(m){alert("Failed: "+m.message)}}function y(s){return String(s).replace(/[&<>"']/g,c=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function h(s,c){let l;return function(){clearTimeout(l),l=setTimeout(()=>s.apply(this,arguments),c)}}})(),(function(){const x=new ErrorHandler;injectModal("weather-modal",`

Weather Settings

+To endpoint: POST /api/v1/security/events/ingest or /events/batch`),v()}catch(m){alert("Failed: "+m.message)}}function g(s){return String(s).replace(/[&<>"']/g,p=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[p])}function b(s,p){let l;return function(){clearTimeout(l),l=setTimeout(()=>s.apply(this,arguments),p)}}})(),(function(){const w=new ErrorHandler;injectModal("weather-modal",`

Weather Settings

Enter a city name, postal code, or “City, Country”
@@ -1863,23 +1906,23 @@ To endpoint: POST /api/v1/security/events/ingest or /events/batch`),v()}catch(m)
-
`);const B="weather-location",A="weather-zip",C="weather-geo",M="weather-unit";!safeGet(B)&&safeGet(A)&&safeSet(B,safeGet(A));function P(){return safeGet(M)||"imperial"}function z(){return{icon:document.querySelector(".weather-icon"),temp:document.querySelector(".weather-temp"),condition:document.querySelector(".weather-condition"),location:document.querySelector(".weather-location"),wind:document.querySelector(".weather-wind")}}const N={0:"Clear sky",1:"Mainly clear",2:"Partly cloudy",3:"Overcast",45:"Fog",48:"Rime fog",51:"Light drizzle",53:"Drizzle",55:"Dense drizzle",56:"Freezing drizzle",57:"Dense freezing drizzle",61:"Light rain",63:"Moderate rain",65:"Heavy rain",66:"Light freezing rain",67:"Heavy freezing rain",71:"Light snow",73:"Moderate snow",75:"Heavy snow",77:"Snow grains",80:"Light showers",81:"Moderate showers",82:"Violent showers",85:"Light snow showers",86:"Heavy snow showers",95:"Thunderstorm",96:"Thunderstorm with hail",99:"Severe thunderstorm"},f={0:"\u2600\uFE0F",1:"\u{1F324}\uFE0F",2:"\u26C5",3:"\u2601\uFE0F",45:"\u{1F32B}\uFE0F",48:"\u{1F32B}\uFE0F",51:"\u{1F326}\uFE0F",53:"\u{1F326}\uFE0F",55:"\u{1F326}\uFE0F",56:"\u{1F328}\uFE0F",57:"\u{1F328}\uFE0F",61:"\u{1F326}\uFE0F",63:"\u{1F327}\uFE0F",65:"\u{1F327}\uFE0F",66:"\u{1F328}\uFE0F",67:"\u{1F328}\uFE0F",71:"\u{1F328}\uFE0F",73:"\u2744\uFE0F",75:"\u2744\uFE0F",77:"\u2744\uFE0F",80:"\u{1F326}\uFE0F",81:"\u{1F327}\uFE0F",82:"\u{1F327}\uFE0F",85:"\u{1F328}\uFE0F",86:"\u2744\uFE0F",95:"\u26C8\uFE0F",96:"\u26C8\uFE0F",99:"\u26C8\uFE0F"},L=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];function w(H){return L[Math.round(H/22.5)%16]}async function $(H){const R=safeGet(C);if(R)try{const b=JSON.parse(R);if(b.query===H)return b}catch{}const D=await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(H)}&count=1&language=en&format=json`);if(!D.ok)throw new Error("Geocoding failed");const O=await D.json();if(!O.results||!O.results.length)throw new Error("Location not found");const p=O.results[0],v={query:H,lat:p.latitude,lon:p.longitude,city:p.name,state:p.admin1||"",country:p.country||"",countryCode:p.country_code||""};return safeSet(C,JSON.stringify(v)),v}function k(H){return H.countryCode==="US"&&H.state?`${H.city}, ${H.state}`:H.country?`${H.city}, ${H.country}`:H.city}async function T(H){try{const R=await $(H),D=P(),O=D==="metric"?"celsius":"fahrenheit",p=D==="metric"?"kmh":"mph",v=`https://api.open-meteo.com/v1/forecast?latitude=${R.lat}&longitude=${R.lon}¤t=temperature_2m,weather_code,wind_speed_10m,wind_direction_10m&temperature_unit=${O}&wind_speed_unit=${p}`,b=await fetch(v);if(!b.ok)throw new Error("Weather fetch failed");const h=(await b.json()).current,s=h.weather_code;return{temp:Math.round(h.temperature_2m),condition:N[s]||"Unknown",icon:f[s]||"\u{1F324}\uFE0F",locationStr:k(R),windSpeed:Math.round(h.wind_speed_10m),windDir:w(h.wind_direction_10m),unit:D}}catch(R){return console.warn("Weather fetch failed:",R),null}}async function E(){const H=z();if(!H.icon||!H.temp||!H.condition||!H.location||!H.wind){console.warn("Weather widget elements not found");return}const R=safeGet(B);if(!R){H.location.textContent="Set Location",H.temp.textContent="--\xB0",H.condition.textContent="Click \u2699\uFE0F to configure",H.wind.textContent="--",H.icon.innerHTML='\u{1F324}\uFE0F';return}try{const D=await T(R);if(D){const O=D.unit==="metric"?"\xB0C":"\xB0F",p=D.unit==="metric"?"km/h":"mph";H.location.textContent=D.locationStr,H.temp.textContent=`${D.temp}${O}`,H.condition.textContent=D.condition,H.wind.textContent=`Wind: ${D.windSpeed} ${p} ${D.windDir}`,H.icon.innerHTML=`${escapeHtml(D.icon)}`}}catch(D){x.logError("[Weather] Update Error",D,{function:"updateWeather"}),H.location.textContent="Weather Error",H.temp.textContent="Error",H.condition.textContent="Failed to load",H.wind.textContent="--"}}const I=document.getElementById("weather-modal"),j=document.getElementById("weather-location-input");document.getElementById("weather-settings")?.addEventListener("click",()=>{j.value=safeGet(B)||"";const H=P(),R=I.querySelector(`input[name="weather-unit-radio"][value="${H}"]`);R&&(R.checked=!0),I.classList.add("show"),j.focus()}),document.getElementById("weather-cancel")?.addEventListener("click",()=>{I.classList.remove("show")}),document.getElementById("weather-save")?.addEventListener("click",()=>{const H=j.value.trim();if(H){safeGet(B)!==H&&safeSet(C,""),safeSet(B,H);const D=I.querySelector('input[name="weather-unit-radio"]:checked'),O=D?D.value:"imperial",p=P();safeSet(M,O),p!==O&&safeSet(C,""),I.classList.remove("show"),E()}else showNotification("Please enter a location (e.g., Hamburg, London, 90210)","warning")}),wireModal(I),document.addEventListener("keydown",H=>{H.key==="Escape"&&I.classList.contains("show")&&I.classList.remove("show")}),E(),setInterval(E,DC.POLL.WEATHER)})(),(function(){const x=document.getElementById("clock-widget"),B=document.getElementById("clock-render");if(!x||!B)return;const A=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],C=["January","February","March","April","May","June","July","August","September","October","November","December"],M=["XII","I","II","III","IV","V","VI","VII","VIII","IX","X","XI"];let P=safeGet("clock-style")||"default",z=-1,N=!1,f="",L="",w=null,$=null;function k(t){if(N||safeGet("clock-chimes")!=="true")return;N=!0;const e=parseInt(safeGet("clock-chime-volume")||"50",10)/100;let a=0;function o(){if(a>=t){N=!1;return}const r=new Audio("/assets/sounds/church-bell.mp3");r.volume=e,r.play().catch(()=>{}),a++,a{N=!1},2500)}o()}function T(t){return A[t.getDay()]+", "+C[t.getMonth()]+" "+t.getDate()+", "+t.getFullYear()}function E(){L="",w=null}function I(){return L!=="digital"&&(B.innerHTML='
',w={main:B.querySelector(".clock-main"),seconds:B.querySelector(".clock-seconds"),ampm:B.querySelector(".clock-ampm"),date:B.querySelector(".clock-date")},L="digital"),w}function j(t){const e=t.getHours(),a=t.getMinutes(),o=t.getSeconds(),r=e>=12?"PM":"AM",n=e%12||12,i=I();i.main.textContent=`${n}:${String(a).padStart(2,"0")}`,i.seconds.textContent=`:${String(o).padStart(2,"0")}`,i.ampm.textContent=r,i.date.textContent=T(t)}function H(t,e){const a=t.getHours(),o=t.getMinutes(),r=t.getSeconds(),n=a>=12?"PM":"AM",i=a%12||12,d=I();d.main.textContent=`${String(i).padStart(2,"0")}:${String(o).padStart(2,"0")}`,d.seconds.textContent=`:${String(r).padStart(2,"0")}`,d.ampm.textContent=n,d.date.textContent=T(t)}function R(t){const e=t.getHours(),a=t.getMinutes(),o=t.getSeconds(),r=e>=12?"PM":"AM",n=e%12||12,i=String(n).padStart(2," ")+String(a).padStart(2,"0")+String(o).padStart(2,"0");let d='
';if(d+=D(i[0],0),d+=D(i[1],1),d+=':',d+=D(i[2],2),d+=D(i[3],3),d+=':',d+=D(i[4],4),d+=D(i[5],5),d+=`${r}`,d+="
",d+=`
${T(t)}
`,B.innerHTML=d,L="flip",f){for(let g=0;g<6;g++)if(i[g]!==f[g]){const S=B.querySelector(`.flip-card[data-idx="${g}"]`);S&&S.classList.add("flipping")}}f=i}function D(t,e){const a=t===" "?"":t;return`
${a}
${a}
`}function O(t){const e=t.getHours(),a=t.getMinutes(),o=t.getSeconds(),r=e%12||12,n=e>=12?"PM":"AM",i=[Math.floor(r/10),r%10,Math.floor(a/10),a%10,Math.floor(o/10),o%10];let d='
';d+='
HHMMSS
';for(let g=3;g>=0;g--){d+='
';for(let S=0;S<6;S++){const U=i[S]>>g&1;d+=`
`}d+="
"}d+='
';for(let g=0;g<6;g++)d+=`${i[g]}`;d+="
",d+=`
${n}
`,d+="
",d+=`
${T(t)}
`,B.innerHTML=d,L="binary"}function p(t,e){const a=t.getHours(),o=t.getMinutes(),r=t.getSeconds(),n=120,i=n/2,d=n/2,g=r/60*360-90,S=(o+r/60)/60*360-90,U=(a%12+o/60)/12*360-90;let q="";for(let X=1;X<=12;X++){const Q=X/12*2*Math.PI-Math.PI/2,ne=47,oe=i+ne*Math.cos(Q),se=d+ne*Math.sin(Q),Y=e?M[X%12]:X;q+=`${Y}`}let F="";for(let X=0;X<60;X++){const Q=X/60*2*Math.PI-Math.PI/2,ne=56,oe=X%5===0?52:54,se=i+oe*Math.cos(Q),Y=d+oe*Math.sin(Q),ie=i+ne*Math.cos(Q),re=d+ne*Math.sin(Q),ae=X%5===0?1.5:.5;F+=``}const _=` - +
`);const B="weather-location",A="weather-zip",S="weather-geo",z="weather-unit";!safeGet(B)&&safeGet(A)&&safeSet(B,safeGet(A));function P(){return safeGet(z)||"imperial"}function M(){return{icon:document.querySelector(".weather-icon"),temp:document.querySelector(".weather-temp"),condition:document.querySelector(".weather-condition"),location:document.querySelector(".weather-location"),wind:document.querySelector(".weather-wind")}}const D={0:"Clear sky",1:"Mainly clear",2:"Partly cloudy",3:"Overcast",45:"Fog",48:"Rime fog",51:"Light drizzle",53:"Drizzle",55:"Dense drizzle",56:"Freezing drizzle",57:"Dense freezing drizzle",61:"Light rain",63:"Moderate rain",65:"Heavy rain",66:"Light freezing rain",67:"Heavy freezing rain",71:"Light snow",73:"Moderate snow",75:"Heavy snow",77:"Snow grains",80:"Light showers",81:"Moderate showers",82:"Violent showers",85:"Light snow showers",86:"Heavy snow showers",95:"Thunderstorm",96:"Thunderstorm with hail",99:"Severe thunderstorm"},h={0:"\u2600\uFE0F",1:"\u{1F324}\uFE0F",2:"\u26C5",3:"\u2601\uFE0F",45:"\u{1F32B}\uFE0F",48:"\u{1F32B}\uFE0F",51:"\u{1F326}\uFE0F",53:"\u{1F326}\uFE0F",55:"\u{1F326}\uFE0F",56:"\u{1F328}\uFE0F",57:"\u{1F328}\uFE0F",61:"\u{1F326}\uFE0F",63:"\u{1F327}\uFE0F",65:"\u{1F327}\uFE0F",66:"\u{1F328}\uFE0F",67:"\u{1F328}\uFE0F",71:"\u{1F328}\uFE0F",73:"\u2744\uFE0F",75:"\u2744\uFE0F",77:"\u2744\uFE0F",80:"\u{1F326}\uFE0F",81:"\u{1F327}\uFE0F",82:"\u{1F327}\uFE0F",85:"\u{1F328}\uFE0F",86:"\u2744\uFE0F",95:"\u26C8\uFE0F",96:"\u26C8\uFE0F",99:"\u26C8\uFE0F"},T=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];function f(C){return T[Math.round(C/22.5)%16]}async function H(C){const j=safeGet(S);if(j)try{const x=JSON.parse(j);if(x.query===C)return x}catch{}const N=await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(C)}&count=1&language=en&format=json`);if(!N.ok)throw new Error("Geocoding failed");const R=await N.json();if(!R.results||!R.results.length)throw new Error("Location not found");const u=R.results[0],v={query:C,lat:u.latitude,lon:u.longitude,city:u.name,state:u.admin1||"",country:u.country||"",countryCode:u.country_code||""};return safeSet(S,JSON.stringify(v)),v}function k(C){return C.countryCode==="US"&&C.state?`${C.city}, ${C.state}`:C.country?`${C.city}, ${C.country}`:C.city}async function $(C){try{const j=await H(C),N=P(),R=N==="metric"?"celsius":"fahrenheit",u=N==="metric"?"kmh":"mph",v=`https://api.open-meteo.com/v1/forecast?latitude=${j.lat}&longitude=${j.lon}¤t=temperature_2m,weather_code,wind_speed_10m,wind_direction_10m&temperature_unit=${R}&wind_speed_unit=${u}`,x=await fetch(v);if(!x.ok)throw new Error("Weather fetch failed");const b=(await x.json()).current,s=b.weather_code;return{temp:Math.round(b.temperature_2m),condition:D[s]||"Unknown",icon:h[s]||"\u{1F324}\uFE0F",locationStr:k(j),windSpeed:Math.round(b.wind_speed_10m),windDir:f(b.wind_direction_10m),unit:N}}catch(j){return console.warn("Weather fetch failed:",j),null}}async function E(){const C=M();if(!C.icon||!C.temp||!C.condition||!C.location||!C.wind){console.warn("Weather widget elements not found");return}const j=safeGet(B);if(!j){C.location.textContent="Set Location",C.temp.textContent="--\xB0",C.condition.textContent="Click \u2699\uFE0F to configure",C.wind.textContent="--",C.icon.innerHTML='\u{1F324}\uFE0F';return}try{const N=await $(j);if(N){const R=N.unit==="metric"?"\xB0C":"\xB0F",u=N.unit==="metric"?"km/h":"mph";C.location.textContent=N.locationStr,C.temp.textContent=`${N.temp}${R}`,C.condition.textContent=N.condition,C.wind.textContent=`Wind: ${N.windSpeed} ${u} ${N.windDir}`,C.icon.innerHTML=`${escapeHtml(N.icon)}`}}catch(N){w.logError("[Weather] Update Error",N,{function:"updateWeather"}),C.location.textContent="Weather Error",C.temp.textContent="Error",C.condition.textContent="Failed to load",C.wind.textContent="--"}}const I=document.getElementById("weather-modal"),O=document.getElementById("weather-location-input");document.getElementById("weather-settings")?.addEventListener("click",()=>{O.value=safeGet(B)||"";const C=P(),j=I.querySelector(`input[name="weather-unit-radio"][value="${C}"]`);j&&(j.checked=!0),I.classList.add("show"),O.focus()}),document.getElementById("weather-cancel")?.addEventListener("click",()=>{I.classList.remove("show")}),document.getElementById("weather-save")?.addEventListener("click",()=>{const C=O.value.trim();if(C){safeGet(B)!==C&&safeSet(S,""),safeSet(B,C);const N=I.querySelector('input[name="weather-unit-radio"]:checked'),R=N?N.value:"imperial",u=P();safeSet(z,R),u!==R&&safeSet(S,""),I.classList.remove("show"),E()}else showNotification("Please enter a location (e.g., Hamburg, London, 90210)","warning")}),wireModal(I),document.addEventListener("keydown",C=>{C.key==="Escape"&&I.classList.contains("show")&&I.classList.remove("show")}),E(),setInterval(E,DC.POLL.WEATHER)})(),(function(){const w=document.getElementById("clock-widget"),B=document.getElementById("clock-render");if(!w||!B)return;const A=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],S=["January","February","March","April","May","June","July","August","September","October","November","December"],z=["XII","I","II","III","IV","V","VI","VII","VIII","IX","X","XI"];let P=safeGet("clock-style")||"default",M=-1,D=!1,h="",T="",f=null,H=null;function k(t){if(D||safeGet("clock-chimes")!=="true")return;D=!0;const e=parseInt(safeGet("clock-chime-volume")||"50",10)/100;let a=0;function o(){if(a>=t){D=!1;return}const i=new Audio("/assets/sounds/church-bell.mp3");i.volume=e,i.play().catch(()=>{}),a++,a{D=!1},2500)}o()}function $(t){return A[t.getDay()]+", "+S[t.getMonth()]+" "+t.getDate()+", "+t.getFullYear()}function E(){T="",f=null}function I(){return T!=="digital"&&(B.innerHTML='
',f={main:B.querySelector(".clock-main"),seconds:B.querySelector(".clock-seconds"),ampm:B.querySelector(".clock-ampm"),date:B.querySelector(".clock-date")},T="digital"),f}function O(t){const e=t.getHours(),a=t.getMinutes(),o=t.getSeconds(),i=e>=12?"PM":"AM",n=e%12||12,r=I();r.main.textContent=`${n}:${String(a).padStart(2,"0")}`,r.seconds.textContent=`:${String(o).padStart(2,"0")}`,r.ampm.textContent=i,r.date.textContent=$(t)}function C(t,e){const a=t.getHours(),o=t.getMinutes(),i=t.getSeconds(),n=a>=12?"PM":"AM",r=a%12||12,d=I();d.main.textContent=`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`,d.seconds.textContent=`:${String(i).padStart(2,"0")}`,d.ampm.textContent=n,d.date.textContent=$(t)}function j(t){const e=t.getHours(),a=t.getMinutes(),o=t.getSeconds(),i=e>=12?"PM":"AM",n=e%12||12,r=String(n).padStart(2," ")+String(a).padStart(2,"0")+String(o).padStart(2,"0");let d='
';if(d+=N(r[0],0),d+=N(r[1],1),d+=':',d+=N(r[2],2),d+=N(r[3],3),d+=':',d+=N(r[4],4),d+=N(r[5],5),d+=`${i}`,d+="
",d+=`
${$(t)}
`,B.innerHTML=d,T="flip",h){for(let y=0;y<6;y++)if(r[y]!==h[y]){const L=B.querySelector(`.flip-card[data-idx="${y}"]`);L&&L.classList.add("flipping")}}h=r}function N(t,e){const a=t===" "?"":t;return`
${a}
${a}
`}function R(t){const e=t.getHours(),a=t.getMinutes(),o=t.getSeconds(),i=e%12||12,n=e>=12?"PM":"AM",r=[Math.floor(i/10),i%10,Math.floor(a/10),a%10,Math.floor(o/10),o%10];let d='
';d+='
HHMMSS
';for(let y=3;y>=0;y--){d+='
';for(let L=0;L<6;L++){const U=r[L]>>y&1;d+=`
`}d+="
"}d+='
';for(let y=0;y<6;y++)d+=`${r[y]}`;d+="
",d+=`
${n}
`,d+="
",d+=`
${$(t)}
`,B.innerHTML=d,T="binary"}function u(t,e){const a=t.getHours(),o=t.getMinutes(),i=t.getSeconds(),n=120,r=n/2,d=n/2,y=i/60*360-90,L=(o+i/60)/60*360-90,U=(a%12+o/60)/12*360-90;let q="";for(let X=1;X<=12;X++){const Q=X/12*2*Math.PI-Math.PI/2,ne=47,oe=r+ne*Math.cos(Q),se=d+ne*Math.sin(Q),Y=e?z[X%12]:X;q+=`${Y}`}let F="";for(let X=0;X<60;X++){const Q=X/60*2*Math.PI-Math.PI/2,ne=56,oe=X%5===0?52:54,se=r+oe*Math.cos(Q),Y=d+oe*Math.sin(Q),ie=r+ne*Math.cos(Q),re=d+ne*Math.sin(Q),ae=X%5===0?1.5:.5;F+=``}const _=` + ${F} ${q} - - - - - `,J=t.getHours()>=12?"PM":"AM";B.innerHTML=`
${_}
${t.getHours()%12||12}:${String(o).padStart(2,"0")} ${J}${T(t)}
`,L="analog"}function v(){const t=new Date,e=t.getHours()%12||12,a=t.getMinutes(),o=t.getSeconds(),r="clock-widget"+(P!=="default"?" "+P:"");switch(x.className!==r&&(x.className=r),P){case"lcd":H(t);break;case"lcd-blue":H(t);break;case"lcd-amber":H(t);break;case"lcd-retro":H(t);break;case"lcd-taxi":H(t);break;case"flip":R(t);break;case"binary":O(t);break;case"analog":p(t,!1);break;case"roman":p(t,!0);break;default:j(t)}a===0&&o===0&&e!==z&&(z=e,k(e)),a!==0&&(z=-1)}function b(){clearTimeout($);const t=document.hidden?6e4:1e3,e=t-Date.now()%t+25;$=setTimeout(()=>{v(),b()},e)}document.addEventListener("visibilitychange",()=>{f="",E(),v(),b()}),v(),b();const y=[{id:"default",label:"Default",icon:"\u{1F550}"},{id:"lcd",label:"LCD Green",icon:"\u{1F49A}"},{id:"lcd-blue",label:"LCD Blue",icon:"\u{1F499}"},{id:"lcd-amber",label:"LCD Amber",icon:"\u{1F7E0}"},{id:"lcd-retro",label:"LCD Retro",icon:"\u{1F7E9}"},{id:"lcd-taxi",label:"LCD Taxi",icon:"\u{1F7E1}"},{id:"flip",label:"Flip Clock",icon:"\u{1F4DF}"},{id:"binary",label:"Binary",icon:"\u{1F4BB}"},{id:"analog",label:"Analog",icon:"\u23F0"},{id:"roman",label:"Roman",icon:"\u{1F3DB}\uFE0F"}];let h='
';y.forEach(t=>{h+=`