archivo del paquete→ .shtukbase/packages/live/server/run.ts
server/run.ts
94 líneas, 4.5 KB.
El archivo tal como está en el paquete: el código y sus comentarios no se traducen.
- // Running package actions for a page: only those the project allowed in `run:` of /base/live.md. An action runs
- // the way `shtuk run` runs it: its file from .shtukbase/packages/<id>/, with the project root as the working folder.
- // `shtuk check` runs every check of the project, the way `shtuk check` does.
- import { existsSync, readFileSync } from 'node:fs';
- import { extname, join } from 'node:path';
- import { parseYaml, pystr, splitFrontMatter } from '../../collections/checks/lib/pages.ts';
- import { Refused } from './records.ts';
- import { CHECK_ALL, PAGE } from './settings.ts';
- export const TIMEOUT_MS = 120_000;
- const BUN = process.versions.bun ? process.execPath : 'bun';
- type Action = { name: string; run: string; check?: boolean };
- /** Ids of the installed packages (the lock), in name order. */
- function installed(root: string): string[] {
- const f = join(root, '.shtukbase', 'packages.lock');
- if (!existsSync(f)) return [];
- const lock = parseYaml(readFileSync(f, 'utf8'));
- return Object.keys((lock.packages as object) ?? {}).sort();
- }
- export function actionsOf(root: string, pkg: string): Action[] {
- const f = join(root, '.shtukbase', 'packages', pkg, 'package.md');
- if (!existsSync(f)) return [];
- const fm = parseYaml(splitFrontMatter(readFileSync(f, 'utf8'))[0]);
- return (Array.isArray(fm.actions) ? fm.actions : []).filter((a: any) => a && a.name && a.run)
- .map((a: any) => ({ name: pystr(a.name), run: pystr(a.run), check: a.check === true }));
- }
- function command(file: string, args: string[]): string[] {
- const ext = extname(file);
- if (ext === '.py') return ['python3', file, ...args];
- if (['.ts', '.js', '.mjs'].includes(ext)) return [BUN, file, ...args];
- return [file, ...args];
- }
- export type Step = { title: string; cmd: string[] };
- /** What a request runs, after the allow list; throws Refused with the reason. */
- export function plan(root: string, allow: string[], pkg: unknown, action: unknown, args: unknown): Step[] {
- const p = pystr(pkg ?? '').trim(), a = pystr(action ?? '').trim();
- const key = `${p} ${a}`;
- if (!allow.includes(key))
- throw new Refused(`action "${key}" is not allowed: the project allows actions by the run: list on the page ${PAGE}${allow.length ? ` (now: ${allow.join(', ')})` : ' (it is empty now)'}`);
- const list = Array.isArray(args) ? args.map((x) => pystr(x)) : args == null ? [] : null;
- if (!list) throw new Refused('args must be a list of strings');
- if (key === CHECK_ALL) {
- const steps: Step[] = [];
- for (const id of installed(root))
- for (const x of actionsOf(root, id).filter((x) => x.check))
- steps.push({ title: `${id}/${x.name}`, cmd: command(join(root, '.shtukbase', 'packages', id, x.run), []) });
- return steps;
- }
- if (!installed(root).includes(p)) throw new Refused(`package ${p} is not installed in the project`);
- const found = actionsOf(root, p).find((x) => x.name === a);
- if (!found) throw new Refused(`package ${p} has no action ${a}`);
- return [{ title: `${p}/${a}`, cmd: command(join(root, '.shtukbase', 'packages', p, found.run), list) }];
- }
- export type Event = { type: 'start'; step: string } | { type: 'out'; text: string } | { type: 'end'; step: string; code: number } | { type: 'exit'; code: number };
- /** Runs the steps one after another; every line of output and every end is an event. The exit code is that of
- * the last failed step, else 0. `signal` stops the running step. */
- export async function execute(root: string, steps: Step[], emit: (e: Event) => void, signal?: AbortSignal): Promise<number> {
- let worst = 0;
- for (const s of steps) {
- if (signal?.aborted) break;
- emit({ type: 'start', step: s.title });
- const child = Bun.spawn(s.cmd, { cwd: root, stdout: 'pipe', stderr: 'pipe', stdin: 'ignore' });
- const kill = () => child.kill();
- signal?.addEventListener('abort', kill);
- const timer = setTimeout(kill, TIMEOUT_MS);
- const pump = async (stream: ReadableStream<Uint8Array>) => {
- const dec = new TextDecoder();
- let rest = '';
- for await (const chunk of stream) {
- rest += dec.decode(chunk, { stream: true });
- const lines = rest.split('\n');
- rest = lines.pop()!;
- for (const l of lines) emit({ type: 'out', text: l });
- }
- if (rest) emit({ type: 'out', text: rest });
- };
- await Promise.all([pump(child.stdout), pump(child.stderr)]);
- const code = await child.exited;
- clearTimeout(timer);
- signal?.removeEventListener('abort', kill);
- emit({ type: 'end', step: s.title, code });
- if (code !== 0) worst = code;
- }
- emit({ type: 'exit', code: worst });
- return worst;
- }