feat: enhance project structure with server and workflow management

- Introduced a new server package with Fastify for handling API requests and workflows.
- Implemented user authentication and authorization with JWT and cookie management.
- Added endpoints for managing workflows, runs, and user accounts.
- Established a dashboard for monitoring workflow status and statistics.
- Included a script sandbox for executing user-defined scripts securely.
- Updated README with setup instructions and API documentation.
- Configured database migrations for user management.
- Enhanced logging capabilities for better traceability.
This commit is contained in:
2026-08-14 14:25:37 +07:00
parent 5574d6f723
commit 023cf83cfa
48 changed files with 6127 additions and 359 deletions
+1
View File
@@ -4,3 +4,4 @@ logs/
*.db
*.db-*
.DS_Store
packages/web/dist
+53
View File
@@ -0,0 +1,53 @@
# scrunner
Workflow runner with a sandboxed script engine, SQLite run history, and an admin UI.
## Packages
- `packages/server` — Fastify runner, HTTP/cron triggers, admin REST API
- `packages/web` — React admin UI (Vite, DaisyUI, React Query)
## Setup
```bash
pnpm install
pnpm dev
```
- API: http://localhost:9000
- UI (dev): http://localhost:5173
The first account created becomes **admin**. Later accounts are created from Users.
## Scripts
| Command | Description |
|---|---|
| `pnpm dev` | Server + Vite together |
| `pnpm dev:server` | API/runner only |
| `pnpm dev:web` | UI only (proxies `/api` to :9000) |
| `pnpm build` | Production UI build |
| `pnpm start` | Serve API and built UI from :9000 |
| `pnpm migrate` | Apply SQLite migrations |
## Environment
| Variable | Default | Notes |
|---|---|---|
| `SCRUNNER_JWT_SECRET` | `scrunner-dev-secret` (dev only) | **Required in production** |
| `SCRUNNER_DB_PATH` | `packages/server/data/scrunner.db` | SQLite file |
| `SCRUNNER_LOG_LEVEL` | `debug` | Pino level |
| `SCRUNNER_RETENTION_DAYS` | `30` | Run history prune |
| `SCRUNNER_CORS_ORIGIN` | `http://localhost:5173` | Vite origin in dev |
| `PORT` | `9000` | HTTP port |
| `NODE_ENV` | — | Set `production` for secure cookies |
## Production
```bash
pnpm install
pnpm build
SCRUNNER_JWT_SECRET=... NODE_ENV=production pnpm start
```
The server serves `packages/web/dist` when that folder exists.
+10 -18
View File
@@ -1,30 +1,22 @@
{
"name": "scrunner",
"version": "1.0.0",
"description": "",
"main": "index.js",
"private": true,
"description": "Script/workflow runner with admin UI",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"dev": "pnpm --filter @scrunner/server --filter @scrunner/web --parallel dev",
"dev:server": "pnpm --filter @scrunner/server dev",
"dev:web": "pnpm --filter @scrunner/web dev",
"build": "pnpm --filter @scrunner/web build",
"start": "pnpm --filter @scrunner/server start",
"migrate": "pnpm --filter @scrunner/server migrate"
},
"keywords": [],
"author": "",
"license": "ISC",
"packageManager": "pnpm@10.25.0",
"pnpm": {
"onlyBuiltDependencies": [
"better-sqlite3"
"better-sqlite3",
"esbuild"
]
},
"dependencies": {
"axios": "^1.19.0",
"better-sqlite3": "^13.0.3",
"fastify": "^5.12.0",
"jsonata": "^2.2.2",
"knex": "^3.3.0",
"node-cron": "^4.6.0",
"pino": "^10.3.1",
"pino-roll": "^4.0.0",
"yaml": "^2.9.0"
}
}
+25 -19
View File
@@ -4,32 +4,38 @@ Content-Type: application/json
0
HTTP/1.1 200 - OK
content-type: application/json; charset=utf-8
content-length: 73
date: Fri, 14 Aug 2026 04:34:56 GMT
connection: close
###
POST http://localhost:9000/u/default/time-to-ntfy
Content-Type: application/json
{}
HTTP/1.1 500 - Internal Server Error
content-type: application/json; charset=utf-8
content-length: 97
date: Fri, 14 Aug 2026 04:11:52 GMT
connection: close
###
GET http://localhost:9000/admin/runs?owner=default&limit=20
###
POST http://localhost:9000/admin/workflows/reregister
### Auth bootstrap
GET http://localhost:9000/api/auth/bootstrap
### Login
POST http://localhost:9000/api/auth/login
Content-Type: application/json
{
"username": "admin",
"password": "changeme1"
}
### Dashboard
GET http://localhost:9000/api/dashboard
### Runs
GET http://localhost:9000/api/runs?owner=default&limit=20
### Reregister
POST http://localhost:9000/api/workflows/reregister
Content-Type: application/json
{}
HTTP/1.1 200 - OK
content-type: application/json; charset=utf-8
content-length: 33
date: Fri, 14 Aug 2026 04:34:22 GMT
connection: close
### Run workflow manually
POST http://localhost:9000/api/workflows/default/manual-trigger.yaml/run
Content-Type: application/json
{}
+128
View File
@@ -0,0 +1,128 @@
import fs from "fs";
import path from "path";
import yaml from "yaml";
import { SCRIPTS_DIR, WORKFLOWS_DIR } from "./paths.js";
export function assertScriptName(name) {
if (typeof name !== "string" || !/^[A-Za-z0-9._-]+\.js$/.test(name)) {
const err = new Error("invalid script name");
err.statusCode = 400;
throw err;
}
return name;
}
export function assertOwner(name) {
if (typeof name !== "string" || !/^[A-Za-z0-9_-]+$/.test(name)) {
const err = new Error("invalid owner");
err.statusCode = 400;
throw err;
}
return name;
}
export function assertWorkflowFile(name) {
if (
typeof name !== "string" ||
!/^[A-Za-z0-9._-]+\.ya?ml$/.test(name) ||
name === "registers.yaml"
) {
const err = new Error("invalid workflow file");
err.statusCode = 400;
throw err;
}
return name;
}
export function listScriptFiles() {
if (!fs.existsSync(SCRIPTS_DIR)) return [];
return fs
.readdirSync(SCRIPTS_DIR)
.filter((f) => f.endsWith(".js"))
.sort();
}
export function readScript(name) {
assertScriptName(name);
const filePath = path.join(SCRIPTS_DIR, name);
if (!fs.existsSync(filePath)) return null;
return fs.readFileSync(filePath, "utf8");
}
export function writeScript(name, content) {
assertScriptName(name);
fs.mkdirSync(SCRIPTS_DIR, { recursive: true });
fs.writeFileSync(path.join(SCRIPTS_DIR, name), content, "utf8");
}
export function deleteScript(name) {
assertScriptName(name);
const filePath = path.join(SCRIPTS_DIR, name);
if (!fs.existsSync(filePath)) return false;
fs.unlinkSync(filePath);
return true;
}
export function listOwners() {
if (!fs.existsSync(WORKFLOWS_DIR)) return [];
return fs
.readdirSync(WORKFLOWS_DIR, { withFileTypes: true })
.filter((d) => d.isDirectory())
.map((d) => d.name)
.sort();
}
function registersPath(owner) {
return path.join(WORKFLOWS_DIR, owner, "registers.yaml");
}
export function readRegisters(owner) {
const filePath = registersPath(owner);
if (!fs.existsSync(filePath)) return [];
const parsed = yaml.parse(fs.readFileSync(filePath, "utf8")) ?? {};
return Array.isArray(parsed.scripts) ? parsed.scripts : [];
}
export function writeRegisters(owner, files) {
const ownerDir = path.join(WORKFLOWS_DIR, owner);
fs.mkdirSync(ownerDir, { recursive: true });
fs.writeFileSync(
registersPath(owner),
yaml.stringify({ scripts: files }),
"utf8",
);
}
export function readWorkflowYaml(owner, file) {
assertOwner(owner);
assertWorkflowFile(file);
const filePath = path.join(WORKFLOWS_DIR, owner, file);
if (!fs.existsSync(filePath)) return null;
return fs.readFileSync(filePath, "utf8");
}
export function writeWorkflowYaml(owner, file, content) {
assertOwner(owner);
assertWorkflowFile(file);
const ownerDir = path.join(WORKFLOWS_DIR, owner);
fs.mkdirSync(ownerDir, { recursive: true });
fs.writeFileSync(path.join(ownerDir, file), content, "utf8");
}
export function deleteWorkflowYaml(owner, file) {
assertOwner(owner);
assertWorkflowFile(file);
const filePath = path.join(WORKFLOWS_DIR, owner, file);
if (!fs.existsSync(filePath)) return false;
fs.unlinkSync(filePath);
return true;
}
export function listOwnerYamlFiles(owner) {
const ownerDir = path.join(WORKFLOWS_DIR, owner);
if (!fs.existsSync(ownerDir)) return [];
return fs
.readdirSync(ownerDir)
.filter((f) => f.endsWith(".yaml") && f !== "registers.yaml")
.sort();
}
+3 -2
View File
@@ -1,7 +1,8 @@
import fs from "fs";
import path from "path";
import { DATA_DIR, SERVER_ROOT } from "./paths.js";
const dbPath = process.env.SCRUNNER_DB_PATH ?? path.resolve("data/scrunner.db");
const dbPath = process.env.SCRUNNER_DB_PATH ?? path.join(DATA_DIR, "scrunner.db");
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
/** @type {import("knex").Knex.Config} */
@@ -12,7 +13,7 @@ const config = {
},
useNullAsDefault: true,
migrations: {
directory: "./migrations",
directory: path.join(SERVER_ROOT, "migrations"),
extension: "js",
loadExtensions: [".js"],
},
+3 -2
View File
@@ -2,6 +2,7 @@ import fs from "fs";
import path from "path";
import pino from "pino";
import * as store from "./store.js";
import { LOGS_DIR } from "./paths.js";
const LEVEL_TO_NUM = {
trace: 10,
@@ -87,12 +88,12 @@ const sqliteStream = {
},
};
fs.mkdirSync("logs", { recursive: true });
fs.mkdirSync(LOGS_DIR, { recursive: true });
const rollingFile = pino.transport({
target: "pino-roll",
options: {
file: path.resolve("logs/scrunner.log"),
file: path.join(LOGS_DIR, "scrunner.log"),
size: "10m",
mkdir: true,
limit: { count: 5 },
@@ -0,0 +1,20 @@
/**
* @param {import("knex").Knex} knex
*/
export async function up(knex) {
await knex.schema.createTable("users", (t) => {
t.text("id").primary();
t.text("username").notNullable().unique();
t.text("password_hash").notNullable();
t.text("role").notNullable();
t.text("created_at").notNullable();
t.text("updated_at").notNullable();
});
}
/**
* @param {import("knex").Knex} knex
*/
export async function down(knex) {
await knex.schema.dropTableIfExists("users");
}
+28
View File
@@ -0,0 +1,28 @@
{
"name": "@scrunner/server",
"version": "1.0.0",
"private": true,
"type": "module",
"main": "runner.js",
"scripts": {
"dev": "node --watch runner.js",
"start": "node runner.js",
"migrate": "node -e \"import('./db.js').then((m) => m.migrate().then(() => process.exit(0)))\""
},
"dependencies": {
"@fastify/cookie": "^11.0.2",
"@fastify/cors": "^11.1.0",
"@fastify/jwt": "^9.1.0",
"@fastify/static": "^8.2.0",
"axios": "^1.19.0",
"bcryptjs": "^3.0.2",
"better-sqlite3": "^13.0.3",
"fastify": "^5.12.0",
"jsonata": "^2.2.2",
"knex": "^3.3.0",
"node-cron": "^4.6.0",
"pino": "^10.3.1",
"pino-roll": "^4.0.0",
"yaml": "^2.9.0"
}
}
+9
View File
@@ -0,0 +1,9 @@
import path from "path";
import { fileURLToPath } from "url";
export const SERVER_ROOT = path.dirname(fileURLToPath(import.meta.url));
export const SCRIPTS_DIR = path.join(SERVER_ROOT, "scripts");
export const WORKFLOWS_DIR = path.join(SERVER_ROOT, "workflows");
export const DATA_DIR = path.join(SERVER_ROOT, "data");
export const LOGS_DIR = path.join(SERVER_ROOT, "logs");
export const WEB_DIST = path.resolve(SERVER_ROOT, "../web/dist");
+288
View File
@@ -0,0 +1,288 @@
import fs from "fs";
import path from "path";
import yaml from "yaml";
import cron from "node-cron";
import { WORKFLOWS_DIR } from "./paths.js";
import { log } from "./logger.js";
import * as store from "./store.js";
import { clearScriptCache, runScript } from "./script-sandbox.js";
import { namespacedPath, parseScriptStep } from "./workflow-parse.js";
import * as fsStore from "./fs-store.js";
/**
* @typedef {{ owner: string, file: string, workflow: any }} WorkflowEntry
*/
/**
* @param {import("fastify").FastifyInstance} server
*/
export function createRegistry(server) {
/** @type {Map<string, WorkflowEntry>} */
const workflows = new Map();
/** @type {Map<string, string>} */
const loadErrors = new Map();
/** @type {import("node-cron").ScheduledTask[]} */
const cronTasks = [];
/** @type {import("node-cron").ScheduledTask | null} */
let pruneTask = null;
/** @type {Set<string>} */
const registeredHttpRoutes = new Set();
function registerWorkflows() {
workflows.clear();
loadErrors.clear();
clearScriptCache();
if (!fs.existsSync(WORKFLOWS_DIR)) {
log.warn("workflows directory missing");
return;
}
const owners = fsStore.listOwners();
for (const owner of owners) {
const registersPath = path.join(WORKFLOWS_DIR, owner, "registers.yaml");
if (!fs.existsSync(registersPath)) {
log.warn(`Skipping owner "${owner}": no registers.yaml`);
continue;
}
let workflowFiles = [];
try {
workflowFiles = fsStore.readRegisters(owner);
} catch (err) {
log.error({ err, owner }, "failed to parse registers.yaml");
continue;
}
const onDisk = fsStore.listOwnerYamlFiles(owner);
for (const file of onDisk) {
if (!workflowFiles.includes(file)) {
log.warn(`Workflow file not in registers.yaml: ${owner}/${file}`);
}
}
for (const file of workflowFiles) {
const key = `${owner}/${file}`;
const filePath = path.join(WORKFLOWS_DIR, owner, file);
try {
const workflowData = fs.readFileSync(filePath, "utf8");
const workflow = yaml.parse(workflowData);
workflows.set(key, { owner, file, workflow });
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
loadErrors.set(key, message);
log.error({ err, workflow: key }, "failed to load workflow; skipping");
}
}
}
log.debug({ count: workflows.size }, "workflows loaded");
}
function registerHttpTriggers() {
const seen = new Set();
for (const [key, { owner, workflow }] of workflows) {
if (workflow.enabled === false) {
log.debug(`Skipping disabled workflow HTTP triggers (${key})`);
continue;
}
for (const trigger of workflow.triggers ?? []) {
if (trigger.type !== "HTTP") continue;
const method = String(trigger.method ?? "POST").toUpperCase();
const url = namespacedPath(owner, trigger.path);
const routeKey = `${method} ${url}`;
if (seen.has(routeKey)) {
log.warn(`Skipping duplicate HTTP trigger ${routeKey} (${key})`);
continue;
}
seen.add(routeKey);
if (registeredHttpRoutes.has(routeKey)) {
continue;
}
registeredHttpRoutes.add(routeKey);
server.route({
method,
url,
handler: async (req, reply) => {
const result = await runWorkflow(
key,
{ data: req.body },
{ type: "http", detail: `${method} ${url}` },
);
if (result.status === "failed") {
return reply.code(500).send({
runId: result.runId,
error: result.error,
});
}
return reply.send({
runId: result.runId,
result: result.result,
});
},
});
log.debug(`Registered HTTP trigger ${routeKey} (${key})`);
}
}
}
function registerCronTriggers() {
for (const task of cronTasks) {
task.destroy();
}
cronTasks.length = 0;
for (const [key, { workflow }] of workflows) {
if (workflow.enabled === false) {
log.debug(`Skipping disabled workflow cron triggers (${key})`);
continue;
}
for (const trigger of workflow.triggers ?? []) {
if (trigger.type !== "cron") continue;
const schedule = trigger.schedule;
if (!schedule || !cron.validate(schedule)) {
log.warn(`Skipping invalid cron schedule "${schedule}" (${key})`);
continue;
}
const task = cron.schedule(
schedule,
() => {
log.debug(`cron firing ${key} (${schedule})`);
return runWorkflow(
key,
{ data: workflow.data ?? null },
{ type: "cron", detail: schedule },
);
},
{ name: `${key}:${schedule}`, noOverlap: true },
);
cronTasks.push(task);
log.debug(`Registered cron trigger ${schedule} (${key})`);
}
}
}
function registerPruneJob() {
if (pruneTask) {
pruneTask.destroy();
pruneTask = null;
}
const days = Number(process.env.SCRUNNER_RETENTION_DAYS ?? 30);
pruneTask = cron.schedule(
"0 0 * * *",
async () => {
try {
const deleted = await store.pruneOlderThan(days);
log.info({ deleted, days }, "pruned old workflow runs");
} catch (err) {
log.error({ err }, "failed to prune old workflow runs");
}
},
{ name: "prune-runs" },
);
}
/**
* @param {string} key
* @param {{ data?: unknown }} context
* @param {{ type: string, detail?: string | null }} trigger
*/
async function runWorkflow(key, context, trigger) {
const entry = workflows.get(key);
if (!entry) {
log.error({ workflow: key }, "workflow not found");
return { runId: null, status: "failed", error: "workflow not found" };
}
const { owner, workflow } = entry;
const run = await store.startRun({
owner,
workflow: key,
workflowName: workflow?.name,
trigger,
input: context.data,
});
const runLog = log.child({ runId: run.id, owner, workflow: key });
runLog.debug("running workflow");
let ctx = {
...context,
data: context.data ?? workflow.data ?? null,
};
try {
for (const [index, rawStep] of (workflow.scripts ?? []).entries()) {
const { script, config } = parseScriptStep(rawStep);
const step = await store.startStep({
runId: run.id,
index,
script,
config,
});
const stepLog = runLog.child({ stepId: step.id, script });
try {
ctx = await runScript(script, { ...ctx, config }, {
log: stepLog,
workflowName: key,
});
await store.finishStep(step.id, "success", ctx);
} catch (err) {
await store.finishStep(step.id, "failed", null, err);
throw err;
}
}
await store.finishRun(run.id, "success", ctx);
return { runId: run.id, status: "success", result: ctx };
} catch (err) {
runLog.error({ err }, "workflow failed");
await store.finishRun(run.id, "failed", null, err);
return {
runId: run.id,
status: "failed",
error: err instanceof Error ? err.message : String(err),
};
}
}
function reregister() {
registerWorkflows();
registerHttpTriggers();
registerCronTriggers();
}
function referencedScripts() {
const refs = new Set();
for (const { workflow } of workflows.values()) {
for (const raw of workflow.scripts ?? []) {
try {
refs.add(parseScriptStep(raw).script);
} catch {
// skip invalid steps
}
}
}
return refs;
}
return {
workflows,
loadErrors,
registerWorkflows,
registerHttpTriggers,
registerCronTriggers,
registerPruneJob,
reregister,
runWorkflow,
referencedScripts,
};
}
+114 -292
View File
@@ -1,307 +1,104 @@
import fs from "fs";
import path from "path";
import yaml from "yaml";
import fastify from "fastify";
import cron from "node-cron";
import cookie from "@fastify/cookie";
import cors from "@fastify/cors";
import jwt from "@fastify/jwt";
import fastifyStatic from "@fastify/static";
import { migrate, db } from "./db.js";
import { log, enableLogPersistence, flushLogs } from "./logger.js";
import * as store from "./store.js";
import { clearScriptCache, runScript } from "./script-sandbox.js";
import { createRegistry } from "./registry.js";
import { COOKIE, OPEN_API_ROUTES } from "./src/api/auth.js";
import authPlugin from "./src/api/auth.js";
import usersPlugin from "./src/api/users.js";
import scriptsPluginFactory from "./src/api/scripts.js";
import workflowsPluginFactory from "./src/api/workflows.js";
import runsPlugin from "./src/api/runs.js";
import dashboardPluginFactory from "./src/api/dashboard.js";
import { WEB_DIST } from "./paths.js";
await migrate();
enableLogPersistence();
/**
* @typedef {{ owner: string, file: string, workflow: any }} WorkflowEntry
*/
const jwtSecret =
process.env.SCRUNNER_JWT_SECRET ??
(process.env.NODE_ENV === "production" ? "" : "scrunner-dev-secret");
/**
* @type {Map<string, WorkflowEntry>}
*/
const workflows = new Map();
/**
* @type {import("node-cron").ScheduledTask[]}
*/
const cronTasks = [];
/**
* @type {import("node-cron").ScheduledTask | null}
*/
let pruneTask = null;
/**
* @type {Set<string>}
*/
const registeredHttpRoutes = new Set();
function parseScriptStep(step) {
if (typeof step === "string") return { script: step, config: null };
if (step?.script) return { script: step.script, config: step.config ?? null };
throw new Error(`Invalid script step: ${JSON.stringify(step)}`);
if (!jwtSecret) {
log.error("SCRUNNER_JWT_SECRET is required in production");
process.exit(1);
}
/**
* Resolve an HTTP path under the owner namespace: /notify -> /u/alice/notify
* @param {string} owner
* @param {string} triggerPath
*/
function namespacedPath(owner, triggerPath) {
const cleaned = String(triggerPath).replace(/^\/+/, "");
return `/u/${owner}/${cleaned}`;
}
function registerWorkflows() {
workflows.clear();
clearScriptCache();
const workflowsRoot = "workflows";
if (!fs.existsSync(workflowsRoot)) {
log.warn("workflows directory missing");
return;
}
const owners = fs
.readdirSync(workflowsRoot, { withFileTypes: true })
.filter((d) => d.isDirectory())
.map((d) => d.name);
for (const owner of owners) {
const registersPath = path.join(workflowsRoot, owner, "registers.yaml");
if (!fs.existsSync(registersPath)) {
log.warn(`Skipping owner "${owner}": no registers.yaml`);
continue;
}
let workflowFiles = [];
try {
const registerData = fs.readFileSync(registersPath, "utf8");
const parsed = yaml.parse(registerData) ?? {};
workflowFiles = parsed.scripts ?? [];
} catch (err) {
log.error({ err, owner }, "failed to parse registers.yaml");
continue;
}
const ownerDir = path.join(workflowsRoot, owner);
const onDisk = fs
.readdirSync(ownerDir)
.filter((f) => f.endsWith(".yaml") && f !== "registers.yaml");
for (const file of onDisk) {
if (!workflowFiles.includes(file)) {
log.warn(
`Workflow file not in registers.yaml: ${owner}/${file}`,
);
}
}
for (const file of workflowFiles) {
const key = `${owner}/${file}`;
const filePath = path.join(ownerDir, file);
try {
const workflowData = fs.readFileSync(filePath, "utf8");
const workflow = yaml.parse(workflowData);
workflows.set(key, { owner, file, workflow });
} catch (err) {
log.error({ err, workflow: key }, "failed to load workflow; skipping");
}
}
}
log.debug({ count: workflows.size }, "workflows loaded");
}
function registerHttpTriggers() {
const seen = new Set();
for (const [key, { owner, workflow }] of workflows) {
if (workflow.enabled === false) {
log.debug(`Skipping disabled workflow HTTP triggers (${key})`);
continue;
}
for (const trigger of workflow.triggers ?? []) {
if (trigger.type !== "HTTP") continue;
const method = String(trigger.method ?? "POST").toUpperCase();
const url = namespacedPath(owner, trigger.path);
const routeKey = `${method} ${url}`;
if (seen.has(routeKey)) {
log.warn(`Skipping duplicate HTTP trigger ${routeKey} (${key})`);
continue;
}
seen.add(routeKey);
if (registeredHttpRoutes.has(routeKey)) {
continue;
}
registeredHttpRoutes.add(routeKey);
server.route({
method,
url,
handler: async (req, reply) => {
const result = await runWorkflow(
key,
{ data: req.body },
{ type: "http", detail: `${method} ${url}` },
);
if (result.status === "failed") {
return reply.code(500).send({
runId: result.runId,
error: result.error,
});
}
return reply.send({
runId: result.runId,
result: result.result,
});
},
});
log.debug(`Registered HTTP trigger ${routeKey} (${key})`);
}
}
}
function registerCronTriggers() {
for (const task of cronTasks) {
task.destroy();
}
cronTasks.length = 0;
for (const [key, { workflow }] of workflows) {
if (workflow.enabled === false) {
log.debug(`Skipping disabled workflow cron triggers (${key})`);
continue;
}
for (const trigger of workflow.triggers ?? []) {
if (trigger.type !== "cron") continue;
const schedule = trigger.schedule;
if (!schedule || !cron.validate(schedule)) {
log.warn(`Skipping invalid cron schedule "${schedule}" (${key})`);
continue;
}
const task = cron.schedule(
schedule,
() => {
log.debug(`cron firing ${key} (${schedule})`);
return runWorkflow(
key,
{ data: workflow.data ?? null },
{ type: "cron", detail: schedule },
);
},
{ name: `${key}:${schedule}`, noOverlap: true },
);
cronTasks.push(task);
log.debug(`Registered cron trigger ${schedule} (${key})`);
}
}
}
function registerPruneJob() {
if (pruneTask) {
pruneTask.destroy();
pruneTask = null;
}
const days = Number(process.env.SCRUNNER_RETENTION_DAYS ?? 30);
pruneTask = cron.schedule(
"0 0 * * *",
async () => {
try {
const deleted = await store.pruneOlderThan(days);
log.info({ deleted, days }, "pruned old workflow runs");
} catch (err) {
log.error({ err }, "failed to prune old workflow runs");
}
},
{ name: "prune-runs" },
);
}
/**
* @param {string} key
* @param {{ data?: unknown }} context
* @param {{ type: string, detail?: string | null }} trigger
*/
async function runWorkflow(key, context, trigger) {
const entry = workflows.get(key);
if (!entry) {
log.error({ workflow: key }, "workflow not found");
return { runId: null, status: "failed", error: "workflow not found" };
}
const { owner, workflow } = entry;
const run = await store.startRun({
owner,
workflow: key,
workflowName: workflow?.name,
trigger,
input: context.data,
});
const runLog = log.child({ runId: run.id, owner, workflow: key });
runLog.debug("running workflow");
let ctx = {
...context,
data: context.data ?? workflow.data ?? null,
};
try {
for (const [index, rawStep] of (workflow.scripts ?? []).entries()) {
const { script, config } = parseScriptStep(rawStep);
const step = await store.startStep({
runId: run.id,
index,
script,
config,
});
const stepLog = runLog.child({ stepId: step.id, script });
try {
ctx = await runScript(script, { ...ctx, config }, {
log: stepLog,
workflowName: key,
});
await store.finishStep(step.id, "success", ctx);
} catch (err) {
await store.finishStep(step.id, "failed", null, err);
throw err;
}
}
await store.finishRun(run.id, "success", ctx);
return { runId: run.id, status: "success", result: ctx };
} catch (err) {
runLog.error({ err }, "workflow failed");
await store.finishRun(run.id, "failed", null, err);
return {
runId: run.id,
status: "failed",
error: err instanceof Error ? err.message : String(err),
};
}
}
registerWorkflows();
const server = fastify({ loggerInstance: log });
registerHttpTriggers();
registerCronTriggers();
registerPruneJob();
server.post("/admin/workflows/reregister", async (_req, reply) => {
registerWorkflows();
// Fastify cannot remove routes; new routes are added, cron is rebuilt.
registerHttpTriggers();
registerCronTriggers();
return reply.send({ message: "Workflows refreshed" });
await server.register(cookie);
await server.register(jwt, {
secret: jwtSecret,
cookie: {
cookieName: COOKIE,
signed: false,
},
});
await server.register(cors, {
origin: process.env.SCRUNNER_CORS_ORIGIN ?? "http://localhost:5173",
credentials: true,
});
server.get("/admin/runs", async (req, reply) => {
server.decorate("authenticate", async function authenticate(req, reply) {
try {
await req.jwtVerify();
} catch {
return reply.code(401).send({ error: "unauthorized" });
}
});
server.decorate("requireAdmin", async function requireAdmin(req, reply) {
if (req.user?.role !== "admin") {
return reply.code(403).send({ error: "forbidden" });
}
});
const registry = createRegistry(server);
registry.registerWorkflows();
registry.registerHttpTriggers();
registry.registerCronTriggers();
registry.registerPruneJob();
await server.register(
async (api) => {
api.addHook("onRequest", async (req, reply) => {
const raw = (req.url || "").split("?")[0];
const stripped = raw.replace(/^\/api/, "") || "/";
const routeUrl = req.routeOptions?.url || stripped;
const open =
OPEN_API_ROUTES.has(`${req.method} ${routeUrl}`) ||
OPEN_API_ROUTES.has(`${req.method} ${stripped}`);
if (open) return;
await server.authenticate(req, reply);
});
await api.register(authPlugin);
await api.register(usersPlugin);
await api.register(scriptsPluginFactory(registry));
await api.register(workflowsPluginFactory(registry));
await api.register(runsPlugin);
await api.register(dashboardPluginFactory(registry));
},
{ prefix: "/api" },
);
server.post(
"/admin/workflows/reregister",
{ onRequest: [server.authenticate] },
async (_req, reply) => {
registry.reregister();
return reply.send({ message: "Workflows refreshed" });
},
);
server.get(
"/admin/runs",
{ onRequest: [server.authenticate] },
async (req, reply) => {
const q = /** @type {Record<string, string | undefined>} */ (req.query);
const limit = q.limit ? Number(q.limit) : undefined;
const runs = await store.listRuns({
@@ -312,16 +109,39 @@ server.get("/admin/runs", async (req, reply) => {
before: q.before,
});
return reply.send({ runs });
});
},
);
server.get("/admin/runs/:id", async (req, reply) => {
server.get(
"/admin/runs/:id",
{ onRequest: [server.authenticate] },
async (req, reply) => {
const { id } = /** @type {{ id: string }} */ (req.params);
const run = await store.getRun(id);
if (!run) {
return reply.code(404).send({ error: "run not found" });
}
return reply.send(run);
},
);
if (fs.existsSync(WEB_DIST)) {
await server.register(fastifyStatic, {
root: WEB_DIST,
wildcard: false,
});
server.setNotFoundHandler((req, reply) => {
const url = req.raw.url ?? "";
if (
url.startsWith("/api") ||
url.startsWith("/u/") ||
url.startsWith("/admin")
) {
return reply.code(404).send({ error: "not found" });
}
return reply.sendFile("index.html");
});
}
async function shutdown() {
try {
@@ -336,13 +156,15 @@ async function shutdown() {
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
const port = Number(process.env.PORT ?? 9000);
server
.listen({
host: "0.0.0.0",
port: 9000,
port,
})
.then(() => {
log.info("Server is running on port 9000");
log.info(`Server is running on port ${port}`);
})
.catch((err) => {
log.error({ err }, "failed to start server");
+3 -2
View File
@@ -1,8 +1,9 @@
import fs from "fs";
import path from "path";
import vm from "node:vm";
import { fileURLToPath } from "node:url";
import { createRequire } from "node:module";
import axios from "axios";
import { SCRIPTS_DIR } from "./paths.js";
const hostRequire = createRequire(import.meta.url);
@@ -291,7 +292,7 @@ function createScriptSandbox({ log, script, workflowName }) {
}
function loadCompiledScript(script) {
const filePath = fileURLToPath(new URL(`./scripts/${script}`, import.meta.url));
const filePath = path.join(SCRIPTS_DIR, script);
const { mtimeMs } = fs.statSync(filePath);
const cached = scriptCache.get(script);
if (cached && cached.mtimeMs === mtimeMs) {
+7 -3
View File
@@ -1,6 +1,10 @@
import jsonata from "jsonata";
export default function jsonataFn(context) {
const expression = jsonata(context.config.expression);
return expression.evaluate(context.data)
export default function jsonataFn(ctx) {
log.info({ctx}, "jsonata: context")
log.info("jsonata: evaluating expression %s", ctx.config.expression);
const expression = jsonata(ctx.config.expression);
const result = expression.evaluate(ctx.data);
log.info({result}, "jsonata: expression result");
return result;
}
+9 -2
View File
@@ -1,12 +1,19 @@
export default async function ntfy(ctx) {
log.info({ ctx }, "ntfy");
log.info({ ctx }, "ntfy incoming context");
const headers = {}
if(ctx.data?.title) {
log.info("ntfy: setting title %s", ctx.data.title);
headers.Title = ctx.data.title
}
await $axios.post(ctx.config?.url || "https://ntfy.sh/scrunner", ctx.data?.message || "Hello from scrunner", {
const ntfyUrl = ctx.config?.url || "https://ntfy.sh/scrunner";
log.info("ntfy sending message to %s", ntfyUrl);
const truncatedMessage = ctx.data?.message?.substring(0, 100);
log.info("ntfy messsage: %s", truncatedMessage);
await $axios.post(ntfyUrl, ctx.data?.message || "Hello from scrunner", {
headers: headers
})
return {sent: "true"}
+103
View File
@@ -0,0 +1,103 @@
import bcrypt from "bcryptjs";
import * as store from "../../store.js";
export const COOKIE = "scrunner_token";
export const OPEN_API_ROUTES = new Set([
"GET /auth/bootstrap",
"POST /auth/register",
"POST /auth/login",
]);
export function cookieOpts() {
return {
httpOnly: true,
path: "/",
sameSite: "lax",
secure: process.env.NODE_ENV === "production",
maxAge: 7 * 24 * 60 * 60,
};
}
export function validateCredentials(username, password) {
if (!/^[A-Za-z0-9_]{3,32}$/.test(username)) {
return "username must be 3-32 letters, numbers, or underscore";
}
if (password.length < 8) {
return "password must be at least 8 characters";
}
return null;
}
/**
* @param {import("fastify").FastifyInstance} fastify
*/
export default async function authPlugin(fastify) {
fastify.get("/auth/bootstrap", async () => {
const count = await store.countUsers();
return { needsSetup: count === 0 };
});
fastify.post("/auth/register", async (req, reply) => {
const count = await store.countUsers();
if (count > 0) {
return reply.code(403).send({ error: "setup already complete" });
}
const body = /** @type {{ username?: string, password?: string }} */ (req.body ?? {});
const username = String(body.username ?? "").trim();
const password = String(body.password ?? "");
const err = validateCredentials(username, password);
if (err) return reply.code(400).send({ error: err });
const passwordHash = await bcrypt.hash(password, 10);
const user = await store.createUser({
username,
passwordHash,
role: "admin",
});
const token = await reply.jwtSign({
id: user.id,
username: user.username,
role: user.role,
});
reply.setCookie(COOKIE, token, cookieOpts());
return { user };
});
fastify.post("/auth/login", async (req, reply) => {
const body = /** @type {{ username?: string, password?: string }} */ (req.body ?? {});
const username = String(body.username ?? "").trim();
const password = String(body.password ?? "");
const row = await store.getUserAuthByUsername(username);
if (!row || !(await bcrypt.compare(password, row.password_hash))) {
return reply.code(401).send({ error: "invalid credentials" });
}
const token = await reply.jwtSign({
id: row.id,
username: row.username,
role: row.role,
});
reply.setCookie(COOKIE, token, cookieOpts());
return {
user: {
id: row.id,
username: row.username,
role: row.role,
created_at: row.created_at,
updated_at: row.updated_at,
},
};
});
fastify.post("/auth/logout", async (_req, reply) => {
reply.clearCookie(COOKIE, { path: "/" });
return { ok: true };
});
fastify.get("/auth/me", async (req, reply) => {
const user = await store.getUserById(req.user.id);
if (!user) {
return reply.code(401).send({ error: "unauthorized" });
}
return { user };
});
}
+86
View File
@@ -0,0 +1,86 @@
import yaml from "yaml";
import * as store from "../../store.js";
import * as fsStore from "../../fs-store.js";
/**
* @param {{ workflows: Map<string, any>, loadErrors: Map<string, string> }} registry
*/
export default function dashboardPluginFactory(registry) {
/**
* @param {import("fastify").FastifyInstance} fastify
*/
return async function dashboardPlugin(fastify) {
fastify.get("/dashboard", async () => {
const owners = fsStore.listOwners();
let workflowCount = 0;
let enabledCount = 0;
let brokenCount = registry.loadErrors.size;
const brokenWorkflows = [];
for (const [key, message] of registry.loadErrors) {
const [owner, ...rest] = key.split("/");
brokenWorkflows.push({
key,
owner,
file: rest.join("/"),
loadError: message,
});
}
for (const owner of owners) {
let registered = [];
try {
registered = fsStore.readRegisters(owner);
} catch {
registered = [];
}
const files = [
...new Set([...registered, ...fsStore.listOwnerYamlFiles(owner)]),
];
for (const file of files) {
workflowCount += 1;
const key = `${owner}/${file}`;
const loaded = registry.workflows.get(key);
if (loaded?.workflow && loaded.workflow.enabled !== false) {
enabledCount += 1;
} else if (!loaded && !registry.loadErrors.has(key)) {
const raw = fsStore.readWorkflowYaml(owner, file);
if (raw) {
try {
const parsed = yaml.parse(raw);
if (parsed?.enabled !== false) enabledCount += 1;
} catch (err) {
brokenCount += 1;
brokenWorkflows.push({
key,
owner,
file,
loadError: err instanceof Error ? err.message : String(err),
});
}
}
}
}
}
const [running, failed, recent] = await Promise.all([
store.listRuns({ status: "running", limit: 10 }),
store.listRuns({ status: "failed", limit: 20 }),
store.listRuns({ limit: 10 }),
]);
return {
workflowCount,
scriptCount: fsStore.listScriptFiles().length,
enabledCount,
brokenCount,
running,
needsAttention: {
failed,
brokenWorkflows,
},
recent,
};
});
};
}
+26
View File
@@ -0,0 +1,26 @@
import * as store from "../../store.js";
/**
* @param {import("fastify").FastifyInstance} fastify
*/
export default async function runsPlugin(fastify) {
fastify.get("/runs", async (req) => {
const q = /** @type {Record<string, string | undefined>} */ (req.query ?? {});
const limit = q.limit ? Number(q.limit) : undefined;
const runs = await store.listRuns({
owner: q.owner,
workflow: q.workflow,
status: q.status,
limit: Number.isFinite(limit) ? limit : undefined,
before: q.before,
});
return { runs };
});
fastify.get("/runs/:id", async (req, reply) => {
const { id } = /** @type {{ id: string }} */ (req.params);
const run = await store.getRun(id);
if (!run) return reply.code(404).send({ error: "run not found" });
return run;
});
}
+64
View File
@@ -0,0 +1,64 @@
import { clearScriptCache } from "../../script-sandbox.js";
import * as fsStore from "../../fs-store.js";
/**
* @param {{ referencedScripts: () => Set<string> }} registry
*/
export default function scriptsPluginFactory(registry) {
/**
* @param {import("fastify").FastifyInstance} fastify
*/
return async function scriptsPlugin(fastify) {
fastify.get("/scripts", async () => {
return { scripts: fsStore.listScriptFiles() };
});
fastify.get("/scripts/:name", async (req, reply) => {
const { name } = /** @type {{ name: string }} */ (req.params);
try {
fsStore.assertScriptName(name);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({ error: err.message });
}
const content = fsStore.readScript(name);
if (content == null) return reply.code(404).send({ error: "script not found" });
return { name, content };
});
fastify.put("/scripts/:name", async (req, reply) => {
const { name } = /** @type {{ name: string }} */ (req.params);
try {
fsStore.assertScriptName(name);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({ error: err.message });
}
const body = /** @type {{ content?: string }} */ (req.body ?? {});
if (typeof body.content !== "string") {
return reply.code(400).send({ error: "content is required" });
}
const existed = fsStore.readScript(name) != null;
fsStore.writeScript(name, body.content);
clearScriptCache();
return reply.code(existed ? 200 : 201).send({ name });
});
fastify.delete("/scripts/:name", async (req, reply) => {
const { name } = /** @type {{ name: string }} */ (req.params);
try {
fsStore.assertScriptName(name);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({ error: err.message });
}
if (registry.referencedScripts().has(name)) {
return reply
.code(409)
.send({ error: "script is referenced by a workflow" });
}
if (!fsStore.deleteScript(name)) {
return reply.code(404).send({ error: "script not found" });
}
clearScriptCache();
return { ok: true };
});
};
}
+85
View File
@@ -0,0 +1,85 @@
import bcrypt from "bcryptjs";
import * as store from "../../store.js";
import { validateCredentials } from "./auth.js";
/**
* @param {import("fastify").FastifyInstance} fastify
*/
export default async function usersPlugin(fastify) {
fastify.addHook("onRequest", fastify.requireAdmin);
fastify.get("/users", async () => {
const users = await store.listUsers();
return { users };
});
fastify.post("/users", async (req, reply) => {
const body = /** @type {{ username?: string, password?: string, role?: string }} */ (
req.body ?? {}
);
const username = String(body.username ?? "").trim();
const password = String(body.password ?? "");
const role = body.role === "admin" ? "admin" : "operator";
const err = validateCredentials(username, password);
if (err) return reply.code(400).send({ error: err });
const existing = await store.getUserAuthByUsername(username);
if (existing) {
return reply.code(409).send({ error: "username taken" });
}
const user = await store.createUser({
username,
passwordHash: await bcrypt.hash(password, 10),
role,
});
return reply.code(201).send({ user });
});
fastify.patch("/users/:id", async (req, reply) => {
const { id } = /** @type {{ id: string }} */ (req.params);
const existing = await store.getUserAuthById(id);
if (!existing) return reply.code(404).send({ error: "user not found" });
const body = /** @type {{ password?: string, role?: string }} */ (req.body ?? {});
/** @type {{ passwordHash?: string, role?: string }} */
const patch = {};
if (body.role) {
if (body.role !== "admin" && body.role !== "operator") {
return reply.code(400).send({ error: "invalid role" });
}
if (existing.role === "admin" && body.role !== "admin") {
const admins = await store.countAdmins();
if (admins <= 1) {
return reply.code(400).send({ error: "cannot demote last admin" });
}
}
patch.role = body.role;
}
if (body.password) {
if (body.password.length < 8) {
return reply.code(400).send({ error: "password must be at least 8 characters" });
}
patch.passwordHash = await bcrypt.hash(body.password, 10);
}
const user = await store.updateUser(id, patch);
return { user };
});
fastify.delete("/users/:id", async (req, reply) => {
const { id } = /** @type {{ id: string }} */ (req.params);
const existing = await store.getUserAuthById(id);
if (!existing) return reply.code(404).send({ error: "user not found" });
if (existing.role === "admin") {
const admins = await store.countAdmins();
if (admins <= 1) {
return reply.code(400).send({ error: "cannot delete last admin" });
}
}
await store.deleteUser(id);
return { ok: true };
});
}
+240
View File
@@ -0,0 +1,240 @@
import yaml from "yaml";
import * as store from "../../store.js";
import * as fsStore from "../../fs-store.js";
import { namespacedPath, parseScriptStep } from "../../workflow-parse.js";
function triggerSummary(owner, workflow) {
if (!workflow || typeof workflow !== "object") return [];
return (workflow.triggers ?? []).map((t) => {
const type = t?.type ?? "unknown";
const isHttp = String(type).toLowerCase() === "http";
return {
type,
method: isHttp ? String(t?.method ?? "POST").toUpperCase() : t?.method ?? null,
path: isHttp && t?.path != null ? namespacedPath(owner, t.path) : t?.path ?? null,
schedule: t?.schedule ?? null,
};
});
}
function scriptNames(workflow) {
if (!workflow || typeof workflow !== "object") return [];
const names = [];
for (const raw of workflow.scripts ?? []) {
try {
names.push(parseScriptStep(raw).script);
} catch {
names.push(null);
}
}
return names;
}
/**
* @param {{ workflows: Map<string, any>, loadErrors: Map<string, string>, reregister: () => void }} registry
*/
export default function workflowsPluginFactory(registry) {
/**
* @param {import("fastify").FastifyInstance} fastify
*/
return async function workflowsPlugin(fastify) {
fastify.get("/owners", async () => {
return { owners: fsStore.listOwners() };
});
fastify.get("/workflows", async (req) => {
const q = /** @type {{ owner?: string }} */ (req.query ?? {});
const stats = await store.workflowStats();
const owners = q.owner
? [fsStore.assertOwner(q.owner)]
: fsStore.listOwners();
const items = [];
for (const owner of owners) {
let registered = [];
try {
registered = fsStore.readRegisters(owner);
} catch {
registered = [];
}
const onDisk = fsStore.listOwnerYamlFiles(owner);
const files = [...new Set([...registered, ...onDisk])];
for (const file of files) {
const key = `${owner}/${file}`;
const loaded = registry.workflows.get(key);
const loadError = registry.loadErrors.get(key) ?? null;
let parsed = loaded?.workflow ?? null;
if (!parsed) {
const raw = fsStore.readWorkflowYaml(owner, file);
if (raw != null) {
try {
parsed = yaml.parse(raw);
} catch (err) {
// keep loadError
if (!loadError) {
// file on disk but unparseable and not in registers
}
}
}
}
const st = stats[key] ?? {
invocationCount: 0,
lastInvokedAt: null,
lastStatus: null,
};
items.push({
owner,
file,
key,
name: parsed?.name ?? file,
description: parsed?.description ?? null,
enabled: parsed ? parsed.enabled !== false : false,
registered: registered.includes(file),
loadError:
loadError ??
(parsed ? null : "unreadable"),
lastInvokedAt: st.lastInvokedAt,
lastStatus: st.lastStatus ?? null,
invocationCount: st.invocationCount,
triggers: triggerSummary(owner, parsed),
scripts: scriptNames(parsed),
});
}
}
return { workflows: items };
});
fastify.get("/workflows/:owner/:file", async (req, reply) => {
const { owner, file } = /** @type {{ owner: string, file: string }} */ (
req.params
);
try {
fsStore.assertOwner(owner);
fsStore.assertWorkflowFile(file);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({ error: err.message });
}
const content = fsStore.readWorkflowYaml(owner, file);
if (content == null) {
return reply.code(404).send({ error: "workflow not found" });
}
const key = `${owner}/${file}`;
let parsed = null;
let parseError = null;
try {
parsed = yaml.parse(content);
} catch (err) {
parseError = err instanceof Error ? err.message : String(err);
}
const stats = (await store.workflowStats())[key] ?? {
invocationCount: 0,
lastInvokedAt: null,
lastStatus: null,
};
return {
owner,
file,
key,
content,
parsed,
parseError,
loadError: registry.loadErrors.get(key) ?? parseError,
lastInvokedAt: stats.lastInvokedAt,
lastStatus: stats.lastStatus ?? null,
invocationCount: stats.invocationCount,
};
});
fastify.put("/workflows/:owner/:file", async (req, reply) => {
const { owner, file } = /** @type {{ owner: string, file: string }} */ (
req.params
);
try {
fsStore.assertOwner(owner);
fsStore.assertWorkflowFile(file);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({ error: err.message });
}
const body = /** @type {{ content?: string }} */ (req.body ?? {});
if (typeof body.content !== "string") {
return reply.code(400).send({ error: "content is required" });
}
try {
yaml.parse(body.content);
} catch (err) {
return reply.code(400).send({
error: `invalid yaml: ${err instanceof Error ? err.message : String(err)}`,
});
}
const existed = fsStore.readWorkflowYaml(owner, file) != null;
fsStore.writeWorkflowYaml(owner, file, body.content);
const registered = fsStore.readRegisters(owner);
if (!registered.includes(file)) {
registered.push(file);
fsStore.writeRegisters(owner, registered);
}
registry.reregister();
return reply.code(existed ? 200 : 201).send({ owner, file });
});
fastify.delete("/workflows/:owner/:file", async (req, reply) => {
const { owner, file } = /** @type {{ owner: string, file: string }} */ (
req.params
);
try {
fsStore.assertOwner(owner);
fsStore.assertWorkflowFile(file);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({ error: err.message });
}
if (!fsStore.deleteWorkflowYaml(owner, file)) {
return reply.code(404).send({ error: "workflow not found" });
}
const registered = fsStore.readRegisters(owner).filter((f) => f !== file);
fsStore.writeRegisters(owner, registered);
registry.reregister();
return { ok: true };
});
fastify.post("/workflows/:owner/:file/run", async (req, reply) => {
const { owner, file } = /** @type {{ owner: string, file: string }} */ (
req.params
);
try {
fsStore.assertOwner(owner);
fsStore.assertWorkflowFile(file);
} catch (err) {
return reply.code(err.statusCode ?? 400).send({ error: err.message });
}
const key = `${owner}/${file}`;
if (!registry.workflows.has(key)) {
return reply.code(404).send({
error: registry.loadErrors.get(key) ?? "workflow not loaded",
});
}
const body = /** @type {{ data?: unknown }} */ (req.body ?? {});
const result = await registry.runWorkflow(
key,
{ data: body.data ?? null },
{ type: "manual", detail: "ui" },
);
if (result.status === "failed") {
return reply.code(result.runId ? 500 : 404).send({
runId: result.runId,
error: result.error,
});
}
return {
runId: result.runId,
status: result.status,
result: result.result,
};
});
fastify.post("/workflows/reregister", async () => {
registry.reregister();
return { message: "Workflows refreshed" };
});
};
}
+99
View File
@@ -235,3 +235,102 @@ export async function pruneOlderThan(days) {
const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
return db("workflow_runs").where("started_at", "<", cutoff).del();
}
/**
* @returns {Promise<Record<string, { invocationCount: number, lastInvokedAt: string | null, lastStatus: string | null }>>}
*/
export async function workflowStats() {
const rows = await db("workflow_runs")
.select("workflow", "status", "started_at")
.orderBy("started_at", "desc");
/** @type {Record<string, { invocationCount: number, lastInvokedAt: string | null, lastStatus: string | null }>} */
const out = {};
for (const row of rows) {
const existing = out[row.workflow];
if (!existing) {
out[row.workflow] = {
invocationCount: 1,
lastInvokedAt: row.started_at ?? null,
lastStatus: row.status ?? null,
};
} else {
existing.invocationCount += 1;
}
}
return out;
}
export async function countUsers() {
const row = await db("users").count({ n: "*" }).first();
return Number(row?.n ?? 0);
}
export async function countAdmins() {
const row = await db("users").where({ role: "admin" }).count({ n: "*" }).first();
return Number(row?.n ?? 0);
}
/**
* @param {{ username: string, passwordHash: string, role: string }} opts
*/
export async function createUser({ username, passwordHash, role }) {
const id = randomUUID();
const now = nowIso();
await db("users").insert({
id,
username,
password_hash: passwordHash,
role,
created_at: now,
updated_at: now,
});
return getUserById(id);
}
export async function getUserById(id) {
const row = await db("users").where({ id }).first();
return row ? publicUser(row) : null;
}
export async function getUserAuthByUsername(username) {
return db("users").where({ username }).first();
}
export async function getUserAuthById(id) {
return db("users").where({ id }).first();
}
export async function listUsers() {
const rows = await db("users")
.select("id", "username", "role", "created_at", "updated_at")
.orderBy("username", "asc");
return rows;
}
/**
* @param {string} id
* @param {{ passwordHash?: string, role?: string }} patch
*/
export async function updateUser(id, patch) {
const update = { updated_at: nowIso() };
if (patch.passwordHash) update.password_hash = patch.passwordHash;
if (patch.role) update.role = patch.role;
await db("users").where({ id }).update(update);
return getUserById(id);
}
export async function deleteUser(id) {
return db("users").where({ id }).del();
}
function publicUser(row) {
return {
id: row.id,
username: row.username,
role: row.role,
created_at: row.created_at,
updated_at: row.updated_at,
};
}
+15
View File
@@ -0,0 +1,15 @@
export function parseScriptStep(step) {
if (typeof step === "string") return { script: step, config: null };
if (step?.script) return { script: step.script, config: step.config ?? null };
throw new Error(`Invalid script step: ${JSON.stringify(step)}`);
}
/**
* Resolve an HTTP path under the owner namespace: /notify -> /u/alice/notify
* @param {string} owner
* @param {string} triggerPath
*/
export function namespacedPath(owner, triggerPath) {
const cleaned = String(triggerPath).replace(/^\/+/, "");
return `/u/${owner}/${cleaned}`;
}
@@ -6,4 +6,5 @@ triggers:
- type: HTTP
method: POST
path: /mt
- type: manual
+1 -1
View File
@@ -1,4 +1,4 @@
name: manual trigger
name: jsonata
scripts:
- get-current-time.js
- script: jsonata.js
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>scrunner</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
+29
View File
@@ -0,0 +1,29 @@
{
"name": "@scrunner/web",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@monaco-editor/react": "^4.7.0",
"@tanstack/react-query": "^5.84.0",
"axios": "^1.11.0",
"mermaid": "^11.9.0",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-icons": "^5.5.0",
"react-router-dom": "^7.8.0",
"yaml": "^2.8.1"
},
"devDependencies": {
"@tailwindcss/vite": "^4.1.11",
"@vitejs/plugin-react": "^5.0.0",
"daisyui": "^5.0.50",
"tailwindcss": "^4.1.11",
"vite": "^7.1.2"
}
}
+60
View File
@@ -0,0 +1,60 @@
import { useEffect } from "react";
import { Navigate, Route, Routes } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import { useBootstrap, useMe } from "./api/hooks.js";
import { Layout } from "./components/Layout.jsx";
import { AuthPage } from "./pages/AuthPage.jsx";
import { HomePage } from "./pages/HomePage.jsx";
import { ScriptsPage } from "./pages/ScriptsPage.jsx";
import { WorkflowsPage } from "./pages/WorkflowsPage.jsx";
import { EventsPage } from "./pages/EventsPage.jsx";
import { EventDetailPage } from "./pages/EventDetailPage.jsx";
import { UsersPage } from "./pages/UsersPage.jsx";
export function App() {
const qc = useQueryClient();
const bootstrap = useBootstrap();
const me = useMe();
useEffect(() => {
function onUnauthorized() {
qc.setQueryData(["me"], null);
}
window.addEventListener("scrunner:unauthorized", onUnauthorized);
return () => window.removeEventListener("scrunner:unauthorized", onUnauthorized);
}, [qc]);
const user = me.data?.user;
const loading =
bootstrap.isLoading || (me.isLoading && !me.isError && me.data === undefined);
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center">
<span className="loading loading-spinner loading-lg" />
</div>
);
}
if (!user) {
return <AuthPage needsSetup={Boolean(bootstrap.data?.needsSetup)} />;
}
return (
<Layout user={user}>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/scripts" element={<ScriptsPage />} />
<Route path="/workflows" element={<WorkflowsPage />} />
<Route path="/events" element={<EventsPage />} />
<Route path="/events/:id" element={<EventDetailPage />} />
{user.role === "admin" ? (
<Route path="/users" element={<UsersPage />} />
) : (
<Route path="/users" element={<Navigate to="/" replace />} />
)}
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</Layout>
);
}
+22
View File
@@ -0,0 +1,22 @@
import axios from "axios";
export const api = axios.create({
baseURL: "/api",
withCredentials: true,
});
api.interceptors.response.use(
(res) => res,
(err) => {
const url = err.config?.url ?? "";
const isAuthCall = url.includes("/auth/login") || url.includes("/auth/register") || url.includes("/auth/me") || url.includes("/auth/bootstrap");
if (err.response?.status === 401 && !isAuthCall) {
window.dispatchEvent(new Event("scrunner:unauthorized"));
}
return Promise.reject(err);
},
);
export function errorMessage(err, fallback = "request failed") {
return err?.response?.data?.error ?? err?.message ?? fallback;
}
+256
View File
@@ -0,0 +1,256 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "./client.js";
export function useBootstrap() {
return useQuery({
queryKey: ["bootstrap"],
queryFn: async () => (await api.get("/auth/bootstrap")).data,
});
}
export function useMe() {
return useQuery({
queryKey: ["me"],
queryFn: async () => {
try {
return (await api.get("/auth/me")).data;
} catch (err) {
if (err.response?.status === 401) return { user: null };
throw err;
}
},
retry: false,
});
}
export function useLogin() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (body) => (await api.post("/auth/login", body)).data,
onSuccess: (data) => {
qc.setQueryData(["me"], data);
qc.invalidateQueries({ queryKey: ["bootstrap"] });
},
});
}
export function useRegister() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (body) => (await api.post("/auth/register", body)).data,
onSuccess: (data) => {
qc.setQueryData(["me"], data);
qc.invalidateQueries({ queryKey: ["bootstrap"] });
},
});
}
export function useLogout() {
const qc = useQueryClient();
return useMutation({
mutationFn: async () => (await api.post("/auth/logout")).data,
onSuccess: () => {
qc.setQueryData(["me"], null);
qc.clear();
},
});
}
export function useDashboard() {
return useQuery({
queryKey: ["dashboard"],
queryFn: async () => (await api.get("/dashboard")).data,
refetchInterval: (query) =>
query.state.data?.running?.length ? 4000 : 15000,
});
}
export function useScripts() {
return useQuery({
queryKey: ["scripts"],
queryFn: async () => (await api.get("/scripts")).data.scripts,
});
}
export function useScript(name, enabled = true) {
return useQuery({
queryKey: ["scripts", name],
queryFn: async () => (await api.get(`/scripts/${encodeURIComponent(name)}`)).data,
enabled: Boolean(name) && enabled,
});
}
export function useSaveScript() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ name, content }) =>
(await api.put(`/scripts/${encodeURIComponent(name)}`, { content })).data,
onSuccess: (_data, vars) => {
qc.invalidateQueries({ queryKey: ["scripts"] });
qc.invalidateQueries({ queryKey: ["scripts", vars.name] });
qc.invalidateQueries({ queryKey: ["dashboard"] });
},
});
}
export function useDeleteScript() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (name) =>
(await api.delete(`/scripts/${encodeURIComponent(name)}`)).data,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["scripts"] });
qc.invalidateQueries({ queryKey: ["dashboard"] });
},
});
}
export function useWorkflows(owner) {
return useQuery({
queryKey: ["workflows", owner ?? "all"],
queryFn: async () => {
const params = owner ? { owner } : {};
return (await api.get("/workflows", { params })).data.workflows;
},
});
}
export function useWorkflow(owner, file, enabled = true) {
return useQuery({
queryKey: ["workflows", owner, file],
queryFn: async () =>
(await api.get(`/workflows/${encodeURIComponent(owner)}/${encodeURIComponent(file)}`))
.data,
enabled: Boolean(owner && file) && enabled,
});
}
export function useOwners() {
return useQuery({
queryKey: ["owners"],
queryFn: async () => (await api.get("/owners")).data.owners,
});
}
export function useSaveWorkflow() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ owner, file, content }) =>
(
await api.put(
`/workflows/${encodeURIComponent(owner)}/${encodeURIComponent(file)}`,
{ content },
)
).data,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["workflows"] });
qc.invalidateQueries({ queryKey: ["owners"] });
qc.invalidateQueries({ queryKey: ["dashboard"] });
},
});
}
export function useDeleteWorkflow() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ owner, file }) =>
(
await api.delete(
`/workflows/${encodeURIComponent(owner)}/${encodeURIComponent(file)}`,
)
).data,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["workflows"] });
qc.invalidateQueries({ queryKey: ["dashboard"] });
},
});
}
export function useRunWorkflow() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ owner, file, data }) =>
(
await api.post(
`/workflows/${encodeURIComponent(owner)}/${encodeURIComponent(file)}/run`,
data !== undefined ? { data } : {},
)
).data,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["workflows"] });
qc.invalidateQueries({ queryKey: ["runs"] });
qc.invalidateQueries({ queryKey: ["dashboard"] });
},
});
}
export function useReregisterWorkflows() {
const qc = useQueryClient();
return useMutation({
mutationFn: async () => (await api.post("/workflows/reregister")).data,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["workflows"] });
qc.invalidateQueries({ queryKey: ["scripts"] });
qc.invalidateQueries({ queryKey: ["owners"] });
qc.invalidateQueries({ queryKey: ["dashboard"] });
},
});
}
export function useRuns(filters = {}) {
const { owner, workflow, status, limit } = filters;
return useQuery({
queryKey: ["runs", { owner, workflow, status, limit }],
queryFn: async () => {
const params = {};
if (owner) params.owner = owner;
if (workflow) params.workflow = workflow;
if (status) params.status = status;
if (limit) params.limit = limit;
return (await api.get("/runs", { params })).data.runs;
},
});
}
export function useRun(id) {
return useQuery({
queryKey: ["runs", id],
queryFn: async () => (await api.get(`/runs/${encodeURIComponent(id)}`)).data,
enabled: Boolean(id),
refetchInterval: (query) =>
query.state.data?.status === "running" ? 2000 : false,
});
}
export function useUsers() {
return useQuery({
queryKey: ["users"],
queryFn: async () => (await api.get("/users")).data.users,
});
}
export function useCreateUser() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (body) => (await api.post("/users", body)).data,
onSuccess: () => qc.invalidateQueries({ queryKey: ["users"] }),
});
}
export function useUpdateUser() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ id, ...body }) =>
(await api.patch(`/users/${encodeURIComponent(id)}`, body)).data,
onSuccess: () => qc.invalidateQueries({ queryKey: ["users"] }),
});
}
export function useDeleteUser() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (id) =>
(await api.delete(`/users/${encodeURIComponent(id)}`)).data,
onSuccess: () => qc.invalidateQueries({ queryKey: ["users"] }),
});
}
@@ -0,0 +1,30 @@
import Editor from "@monaco-editor/react";
import { useTheme } from "../theme.jsx";
export function CodeEditor({ language, value, onChange, height = "50vh" }) {
const { theme } = useTheme();
const isMobile = typeof window !== "undefined" && window.innerWidth < 768;
return (
<div className="overflow-hidden rounded-box border border-base-300">
<Editor
height={height}
language={language}
value={value}
onChange={(v) => onChange(v ?? "")}
theme={theme === "dark" ? "vs-dark" : "light"}
options={{
minimap: { enabled: !isMobile },
lineNumbers: "on",
tabSize: 2,
insertSpaces: true,
autoIndent: "full",
automaticLayout: true,
wordWrap: "on",
scrollBeyondLastLine: false,
fontSize: 13,
}}
/>
</div>
);
}
+93
View File
@@ -0,0 +1,93 @@
import { NavLink, useNavigate } from "react-router-dom";
import {
LuActivity,
LuCode,
LuGitBranch,
LuHouse,
LuLogOut,
LuMenu,
LuMoon,
LuSun,
LuUsers,
} from "react-icons/lu";
import { useLogout } from "../api/hooks.js";
import { useTheme } from "../theme.jsx";
const links = [
{ to: "/", label: "Home", icon: LuHouse, end: true },
{ to: "/scripts", label: "Scripts", icon: LuCode },
{ to: "/workflows", label: "Workflows", icon: LuGitBranch },
{ to: "/events", label: "Events", icon: LuActivity },
];
export function Layout({ user, children }) {
const { theme, toggle } = useTheme();
const logout = useLogout();
const navigate = useNavigate();
const navItems = [
...links,
...(user.role === "admin"
? [{ to: "/users", label: "Users", icon: LuUsers }]
: []),
];
function closeDrawer() {
const el = document.getElementById("nav-drawer");
if (el) el.checked = false;
}
return (
<div className="drawer lg:drawer-open">
<input id="nav-drawer" type="checkbox" className="drawer-toggle" />
<div className="drawer-content flex min-h-screen flex-col">
<div className="navbar bg-base-100 border-base-300 sticky top-0 z-10 border-b">
<div className="flex-none lg:hidden">
<label htmlFor="nav-drawer" className="btn btn-square btn-ghost" aria-label="Open menu">
<LuMenu className="size-5" />
</label>
</div>
<div className="flex-1 px-2 text-lg font-semibold">scrunner</div>
<div className="flex items-center gap-1">
<button
type="button"
className="btn btn-ghost btn-square"
onClick={toggle}
title={theme === "dark" ? "Light" : "Dark"}
aria-label="Toggle theme"
>
{theme === "dark" ? <LuSun className="size-5" /> : <LuMoon className="size-5" />}
</button>
<span className="hidden sm:inline text-sm opacity-70 px-2">{user.username}</span>
<button
type="button"
className="btn btn-ghost btn-square"
title="Log out"
aria-label="Log out"
onClick={() =>
logout.mutate(undefined, { onSuccess: () => navigate("/") })
}
>
<LuLogOut className="size-5" />
</button>
</div>
</div>
<main className="flex-1 p-4">{children}</main>
</div>
<div className="drawer-side z-20">
<label htmlFor="nav-drawer" aria-label="Close menu" className="drawer-overlay" />
<ul className="menu bg-base-200 min-h-full w-64 p-4">
<li className="menu-title">scrunner</li>
{navItems.map(({ to, label, icon: Icon, end }) => (
<li key={to}>
<NavLink to={to} end={end} onClick={closeDrawer}>
<Icon className="size-4" />
{label}
</NavLink>
</li>
))}
</ul>
</div>
</div>
);
}
@@ -0,0 +1,75 @@
import { useEffect, useId, useRef } from "react";
import { useNavigate } from "react-router-dom";
import mermaid from "mermaid";
import { useTheme } from "../theme.jsx";
function findNode(root, id) {
return (
root.querySelector(`#${CSS.escape(id)}`) ||
root.querySelector(`[id="${CSS.escape(id)}"]`) ||
root.querySelector(`[id*="${CSS.escape(id)}"]`)
);
}
export function MermaidDiagram({ chart, scriptIds = {} }) {
const { theme } = useTheme();
const navigate = useNavigate();
const ref = useRef(null);
const reactId = useId().replace(/:/g, "");
const scriptKey = JSON.stringify(scriptIds);
useEffect(() => {
if (!chart || !ref.current) {
if (ref.current) ref.current.innerHTML = "";
return;
}
let cancelled = false;
mermaid.initialize({
startOnLoad: false,
securityLevel: "loose",
suppressErrorRendering: true,
theme: theme === "dark" ? "dark" : "default",
});
const ids = JSON.parse(scriptKey);
const renderId = `mmd-${reactId}-${Date.now()}`;
mermaid
.render(renderId, chart)
.then(({ svg }) => {
if (cancelled || !ref.current) return;
ref.current.innerHTML = svg;
for (const [nodeId, script] of Object.entries(ids)) {
const el = findNode(ref.current, nodeId);
if (!el) continue;
el.style.cursor = "pointer";
el.setAttribute("title", script);
el.addEventListener("click", () => {
navigate(`/scripts?edit=${encodeURIComponent(script)}`);
});
}
})
.catch((err) => {
if (cancelled || !ref.current) return;
ref.current.innerHTML = "";
const p = document.createElement("p");
p.className = "text-error text-sm";
p.textContent = "Could not render diagram";
ref.current.appendChild(p);
});
return () => {
cancelled = true;
};
}, [chart, scriptKey, theme, navigate, reactId]);
if (!chart) return null;
return (
<div
ref={ref}
className="mermaid-clickable overflow-x-auto rounded-box border border-base-300 bg-base-200 p-3"
/>
);
}
+14
View File
@@ -0,0 +1,14 @@
@import "tailwindcss";
@plugin "daisyui" {
themes: light --default, dark --prefersdark;
}
html,
body,
#root {
min-height: 100%;
}
.mermaid-clickable [id^="s"] {
cursor: pointer;
}
+51
View File
@@ -0,0 +1,51 @@
export function formatTime(iso) {
if (!iso) return "—";
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return "—";
return d.toLocaleString();
}
export function StatusBadge({ status }) {
const cls =
status === "success"
? "badge-success"
: status === "failed"
? "badge-error"
: status === "running"
? "badge-warning"
: "badge-ghost";
return <span className={`badge badge-sm ${cls}`}>{status ?? "—"}</span>;
}
/** Config load + last-run health for the workflows list. */
export function WorkflowStatusBadge({ workflow }) {
if (workflow.loadError) {
return (
<span className="badge badge-error badge-sm" title={workflow.loadError}>
broken
</span>
);
}
if (!workflow.enabled) {
return <span className="badge badge-ghost badge-sm">disabled</span>;
}
if (workflow.lastStatus === "failed") {
return <span className="badge badge-error badge-sm">failed</span>;
}
if (workflow.lastStatus === "running") {
return <span className="badge badge-warning badge-sm">running</span>;
}
if (workflow.lastStatus === "success") {
return <span className="badge badge-success badge-sm">working</span>;
}
return <span className="badge badge-ghost badge-sm">never run</span>;
}
export function levelName(level) {
if (level <= 10) return "trace";
if (level <= 20) return "debug";
if (level <= 30) return "info";
if (level <= 40) return "warn";
if (level <= 50) return "error";
return "fatal";
}
+67
View File
@@ -0,0 +1,67 @@
function sanitize(label) {
const cleaned = String(label ?? "")
.replace(/[^A-Za-z0-9]+/g, "_")
.replace(/_+/g, "_")
.replace(/^_|_$/g, "")
.slice(0, 48);
return cleaned || "node";
}
function parseStep(step) {
if (typeof step === "string") return step;
if (step?.script) return step.script;
return null;
}
export function workflowToArchitecture(parsed) {
/** @type {Record<string, string>} */
const scriptIds = {};
if (!parsed || typeof parsed !== "object") {
return { chart: "", scriptIds };
}
const groupId = "wf";
const name = sanitize(parsed.name || "workflow");
const lines = ["architecture-beta", ` group ${groupId}[${name}]`];
const triggerIds = [];
const triggers = Array.isArray(parsed.triggers) ? parsed.triggers : [];
triggers.forEach((t, i) => {
const id = `t${i}`;
const icon = t?.type === "cron" ? "cloud" : "internet";
const label =
t?.type === "cron"
? `cron ${t.schedule ?? ""}`
: `${t?.method ?? "POST"} ${t?.path ?? ""}`;
lines.push(` service ${id}(${icon})[${sanitize(label)}] in ${groupId}`);
triggerIds.push(id);
});
const scripts = Array.isArray(parsed.scripts) ? parsed.scripts : [];
let prev = null;
let firstScript = null;
scripts.forEach((step, i) => {
const script = parseStep(step);
if (!script) return;
const id = `s${i}`;
scriptIds[id] = script;
lines.push(` service ${id}(server)[${sanitize(script)}] in ${groupId}`);
if (!firstScript) firstScript = id;
if (prev) lines.push(` ${prev}:R -- L:${id}`);
prev = id;
});
// All triggers point at the first script (not chained to each other).
if (firstScript) {
for (const tid of triggerIds) {
lines.push(` ${tid}:R -- L:${firstScript}`);
}
}
// Keep multiple triggers in one column so they don't overlap.
if (triggerIds.length >= 2) {
lines.push(` align column ${triggerIds.join(" ")}`);
}
return { chart: lines.join("\n"), scriptIds };
}
+28
View File
@@ -0,0 +1,28 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider } from "./theme.jsx";
import { App } from "./App.jsx";
import "./index.css";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 10_000,
refetchOnWindowFocus: false,
},
},
});
createRoot(document.getElementById("root")).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<ThemeProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</ThemeProvider>
</QueryClientProvider>
</StrictMode>,
);
+64
View File
@@ -0,0 +1,64 @@
import { useState } from "react";
import { LuLogIn, LuUserPlus } from "react-icons/lu";
import { errorMessage } from "../api/client.js";
import { useLogin, useRegister } from "../api/hooks.js";
export function AuthPage({ needsSetup }) {
const login = useLogin();
const register = useRegister();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const mutation = needsSetup ? register : login;
const error = mutation.isError ? errorMessage(mutation.error) : null;
function onSubmit(e) {
e.preventDefault();
mutation.mutate({ username, password });
}
return (
<div className="min-h-screen flex items-center justify-center p-4 bg-base-200">
<form
onSubmit={onSubmit}
className="fieldset bg-base-100 border-base-300 rounded-box w-full max-w-sm border p-6 gap-3"
>
<legend className="fieldset-legend text-lg">
{needsSetup ? "Create admin" : "Sign in"}
</legend>
<label className="label" htmlFor="username">
Username
</label>
<input
id="username"
className="input w-full"
autoComplete="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/>
<label className="label" htmlFor="password">
Password
</label>
<input
id="password"
type="password"
className="input w-full"
autoComplete={needsSetup ? "new-password" : "current-password"}
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={8}
/>
{error ? <p className="text-error text-sm">{error}</p> : null}
<button
type="submit"
className="btn btn-primary mt-2"
disabled={mutation.isPending}
>
{needsSetup ? <LuUserPlus className="size-4" /> : <LuLogIn className="size-4" />}
{needsSetup ? "Create" : "Sign in"}
</button>
</form>
</div>
);
}
+129
View File
@@ -0,0 +1,129 @@
import { useState } from "react";
import { Link, useParams } from "react-router-dom";
import { LuArrowLeft } from "react-icons/lu";
import { useRun } from "../api/hooks.js";
import { formatTime, levelName, StatusBadge } from "../lib/format.jsx";
export function EventDetailPage() {
const { id } = useParams();
const { data: run, isLoading, error } = useRun(id);
const [wordWrap, setWordWrap] = useState(true);
if (isLoading) return <span className="loading loading-spinner loading-lg" />;
if (error || !run) return <p className="text-error">Event not found</p>;
return (
<div className="space-y-4">
<div className="flex items-center gap-2">
<Link to="/events" className="btn btn-ghost btn-sm btn-square" aria-label="Back">
<LuArrowLeft className="size-4" />
</Link>
<h1 className="text-xl font-semibold truncate">{run.workflow_name || run.workflow}</h1>
<StatusBadge status={run.status} />
</div>
<dl className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-1 text-sm">
<div>
<dt className="opacity-60">Started</dt>
<dd>{formatTime(run.started_at)}</dd>
</div>
<div>
<dt className="opacity-60">Finished</dt>
<dd>{formatTime(run.finished_at)}</dd>
</div>
<div>
<dt className="opacity-60">Trigger</dt>
<dd>
{run.trigger_type}
{run.trigger_detail ? ` · ${run.trigger_detail}` : ""}
</dd>
</div>
<div>
<dt className="opacity-60">Duration</dt>
<dd>{run.duration_ms != null ? `${run.duration_ms}ms` : "—"}</dd>
</div>
</dl>
{run.error ? (
<div role="alert" className="alert alert-error text-sm">
{run.error}
</div>
) : null}
<section>
<h2 className="font-semibold mb-2">Steps</h2>
<div className="overflow-x-auto">
<table className="table table-sm">
<thead>
<tr>
<th>#</th>
<th>Script</th>
<th>Status</th>
<th>Duration</th>
<th>Error</th>
</tr>
</thead>
<tbody>
{(run.steps ?? []).map((s) => (
<tr key={s.id}>
<td>{s.step_index}</td>
<td className="font-mono">
<Link className="link" to={`/scripts?edit=${encodeURIComponent(s.script)}`}>
{s.script}
</Link>
</td>
<td>
<StatusBadge status={s.status} />
</td>
<td>{s.duration_ms != null ? `${s.duration_ms}ms` : "—"}</td>
<td className="text-error text-xs">{s.error || ""}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
<section>
<div className="mb-2 flex items-center justify-between gap-2">
<h2 className="font-semibold">Logs</h2>
<label className="label cursor-pointer gap-2 py-0">
<span className="label-text text-sm">Word wrap</span>
<input
type="checkbox"
className="checkbox checkbox-sm"
checked={wordWrap}
onChange={(e) => setWordWrap(e.target.checked)}
/>
</label>
</div>
<div className="mockup-code text-xs max-h-[50vh] overflow-auto">
{(run.logs ?? []).length === 0 ? (
<div className="flex gap-3 px-5 py-0.5 font-mono opacity-50">
<span className="w-12 shrink-0 text-right">—</span>
<span>no logs</span>
</div>
) : (
run.logs.map((l) => (
<div key={l.id} className="flex gap-3 px-5 py-0.5 font-mono">
<span className="w-12 shrink-0 text-right opacity-50">
{levelName(l.level)}
</span>
<span
className={
wordWrap
? "min-w-0 flex-1 whitespace-pre-wrap break-words"
: "whitespace-pre"
}
>
{l.ts} {l.msg ?? ""}
{l.payload ? ` ${JSON.stringify(l.payload)}` : ""}
</span>
</div>
))
)}
</div>
</section>
</div>
);
}
+82
View File
@@ -0,0 +1,82 @@
import { Link, useSearchParams } from "react-router-dom";
import { useRuns } from "../api/hooks.js";
import { formatTime, StatusBadge } from "../lib/format.jsx";
export function EventsPage() {
const [params, setParams] = useSearchParams();
const workflow = params.get("workflow") || "";
const status = params.get("status") || "";
const { data: runs = [], isLoading } = useRuns({
workflow: workflow || undefined,
status: status || undefined,
limit: 100,
});
function update(key, value) {
const next = new URLSearchParams(params);
if (value) next.set(key, value);
else next.delete(key);
setParams(next);
}
return (
<div className="space-y-4">
<h1 className="text-xl font-semibold">Events</h1>
<div className="flex flex-col sm:flex-row gap-2">
<input
className="input input-sm w-full sm:max-w-sm"
placeholder="workflow key"
value={workflow}
onChange={(e) => update("workflow", e.target.value)}
/>
<select
className="select select-sm w-full sm:max-w-xs"
value={status}
onChange={(e) => update("status", e.target.value)}
>
<option value="">all statuses</option>
<option value="running">running</option>
<option value="success">success</option>
<option value="failed">failed</option>
</select>
</div>
{isLoading ? (
<span className="loading loading-spinner" />
) : (
<div className="overflow-x-auto">
<table className="table table-sm">
<thead>
<tr>
<th>Status</th>
<th>Workflow</th>
<th>Trigger</th>
<th>Started</th>
<th>Duration</th>
</tr>
</thead>
<tbody>
{runs.map((r) => (
<tr key={r.id} className="hover">
<td>
<StatusBadge status={r.status} />
</td>
<td>
<Link className="link" to={`/events/${r.id}`}>
{r.workflow_name || r.workflow}
</Link>
</td>
<td className="text-xs">
{r.trigger_type}
{r.trigger_detail ? ` · ${r.trigger_detail}` : ""}
</td>
<td className="whitespace-nowrap">{formatTime(r.started_at)}</td>
<td>{r.duration_ms != null ? `${r.duration_ms}ms` : "—"}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
}
+124
View File
@@ -0,0 +1,124 @@
import { Link } from "react-router-dom";
import {
LuActivity,
LuCode,
LuGitBranch,
LuTriangleAlert,
} from "react-icons/lu";
import { useDashboard } from "../api/hooks.js";
import { formatTime, StatusBadge } from "../lib/format.jsx";
export function HomePage() {
const { data, isLoading, error } = useDashboard();
if (isLoading) {
return <span className="loading loading-spinner loading-lg" />;
}
if (error) {
return <p className="text-error">Failed to load dashboard</p>;
}
const failed = data.needsAttention?.failed ?? [];
const broken = data.needsAttention?.brokenWorkflows ?? [];
return (
<div className="space-y-6">
<div className="stats stats-vertical sm:stats-horizontal shadow w-full bg-base-100">
<div className="stat">
<div className="stat-figure text-primary">
<LuGitBranch className="size-7" />
</div>
<div className="stat-title">Workflows</div>
<div className="stat-value text-2xl">{data.workflowCount}</div>
<div className="stat-desc">{data.enabledCount} enabled</div>
</div>
<div className="stat">
<div className="stat-figure text-secondary">
<LuCode className="size-7" />
</div>
<div className="stat-title">Scripts</div>
<div className="stat-value text-2xl">{data.scriptCount}</div>
</div>
<div className="stat">
<div className="stat-figure text-warning">
<LuActivity className="size-7" />
</div>
<div className="stat-title">Running</div>
<div className="stat-value text-2xl">{data.running?.length ?? 0}</div>
</div>
<div className="stat">
<div className="stat-figure text-error">
<LuTriangleAlert className="size-7" />
</div>
<div className="stat-title">Attention</div>
<div className="stat-value text-2xl">
{failed.length + broken.length}
</div>
</div>
</div>
<section>
<h2 className="text-lg font-semibold mb-2">Running</h2>
<RunList runs={data.running} empty="None" />
</section>
<section>
<h2 className="text-lg font-semibold mb-2">Needs attention</h2>
{broken.length > 0 ? (
<ul className="mb-3 space-y-1">
{broken.map((w) => (
<li key={w.key}>
<Link
className="link link-error"
to={`/workflows?edit=${encodeURIComponent(w.owner)}/${encodeURIComponent(w.file)}`}
>
{w.key}: {w.loadError}
</Link>
</li>
))}
</ul>
) : null}
<RunList runs={failed} empty={broken.length ? "" : "None"} />
</section>
<section>
<h2 className="text-lg font-semibold mb-2">Recent</h2>
<RunList runs={data.recent} empty="None" />
</section>
</div>
);
}
function RunList({ runs, empty }) {
if (!runs?.length) {
return empty ? <p className="opacity-60 text-sm">{empty}</p> : null;
}
return (
<div className="overflow-x-auto">
<table className="table table-sm">
<thead>
<tr>
<th>Status</th>
<th>Workflow</th>
<th>Started</th>
</tr>
</thead>
<tbody>
{runs.map((r) => (
<tr key={r.id} className="hover">
<td>
<StatusBadge status={r.status} />
</td>
<td>
<Link className="link" to={`/events/${r.id}`}>
{r.workflow_name || r.workflow}
</Link>
</td>
<td className="whitespace-nowrap">{formatTime(r.started_at)}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
+198
View File
@@ -0,0 +1,198 @@
import { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { LuPencil, LuPlus, LuSave, LuTrash2, LuX } from "react-icons/lu";
import { errorMessage } from "../api/client.js";
import {
useDeleteScript,
useSaveScript,
useScript,
useScripts,
} from "../api/hooks.js";
import { CodeEditor } from "../components/CodeEditor.jsx";
const NEW_TEMPLATE = `export default async function main(ctx) {
return ctx;
}
`;
export function ScriptsPage() {
const [params, setParams] = useSearchParams();
const editName = params.get("edit");
const { data: scripts = [], isLoading } = useScripts();
const [mode, setMode] = useState(null);
const [name, setName] = useState("");
const [content, setContent] = useState("");
const [confirmDelete, setConfirmDelete] = useState(null);
const existing = useScript(mode === "edit" ? name : null, mode === "edit");
const save = useSaveScript();
const del = useDeleteScript();
useEffect(() => {
if (editName) {
setMode("edit");
setName(editName);
}
}, [editName]);
useEffect(() => {
if (mode === "edit" && existing.data?.content != null) {
setContent(existing.data.content);
}
}, [mode, existing.data]);
function openAdd() {
setMode("add");
setName("");
setContent(NEW_TEMPLATE);
setParams({});
}
function openEdit(script) {
setMode("edit");
setName(script);
setParams({ edit: script });
}
function closeForm() {
setMode(null);
setName("");
setContent("");
setParams({});
}
function onSave(e) {
e.preventDefault();
const file = name.endsWith(".js") ? name : `${name}.js`;
save.mutate(
{ name: file, content },
{
onSuccess: () => {
setMode("edit");
setName(file);
setParams({ edit: file });
},
},
);
}
return (
<div className="space-y-4">
<div className="flex items-center justify-between gap-2">
<h1 className="text-xl font-semibold">Scripts</h1>
<button type="button" className="btn btn-primary btn-sm" onClick={openAdd}>
<LuPlus className="size-4" />
Add
</button>
</div>
{isLoading ? (
<span className="loading loading-spinner" />
) : (
<div className="overflow-x-auto">
<table className="table table-sm">
<thead>
<tr>
<th>Name</th>
<th className="w-24" />
</tr>
</thead>
<tbody>
{scripts.map((s) => (
<tr key={s} className="hover">
<td className="font-mono">{s}</td>
<td className="text-right whitespace-nowrap">
<button
type="button"
className="btn btn-ghost btn-xs"
title="Edit"
onClick={() => openEdit(s)}
>
<LuPencil className="size-4" />
</button>
<button
type="button"
className="btn btn-ghost btn-xs text-error"
title="Delete"
onClick={() => setConfirmDelete(s)}
>
<LuTrash2 className="size-4" />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{mode ? (
<form onSubmit={onSave} className="space-y-3">
<div className="flex items-center justify-between">
<h2 className="font-semibold">{mode === "add" ? "New script" : name}</h2>
<button type="button" className="btn btn-ghost btn-sm btn-square" onClick={closeForm} aria-label="Close">
<LuX className="size-4" />
</button>
</div>
{mode === "add" ? (
<input
className="input input-sm w-full max-w-md"
placeholder="name.js"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
) : null}
{mode === "edit" && existing.isLoading ? (
<span className="loading loading-spinner" />
) : (
<CodeEditor language="javascript" value={content} onChange={setContent} />
)}
{save.isError ? (
<p className="text-error text-sm">{errorMessage(save.error)}</p>
) : null}
<button type="submit" className="btn btn-primary btn-sm" disabled={save.isPending}>
<LuSave className="size-4" />
Save
</button>
</form>
) : null}
{confirmDelete ? (
<dialog className="modal modal-open">
<div className="modal-box">
<h3 className="font-bold">Delete {confirmDelete}?</h3>
{del.isError ? (
<p className="text-error text-sm mt-2">{errorMessage(del.error)}</p>
) : null}
<div className="modal-action">
<button type="button" className="btn btn-ghost" onClick={() => setConfirmDelete(null)}>
Cancel
</button>
<button
type="button"
className="btn btn-error"
disabled={del.isPending}
onClick={() =>
del.mutate(confirmDelete, {
onSuccess: () => {
if (name === confirmDelete) closeForm();
setConfirmDelete(null);
},
})
}
>
Delete
</button>
</div>
</div>
<form method="dialog" className="modal-backdrop">
<button type="button" onClick={() => setConfirmDelete(null)}>
close
</button>
</form>
</dialog>
) : null}
</div>
);
}
+194
View File
@@ -0,0 +1,194 @@
import { useState } from "react";
import { LuPencil, LuPlus, LuTrash2, LuX } from "react-icons/lu";
import { errorMessage } from "../api/client.js";
import {
useCreateUser,
useDeleteUser,
useUpdateUser,
useUsers,
} from "../api/hooks.js";
export function UsersPage() {
const { data: users = [], isLoading } = useUsers();
const create = useCreateUser();
const update = useUpdateUser();
const del = useDeleteUser();
const [mode, setMode] = useState(null);
const [form, setForm] = useState({
username: "",
password: "",
role: "operator",
id: null,
});
const [confirmDelete, setConfirmDelete] = useState(null);
function openAdd() {
setMode("add");
setForm({ username: "", password: "", role: "operator", id: null });
}
function openEdit(u) {
setMode("edit");
setForm({ username: u.username, password: "", role: u.role, id: u.id });
}
function closeForm() {
setMode(null);
}
function onSubmit(e) {
e.preventDefault();
if (mode === "add") {
create.mutate(
{
username: form.username,
password: form.password,
role: form.role,
},
{ onSuccess: closeForm },
);
} else {
const body = { id: form.id, role: form.role };
if (form.password) body.password = form.password;
update.mutate(body, { onSuccess: closeForm });
}
}
const mutation = mode === "add" ? create : update;
return (
<div className="space-y-4">
<div className="flex items-center justify-between gap-2">
<h1 className="text-xl font-semibold">Users</h1>
<button type="button" className="btn btn-primary btn-sm" onClick={openAdd}>
<LuPlus className="size-4" />
Add
</button>
</div>
{isLoading ? (
<span className="loading loading-spinner" />
) : (
<div className="overflow-x-auto">
<table className="table table-sm">
<thead>
<tr>
<th>Username</th>
<th>Role</th>
<th />
</tr>
</thead>
<tbody>
{users.map((u) => (
<tr key={u.id} className="hover">
<td>{u.username}</td>
<td>
<span className="badge badge-sm">{u.role}</span>
</td>
<td className="text-right whitespace-nowrap">
<button
type="button"
className="btn btn-ghost btn-xs"
title="Edit"
onClick={() => openEdit(u)}
>
<LuPencil className="size-4" />
</button>
<button
type="button"
className="btn btn-ghost btn-xs text-error"
title="Delete"
onClick={() => setConfirmDelete(u)}
>
<LuTrash2 className="size-4" />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{mode ? (
<form onSubmit={onSubmit} className="fieldset bg-base-100 border-base-300 rounded-box max-w-md border p-4">
<div className="flex items-center justify-between">
<legend className="fieldset-legend">
{mode === "add" ? "New user" : form.username}
</legend>
<button type="button" className="btn btn-ghost btn-sm btn-square" onClick={closeForm} aria-label="Close">
<LuX className="size-4" />
</button>
</div>
{mode === "add" ? (
<>
<label className="label">Username</label>
<input
className="input w-full"
value={form.username}
onChange={(e) => setForm({ ...form, username: e.target.value })}
required
/>
</>
) : null}
<label className="label">{mode === "add" ? "Password" : "New password"}</label>
<input
type="password"
className="input w-full"
value={form.password}
onChange={(e) => setForm({ ...form, password: e.target.value })}
required={mode === "add"}
minLength={mode === "add" ? 8 : undefined}
placeholder={mode === "edit" ? "leave blank to keep" : ""}
/>
<label className="label">Role</label>
<select
className="select w-full"
value={form.role}
onChange={(e) => setForm({ ...form, role: e.target.value })}
>
<option value="operator">operator</option>
<option value="admin">admin</option>
</select>
{mutation.isError ? (
<p className="text-error text-sm">{errorMessage(mutation.error)}</p>
) : null}
<button type="submit" className="btn btn-primary mt-2" disabled={mutation.isPending}>
Save
</button>
</form>
) : null}
{confirmDelete ? (
<dialog className="modal modal-open">
<div className="modal-box">
<h3 className="font-bold">Delete {confirmDelete.username}?</h3>
{del.isError ? (
<p className="text-error text-sm mt-2">{errorMessage(del.error)}</p>
) : null}
<div className="modal-action">
<button type="button" className="btn btn-ghost" onClick={() => setConfirmDelete(null)}>
Cancel
</button>
<button
type="button"
className="btn btn-error"
disabled={del.isPending}
onClick={() =>
del.mutate(confirmDelete.id, { onSuccess: () => setConfirmDelete(null) })
}
>
Delete
</button>
</div>
</div>
<form method="dialog" className="modal-backdrop">
<button type="button" onClick={() => setConfirmDelete(null)}>
close
</button>
</form>
</dialog>
) : null}
</div>
);
}
+384
View File
@@ -0,0 +1,384 @@
import { useEffect, useMemo, useState } from "react";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import { parse as parseYaml } from "yaml";
import {
LuActivity,
LuPencil,
LuPlay,
LuPlus,
LuRefreshCw,
LuSave,
LuTrash2,
LuX,
} from "react-icons/lu";
import { errorMessage } from "../api/client.js";
import {
useDeleteWorkflow,
useOwners,
useReregisterWorkflows,
useRunWorkflow,
useSaveWorkflow,
useWorkflow,
useWorkflows,
} from "../api/hooks.js";
import { CodeEditor } from "../components/CodeEditor.jsx";
import { MermaidDiagram } from "../components/MermaidDiagram.jsx";
import { formatTime, WorkflowStatusBadge } from "../lib/format.jsx";
import { workflowToArchitecture } from "../lib/workflow-mermaid.js";
const NEW_YAML = `name: new workflow
scripts:
- get-current-time.js
triggers:
- type: HTTP
method: POST
path: /new
`;
export function WorkflowsPage() {
const navigate = useNavigate();
const [params, setParams] = useSearchParams();
const editParam = params.get("edit");
const { data: workflows = [], isLoading } = useWorkflows();
const { data: owners = [] } = useOwners();
const [mode, setMode] = useState(null);
const [owner, setOwner] = useState("default");
const [file, setFile] = useState("");
const [content, setContent] = useState("");
const [confirmDelete, setConfirmDelete] = useState(null);
const [runError, setRunError] = useState(null);
const existing = useWorkflow(
mode === "edit" ? owner : null,
mode === "edit" ? file : null,
mode === "edit",
);
const save = useSaveWorkflow();
const del = useDeleteWorkflow();
const run = useRunWorkflow();
const reregister = useReregisterWorkflows();
useEffect(() => {
if (!editParam) return;
const slash = editParam.indexOf("/");
if (slash === -1) return;
setMode("edit");
setOwner(editParam.slice(0, slash));
setFile(editParam.slice(slash + 1));
}, [editParam]);
useEffect(() => {
if (mode === "edit" && existing.data?.content != null) {
setContent(existing.data.content);
}
}, [mode, existing.data]);
const { parsed, parseError, mermaid } = useMemo(() => {
try {
const parsedYaml = parseYaml(content);
const arch = workflowToArchitecture(parsedYaml);
return { parsed: parsedYaml, parseError: null, mermaid: arch };
} catch (err) {
return {
parsed: null,
parseError: err instanceof Error ? err.message : String(err),
mermaid: { chart: "", scriptIds: {} },
};
}
}, [content]);
function openAdd() {
setMode("add");
setOwner(owners[0] || "default");
setFile("");
setContent(NEW_YAML);
setParams({});
}
function openEdit(w) {
setMode("edit");
setOwner(w.owner);
setFile(w.file);
setParams({ edit: `${w.owner}/${w.file}` });
}
function closeForm() {
setMode(null);
setFile("");
setContent("");
setParams({});
}
function onSave(e) {
e.preventDefault();
const yamlFile = file.endsWith(".yaml") || file.endsWith(".yml") ? file : `${file}.yaml`;
save.mutate(
{ owner, file: yamlFile, content },
{
onSuccess: () => {
setMode("edit");
setFile(yamlFile);
setParams({ edit: `${owner}/${yamlFile}` });
},
},
);
}
function onRun(w) {
setRunError(null);
run.mutate(
{ owner: w.owner, file: w.file },
{
onSuccess: (data) => {
if (data?.runId) navigate(`/events/${data.runId}`);
},
onError: (err) => {
const runId = err?.response?.data?.runId;
if (runId) {
navigate(`/events/${runId}`);
return;
}
setRunError(`${w.key}: ${errorMessage(err)}`);
},
},
);
}
const runningKey =
run.isPending && run.variables
? `${run.variables.owner}/${run.variables.file}`
: null;
return (
<div className="space-y-4">
<div className="flex items-center justify-between gap-2">
<h1 className="text-xl font-semibold">Workflows</h1>
<div className="flex items-center gap-2">
<button
type="button"
className="btn btn-ghost btn-sm"
title="Reregister workflows"
disabled={reregister.isPending}
onClick={() => reregister.mutate()}
>
{reregister.isPending ? (
<span className="loading loading-spinner loading-xs" />
) : (
<LuRefreshCw className="size-4" />
)}
Reregister
</button>
<button type="button" className="btn btn-primary btn-sm" onClick={openAdd}>
<LuPlus className="size-4" />
Add
</button>
</div>
</div>
{reregister.isError ? (
<p className="text-error text-sm">{errorMessage(reregister.error)}</p>
) : null}
{runError ? <p className="text-error text-sm">{runError}</p> : null}
{isLoading ? (
<span className="loading loading-spinner" />
) : (
<div className="overflow-x-auto">
<table className="table table-sm">
<thead>
<tr>
<th>Name</th>
<th>Owner</th>
<th>Status</th>
<th>Triggers</th>
<th>Last run</th>
<th>Runs</th>
<th />
</tr>
</thead>
<tbody>
{workflows.map((w) => (
<tr key={w.key} className="hover">
<td>{w.name}</td>
<td className="font-mono text-xs">{w.owner}</td>
<td>
<WorkflowStatusBadge workflow={w} />
</td>
<td>
<TriggerList triggers={w.triggers} />
</td>
<td className="whitespace-nowrap">{formatTime(w.lastInvokedAt)}</td>
<td>{w.invocationCount}</td>
<td className="text-right whitespace-nowrap">
<button
type="button"
className="btn btn-ghost btn-xs"
title="Run"
disabled={Boolean(w.loadError) || runningKey === w.key}
onClick={() => onRun(w)}
>
{runningKey === w.key ? (
<span className="loading loading-spinner loading-xs" />
) : (
<LuPlay className="size-4" />
)}
</button>
<Link
className="btn btn-ghost btn-xs"
title="Events"
to={`/events?workflow=${encodeURIComponent(w.key)}`}
>
<LuActivity className="size-4" />
</Link>
<button
type="button"
className="btn btn-ghost btn-xs"
title="Edit"
onClick={() => openEdit(w)}
>
<LuPencil className="size-4" />
</button>
<button
type="button"
className="btn btn-ghost btn-xs text-error"
title="Delete"
onClick={() => setConfirmDelete(w)}
>
<LuTrash2 className="size-4" />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{mode ? (
<form onSubmit={onSave} className="space-y-3">
<div className="flex items-center justify-between">
<h2 className="font-semibold">
{mode === "add" ? "New workflow" : `${owner}/${file}`}
</h2>
<button type="button" className="btn btn-ghost btn-sm btn-square" onClick={closeForm} aria-label="Close">
<LuX className="size-4" />
</button>
</div>
{mode === "add" ? (
<div className="flex flex-col sm:flex-row gap-2">
<input
className="input input-sm w-full sm:max-w-xs"
placeholder="owner"
value={owner}
onChange={(e) => setOwner(e.target.value)}
required
/>
<input
className="input input-sm w-full sm:max-w-xs"
placeholder="file.yaml"
value={file}
onChange={(e) => setFile(e.target.value)}
required
/>
</div>
) : null}
{mode === "edit" && existing.isLoading ? (
<span className="loading loading-spinner" />
) : (
<div className="grid gap-3 lg:grid-cols-2">
<CodeEditor language="yaml" value={content} onChange={setContent} />
<div>
{parseError ? (
<p className="text-error text-sm">{parseError}</p>
) : (
<MermaidDiagram
chart={mermaid.chart}
scriptIds={mermaid.scriptIds}
/>
)}
{parsed?.name ? (
<p className="text-sm opacity-70 mt-2">{parsed.name}</p>
) : null}
</div>
</div>
)}
{save.isError ? (
<p className="text-error text-sm">{errorMessage(save.error)}</p>
) : null}
<button type="submit" className="btn btn-primary btn-sm" disabled={save.isPending}>
<LuSave className="size-4" />
Save
</button>
</form>
) : null}
{confirmDelete ? (
<dialog className="modal modal-open">
<div className="modal-box">
<h3 className="font-bold">Delete {confirmDelete.key}?</h3>
{del.isError ? (
<p className="text-error text-sm mt-2">{errorMessage(del.error)}</p>
) : null}
<div className="modal-action">
<button type="button" className="btn btn-ghost" onClick={() => setConfirmDelete(null)}>
Cancel
</button>
<button
type="button"
className="btn btn-error"
disabled={del.isPending}
onClick={() =>
del.mutate(
{ owner: confirmDelete.owner, file: confirmDelete.file },
{
onSuccess: () => {
if (owner === confirmDelete.owner && file === confirmDelete.file) {
closeForm();
}
setConfirmDelete(null);
},
},
)
}
>
Delete
</button>
</div>
</div>
<form method="dialog" className="modal-backdrop">
<button type="button" onClick={() => setConfirmDelete(null)}>
close
</button>
</form>
</dialog>
) : null}
</div>
);
}
function triggerLabel(t) {
const type = String(t?.type ?? "").toLowerCase();
if (type === "cron") return t.schedule || "cron";
if (type === "http") return t.path || "/";
return t?.type ?? "—";
}
function triggerKind(t) {
const type = String(t?.type ?? "").toLowerCase();
if (type === "http") return t.method || "POST";
return t?.type ?? "—";
}
function TriggerList({ triggers }) {
if (!triggers?.length) return <span className="opacity-50">—</span>;
return (
<ul className="space-y-0.5">
{triggers.map((t, i) => (
<li key={i} className="font-mono text-xs whitespace-nowrap">
<span className="opacity-60">{triggerKind(t)}</span> {triggerLabel(t)}
</li>
))}
</ul>
);
}
+27
View File
@@ -0,0 +1,27 @@
import { createContext, useContext, useEffect, useState } from "react";
const ThemeContext = createContext(null);
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState(() => {
if (typeof localStorage === "undefined") return "light";
return localStorage.getItem("theme") || "light";
});
useEffect(() => {
document.documentElement.setAttribute("data-theme", theme);
localStorage.setItem("theme", theme);
}, [theme]);
const toggle = () => setTheme((t) => (t === "dark" ? "light" : "dark"));
return (
<ThemeContext.Provider value={{ theme, setTheme, toggle }}>
{children}
</ThemeContext.Provider>
);
}
export function useTheme() {
return useContext(ThemeContext);
}
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
plugins: [react(), tailwindcss()],
server: {
port: 5173,
proxy: {
"/api": { target: "http://127.0.0.1:9000", changeOrigin: true },
"/admin": { target: "http://127.0.0.1:9000", changeOrigin: true },
},
},
});
+2734 -1
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
packages:
- packages/*