resources
This commit is contained in:
@@ -0,0 +1,165 @@
|
||||
import { readdir } from 'node:fs/promises';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { createRouter } from '../../create-router';
|
||||
import { getResourcesDir } from '../../data-path';
|
||||
|
||||
type Resource = {
|
||||
id: string;
|
||||
name: string;
|
||||
subtitle: string;
|
||||
type: string;
|
||||
port: string | null;
|
||||
path: string | null;
|
||||
description: string;
|
||||
installCommand: string | null;
|
||||
uninstallCommand: string | null;
|
||||
manageCommand: string | null;
|
||||
verifyCommand: string | null;
|
||||
updateCommand: string | null;
|
||||
installed: boolean;
|
||||
version: string | null;
|
||||
};
|
||||
|
||||
const stripBackticks = (value: string) => value.replace(/^`(.+)`$/, '$1');
|
||||
|
||||
function parseResourceFile(filename: string, content: string): Omit<Resource, 'installed' | 'version'> {
|
||||
const id = filename
|
||||
.replace(/^SERVICE_/, '')
|
||||
.replace(/\.md$/, '')
|
||||
.toLowerCase()
|
||||
.replace(/_/g, '-');
|
||||
|
||||
const headingMatch = content.match(/^#\s+(.+?)\s+—\s+(.+)$/m);
|
||||
const name = headingMatch?.[1] ?? id;
|
||||
const subtitle = headingMatch?.[2] ?? '';
|
||||
|
||||
const field = (key: string): string | null => {
|
||||
const match = content.match(new RegExp(`^-\\s+\\*\\*${key}:\\*\\*\\s+(.+)$`, 'm'));
|
||||
return match?.[1]?.trim() ?? null;
|
||||
};
|
||||
|
||||
const rawType = field('Type') ?? 'native';
|
||||
const rawPort = field('Port');
|
||||
const port = rawPort && !rawPort.startsWith('none') ? rawPort : null;
|
||||
|
||||
const rawPath = field('Path');
|
||||
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
subtitle,
|
||||
type: rawType,
|
||||
port,
|
||||
path: rawPath ? stripBackticks(rawPath) : null,
|
||||
description: field('Description') ?? '',
|
||||
installCommand: field('Install') ? stripBackticks(field('Install')!) : null,
|
||||
uninstallCommand: field('Uninstall') ? stripBackticks(field('Uninstall')!) : null,
|
||||
manageCommand: field('Manage') ? stripBackticks(field('Manage')!) : null,
|
||||
verifyCommand: field('Verify') ? stripBackticks(field('Verify')!) : null,
|
||||
updateCommand: field('Update') ? stripBackticks(field('Update')!) : null,
|
||||
};
|
||||
}
|
||||
|
||||
const CHECK_TIMEOUT_MS = 3_000;
|
||||
|
||||
async function checkPort(port: number): Promise<boolean> {
|
||||
try {
|
||||
const socket = await Bun.connect({
|
||||
hostname: '127.0.0.1',
|
||||
port,
|
||||
socket: {
|
||||
data() {},
|
||||
open(s) {
|
||||
s.end();
|
||||
},
|
||||
error() {},
|
||||
},
|
||||
});
|
||||
socket.end();
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function checkVerifyCommand(command: string): Promise<{ installed: boolean; version: string | null }> {
|
||||
try {
|
||||
const proc = Bun.spawn(['sh', '-c', command], { stdout: 'pipe', stderr: 'pipe' });
|
||||
const timeout = new Promise<never>((_, reject) =>
|
||||
setTimeout(() => {
|
||||
proc.kill();
|
||||
reject(new Error('timeout'));
|
||||
}, CHECK_TIMEOUT_MS),
|
||||
);
|
||||
const result = Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
|
||||
const [stdout, stderr] = await Promise.race([result, timeout]);
|
||||
if (proc.exitCode !== 0) return { installed: false, version: null };
|
||||
const output = (stdout + stderr).trim();
|
||||
const versionMatch = output.match(/(\d+\.\d+[\w.-]*)/);
|
||||
return { installed: true, version: versionMatch?.[1] ?? null };
|
||||
} catch {
|
||||
return { installed: false, version: null };
|
||||
}
|
||||
}
|
||||
|
||||
function extractFirstPort(portStr: string): number | null {
|
||||
const match = portStr.match(/(\d+)/);
|
||||
return match ? parseInt(match[1]!, 10) : null;
|
||||
}
|
||||
|
||||
async function checkResourceStatus(
|
||||
resource: Omit<Resource, 'installed' | 'version'>,
|
||||
): Promise<{ installed: boolean; version: string | null }> {
|
||||
if (resource.path) {
|
||||
const fullPath = `${getResourcesDir()}/${resource.path}`;
|
||||
return { installed: existsSync(fullPath), version: null };
|
||||
}
|
||||
if (resource.port) {
|
||||
const port = extractFirstPort(resource.port);
|
||||
if (port) {
|
||||
const reachable = await checkPort(port);
|
||||
return { installed: reachable, version: null };
|
||||
}
|
||||
}
|
||||
if (resource.verifyCommand) {
|
||||
return checkVerifyCommand(resource.verifyCommand);
|
||||
}
|
||||
return { installed: false, version: null };
|
||||
}
|
||||
|
||||
async function loadResources(): Promise<Resource[]> {
|
||||
const dir = getResourcesDir();
|
||||
if (!existsSync(dir)) return [];
|
||||
const files = await readdir(dir);
|
||||
const serviceFiles = files.filter((f) => f.startsWith('SERVICE_') && f.endsWith('.md'));
|
||||
|
||||
const parsed = await Promise.all(
|
||||
serviceFiles.map(async (filename) => {
|
||||
const content = await Bun.file(`${dir}/${filename}`).text();
|
||||
return parseResourceFile(filename, content);
|
||||
}),
|
||||
);
|
||||
|
||||
const resources = await Promise.all(
|
||||
parsed.map(async (r) => {
|
||||
const status = await checkResourceStatus(r);
|
||||
return { ...r, ...status };
|
||||
}),
|
||||
);
|
||||
|
||||
return resources;
|
||||
}
|
||||
|
||||
export const resourcesRouter = createRouter();
|
||||
|
||||
resourcesRouter.get('/', async (ctx) => {
|
||||
const resources = await loadResources();
|
||||
return ctx.json(resources);
|
||||
});
|
||||
|
||||
resourcesRouter.get('/:id', async (ctx) => {
|
||||
const resources = await loadResources();
|
||||
const resource = resources.find((r) => r.id === ctx.req.param('id'));
|
||||
if (!resource) return ctx.json({ error: 'Resource not found' }, 404);
|
||||
return ctx.json(resource);
|
||||
});
|
||||
Reference in New Issue
Block a user