@portqueue/dashboard 1.0.3 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{index-Bi6fyaCo.js → index-DORFyd1J.js} +16 -16
- package/dist/client/index.html +1 -1
- package/dist/index.cjs +28 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +29 -5
- package/dist/index.mjs.map +1 -1
- package/dist/shared/dto/action.d.ts +4 -2
- package/dist/shared/dto/queue.d.ts +6 -0
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { MAX_BATCH_IDS, JobBatchAction, PauseMode, DEFAULT_PAGE_LIMIT, DASHBOARD_MAX_PAGE_LIMIT, JobStatus, PortQueue } from "@portqueue/core";
|
|
1
|
+
import { MAX_BATCH_IDS, JobBatchAction, PauseMode, DEFAULT_PAGE_LIMIT, DASHBOARD_MAX_PAGE_LIMIT, JobStatus, secondsToMs, INSTANCE_REMOVAL_STALE_SECONDS, PortQueue } from "@portqueue/core";
|
|
2
2
|
import { randomBytes } from "node:crypto";
|
|
3
3
|
import { stat, readFile } from "node:fs/promises";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
@@ -33,12 +33,14 @@ function requireInstanceKey(action) {
|
|
|
33
33
|
return { ok: true, value: action.instanceKey };
|
|
34
34
|
}
|
|
35
35
|
function requireJobIds(action) {
|
|
36
|
-
|
|
37
|
-
return checkIds(ids, "jobId(s)");
|
|
36
|
+
return checkIds(idsOf(action.jobIds, action.jobId), "jobId(s)");
|
|
38
37
|
}
|
|
39
38
|
function requireScheduleIds(action) {
|
|
40
|
-
|
|
41
|
-
|
|
39
|
+
return checkIds(idsOf(action.scheduleIds, action.scheduleId), "scheduleId(s)");
|
|
40
|
+
}
|
|
41
|
+
function idsOf(many, one) {
|
|
42
|
+
if (many !== void 0 && !(Array.isArray(many) && many.length === 0)) return many;
|
|
43
|
+
return one === void 0 || one === "" ? [] : [one];
|
|
42
44
|
}
|
|
43
45
|
function requireScheduleId(action) {
|
|
44
46
|
if (typeof action.scheduleId !== "string" || !action.scheduleId) {
|
|
@@ -47,7 +49,11 @@ function requireScheduleId(action) {
|
|
|
47
49
|
return { ok: true, value: action.scheduleId };
|
|
48
50
|
}
|
|
49
51
|
function checkIds(ids, what) {
|
|
52
|
+
if (!Array.isArray(ids)) return invalid(`Invalid ${what}: expected a list of ids`);
|
|
50
53
|
if (!ids.length) return invalid(`Missing ${what}`);
|
|
54
|
+
if (!ids.every((id) => typeof id === "string" && id.length > 0)) {
|
|
55
|
+
return invalid(`Invalid ${what}: every id must be a non-empty string`);
|
|
56
|
+
}
|
|
51
57
|
if (ids.length > MAX_BATCH_IDS) {
|
|
52
58
|
return invalid(`Too many ids: ${ids.length} — the limit is ${MAX_BATCH_IDS} per request`);
|
|
53
59
|
}
|
|
@@ -381,6 +387,9 @@ function serializeInstance(i) {
|
|
|
381
387
|
createdAt: i.createdAt.toISOString(),
|
|
382
388
|
updatedAt: i.updatedAt.toISOString(),
|
|
383
389
|
lastSeenAt: i.lastSeenAt.toISOString(),
|
|
390
|
+
removableAfter: new Date(
|
|
391
|
+
i.lastSeenAt.getTime() + secondsToMs(INSTANCE_REMOVAL_STALE_SECONDS, "instance removal staleness window")
|
|
392
|
+
).toISOString(),
|
|
384
393
|
cpuPercent: i.cpuPercent,
|
|
385
394
|
memoryPercent: i.memoryPercent,
|
|
386
395
|
counts: counts(i.counts)
|
|
@@ -703,6 +712,7 @@ function escapeHtml(s) {
|
|
|
703
712
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
704
713
|
}
|
|
705
714
|
function readBody(req) {
|
|
715
|
+
if (req.readableEnded) return alreadyRead(req);
|
|
706
716
|
return new Promise((resolveBody, reject) => {
|
|
707
717
|
const chunks = [];
|
|
708
718
|
let size = 0;
|
|
@@ -727,6 +737,16 @@ function readBody(req) {
|
|
|
727
737
|
req.on("error", reject);
|
|
728
738
|
});
|
|
729
739
|
}
|
|
740
|
+
function alreadyRead(req) {
|
|
741
|
+
const parsed = req.body;
|
|
742
|
+
let text2;
|
|
743
|
+
if (parsed === void 0 || parsed === null) text2 = "";
|
|
744
|
+
else if (typeof parsed === "string") text2 = parsed;
|
|
745
|
+
else if (Buffer.isBuffer(parsed)) text2 = parsed.toString("utf8");
|
|
746
|
+
else text2 = JSON.stringify(parsed);
|
|
747
|
+
if (Buffer.byteLength(text2) > MAX_BODY_BYTES) return Promise.reject(new BodyTooLargeError());
|
|
748
|
+
return Promise.resolve(text2);
|
|
749
|
+
}
|
|
730
750
|
class BodyTooLargeError extends Error {
|
|
731
751
|
constructor() {
|
|
732
752
|
super(`Request body exceeds the ${MAX_BODY_BYTES}-byte limit`);
|
|
@@ -789,6 +809,7 @@ function createEngine(options) {
|
|
|
789
809
|
function owns(url) {
|
|
790
810
|
if (!url) return false;
|
|
791
811
|
const path = url.split("?")[0] ?? "";
|
|
812
|
+
if (basePath === "/") return path.startsWith("/");
|
|
792
813
|
return path === basePath || path.startsWith(`${basePath}/`);
|
|
793
814
|
}
|
|
794
815
|
function relPath(url) {
|
|
@@ -875,6 +896,9 @@ function createKoaMiddleware(engine) {
|
|
|
875
896
|
return;
|
|
876
897
|
}
|
|
877
898
|
ctx.respond = false;
|
|
899
|
+
const parsed = ctx.request?.body;
|
|
900
|
+
const raw = ctx.req;
|
|
901
|
+
if (parsed !== void 0 && raw.body === void 0) raw.body = parsed;
|
|
878
902
|
await engine.serve(ctx.req, ctx.res);
|
|
879
903
|
};
|
|
880
904
|
}
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../src/server/api/http.ts","../src/server/api/routes/actions/validate.ts","../src/shared/dto/action.ts","../src/server/api/routes/actions/add.ts","../src/server/api/routes/actions/job-batch.ts","../src/server/api/routes/actions/cancel.ts","../src/server/api/routes/actions/pause.ts","../src/server/api/routes/actions/pause-instance.ts","../src/server/api/routes/actions/remove.ts","../src/server/api/routes/actions/remove-instance.ts","../src/server/api/routes/actions/remove-queue.ts","../src/server/api/routes/actions/remove-schedule.ts","../src/server/api/routes/actions/resume.ts","../src/server/api/routes/actions/resume-instance.ts","../src/server/api/routes/actions/retry.ts","../src/server/api/routes/actions/set-schedule-enabled.ts","../src/server/api/routes/actions/index.ts","../src/server/api/routes/config.ts","../src/server/api/params.ts","../src/server/api/serialize.ts","../src/server/api/routes/instances.ts","../src/server/api/routes/jobs.ts","../src/server/api/routes/queues.ts","../src/server/api/routes/schedules.ts","../src/server/api/routes/stats.ts","../src/shared/constants.ts","../src/server/api/routes/index.ts","../src/server/assets.ts","../src/server/request.ts","../src/server/client.ts","../src/server/engine.ts","../src/server/adapters/express.ts","../src/server/adapters/fastify.ts","../src/server/adapters/koa.ts","../src/server/adapters/nest.ts","../src/server/adapters/node.ts","../src/server/create-dashboard.ts"],"sourcesContent":["/**\n * The request/response shapes every route speaks, and the two helpers that build a reply.\n *\n * Deliberately tiny and framework-free: an adapter translates its framework's request into\n * {@link HandlerInput}, the router hands back a {@link HandlerResult}, and the adapter writes it.\n * Nothing here knows about Node's `http`, so a route is a pure function of its input.\n */\n\nexport interface HandlerInput {\n method: string;\n /** URL path + query, already stripped to be relative-friendly (may still include basePath). */\n url: string;\n body: string | undefined;\n headers: Record<string, string | string[] | undefined>;\n}\n\nexport interface HandlerResult {\n status: number;\n body: string;\n headers?: Record<string, string>;\n}\n\nconst JSON_HEADERS: Record<string, string> = { 'content-type': 'application/json; charset=utf-8' };\n\n/** A JSON reply. Every route returns one of these — there is no other response shape. */\nexport function json(\n status: number,\n payload: unknown,\n extra?: Record<string, string>,\n): HandlerResult {\n return { status, body: JSON.stringify(payload), headers: { ...JSON_HEADERS, ...extra } };\n}\n\n/**\n * A 409 carrying the actionable message core threw (queue in use, instance still active, …).\n * Those refusals are the caller's problem to fix, not a server fault, so they must not read as 500s.\n */\nexport function conflict(err: unknown, fallback: string): HandlerResult {\n return json(409, { error: err instanceof Error ? err.message : fallback });\n}\n\n/** Strip the mount base path so route matching sees `/api/...`. */\nexport function relativePath(url: string, basePath: string): string {\n const qIndex = url.indexOf('?');\n let path = qIndex === -1 ? url : url.slice(0, qIndex);\n if (basePath && path.startsWith(basePath)) path = path.slice(basePath.length);\n if (!path.startsWith('/')) path = `/${path}`;\n return path;\n}\n\n/** The query string of a URL, as `URLSearchParams` (empty when there isn't one). */\nexport function queryOf(url: string): URLSearchParams {\n const qIndex = url.indexOf('?');\n return new URLSearchParams(qIndex === -1 ? '' : url.slice(qIndex + 1));\n}\n","/**\n * Field checks shared by the action routes.\n *\n * Each returns either the value or a ready-made 400, so a handler reads as a short list of\n * requirements followed by the one call that does the work. A `400` is always the client's mistake:\n * anything core refuses for a legitimate request is a 409 (see `conflict`) or a 400 with core's own\n * message.\n */\nimport { MAX_BATCH_IDS } from '@portqueue/core';\nimport { json, type HandlerResult } from '../../http';\nimport type { ActionPayloadDto } from '../../../../shared/dto';\n\n/** Either a validated value, or the response to send instead. */\nexport type Checked<T> = { ok: true; value: T } | { ok: false; response: HandlerResult };\n\nconst invalid = (error: string): Checked<never> => ({ ok: false, response: json(400, { error }) });\n\n/** The target queue name. Required by every queue-scoped action. */\nexport function requireQueue(action: ActionPayloadDto): Checked<string> {\n if (typeof action.queue !== 'string' || !action.queue) return invalid('Missing queue');\n return { ok: true, value: action.queue };\n}\n\n/** The target instance key. Required by the three instance actions. */\nexport function requireInstanceKey(action: ActionPayloadDto): Checked<string> {\n if (typeof action.instanceKey !== 'string' || !action.instanceKey) {\n return invalid('Missing instanceKey');\n }\n return { ok: true, value: action.instanceKey };\n}\n\n/**\n * The job ids a retry/cancel/remove applies to. `jobIds` (a bulk selection) and `jobId` (one row\n * action) are the same operation at different sizes, so both normalize to a list here rather than\n * taking separate paths through the handler.\n */\nexport function requireJobIds(action: ActionPayloadDto): Checked<string[]> {\n const ids = action.jobIds?.length ? action.jobIds : action.jobId ? [action.jobId] : [];\n return checkIds(ids, 'jobId(s)');\n}\n\n/** The schedule ids a removal applies to — same one-or-many normalization as the job ids. */\nexport function requireScheduleIds(action: ActionPayloadDto): Checked<string[]> {\n const ids = action.scheduleIds?.length\n ? action.scheduleIds\n : action.scheduleId\n ? [action.scheduleId]\n : [];\n return checkIds(ids, 'scheduleId(s)');\n}\n\n/** One schedule id, for the actions that address exactly one. */\nexport function requireScheduleId(action: ActionPayloadDto): Checked<string> {\n if (typeof action.scheduleId !== 'string' || !action.scheduleId) {\n return invalid('Missing scheduleId');\n }\n return { ok: true, value: action.scheduleId };\n}\n\n/**\n * A non-empty id list within core's batch cap.\n *\n * Checked here as well as in core so an oversized selection is a 400 that names the limit rather\n * than a driver error an operator has to interpret. The client stops a selection growing past the\n * same cap, so reaching this means a hand-made request.\n */\nfunction checkIds(ids: string[], what: string): Checked<string[]> {\n if (!ids.length) return invalid(`Missing ${what}`);\n if (ids.length > MAX_BATCH_IDS) {\n return invalid(`Too many ids: ${ids.length} — the limit is ${MAX_BATCH_IDS} per request`);\n }\n return { ok: true, value: ids };\n}\n","/** Mutation request/response wire DTOs for the dashboard action endpoints. */\nimport type { PauseMode } from '@portqueue/core';\n\n/**\n * Every mutation the dashboard can ask for. An enum, so no route matches a magic string — and the\n * value **is** the URL segment the mutation posts to (`POST {basePath}/api/actions/<kind>`), so an\n * action has exactly one endpoint and there is no second spelling to keep in sync.\n */\nexport enum ActionKind {\n PAUSE = 'pause',\n RESUME = 'resume',\n RETRY = 'retry',\n REMOVE = 'remove',\n CANCEL = 'cancel',\n ADD = 'add',\n REMOVE_SCHEDULE = 'removeSchedule',\n SET_SCHEDULE_ENABLED = 'setScheduleEnabled',\n REMOVE_QUEUE = 'removeQueue',\n PAUSE_INSTANCE = 'pauseInstance',\n RESUME_INSTANCE = 'resumeInstance',\n REMOVE_INSTANCE = 'removeInstance',\n}\n\n/** The payload an `add` action carries — the subset of core `AddJobOptions` the form exposes. */\nexport interface AddJobRequestDto {\n data: unknown;\n priority?: number;\n idempotencyKey?: string;\n singletonKey?: string;\n /** Cap on automatic retries for this job. */\n retryMaxAttempts?: number;\n /** Regex matching the instance keys this job may run on. */\n preferredInstanceKeyPattern?: string;\n /** One-off: delay this many **seconds** from now. */\n startAfterSeconds?: number;\n /** Recurring: fixed interval, in **seconds**. */\n startEverySeconds?: number;\n /** Recurring: cron expression, optionally with a timezone. */\n cron?: string | { pattern: string; tz?: string };\n}\n\n/**\n * The body of a mutation — the per-action fields, and nothing that selects the action.\n *\n * Which mutation runs is decided by the URL alone (`/api/actions/<kind>`). The body carried a `kind`\n * field once, back when every mutation posted to one endpoint; keeping both would be two doors to\n * one room, and a body whose `kind` disagreed with its path would have to mean something.\n */\nexport interface ActionPayloadDto {\n /** Target queue name — required for all queue/job actions; omitted for instance actions. */\n queue?: string;\n /** Target instance key — required for `pauseInstance` / `resumeInstance` / `removeInstance`. */\n instanceKey?: string;\n jobId?: string;\n /**\n * Many job ids for a bulk retry / cancel / remove. The server applies them in **one transaction**,\n * so the batch either lands whole or not at all. Capped at {@link MAX_BATCH_IDS} ids per request.\n */\n jobIds?: string[];\n scheduleId?: string;\n /** Many schedule ids for a bulk removal, in one transaction. */\n scheduleIds?: string[];\n /** For `setScheduleEnabled`: whether the schedule should be armed. */\n enabled?: boolean;\n mode?: PauseMode;\n add?: AddJobRequestDto;\n}\n\n/**\n * A mutation, as the client's `api.action` takes it: the payload plus the `kind` that names the\n * endpoint. `kind` is stripped into the URL before the request goes out and never reaches the wire.\n */\nexport interface ActionRequestDto extends ActionPayloadDto {\n kind: ActionKind;\n}\n\nexport interface ActionResultDto {\n ok: boolean;\n jobId?: string;\n scheduleId?: string;\n /** Rows the action actually changed. */\n affected?: number;\n /** Ids submitted, when the action was a batch — so the UI can say \"3 of 5\". */\n requested?: number;\n /**\n * Jobs a cancel could only *ask* to stop, because they are running in the dashboard's own process.\n * Reported apart from `affected`: nothing has been cancelled yet, and a handler that ignores\n * `job.signal` finishes normally.\n */\n signalled?: number;\n}\n","import { json } from '../../http';\nimport { requireQueue } from './validate';\nimport { ActionKind, type ActionRequestDto, type ActionResultDto } from '../../../../shared/dto';\nimport type { AddJobOptions } from '@portqueue/core';\nimport type { ActionRoute } from './types';\n\n/**\n * `add` — the one action that legitimately produces onto a queue.\n *\n * It goes through the public producer path, so every validation core already enforces applies\n * unchanged. The queue is addressed by name: the dashboard's client is headless, so a name with no\n * queue row is refused rather than invented — which surfaces here as a 400 carrying core's message.\n */\nexport const addAction: ActionRoute = {\n kind: ActionKind.ADD,\n summary: 'Enqueue a job, or create a recurring schedule',\n handle: async ({ portQueue, action }) => {\n const queue = requireQueue(action);\n if (!queue.ok) return queue.response;\n if (!action.add || typeof action.add !== 'object') {\n return json(400, { error: 'Missing add payload' });\n }\n try {\n const result = await portQueue.addJob({\n queue: queue.value,\n ...buildAddOptions(action.add),\n });\n return json(200, {\n ok: true,\n ...(result.jobId ? { jobId: result.jobId } : {}),\n ...(result.scheduleId ? { scheduleId: result.scheduleId } : {}),\n } satisfies ActionResultDto);\n } catch (err) {\n // A bad cron, both cadences at once, a paused queue, an unknown queue — all actionable, and\n // none of them a server fault.\n return json(400, { error: err instanceof Error ? err.message : 'Cannot add job' });\n }\n },\n};\n\n/**\n * Translate the form's payload into core's `AddJobOptions`.\n *\n * Only keys the client actually set are forwarded, so an omitted field inherits the queue's default\n * rather than being pinned to a value the form invented. `cron` wins over `startEverySeconds` if both\n * somehow arrive: core rejects the pair, and picking one is friendlier than a 400 for a request the\n * UI cannot produce.\n */\nfunction buildAddOptions(add: NonNullable<ActionRequestDto['add']>): AddJobOptions<unknown> {\n const opts: AddJobOptions<unknown> = { data: add.data };\n if (typeof add.priority === 'number') opts.priority = add.priority;\n if (add.idempotencyKey) opts.idempotencyKey = add.idempotencyKey;\n if (add.singletonKey) opts.singletonKey = add.singletonKey;\n if (typeof add.retryMaxAttempts === 'number') opts.retry = { maxAttempts: add.retryMaxAttempts };\n if (add.preferredInstanceKeyPattern) {\n opts.preferredInstanceKeyPattern = add.preferredInstanceKeyPattern;\n }\n const schedule: NonNullable<AddJobOptions<unknown>['schedule']> = {};\n if (add.startAfterSeconds != null) schedule.startAfterSeconds = add.startAfterSeconds;\n if (add.cron != null) schedule.cron = add.cron;\n else if (add.startEverySeconds != null) schedule.startEverySeconds = add.startEverySeconds;\n if (Object.keys(schedule).length > 0) opts.schedule = schedule;\n return opts;\n}\n","/**\n * The one path every job mutation takes.\n *\n * `retry`, `cancel` and `remove` differ only in the verb they hand to the facade, and the facade\n * turns each into a **single** statement over the whole id set — so a bulk selection costs the same\n * round trips as one row, and an id the action refuses (already gone, or an `ACTIVE` row) is simply\n * absent from `affected` rather than failing the rest.\n *\n * There is deliberately no `queue` field. A job id identifies a row on its own and the statements\n * never narrowed by queue, so requiring one was validation theatre — and it forced the client to\n * split a selection spanning queues into one request per queue, which is exactly how a bulk action\n * came to be half-applied with a success toast and an error toast side by side.\n */\nimport { json, type HandlerResult } from '../../http';\nimport { requireJobIds } from './validate';\nimport type { ActionContext } from './types';\nimport type { JobBatchAction } from '@portqueue/core';\nimport type { ActionResultDto } from '../../../../shared/dto';\n\nexport async function runJobBatch(\n { portQueue, action }: ActionContext,\n verb: JobBatchAction,\n): Promise<HandlerResult> {\n const jobIds = requireJobIds(action);\n if (!jobIds.ok) return jobIds.response;\n\n const result = await portQueue._dashboard.runJobBatch({\n jobIds: jobIds.value,\n action: verb,\n });\n const signalled = result.signalled ?? 0;\n return json(200, {\n ok: result.affected > 0 || signalled > 0,\n affected: result.affected,\n requested: result.requested,\n ...(signalled ? { signalled } : {}),\n } satisfies ActionResultDto);\n}\n","import { JobBatchAction } from '@portqueue/core';\nimport { runJobBatch } from './job-batch';\nimport { ActionKind } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `cancel` — stop the selected jobs from running, without deleting their rows.\n *\n * A job running in the client's own process is cancelled by firing its handler's `AbortSignal`; the\n * rest are marked `CANCELLED` so they never start.\n */\nexport const cancelAction: ActionRoute = {\n kind: ActionKind.CANCEL,\n summary: 'Cancel the selected jobs',\n handle: (ctx) => runJobBatch(ctx, JobBatchAction.CANCEL),\n};\n","import { PauseMode } from '@portqueue/core';\nimport { json } from '../../http';\nimport { requireQueue } from './validate';\nimport { ActionKind, type ActionResultDto } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `pause` — stop every instance from claiming this queue's jobs.\n *\n * `mode: ALL` also refuses new jobs. Anything other than `ALL` reads as `PROCESSING` rather than\n * being rejected: the stricter mode must always be asked for explicitly.\n */\nexport const pauseAction: ActionRoute = {\n kind: ActionKind.PAUSE,\n summary: 'Pause a queue (processing, or everything)',\n handle: async ({ portQueue, action }) => {\n const queue = requireQueue(action);\n if (!queue.ok) return queue.response;\n const mode = action.mode === PauseMode.ALL ? PauseMode.ALL : PauseMode.PROCESSING;\n await portQueue.pauseQueue({ queue: queue.value, mode });\n return json(200, { ok: true } satisfies ActionResultDto);\n },\n};\n","import { json } from '../../http';\nimport { requireInstanceKey } from './validate';\nimport { ActionKind, type ActionResultDto } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `pauseInstance` — stop one named process from claiming jobs.\n *\n * Persisted on the instance row, so the target picks it up on its next heartbeat rather than needing\n * to be reachable from here.\n */\nexport const pauseInstanceAction: ActionRoute = {\n kind: ActionKind.PAUSE_INSTANCE,\n summary: 'Stop one instance from claiming jobs',\n handle: async ({ portQueue, action }) => {\n const instanceKey = requireInstanceKey(action);\n if (!instanceKey.ok) return instanceKey.response;\n await portQueue.pauseInstance({ instanceKey: instanceKey.value });\n return json(200, { ok: true } satisfies ActionResultDto);\n },\n};\n","import { JobBatchAction } from '@portqueue/core';\nimport { runJobBatch } from './job-batch';\nimport { ActionKind } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `remove` — delete the selected job rows.\n *\n * An `ACTIVE` row belongs to a live handler and is never deleted; cancel it first, then remove it\n * once it has settled.\n */\nexport const removeAction: ActionRoute = {\n kind: ActionKind.REMOVE,\n summary: 'Delete the selected job rows',\n handle: (ctx) => runJobBatch(ctx, JobBatchAction.REMOVE),\n};\n","import { conflict, json } from '../../http';\nimport { requireInstanceKey } from './validate';\nimport { ActionKind, type ActionResultDto } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `removeInstance` — tidy a long-inactive process out of the instances list.\n *\n * Core refuses while the instance is still heartbeating (a live one would simply re-register on its\n * next beat), which arrives here as a 409. Job rows record the instance key as a plain string, so\n * removal never touches them.\n */\nexport const removeInstanceAction: ActionRoute = {\n kind: ActionKind.REMOVE_INSTANCE,\n summary: 'Remove a long-inactive instance row',\n handle: async ({ portQueue, action }) => {\n const instanceKey = requireInstanceKey(action);\n if (!instanceKey.ok) return instanceKey.response;\n try {\n const ok = await portQueue.removeInstance({ instanceKey: instanceKey.value });\n return json(200, { ok } satisfies ActionResultDto);\n } catch (err) {\n return conflict(err, 'Cannot remove instance');\n }\n },\n};\n","import { conflict, json } from '../../http';\nimport { requireQueue } from './validate';\nimport { ActionKind, type ActionResultDto } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `removeQueue` — delete a queue's row.\n *\n * Core refuses while any process still declares the queue, which arrives here as a 409 carrying its\n * message. Job rows link by name with no foreign key, so they are untouched either way.\n */\nexport const removeQueueAction: ActionRoute = {\n kind: ActionKind.REMOVE_QUEUE,\n summary: 'Delete a queue row',\n handle: async ({ portQueue, action }) => {\n const queue = requireQueue(action);\n if (!queue.ok) return queue.response;\n try {\n const ok = await portQueue.removeQueue({ name: queue.value });\n return json(200, { ok } satisfies ActionResultDto);\n } catch (err) {\n return conflict(err, 'Cannot remove queue');\n }\n },\n};\n","import { json } from '../../http';\nimport { requireScheduleIds } from './validate';\nimport { ActionKind, type ActionResultDto } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `removeSchedule` — stop one or many recurrences from producing new jobs.\n *\n * The client never has to know which queue a schedule belongs to: the row carries it, and the facade\n * returns it, so the whole set goes in one statement and each removal still names its queue in the\n * event it emits. Jobs the schedule already produced are untouched.\n */\nexport const removeScheduleAction: ActionRoute = {\n kind: ActionKind.REMOVE_SCHEDULE,\n summary: 'Delete one or many schedules',\n handle: async ({ portQueue, action }) => {\n const ids = requireScheduleIds(action);\n if (!ids.ok) return ids.response;\n const result = await portQueue._dashboard.removeSchedules({ scheduleIds: ids.value });\n return json(200, {\n ok: result.affected > 0,\n affected: result.affected,\n requested: result.requested,\n } satisfies ActionResultDto);\n },\n};\n","import { json } from '../../http';\nimport { requireQueue } from './validate';\nimport { ActionKind, type ActionResultDto } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/** `resume` — let instances claim this queue again, and accept new jobs. */\nexport const resumeAction: ActionRoute = {\n kind: ActionKind.RESUME,\n summary: 'Resume a paused queue',\n handle: async ({ portQueue, action }) => {\n const queue = requireQueue(action);\n if (!queue.ok) return queue.response;\n await portQueue.resumeQueue({ queue: queue.value });\n return json(200, { ok: true } satisfies ActionResultDto);\n },\n};\n","import { json } from '../../http';\nimport { requireInstanceKey } from './validate';\nimport { ActionKind, type ActionResultDto } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/** `resumeInstance` — let one named process claim jobs again. */\nexport const resumeInstanceAction: ActionRoute = {\n kind: ActionKind.RESUME_INSTANCE,\n summary: 'Let one instance claim jobs again',\n handle: async ({ portQueue, action }) => {\n const instanceKey = requireInstanceKey(action);\n if (!instanceKey.ok) return instanceKey.response;\n await portQueue.resumeInstance({ instanceKey: instanceKey.value });\n return json(200, { ok: true } satisfies ActionResultDto);\n },\n};\n","import { JobBatchAction } from '@portqueue/core';\nimport { runJobBatch } from './job-batch';\nimport { ActionKind } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `retry` — re-arm the selected jobs so they run again.\n *\n * A job that is still `ACTIVE` is left alone: clearing a running job's lock would let a second worker\n * claim it, so the same job would run twice at once. Those ids just don't count toward `affected`.\n */\nexport const retryAction: ActionRoute = {\n kind: ActionKind.RETRY,\n summary: 'Re-arm the selected jobs',\n handle: (ctx) => runJobBatch(ctx, JobBatchAction.RETRY),\n};\n","import { json } from '../../http';\nimport { requireScheduleId } from './validate';\nimport { ActionKind, type ActionResultDto } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `setScheduleEnabled` — arm or disarm a schedule without deleting it.\n *\n * `enabled` must be sent explicitly. Treating a missing flag as a toggle would make the result depend\n * on state the client may not have refreshed, so two clicks could land as one no-op.\n */\nexport const setScheduleEnabledAction: ActionRoute = {\n kind: ActionKind.SET_SCHEDULE_ENABLED,\n summary: 'Arm or disarm a schedule',\n handle: async ({ portQueue, action }) => {\n const scheduleId = requireScheduleId(action);\n if (!scheduleId.ok) return scheduleId.response;\n if (typeof action.enabled !== 'boolean') return json(400, { error: 'Missing enabled' });\n const ok = await portQueue._dashboard.setScheduleEnabled({\n scheduleId: scheduleId.value,\n enabled: action.enabled,\n });\n return json(200, { ok } satisfies ActionResultDto);\n },\n};\n","/**\n * The action registry. One entry per mutation, each defined in its own file.\n *\n * Dispatch is a `Map` lookup on {@link ActionKind}, so an unknown kind is a miss rather than a\n * fall-through, and adding an action is adding a file plus one line here. Same shape as the CLI's\n * command registry, for the same reason: the list *is* the documentation of what the API can do.\n */\nimport { addAction } from './add';\nimport { cancelAction } from './cancel';\nimport { pauseAction } from './pause';\nimport { pauseInstanceAction } from './pause-instance';\nimport { removeAction } from './remove';\nimport { removeInstanceAction } from './remove-instance';\nimport { removeQueueAction } from './remove-queue';\nimport { removeScheduleAction } from './remove-schedule';\nimport { resumeAction } from './resume';\nimport { resumeInstanceAction } from './resume-instance';\nimport { retryAction } from './retry';\nimport { setScheduleEnabledAction } from './set-schedule-enabled';\nimport type { ActionKind } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\nexport const ACTIONS: readonly ActionRoute[] = [\n // Job-scoped (one id or many — the same single-statement batch either way)\n retryAction,\n cancelAction,\n removeAction,\n addAction,\n // Queue-scoped\n pauseAction,\n resumeAction,\n removeQueueAction,\n // Schedule-scoped (they resolve their own queue from the id)\n removeScheduleAction,\n setScheduleEnabledAction,\n // Instance-scoped (queue-less)\n pauseInstanceAction,\n resumeInstanceAction,\n removeInstanceAction,\n];\n\nexport const ACTIONS_BY_KIND: ReadonlyMap<ActionKind, ActionRoute> = new Map(\n ACTIONS.map((action) => [action.kind, action]),\n);\n\nexport type { ActionContext, ActionRoute } from './types';\n","import { json } from '../http';\nimport type { Route } from './types';\n\n/**\n * `GET /api/config` — a liveness probe with no payload of its own.\n *\n * It exists so a client can confirm it is talking to a PortQueue dashboard at all, which is a\n * different question from whether any particular page has data. Deliberately carries no\n * configuration: anything the SPA needs to render is baked into the shell it was served.\n */\nexport const configRoute: Route = {\n method: 'GET',\n path: '/api/config',\n summary: 'Confirm the mount is a PortQueue dashboard',\n handle: async () => json(200, { ok: true }),\n};\n","/**\n * Query-string parsing shared by the read routes. Every value a client can send arrives as a\n * string, so each reader here is the one place that decides what a missing, blank or nonsense\n * value means — and the answer is always \"don't narrow\", never \"guess\".\n */\nimport {\n DASHBOARD_MAX_PAGE_LIMIT,\n DEFAULT_PAGE_LIMIT,\n JobStatus,\n type GetJobsQuery,\n type JobInstanceFilter,\n} from '@portqueue/core';\n\n/** Read a paging window, clamped to the ceiling core's dashboard facade would clamp to anyway. */\nexport function paging(params: URLSearchParams): { limit: number; offset: number } {\n const rawLimit = Number(params.get('limit'));\n const rawOffset = Number(params.get('offset'));\n return {\n limit:\n Number.isFinite(rawLimit) && rawLimit > 0\n ? Math.min(Math.trunc(rawLimit), DASHBOARD_MAX_PAGE_LIMIT)\n : DEFAULT_PAGE_LIMIT,\n offset: Number.isFinite(rawOffset) && rawOffset > 0 ? Math.trunc(rawOffset) : 0,\n };\n}\n\n/** A tri-state boolean query param: `true`/`false` narrow, anything else means \"don't filter\". */\nexport function triBool(raw: string | null): boolean | undefined {\n if (raw === 'true') return true;\n if (raw === 'false') return false;\n return undefined;\n}\n\n/** A non-empty string param, or `undefined` — so `?search=` reads as \"no search\". */\nexport function text(params: URLSearchParams, key: string): string | undefined {\n const raw = params.get(key);\n return raw ? raw : undefined;\n}\n\n/**\n * Spread a named filter into an options object only when it is set. Keeps every route's query\n * assembly to one line per filter, instead of a conditional spread per filter.\n */\nexport function when<K extends string, V>(key: K, value: V | undefined): Partial<Record<K, V>> {\n return value === undefined ? {} : ({ [key]: value } as Record<K, V>);\n}\n\n/** A comma-separated status list, ignoring anything that isn't a `JobStatus`. */\nexport function statuses(raw: string | null): JobStatus[] | undefined {\n if (!raw) return undefined;\n const valid = new Set<string>(Object.values(JobStatus));\n const out = raw\n .split(',')\n .map((s) => s.trim().toUpperCase())\n .filter((s) => valid.has(s)) as JobStatus[];\n return out.length ? out : undefined;\n}\n\n/** The job filter both `/api/jobs` and the job detail route build from a query string. */\nexport function jobsQuery(params: URLSearchParams): GetJobsQuery & JobInstanceFilter {\n return {\n ...paging(params),\n ...when('queue', text(params, 'queue')),\n ...when('statuses', statuses(params.get('statuses'))),\n ...when('scheduleId', text(params, 'scheduleId')),\n ...when('instanceKey', text(params, 'instanceKey')),\n };\n}\n","/**\n * Maps PortQueue snapshots → wire DTOs. Pure functions, fully typed;\n * the single place Dates become ISO strings for the JSON boundary.\n */\nimport type { JobSnapshot, InstanceInfo, QueueInfo, QueueStats, Page } from '@portqueue/core';\nimport type {\n JobDto,\n JobPageDto,\n QueueDto,\n QueuePageDto,\n ScheduleDto,\n SchedulePageDto,\n StatsDto,\n InstanceDto,\n InstancePageDto,\n CountsDto,\n} from '../../shared/dto';\n\n/** A schedule as core's dashboard facade returns it: `ScheduleInfo` plus its queue. */\nexport interface ScheduleInfo {\n scheduleId: string;\n queue: string;\n cron?: string | null;\n /** For an interval schedule: the seconds between runs. */\n everySeconds?: number | null;\n timezone?: string | null;\n nextRunAt?: Date | null;\n lastRunAt?: Date | null;\n enabled: boolean;\n idempotencyKey?: string | null;\n}\n\nfunction iso(d: Date | null | undefined): string | null | undefined {\n if (d === null) return null;\n if (d === undefined) return undefined;\n return d.toISOString();\n}\n\nfunction counts(c: QueueInfo['counts']): CountsDto {\n return { ...c } as CountsDto;\n}\n\nexport function serializeJob(job: JobSnapshot): JobDto {\n return {\n id: job.id,\n queue: job.queue,\n status: job.status,\n data: job.data,\n returnValue: job.returnValue,\n priority: job.priority,\n retryAttempt: job.retryAttempt,\n retryMaxAttempts: job.retryMaxAttempts,\n createdAt: job.createdAt.toISOString(),\n updatedAt: job.updatedAt.toISOString(),\n startAfter: job.startAfter.toISOString(),\n startedAt: iso(job.startedAt),\n completedAt: iso(job.completedAt),\n failedAt: iso(job.failedAt),\n cancelledAt: iso(job.cancelledAt),\n expiredAt: iso(job.expiredAt),\n retriedAt: iso(job.retriedAt),\n stalledAt: iso(job.stalledAt),\n lockedUntil: iso(job.lockedUntil),\n preferredInstanceKeyPattern: job.preferredInstanceKeyPattern,\n processedOnInstanceKey: job.processedOnInstanceKey,\n failureMessage: job.failureMessage,\n idempotencyKey: job.idempotencyKey,\n scheduleId: job.scheduleId,\n stalled: job.stalled,\n };\n}\n\nexport function serializeQueue(q: QueueInfo): QueueDto {\n return {\n name: q.name,\n processingPaused: q.processingPaused,\n acceptingPaused: q.acceptingPaused,\n counts: counts(q.counts),\n };\n}\n\nexport function serializeQueuePage(page: Page<QueueInfo>): QueuePageDto {\n return { items: page.items.map(serializeQueue), total: page.total };\n}\n\nexport function serializeStats(s: QueueStats): StatsDto {\n return {\n ...(s.queue !== undefined ? { queue: s.queue } : {}),\n counts: counts(s.counts),\n };\n}\n\nexport function serializeJobPage(page: Page<JobSnapshot>): JobPageDto {\n return {\n items: page.items.map(serializeJob),\n total: page.total,\n };\n}\n\nexport function serializeSchedule(s: ScheduleInfo): ScheduleDto {\n return {\n scheduleId: s.scheduleId,\n queue: s.queue,\n cron: s.cron,\n everySeconds: s.everySeconds,\n timezone: s.timezone,\n nextRunAt: iso(s.nextRunAt),\n lastRunAt: iso(s.lastRunAt),\n enabled: s.enabled,\n idempotencyKey: s.idempotencyKey,\n };\n}\n\nexport function serializeSchedulePage(page: Page<ScheduleInfo>): SchedulePageDto {\n return { items: page.items.map(serializeSchedule), total: page.total };\n}\n\n/** Serialize an instance overview row. */\nexport function serializeInstance(i: InstanceInfo): InstanceDto {\n return {\n instanceKey: i.instanceKey,\n processingPaused: i.processingPaused,\n alive: i.alive,\n createdAt: i.createdAt.toISOString(),\n updatedAt: i.updatedAt.toISOString(),\n lastSeenAt: i.lastSeenAt.toISOString(),\n cpuPercent: i.cpuPercent,\n memoryPercent: i.memoryPercent,\n counts: counts(i.counts),\n };\n}\n\nexport function serializeInstancePage(page: Page<InstanceInfo>): InstancePageDto {\n return { items: page.items.map(serializeInstance), total: page.total };\n}\n","import { json } from '../http';\nimport { paging, text, triBool, when } from '../params';\nimport { serializeInstance, serializeInstancePage } from '../serialize';\nimport type { Route } from './types';\n\n/** `GET /api/instances` — a page of instances with liveness and per-instance job attribution. */\nexport const instancesRoute: Route = {\n method: 'GET',\n path: '/api/instances',\n summary: 'List instances with liveness and job attribution',\n handle: async ({ portQueue, query }) => {\n const page = await portQueue._dashboard.getInstances({\n ...paging(query),\n ...when('search', text(query, 'search')),\n ...when('processingPaused', triBool(query.get('processingPaused'))),\n ...when('alive', triBool(query.get('alive'))),\n });\n return json(200, serializeInstancePage(page));\n },\n};\n\n/** `GET /api/instances/:instanceKey` — the instance detail page's header. */\nexport const instanceRoute: Route = {\n method: 'GET',\n path: /^\\/api\\/instances\\/([^/]+)$/,\n summary: 'One instance by key',\n handle: async ({ portQueue, params }) => {\n const instance = await portQueue._dashboard.getInstance({ instanceKey: params[0]! });\n if (!instance) return json(404, { error: 'Instance not found' });\n return json(200, serializeInstance(instance));\n },\n};\n","import { json } from '../http';\nimport { jobsQuery, text, when } from '../params';\nimport { serializeJob, serializeJobPage } from '../serialize';\nimport type { Route } from './types';\n\n/**\n * `GET /api/jobs` — a page of jobs, newest first, optionally narrowed by a free-text search.\n *\n * The search is a `LIKE` in the database, so it is a paged query like any other read rather than a\n * scan of the table through this process.\n */\nexport const jobsRoute: Route = {\n method: 'GET',\n path: '/api/jobs',\n summary: 'List jobs, with filters and free-text search',\n handle: async ({ portQueue, query }) => {\n const page = await portQueue._dashboard.getJobs({\n ...jobsQuery(query),\n ...when('search', text(query, 'search')),\n });\n return json(200, serializeJobPage(page));\n },\n};\n\n/**\n * `GET /api/jobs/:jobId` — one job by id, from the public API.\n *\n * A job id already identifies exactly one row, so this needs no queue and takes none.\n */\nexport const jobRoute: Route = {\n method: 'GET',\n path: /^\\/api\\/jobs\\/([^/]+)$/,\n summary: 'One job by id',\n handle: async ({ portQueue, params }) => {\n const job = await portQueue.getJob({ jobId: params[0]! });\n if (!job) return json(404, { error: 'Job not found' });\n return json(200, serializeJob(job));\n },\n};\n","import { json } from '../http';\nimport { paging, text, triBool, when } from '../params';\nimport { serializeQueuePage } from '../serialize';\nimport type { Route } from './types';\n\n/**\n * `GET /api/queues` — a page of queues with their per-status counts.\n *\n * Filtering and paging both happen in the database; the counts arrive from one grouped query over\n * this page's names. There is no `inUse` filter: that flag means \"declared in the process that\n * produced this row\", and the dashboard runs on its own client, so it cannot know.\n */\nexport const queuesRoute: Route = {\n method: 'GET',\n path: '/api/queues',\n summary: 'List queues with their per-status counts',\n handle: async ({ portQueue, query }) => {\n const page = await portQueue._dashboard.getQueues({\n ...paging(query),\n ...when('search', text(query, 'search')),\n ...when('processingPaused', triBool(query.get('processingPaused'))),\n });\n return json(200, serializeQueuePage(page));\n },\n};\n","import { json } from '../http';\nimport { paging, text, triBool, when } from '../params';\nimport { serializeSchedule, serializeSchedulePage } from '../serialize';\nimport type { Route } from './types';\n\n/** `GET /api/schedules` — a page of schedules, across every queue unless `queue` narrows it. */\nexport const schedulesRoute: Route = {\n method: 'GET',\n path: '/api/schedules',\n summary: 'List recurring schedules',\n handle: async ({ portQueue, query }) => {\n const page = await portQueue._dashboard.getSchedules({\n ...paging(query),\n ...when('queue', text(query, 'queue')),\n ...when('search', text(query, 'search')),\n ...when('enabled', triBool(query.get('enabled'))),\n });\n return json(200, serializeSchedulePage(page));\n },\n};\n\n/** `GET /api/schedules/:scheduleId` — the schedule detail page's header. */\nexport const scheduleRoute: Route = {\n method: 'GET',\n path: /^\\/api\\/schedules\\/([^/]+)$/,\n summary: 'One schedule by id',\n handle: async ({ portQueue, params }) => {\n const schedule = await portQueue._dashboard.getSchedule({ scheduleId: params[0]! });\n if (!schedule) return json(404, { error: 'Schedule not found' });\n return json(200, serializeSchedule(schedule));\n },\n};\n","import { json } from '../http';\nimport { text, when } from '../params';\nimport { serializeStats } from '../serialize';\nimport type { Route } from './types';\n\n/**\n * `GET /api/stats` — per-status counts for one queue, or client-wide when `queue` is omitted.\n *\n * Counts only. The dashboard renders activity cards and nothing else, so there is deliberately no\n * throughput or failure-rate derivation here to disagree with the numbers on the tables.\n */\nexport const statsRoute: Route = {\n method: 'GET',\n path: '/api/stats',\n summary: 'Per-status counts, for one queue or the whole client',\n handle: async ({ portQueue, query }) => {\n const stats = await portQueue._dashboard.getStats({ ...when('queue', text(query, 'queue')) });\n return json(200, serializeStats(stats));\n },\n};\n","/** Constants shared between the dashboard client and server (avoid literal drift). */\n\n/**\n * The dashboard's name, in the browser tab and in the fallback shell. Fixed, not a host option:\n * the product has one name, and a host-set title only made the tab disagree with the header, the\n * docs and every screenshot.\n */\nexport const DASHBOARD_TITLE = 'PortQueue Dashboard';\n\n/**\n * Header + marker the client sends on every request, and the server **requires** on every mutation.\n *\n * This is the mount's CSRF defence, and it works because of what a browser will not do: a custom\n * request header cannot be set on a cross-origin request unless a preflight allows it, and the\n * dashboard answers no CORS preflight at all. So a form post or `fetch` from another page reaches\n * the mount without the marker and is refused — which matters because the mount is usually behind\n * cookie or basic auth, and a browser replays both on a cross-site request.\n *\n * It costs the host nothing: there is no option to set and nothing to configure.\n */\nexport const REQUESTED_WITH_HEADER = 'x-requested-with';\nexport const REQUESTED_WITH_MARKER = 'portqueue-dashboard';\n\n/**\n * The largest request body the mount reads, in bytes.\n *\n * Here rather than in the reader that enforces it, because it is a property of the API the client\n * talks to: the only mutation that carries a payload of any size is `add`, whose `data` this bounds.\n */\nexport const MAX_BODY_BYTES = 1024 * 1024;\n","/**\n * The route registry and the router built from it.\n *\n * Reads are dispatched by path against {@link ROUTES}. Mutations are too: each one owns\n * `POST /api/actions/<kind>` and is dispatched against `ACTIONS_BY_KIND` by that path segment, so a\n * request names exactly one operation. Both registries are plain lists of self-describing objects,\n * so the whole API surface is readable in one place and adding to it never means extending a\n * conditional chain.\n *\n * The one guard that lives here is the CSRF check: a mutation must carry\n * {@link REQUESTED_WITH_HEADER}. See that constant for why a custom header is the defence, and\n * {@link assertSameOrigin} for what it refuses.\n *\n * There is otherwise **no authentication and no read-only mode anywhere in here**: protecting the\n * mount belongs to whatever middleware the host puts in front of it (see `docs/docs/dashboard.mdx`).\n * Anyone who can reach these routes can perform every action.\n */\nimport { json, queryOf, relativePath, type HandlerInput, type HandlerResult } from '../http';\nimport { ACTIONS, ACTIONS_BY_KIND } from './actions';\nimport { configRoute } from './config';\nimport { instanceRoute, instancesRoute } from './instances';\nimport { jobRoute, jobsRoute } from './jobs';\nimport { queuesRoute } from './queues';\nimport { scheduleRoute, schedulesRoute } from './schedules';\nimport { statsRoute } from './stats';\nimport { REQUESTED_WITH_HEADER, REQUESTED_WITH_MARKER } from '../../../shared/constants';\nimport type { PortQueue } from '@portqueue/core';\nimport type { DashboardClient } from '../../client';\nimport type { ActionKind, ActionPayloadDto } from '../../../shared/dto';\nimport type { Route } from './types';\n\nexport type { HandlerInput, HandlerResult } from '../http';\nexport type { Route, RouteContext } from './types';\nexport type { ActionContext, ActionRoute } from './actions';\nexport { ACTIONS, ACTIONS_BY_KIND };\n\n/** The prefix every mutation posts under; the segment that follows names the action. */\nexport const ACTIONS_PATH_PREFIX = '/api/actions/';\n\n/**\n * Every read route. Literal paths are matched before patterns, so `/api/jobs` can sit beside\n * `/api/jobs/:id` without their order here mattering.\n */\nexport const ROUTES: readonly Route[] = [\n configRoute,\n queuesRoute,\n jobsRoute,\n jobRoute,\n schedulesRoute,\n scheduleRoute,\n instancesRoute,\n instanceRoute,\n statsRoute,\n];\n\nexport interface RouterOptions {\n /** Resolves (and, on the first call, connects) the dashboard's own headless client. */\n client: DashboardClient;\n basePath: string;\n}\n\n/**\n * Create the router. Returns the pure JSON handler plus the path predicate the adapters use to\n * decide between an API call and a static asset.\n */\nexport function createRouter(options: RouterOptions): {\n handle: (input: HandlerInput) => Promise<HandlerResult>;\n isApiPath: (url: string) => boolean;\n} {\n const { client, basePath } = options;\n\n const isApiPath = (url: string): boolean => relativePath(url, basePath).startsWith('/api/');\n\n async function handle(input: HandlerInput): Promise<HandlerResult> {\n const path = relativePath(input.url, basePath);\n const method = input.method.toUpperCase();\n\n // Checked before anything reaches the database, and before the body is even parsed.\n const rejection = assertSameOrigin(method, input.headers);\n if (rejection) return rejection;\n\n // Resolved per request: the first one connects, and a failure here is a 503 the client can retry\n // rather than a mount-time crash the host can do nothing about.\n let portQueue: PortQueue;\n try {\n portQueue = await client.get();\n } catch (err) {\n return json(503, {\n error: err instanceof Error ? err.message : 'Cannot reach the PortQueue database',\n });\n }\n\n if (method === 'POST' && path.startsWith(ACTIONS_PATH_PREFIX)) {\n return handleAction(portQueue, path.slice(ACTIONS_PATH_PREFIX.length), input.body);\n }\n if (method === 'GET') return handleRead(portQueue, path, queryOf(input.url));\n return json(404, { error: 'Not found' });\n }\n\n return { handle, isApiPath };\n}\n\n/**\n * Refuse a mutation that did not come from the dashboard's own client.\n *\n * A `GET` changes nothing and is left alone — reading the JSON API with `curl` should not need a\n * header. Everything else must carry the marker: a cross-origin page cannot set a custom header\n * without a preflight this mount never answers, so this is what stops another site purging a queue\n * with the operator's own cookies (or replayed basic credentials).\n */\nexport function assertSameOrigin(\n method: string,\n headers: Record<string, string | string[] | undefined>,\n): HandlerResult | null {\n if (method === 'GET' || method === 'HEAD') return null;\n const raw = headers[REQUESTED_WITH_HEADER];\n const value = Array.isArray(raw) ? raw[0] : raw;\n if (value === REQUESTED_WITH_MARKER) return null;\n return json(403, {\n error: `Missing or invalid ${REQUESTED_WITH_HEADER} header — a mutation must come from the dashboard client.`,\n });\n}\n\n/** Dispatch a read to the first route whose `path` matches. */\nasync function handleRead(\n portQueue: PortQueue,\n path: string,\n query: URLSearchParams,\n): Promise<HandlerResult> {\n for (const route of ROUTES) {\n const params = match(route, path);\n if (params) return route.handle({ portQueue, query, params });\n }\n return json(404, { error: 'Not found' });\n}\n\n/** The captured, decoded segments when `route` matches `path`, or `null` when it doesn't. */\nfunction match(route: Route, path: string): string[] | null {\n if (typeof route.path === 'string') return route.path === path ? [] : null;\n const found = route.path.exec(path);\n if (!found) return null;\n return found.slice(1).map((segment) => decodeURIComponent(segment));\n}\n\n/** Parse a mutation body and hand it to the action the URL segment names. */\nasync function handleAction(\n portQueue: PortQueue,\n segment: string,\n body: string | undefined,\n): Promise<HandlerResult> {\n const route = ACTIONS_BY_KIND.get(decodeURIComponent(segment) as ActionKind);\n if (!route) return json(404, { error: 'Unknown action' });\n let action: ActionPayloadDto;\n try {\n // An action with no fields of its own still posts `{}`, so an empty body is a malformed request\n // rather than a shorthand for \"no fields\".\n action = JSON.parse(body ?? '') as ActionPayloadDto;\n } catch {\n return json(400, { error: 'Invalid JSON body' });\n }\n if (!action || typeof action !== 'object') return json(400, { error: 'Invalid JSON body' });\n return route.handle({ portQueue, action });\n}\n","/**\n * Serves the built client bundle + index.html from the packaged `dist/client` directory. If that\n * directory is absent (the client hasn't been built), serves a minimal inline HTML shell so the\n * mount still responds and says why. No dependency beyond Node fs.\n */\nimport { randomBytes } from 'node:crypto';\nimport { readFile, stat } from 'node:fs/promises';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, extname, isAbsolute, join, relative, resolve } from 'node:path';\nimport { DASHBOARD_TITLE } from '../shared/constants';\nimport type { DashboardConfigDto } from '../shared/dto';\n\nconst HTML_MIME = 'text/html; charset=utf-8';\n\nconst MIME: Record<string, string> = {\n '.html': HTML_MIME,\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.map': 'application/json; charset=utf-8',\n};\n\n/**\n * Vite emits content-hashed asset filenames, so a given URL's bytes never change — those can be\n * cached indefinitely. HTML carries the injected runtime config and must always be revalidated.\n */\nconst IMMUTABLE_CACHE = 'public, max-age=31536000, immutable';\nconst NO_CACHE = 'no-cache';\n\nexport interface AssetResult {\n status: number;\n body: Buffer | string;\n contentType: string;\n /** Extra response headers — caching and, for HTML, the CSP naming the inline script's nonce. */\n headers?: Record<string, string>;\n}\n\n/** Resolve the packaged client bundle directory relative to this module. */\nfunction clientDistDir(): string {\n const here = dirname(fileURLToPath(import.meta.url));\n // At runtime the server lives at dist/index.{mjs,cjs}; the client bundle sits in dist/client.\n return resolve(here, 'client');\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n const s = await stat(path);\n return s.isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * True when a built client bundle is present in the package.\n *\n * Resolved **once** and memoized: the bundle ships inside the package and cannot appear or disappear\n * while the process runs, so asking the filesystem on every asset request was one `stat` per request\n * for an answer that never changes. `createEngine` awaits it at mount to warn about a missing\n * bundle, which is also what primes it.\n */\nexport function hasBuiltClient(): Promise<boolean> {\n builtClient ??= exists(join(clientDistDir(), 'index.html'));\n return builtClient;\n}\n\n/** The memoized answer. A promise, so concurrent first requests share one `stat`. */\nlet builtClient: Promise<boolean> | null = null;\n\n/** Clear the memo. Test-only: a suite that creates and removes a fake bundle needs to re-ask. */\nexport function resetBuiltClientCache(): void {\n builtClient = null;\n}\n\n/**\n * Resolve a request path inside the bundle directory, or null if it escapes.\n *\n * `resolve` + `relative`, not a string prefix test: a prefix check accepts a sibling directory\n * whose name merely starts with the root's (`…/client-evil` passes `startsWith('…/client')`), and\n * it mishandles an absolute request path. Here anything resolving outside the root — a `..`\n * segment, an absolute path — comes back as a relative path that starts with `..` or is itself\n * absolute, and is rejected.\n */\nexport function safeResolve(root: string, relPath: string): string | null {\n const target = resolve(root, `.${relPath.startsWith('/') ? relPath : `/${relPath}`}`);\n const rel = relative(root, target);\n if (rel === '') return target; // the root itself\n if (rel.startsWith('..') || isAbsolute(rel)) return null;\n return target;\n}\n\n/**\n * Serve a static asset by relative path (already stripped of basePath). SPA fallback: unknown\n * non-file paths resolve to index.html so client-side routing works.\n */\nexport async function serveAsset(\n relPath: string,\n config: DashboardConfigDto,\n): Promise<AssetResult> {\n const root = clientDistDir();\n const built = await hasBuiltClient();\n\n if (!built) {\n // No bundle: serve the inline shell for any navigation, 404 for asset-looking requests.\n if (extname(relPath) && relPath !== '/index.html') {\n return { status: 404, body: 'Not found', contentType: 'text/plain; charset=utf-8' };\n }\n return htmlResult(inlineShell(config), config);\n }\n\n const requested = relPath === '/' ? '/index.html' : relPath;\n const target = safeResolve(root, requested);\n if (target === null) {\n return { status: 403, body: 'Forbidden', contentType: 'text/plain; charset=utf-8' };\n }\n\n if (await exists(target)) {\n const ext = extname(target).toLowerCase();\n const body = await readFile(target);\n if (ext === '.html') {\n return htmlResult(rewriteAssetUrls(body.toString('utf8'), config.basePath), config);\n }\n return {\n status: 200,\n body,\n contentType: MIME[ext] ?? 'application/octet-stream',\n // Content-hashed filenames make this safe: the browser never re-requests a cached bundle.\n headers: { 'cache-control': IMMUTABLE_CACHE },\n };\n }\n\n // SPA fallback: any non-asset path → index.html with injected config.\n if (!extname(requested)) {\n const indexPath = join(root, 'index.html');\n if (await exists(indexPath)) {\n const raw = (await readFile(indexPath)).toString('utf8');\n return htmlResult(rewriteAssetUrls(raw, config.basePath), config);\n }\n }\n return { status: 404, body: 'Not found', contentType: 'text/plain; charset=utf-8' };\n}\n\n/**\n * Finish an HTML response: inject the runtime config under a fresh nonce, and emit the CSP that\n * authorizes exactly that one inline script. The nonce is per-response, so an injected `<script>`\n * without it is refused by the browser even if it does reach the page.\n */\nfunction htmlResult(html: string, config: DashboardConfigDto): AssetResult {\n const nonce = randomBytes(16).toString('base64');\n return {\n status: 200,\n body: injectConfig(html, config, nonce),\n contentType: HTML_MIME,\n headers: {\n 'cache-control': NO_CACHE,\n 'content-security-policy': contentSecurityPolicy(nonce),\n },\n };\n}\n\n/**\n * The dashboard's CSP. The SPA has exactly one inline script (the config blob), so it carries a\n * nonce and every other inline script is refused. `style-src` must allow `unsafe-inline`: the\n * SPA's own styles ship as a stylesheet, but `@ant-design/icons` injects its base icon rules into a\n * `<style>` element at runtime, and the shell carries a small inline `<style>` of its own.\n */\nfunction contentSecurityPolicy(nonce: string): string {\n return [\n \"default-src 'self'\",\n `script-src 'self' 'nonce-${nonce}'`,\n \"style-src 'self' 'unsafe-inline'\",\n \"img-src 'self' data:\",\n \"font-src 'self' data:\",\n \"connect-src 'self'\",\n \"frame-ancestors 'none'\",\n \"base-uri 'self'\",\n \"form-action 'self'\",\n \"object-src 'none'\",\n ].join('; ');\n}\n\n/**\n * The client is built with Vite `base: './'`, so `index.html` references its bundle relatively\n * (`./assets/app.js`). The browser would resolve that against the *current* URL, which breaks\n * for every mount-relative navigation: `/portqueue` → `/assets/app.js` (outside the mount) and\n * `/portqueue/jobs/1` → `/portqueue/jobs/assets/app.js`. Rewriting the references to absolute\n * paths under the mount makes them resolve identically from any URL, with or without a trailing\n * slash. A root mount (`/`) needs no prefix — `//assets/...` would read as protocol-relative.\n */\nexport function rewriteAssetUrls(html: string, basePath: string): string {\n const prefix = basePath === '/' ? '' : basePath;\n return html.replace(\n /(\\b(?:src|href)=\")\\.\\/([^\"]*)\"/g,\n (_match, attr: string, path: string) => `${attr}${prefix}/${path}\"`,\n );\n}\n\n/** Inject the runtime config as a global the SPA reads on boot. */\nfunction injectConfig(html: string, config: DashboardConfigDto, nonce: string): string {\n const tag = `<script nonce=\"${nonce}\">window.__PORTQUEUE_DASHBOARD__=${serializeConfig(config)};</script>`;\n if (html.includes('</head>')) return html.replace('</head>', `${tag}</head>`);\n return `${tag}${html}`;\n}\n\n/**\n * JSON for embedding inside a `<script>` element. `JSON.stringify` does not escape `<`, so a\n * developer-supplied `basePath` of `</script>…` would otherwise close the element early and let\n * what follows be parsed as markup. Escaping `<` and `>` — plus U+2028/U+2029, which are legal\n * inside a JSON string but count as line terminators to a JS parser — makes the value inert while\n * keeping it valid JSON.\n */\nexport function serializeConfig(config: DashboardConfigDto): string {\n return JSON.stringify(config)\n .replace(/</g, '\\\\u003c')\n .replace(/>/g, '\\\\u003e')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029');\n}\n\n/** A minimal, dependency-free HTML shell used when no built client is packaged. */\nfunction inlineShell(config: DashboardConfigDto): string {\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<title>${DASHBOARD_TITLE}</title>\n<style>\n :root { color-scheme: light dark; }\n body { margin:0; font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", system-ui, sans-serif; background:#f7f8fa; color:#1a1d23; }\n @media (prefers-color-scheme: dark){ body{ background:#0b0e14; color:#e6e8ec; } .card{ background:#131722 !important; } }\n .wrap{ max-width:720px; margin:12vh auto; padding:24px; }\n .card{ background:#fff; border-radius:16px; padding:32px; box-shadow:0 12px 32px rgba(16,24,40,0.12),0 6px 16px rgba(16,24,40,0.08); }\n code{ font-family: ui-monospace, \"SF Mono\", Menlo, monospace; background:rgba(127,127,127,0.15); padding:2px 6px; border-radius:6px; }\n h1{ font-size:22px; margin:0 0 8px; }\n</style>\n</head>\n<body>\n<div class=\"wrap\"><div class=\"card\">\n<h1>${DASHBOARD_TITLE}</h1>\n<p>The PortQueue dashboard server is mounted at <code>${escapeHtml(config.basePath)}</code>, but the client bundle has not been built into this package yet.</p>\n<p>Build it with <code>npm run build:client</code> in <code>@portqueue/dashboard</code>, then reload. The JSON API is already live at <code>${escapeHtml(config.basePath)}/api</code>.</p>\n</div></div>\n</body>\n</html>`;\n}\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\n}\n","/** Raw-Node request helpers shared by the engine and adapters. */\nimport type { IncomingMessage } from 'node:http';\nimport { MAX_BODY_BYTES } from '../shared/constants';\n\n/**\n * Read a request body to a string, rejecting anything over {@link MAX_BODY_BYTES}.\n *\n * On overflow it stops accumulating and **keeps reading** rather than destroying the socket. The\n * caller answers 413, and a client can only read that answer if the connection is still there —\n * `req.destroy()` mid-stream closed a keep-alive connection instead, so the client saw a transport\n * error where a clear status was available. The remaining bytes are discarded as they arrive, so\n * nothing accumulates in memory either way.\n */\nexport function readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolveBody, reject) => {\n const chunks: Buffer[] = [];\n let size = 0;\n let tooLarge = false;\n req.on('data', (chunk: Buffer) => {\n size += chunk.length;\n if (tooLarge) return;\n if (size > MAX_BODY_BYTES) {\n tooLarge = true;\n chunks.length = 0;\n return;\n }\n chunks.push(chunk);\n });\n req.on('end', () => {\n if (tooLarge) {\n reject(new BodyTooLargeError());\n return;\n }\n resolveBody(Buffer.concat(chunks).toString('utf8'));\n });\n req.on('error', reject);\n });\n}\n\n/** Why {@link readBody} rejected: the body passed the cap, and the answer is a 413. */\nexport class BodyTooLargeError extends Error {\n constructor() {\n super(`Request body exceeds the ${MAX_BODY_BYTES}-byte limit`);\n this.name = 'BodyTooLargeError';\n }\n}\n\nexport function toHeaders(req: IncomingMessage): Record<string, string | string[] | undefined> {\n return req.headers as Record<string, string | string[] | undefined>;\n}\n\n/** Normalize a mount path: ensure a leading slash, drop a trailing one. */\nexport function normalizeBase(basePath: string): string {\n let b = basePath.trim();\n if (!b.startsWith('/')) b = `/${b}`;\n if (b.length > 1 && b.endsWith('/')) b = b.slice(0, -1);\n return b;\n}\n","/**\n * The dashboard's own PortQueue.\n *\n * `createDashboard` takes a **driver**, not a running `PortQueue`. That is the whole point: the\n * dashboard is an operations console for a deployment, and in almost every real deployment it is a\n * different process from the workers — so being handed the app's client only ever worked in the one\n * case where they happened to share a process, and it quietly coupled the two.\n *\n * The client it builds is **headless** (`_headless: true`), which is what keeps an observer from\n * behaving like a participant:\n *\n * - it declares no queues and writes no queue rows, so browsing never creates anything;\n * - it registers no instance row, so the dashboard never shows up in its own instances list;\n * - it consumes no queue and runs no scheduler, retention sweep or health monitor — the app's processes own that\n * work, and a dashboard quietly firing the cluster's schedules would be a second producer nobody\n * asked for;\n * - it never migrates: pointing the dashboard at a database must not change its schema.\n *\n * `init()` is deferred to the first request and memoized, because `createDashboard` is synchronous\n * and a mount must not open a connection the host may never use.\n */\nimport { PortQueue } from '@portqueue/core';\nimport type { Driver, Logger } from '@portqueue/core';\n\nexport interface DashboardClient {\n /** The initialized client. Connects on the first call; every later call reuses it. */\n get(): Promise<PortQueue>;\n /** Disconnect, if a request ever caused a connection. Safe to call more than once. */\n close(): Promise<void>;\n}\n\nexport function createDashboardClient(options: {\n driver: Driver;\n logger?: Pick<Logger, 'warn'>;\n}): DashboardClient {\n let started: Promise<PortQueue> | null = null;\n let instance: PortQueue | null = null;\n\n return {\n get(): Promise<PortQueue> {\n if (!started) {\n started = (async () => {\n const pq = new PortQueue({ driver: options.driver, _headless: true });\n await pq.init();\n instance = pq;\n return pq;\n })().catch((err: unknown) => {\n // Don't cache a failed connection — the next request must be able to retry.\n started = null;\n throw err;\n });\n }\n return started;\n },\n async close(): Promise<void> {\n const pq = instance;\n started = null;\n instance = null;\n if (pq) await pq.shutdown();\n },\n };\n}\n","/**\n * The framework-agnostic serve core. Holds the router, config and path matching, and exposes\n * `serve`/`serveSafely` that every adapter drives with a raw Node `(req, res)` pair.\n *\n * It owns the dashboard's own headless client (see `client.ts`), built from the driver it was given.\n * Nothing connects at mount: the first API request opens the connection, and `close()` releases it.\n *\n * The dashboard has no authentication of its own — see `api/routes.ts` and the dashboard docs.\n */\nimport { MAX_BATCH_IDS } from '@portqueue/core';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { createRouter, type HandlerInput } from './api/routes';\nimport { hasBuiltClient, serveAsset } from './assets';\nimport { normalizeBase, readBody, toHeaders } from './request';\nimport { createDashboardClient, type DashboardClient } from './client';\nimport type { DashboardOptions } from './types';\nimport type { DashboardConfigDto } from '../shared/dto';\n\n/**\n * Headers on every response the dashboard writes. `nosniff` stops a browser second-guessing a\n * declared content type; the rest keep the UI out of frames and stop the referrer leaking a job\n * id (which URLs carry) to any external link a user follows.\n */\nconst SECURITY_HEADERS: Record<string, string> = {\n 'x-content-type-options': 'nosniff',\n 'x-frame-options': 'DENY',\n 'referrer-policy': 'no-referrer',\n};\n\nexport interface DashboardEngine {\n /** The resolved, normalized mount path. */\n readonly basePath: string;\n /** True when the URL falls under our mount. */\n owns(url: string | undefined): boolean;\n /** The core async serve routine — writes directly to the raw response. */\n serve(req: IncomingMessage, res: ServerResponse): Promise<void>;\n /** `serve` wrapped so any error becomes a 500 instead of an unhandled rejection. */\n serveSafely(req: IncomingMessage, res: ServerResponse): void;\n /** Release the dashboard's own client. */\n close(): Promise<void>;\n}\n\nexport function createEngine(\n options: DashboardOptions & { client?: DashboardClient },\n): DashboardEngine {\n const basePath = normalizeBase(options.basePath ?? '/portqueue');\n const config: DashboardConfigDto = { basePath, maxBatchIds: MAX_BATCH_IDS };\n const logger = options.logger ?? console;\n // The client is injectable so a test can drive the router without a driver; production always\n // builds it from the driver the host supplied.\n const client =\n options.client ??\n createDashboardClient({ driver: options.driver, ...(options.logger ? { logger } : {}) });\n const router = createRouter({ client, basePath });\n\n // A missing bundle makes every navigation serve the \"not built\" shell with a 200, which reads\n // as a working deploy. Say so once, at mount time, rather than letting it pass silently.\n void hasBuiltClient().then((built) => {\n if (!built) {\n logger.warn(\n `[@portqueue/dashboard] No client bundle found; serving the fallback shell at ${basePath}. ` +\n 'The package was published or built without its SPA — run `npm run build` in ' +\n '@portqueue/dashboard, or reinstall the package.',\n );\n }\n });\n\n /**\n * Whether a URL falls under the mount. The query string is stripped first, so this compares paths\n * — `/portqueue` exactly, or something below it. There is no third `basePath?` case: after the\n * split, a path cannot contain a `?`.\n */\n function owns(url: string | undefined): boolean {\n if (!url) return false;\n const path = url.split('?')[0] ?? '';\n return path === basePath || path.startsWith(`${basePath}/`);\n }\n\n function relPath(url: string): string {\n const path = (url.split('?')[0] ?? '').slice(basePath.length);\n return path.startsWith('/') || path === '' ? path || '/' : `/${path}`;\n }\n\n /** Handle a JSON API request. */\n async function handleApi(\n req: IncomingMessage,\n res: ServerResponse,\n method: string,\n url: string,\n ): Promise<void> {\n let body: string | undefined;\n if (method === 'POST' || method === 'PUT' || method === 'PATCH') {\n try {\n body = await readBody(req);\n } catch {\n res.writeHead(413, { ...SECURITY_HEADERS, 'content-type': 'application/json' });\n res.end(JSON.stringify({ error: 'Request body too large' }));\n return;\n }\n }\n const input: HandlerInput = { method, url, body, headers: toHeaders(req) };\n const result = await router.handle(input);\n res.writeHead(result.status, { ...SECURITY_HEADERS, ...result.headers });\n res.end(result.body);\n }\n\n /** Serve the static SPA shell / assets. */\n async function handleAsset(res: ServerResponse, url: string): Promise<void> {\n const asset = await serveAsset(relPath(url), config);\n res.writeHead(asset.status, {\n ...SECURITY_HEADERS,\n 'content-type': asset.contentType,\n ...asset.headers,\n });\n res.end(asset.body);\n }\n\n async function serve(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const url = req.url ?? '';\n const method = (req.method ?? 'GET').toUpperCase();\n if (router.isApiPath(url)) return handleApi(req, res, method, url);\n return handleAsset(res, url);\n }\n\n function serveSafely(req: IncomingMessage, res: ServerResponse): void {\n void serve(req, res).catch(() => {\n if (!res.headersSent) {\n res.writeHead(500, { ...SECURITY_HEADERS, 'content-type': 'application/json' });\n }\n res.end(JSON.stringify({ error: 'Internal dashboard error' }));\n });\n }\n\n return { basePath, owns, serve, serveSafely, close: () => client.close() };\n}\n","/**\n * Express adapter. `app.use(basePath, expressAdapter(dashboard))` or\n * `app.use(dashboard.express())`.\n */\nimport type { DashboardEngine } from '../engine';\nimport type { Dashboard, ExpressMiddleware } from '../types';\n\nexport function createExpressMiddleware(engine: DashboardEngine): ExpressMiddleware {\n return (req, res, next) => {\n // Express strips the mount path from req.url; reconstruct so our router sees basePath.\n const original = req.url ?? '';\n const originalUrl = (req as unknown as { originalUrl?: string }).originalUrl;\n if (originalUrl) req.url = originalUrl;\n if (!engine.owns(req.url)) {\n req.url = original;\n next();\n return;\n }\n engine.serveSafely(req, res);\n };\n}\n\n/** Ergonomic named-import wrapper, equivalent to `dashboard.express()`. */\nexport function expressAdapter(dashboard: Dashboard): ExpressMiddleware {\n return dashboard.express();\n}\n","/**\n * Fastify adapter. `app.register(fastifyAdapter(dashboard))` or\n * `app.register(dashboard.fastify())`.\n *\n * **The plugin opts out of Fastify's encapsulation, and it has to.** `register` normally gives a\n * plugin its own child context, and a hook added inside one only runs for routes registered in that\n * context — of which the dashboard has none, because it serves the raw request itself rather than\n * declaring Fastify routes. So the hook never fired and every dashboard URL fell through to\n * Fastify's own 404. Setting `skip-override` (what `fastify-plugin` does, without the dependency)\n * makes `addHook` apply to the instance the host registered it on.\n */\nimport type { DashboardEngine } from '../engine';\nimport type { Dashboard, FastifyPlugin } from '../types';\n\n/** Fastify's marker for \"run me on the parent instance, not a child context\". */\nconst SKIP_OVERRIDE = Symbol.for('skip-override');\n\nexport function createFastifyPlugin(engine: DashboardEngine): FastifyPlugin {\n const plugin: FastifyPlugin = (fastify, _opts, done) => {\n // `async`, so Fastify sees a promise from a two-parameter hook rather than guessing whether the\n // hook is done — a bare `undefined` return leaves the request waiting for a `done` it never gets.\n fastify.addHook('onRequest', async (request, reply) => {\n if (!engine.owns(request.raw.url)) return;\n // Fastify owns the reply until this call; without it Fastify would answer too, and the second\n // write to the same response throws.\n reply.hijack();\n engine.serveSafely(request.raw, reply.raw);\n });\n done();\n };\n (plugin as unknown as Record<symbol, boolean>)[SKIP_OVERRIDE] = true;\n return plugin;\n}\n\n/** Ergonomic named-import wrapper, equivalent to `dashboard.fastify()`. */\nexport function fastifyAdapter(dashboard: Dashboard): FastifyPlugin {\n return dashboard.fastify();\n}\n","/**\n * Koa adapter. `app.use(koaAdapter(dashboard))` or\n * `app.use(dashboard.koa())`.\n */\nimport type { DashboardEngine } from '../engine';\nimport type { Dashboard, KoaMiddleware } from '../types';\n\nexport function createKoaMiddleware(engine: DashboardEngine): KoaMiddleware {\n return async (ctx, next) => {\n if (!engine.owns(ctx.req.url)) {\n await next();\n return;\n }\n ctx.respond = false; // we write to the raw response directly\n await engine.serve(ctx.req, ctx.res);\n };\n}\n\n/** Ergonomic named-import wrapper, equivalent to `dashboard.koa()`. */\nexport function koaAdapter(dashboard: Dashboard): KoaMiddleware {\n return dashboard.koa();\n}\n","/**\n * NestJS adapter. Nest's default platform is Express, so the dashboard mounts\n * as ordinary functional middleware — no `@nestjs/*` dependency is required. Wire it in a module:\n *\n * ```ts\n * @Module({})\n * export class DashboardModule implements NestModule {\n * constructor(private readonly dashboard: Dashboard) {}\n * configure(consumer: MiddlewareConsumer): void {\n * consumer.apply(nestAdapter(this.dashboard)).forRoutes('/portqueue');\n * }\n * }\n * ```\n *\n * The middleware reconstructs the full mount path from `req.originalUrl`, exactly like the\n * Express adapter, so it behaves identically under `@nestjs/platform-express`.\n */\nimport type { DashboardEngine } from '../engine';\nimport type { Dashboard, NestMiddleware } from '../types';\nimport { createExpressMiddleware } from './express';\n\nexport function createNestMiddleware(engine: DashboardEngine): NestMiddleware {\n // Nest (platform-express) middleware is Express middleware.\n return createExpressMiddleware(engine);\n}\n\n/** Ergonomic named-import wrapper, equivalent to `dashboard.nest()`. */\nexport function nestAdapter(dashboard: Dashboard): NestMiddleware {\n return dashboard.nest();\n}\n","/**\n * Raw-Node adapter. The `(req, res) => boolean` handler: returns true when\n * it served the request, so you can fall through to your own routing otherwise.\n */\nimport type { DashboardEngine } from '../engine';\nimport type { Dashboard, NodeHandler } from '../types';\n\nexport function createNodeHandler(engine: DashboardEngine): NodeHandler {\n return (req, res) => {\n if (!engine.owns(req.url)) return false;\n engine.serveSafely(req, res);\n return true;\n };\n}\n\n/** Ergonomic named-import wrapper, equivalent to `dashboard.node()`. */\nexport function nodeAdapter(dashboard: Dashboard): NodeHandler {\n return dashboard.node();\n}\n","/**\n * `createDashboard(options)` — the single named-options factory. Builds the framework-agnostic\n * engine (see `engine.ts`) once, then exposes per-framework handlers, each a thin wrapper defined in\n * `adapters/`.\n *\n * It takes a **driver** and builds its own headless client from it (see `client.ts`), rather than\n * riding on the application's `PortQueue`. Mounting opens no connection; the first API request does,\n * and `close()` releases it.\n */\nimport { createEngine } from './engine';\nimport { createExpressMiddleware } from './adapters/express';\nimport { createFastifyPlugin } from './adapters/fastify';\nimport { createKoaMiddleware } from './adapters/koa';\nimport { createNestMiddleware } from './adapters/nest';\nimport { createNodeHandler } from './adapters/node';\nimport type { DashboardClient } from './client';\nimport type { Dashboard, DashboardOptions } from './types';\n\nexport function createDashboard(\n /**\n * `client` is an internal seam: it lets a test drive the router without a database and is never\n * part of the documented option surface. Production always passes `driver` alone.\n */\n options: DashboardOptions & { client?: DashboardClient },\n): Dashboard {\n const engine = createEngine(options);\n return {\n basePath: engine.basePath,\n node: () => createNodeHandler(engine),\n express: () => createExpressMiddleware(engine),\n koa: () => createKoaMiddleware(engine),\n fastify: () => createFastifyPlugin(engine),\n nest: () => createNestMiddleware(engine),\n close: () => engine.close(),\n };\n}\n"],"names":["ActionKind"],"mappings":";;;;;AAsBA,MAAM,eAAuC,EAAE,gBAAgB,kCAAA;AAGxD,SAAS,KACd,QACA,SACA,OACe;AACf,SAAO,EAAE,QAAQ,MAAM,KAAK,UAAU,OAAO,GAAG,SAAS,EAAE,GAAG,cAAc,GAAG,QAAM;AACvF;AAMO,SAAS,SAAS,KAAc,UAAiC;AACtE,SAAO,KAAK,KAAK,EAAE,OAAO,eAAe,QAAQ,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AAO;AAAA,IACL,UAAU,OAAO;AAAA,IACjB,MAAM,MAAM,kBAAkB,MAAM;AAAA,IACpC,SAAS,MAAM,wBAAwB,MAAM;AAAA,IAC7C,KAAK,MAAM,oBAAoB,MAAM;AAAA,IACrC,SAAS,MAAM,oBAAoB,MAAM;AAAA,IACzC,MAAM,MAAM,qBAAqB,MAAM;AAAA,IACvC,OAAO,MAAM,OAAO,MAAA;AAAA,EAAM;AAE9B;"}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../src/server/api/http.ts","../src/server/api/routes/actions/validate.ts","../src/shared/dto/action.ts","../src/server/api/routes/actions/add.ts","../src/server/api/routes/actions/job-batch.ts","../src/server/api/routes/actions/cancel.ts","../src/server/api/routes/actions/pause.ts","../src/server/api/routes/actions/pause-instance.ts","../src/server/api/routes/actions/remove.ts","../src/server/api/routes/actions/remove-instance.ts","../src/server/api/routes/actions/remove-queue.ts","../src/server/api/routes/actions/remove-schedule.ts","../src/server/api/routes/actions/resume.ts","../src/server/api/routes/actions/resume-instance.ts","../src/server/api/routes/actions/retry.ts","../src/server/api/routes/actions/set-schedule-enabled.ts","../src/server/api/routes/actions/index.ts","../src/server/api/routes/config.ts","../src/server/api/params.ts","../src/server/api/serialize.ts","../src/server/api/routes/instances.ts","../src/server/api/routes/jobs.ts","../src/server/api/routes/queues.ts","../src/server/api/routes/schedules.ts","../src/server/api/routes/stats.ts","../src/shared/constants.ts","../src/server/api/routes/index.ts","../src/server/assets.ts","../src/server/request.ts","../src/server/client.ts","../src/server/engine.ts","../src/server/adapters/express.ts","../src/server/adapters/fastify.ts","../src/server/adapters/koa.ts","../src/server/adapters/nest.ts","../src/server/adapters/node.ts","../src/server/create-dashboard.ts"],"sourcesContent":["/**\n * The request/response shapes every route speaks, and the two helpers that build a reply.\n *\n * Deliberately tiny and framework-free: an adapter translates its framework's request into\n * {@link HandlerInput}, the router hands back a {@link HandlerResult}, and the adapter writes it.\n * Nothing here knows about Node's `http`, so a route is a pure function of its input.\n */\n\nexport interface HandlerInput {\n method: string;\n /** URL path + query, already stripped to be relative-friendly (may still include basePath). */\n url: string;\n body: string | undefined;\n headers: Record<string, string | string[] | undefined>;\n}\n\nexport interface HandlerResult {\n status: number;\n body: string;\n headers?: Record<string, string>;\n}\n\nconst JSON_HEADERS: Record<string, string> = { 'content-type': 'application/json; charset=utf-8' };\n\n/** A JSON reply. Every route returns one of these — there is no other response shape. */\nexport function json(\n status: number,\n payload: unknown,\n extra?: Record<string, string>,\n): HandlerResult {\n return { status, body: JSON.stringify(payload), headers: { ...JSON_HEADERS, ...extra } };\n}\n\n/**\n * A 409 carrying the actionable message core threw (queue in use, instance still active, …).\n * Those refusals are the caller's problem to fix, not a server fault, so they must not read as 500s.\n */\nexport function conflict(err: unknown, fallback: string): HandlerResult {\n return json(409, { error: err instanceof Error ? err.message : fallback });\n}\n\n/** Strip the mount base path so route matching sees `/api/...`. */\nexport function relativePath(url: string, basePath: string): string {\n const qIndex = url.indexOf('?');\n let path = qIndex === -1 ? url : url.slice(0, qIndex);\n if (basePath && path.startsWith(basePath)) path = path.slice(basePath.length);\n if (!path.startsWith('/')) path = `/${path}`;\n return path;\n}\n\n/** The query string of a URL, as `URLSearchParams` (empty when there isn't one). */\nexport function queryOf(url: string): URLSearchParams {\n const qIndex = url.indexOf('?');\n return new URLSearchParams(qIndex === -1 ? '' : url.slice(qIndex + 1));\n}\n","/**\n * Field checks shared by the action routes.\n *\n * Each returns either the value or a ready-made 400, so a handler reads as a short list of\n * requirements followed by the one call that does the work. A `400` is always the client's mistake:\n * anything core refuses for a legitimate request is a 409 (see `conflict`) or a 400 with core's own\n * message.\n */\nimport { MAX_BATCH_IDS } from '@portqueue/core';\nimport { json, type HandlerResult } from '../../http';\nimport type { ActionPayloadDto } from '../../../../shared/dto';\n\n/** Either a validated value, or the response to send instead. */\nexport type Checked<T> = { ok: true; value: T } | { ok: false; response: HandlerResult };\n\nconst invalid = (error: string): Checked<never> => ({ ok: false, response: json(400, { error }) });\n\n/** The target queue name. Required by every queue-scoped action. */\nexport function requireQueue(action: ActionPayloadDto): Checked<string> {\n if (typeof action.queue !== 'string' || !action.queue) return invalid('Missing queue');\n return { ok: true, value: action.queue };\n}\n\n/** The target instance key. Required by the three instance actions. */\nexport function requireInstanceKey(action: ActionPayloadDto): Checked<string> {\n if (typeof action.instanceKey !== 'string' || !action.instanceKey) {\n return invalid('Missing instanceKey');\n }\n return { ok: true, value: action.instanceKey };\n}\n\n/**\n * The job ids a retry/cancel/remove applies to. `jobIds` (a bulk selection) and `jobId` (one row\n * action) are the same operation at different sizes, so both normalize to a list here rather than\n * taking separate paths through the handler.\n */\nexport function requireJobIds(action: ActionPayloadDto): Checked<string[]> {\n return checkIds(idsOf(action.jobIds, action.jobId), 'jobId(s)');\n}\n\n/** The schedule ids a removal applies to — same one-or-many normalization as the job ids. */\nexport function requireScheduleIds(action: ActionPayloadDto): Checked<string[]> {\n return checkIds(idsOf(action.scheduleIds, action.scheduleId), 'scheduleId(s)');\n}\n\n/**\n * The list form when there is one, else the single id as a list of one. Returned as `unknown`: the\n * body is whatever the request sent, and {@link checkIds} is what proves it is a list of ids.\n */\nfunction idsOf(many: unknown, one: unknown): unknown {\n if (many !== undefined && !(Array.isArray(many) && many.length === 0)) return many;\n return one === undefined || one === '' ? [] : [one];\n}\n\n/** One schedule id, for the actions that address exactly one. */\nexport function requireScheduleId(action: ActionPayloadDto): Checked<string> {\n if (typeof action.scheduleId !== 'string' || !action.scheduleId) {\n return invalid('Missing scheduleId');\n }\n return { ok: true, value: action.scheduleId };\n}\n\n/**\n * A non-empty id list within core's batch cap.\n *\n * Checked here as well as in core so an oversized selection is a 400 that names the limit rather\n * than a driver error an operator has to interpret. The client stops a selection growing past the\n * same cap, so reaching this means a hand-made request.\n */\nfunction checkIds(ids: unknown, what: string): Checked<string[]> {\n // A string's `.length` would pass the checks below and reach core as a list of characters.\n if (!Array.isArray(ids)) return invalid(`Invalid ${what}: expected a list of ids`);\n if (!ids.length) return invalid(`Missing ${what}`);\n if (!ids.every((id): id is string => typeof id === 'string' && id.length > 0)) {\n return invalid(`Invalid ${what}: every id must be a non-empty string`);\n }\n if (ids.length > MAX_BATCH_IDS) {\n return invalid(`Too many ids: ${ids.length} — the limit is ${MAX_BATCH_IDS} per request`);\n }\n return { ok: true, value: ids };\n}\n","/** Mutation request/response wire DTOs for the dashboard action endpoints. */\nimport type { PauseMode } from '@portqueue/core';\n\n/**\n * Every mutation the dashboard can ask for. An enum, so no route matches a magic string — and the\n * value **is** the URL segment the mutation posts to (`POST {basePath}/api/actions/<kind>`), so an\n * action has exactly one endpoint and there is no second spelling to keep in sync.\n */\nexport enum ActionKind {\n PAUSE = 'pause',\n RESUME = 'resume',\n RETRY = 'retry',\n REMOVE = 'remove',\n CANCEL = 'cancel',\n ADD = 'add',\n REMOVE_SCHEDULE = 'removeSchedule',\n SET_SCHEDULE_ENABLED = 'setScheduleEnabled',\n REMOVE_QUEUE = 'removeQueue',\n PAUSE_INSTANCE = 'pauseInstance',\n RESUME_INSTANCE = 'resumeInstance',\n REMOVE_INSTANCE = 'removeInstance',\n}\n\n/** The payload an `add` action carries — the subset of core `AddJobOptions` the form exposes. */\nexport interface AddJobRequestDto {\n data: unknown;\n priority?: number;\n idempotencyKey?: string;\n singletonKey?: string;\n /** Cap on automatic retries for this job. */\n retryMaxAttempts?: number;\n /** Regex matching the instance keys this job may run on. */\n preferredInstanceKeyPattern?: string;\n /** One-off: delay this many **seconds** from now. */\n startAfterSeconds?: number;\n /** Recurring: fixed interval, in **seconds**. */\n startEverySeconds?: number;\n /** Recurring: cron expression, optionally with a timezone. */\n cron?: string | { pattern: string; tz?: string };\n}\n\n/**\n * The body of a mutation — the per-action fields, and nothing that selects the action.\n *\n * Which mutation runs is decided by the URL alone (`/api/actions/<kind>`). The body carried a `kind`\n * field once, back when every mutation posted to one endpoint; keeping both would be two doors to\n * one room, and a body whose `kind` disagreed with its path would have to mean something.\n */\nexport interface ActionPayloadDto {\n /** Target queue name — required for all queue/job actions; omitted for instance actions. */\n queue?: string;\n /** Target instance key — required for `pauseInstance` / `resumeInstance` / `removeInstance`. */\n instanceKey?: string;\n jobId?: string;\n /**\n * Many job ids for a bulk retry / cancel / remove. The server hands the whole set to **one**\n * statement; an id it refuses (gone, or an `ACTIVE` row) is skipped rather than failing the rest,\n * and `affected` says how many landed. Capped at core's `MAX_BATCH_IDS` per request — the client\n * learns the number from `DashboardConfigDto.maxBatchIds`.\n */\n jobIds?: string[];\n scheduleId?: string;\n /** Many schedule ids for a bulk removal, in one transaction. */\n scheduleIds?: string[];\n /** For `setScheduleEnabled`: whether the schedule should be armed. */\n enabled?: boolean;\n mode?: PauseMode;\n add?: AddJobRequestDto;\n}\n\n/**\n * A mutation, as the client's `api.action` takes it: the payload plus the `kind` that names the\n * endpoint. `kind` is stripped into the URL before the request goes out and never reaches the wire.\n */\nexport interface ActionRequestDto extends ActionPayloadDto {\n kind: ActionKind;\n}\n\nexport interface ActionResultDto {\n ok: boolean;\n jobId?: string;\n scheduleId?: string;\n /** Rows the action actually changed. */\n affected?: number;\n /** Ids submitted, when the action was a batch — so the UI can say \"3 of 5\". */\n requested?: number;\n /**\n * Jobs a cancel could only *ask* to stop, because they are running in the dashboard's own process.\n * Reported apart from `affected`: nothing has been cancelled yet, and a handler that ignores\n * `job.signal` finishes normally.\n */\n signalled?: number;\n}\n","import { json } from '../../http';\nimport { requireQueue } from './validate';\nimport { ActionKind, type ActionRequestDto, type ActionResultDto } from '../../../../shared/dto';\nimport type { AddJobOptions } from '@portqueue/core';\nimport type { ActionRoute } from './types';\n\n/**\n * `add` — the one action that legitimately produces onto a queue.\n *\n * It goes through the public producer path, so every validation core already enforces applies\n * unchanged. The queue is addressed by name: the dashboard's client is headless, so a name with no\n * queue row is refused rather than invented — which surfaces here as a 400 carrying core's message.\n */\nexport const addAction: ActionRoute = {\n kind: ActionKind.ADD,\n summary: 'Enqueue a job, or create a recurring schedule',\n handle: async ({ portQueue, action }) => {\n const queue = requireQueue(action);\n if (!queue.ok) return queue.response;\n if (!action.add || typeof action.add !== 'object') {\n return json(400, { error: 'Missing add payload' });\n }\n try {\n const result = await portQueue.addJob({\n queue: queue.value,\n ...buildAddOptions(action.add),\n });\n return json(200, {\n ok: true,\n ...(result.jobId ? { jobId: result.jobId } : {}),\n ...(result.scheduleId ? { scheduleId: result.scheduleId } : {}),\n } satisfies ActionResultDto);\n } catch (err) {\n // A bad cron, both cadences at once, a paused queue, an unknown queue — all actionable, and\n // none of them a server fault.\n return json(400, { error: err instanceof Error ? err.message : 'Cannot add job' });\n }\n },\n};\n\n/**\n * Translate the form's payload into core's `AddJobOptions`.\n *\n * Only keys the client actually set are forwarded, so an omitted field inherits the queue's default\n * rather than being pinned to a value the form invented. `cron` wins over `startEverySeconds` if both\n * somehow arrive: core rejects the pair, and picking one is friendlier than a 400 for a request the\n * UI cannot produce.\n */\nfunction buildAddOptions(add: NonNullable<ActionRequestDto['add']>): AddJobOptions<unknown> {\n const opts: AddJobOptions<unknown> = { data: add.data };\n if (typeof add.priority === 'number') opts.priority = add.priority;\n if (add.idempotencyKey) opts.idempotencyKey = add.idempotencyKey;\n if (add.singletonKey) opts.singletonKey = add.singletonKey;\n if (typeof add.retryMaxAttempts === 'number') opts.retry = { maxAttempts: add.retryMaxAttempts };\n if (add.preferredInstanceKeyPattern) {\n opts.preferredInstanceKeyPattern = add.preferredInstanceKeyPattern;\n }\n const schedule: NonNullable<AddJobOptions<unknown>['schedule']> = {};\n if (add.startAfterSeconds != null) schedule.startAfterSeconds = add.startAfterSeconds;\n if (add.cron != null) schedule.cron = add.cron;\n else if (add.startEverySeconds != null) schedule.startEverySeconds = add.startEverySeconds;\n if (Object.keys(schedule).length > 0) opts.schedule = schedule;\n return opts;\n}\n","/**\n * The one path every job mutation takes.\n *\n * `retry`, `cancel` and `remove` differ only in the verb they hand to the facade, and the facade\n * turns each into a **single** statement over the whole id set — so a bulk selection costs the same\n * round trips as one row, and an id the action refuses (already gone, or an `ACTIVE` row) is simply\n * absent from `affected` rather than failing the rest.\n *\n * There is deliberately no `queue` field. A job id identifies a row on its own and the statements\n * never narrowed by queue, so requiring one was validation theatre — and it forced the client to\n * split a selection spanning queues into one request per queue, which is exactly how a bulk action\n * came to be half-applied with a success toast and an error toast side by side.\n */\nimport { json, type HandlerResult } from '../../http';\nimport { requireJobIds } from './validate';\nimport type { ActionContext } from './types';\nimport type { JobBatchAction } from '@portqueue/core';\nimport type { ActionResultDto } from '../../../../shared/dto';\n\nexport async function runJobBatch(\n { portQueue, action }: ActionContext,\n verb: JobBatchAction,\n): Promise<HandlerResult> {\n const jobIds = requireJobIds(action);\n if (!jobIds.ok) return jobIds.response;\n\n const result = await portQueue._dashboard.runJobBatch({\n jobIds: jobIds.value,\n action: verb,\n });\n const signalled = result.signalled ?? 0;\n return json(200, {\n ok: result.affected > 0 || signalled > 0,\n affected: result.affected,\n requested: result.requested,\n ...(signalled ? { signalled } : {}),\n } satisfies ActionResultDto);\n}\n","import { JobBatchAction } from '@portqueue/core';\nimport { runJobBatch } from './job-batch';\nimport { ActionKind } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `cancel` — stop the selected jobs from running, without deleting their rows.\n *\n * A job running in the client's own process is cancelled by firing its handler's `AbortSignal`; the\n * rest are marked `CANCELLED` so they never start.\n */\nexport const cancelAction: ActionRoute = {\n kind: ActionKind.CANCEL,\n summary: 'Cancel the selected jobs',\n handle: (ctx) => runJobBatch(ctx, JobBatchAction.CANCEL),\n};\n","import { PauseMode } from '@portqueue/core';\nimport { json } from '../../http';\nimport { requireQueue } from './validate';\nimport { ActionKind, type ActionResultDto } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `pause` — stop every instance from claiming this queue's jobs.\n *\n * `mode: ALL` also refuses new jobs. Anything other than `ALL` reads as `PROCESSING` rather than\n * being rejected: the stricter mode must always be asked for explicitly.\n */\nexport const pauseAction: ActionRoute = {\n kind: ActionKind.PAUSE,\n summary: 'Pause a queue (processing, or everything)',\n handle: async ({ portQueue, action }) => {\n const queue = requireQueue(action);\n if (!queue.ok) return queue.response;\n const mode = action.mode === PauseMode.ALL ? PauseMode.ALL : PauseMode.PROCESSING;\n await portQueue.pauseQueue({ queue: queue.value, mode });\n return json(200, { ok: true } satisfies ActionResultDto);\n },\n};\n","import { json } from '../../http';\nimport { requireInstanceKey } from './validate';\nimport { ActionKind, type ActionResultDto } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `pauseInstance` — stop one named process from claiming jobs.\n *\n * Persisted on the instance row, so the target picks it up on its next heartbeat rather than needing\n * to be reachable from here.\n */\nexport const pauseInstanceAction: ActionRoute = {\n kind: ActionKind.PAUSE_INSTANCE,\n summary: 'Stop one instance from claiming jobs',\n handle: async ({ portQueue, action }) => {\n const instanceKey = requireInstanceKey(action);\n if (!instanceKey.ok) return instanceKey.response;\n await portQueue.pauseInstance({ instanceKey: instanceKey.value });\n return json(200, { ok: true } satisfies ActionResultDto);\n },\n};\n","import { JobBatchAction } from '@portqueue/core';\nimport { runJobBatch } from './job-batch';\nimport { ActionKind } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `remove` — delete the selected job rows.\n *\n * An `ACTIVE` row belongs to a live handler and is never deleted; cancel it first, then remove it\n * once it has settled.\n */\nexport const removeAction: ActionRoute = {\n kind: ActionKind.REMOVE,\n summary: 'Delete the selected job rows',\n handle: (ctx) => runJobBatch(ctx, JobBatchAction.REMOVE),\n};\n","import { conflict, json } from '../../http';\nimport { requireInstanceKey } from './validate';\nimport { ActionKind, type ActionResultDto } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `removeInstance` — tidy a long-inactive process out of the instances list.\n *\n * Core refuses while the instance is still heartbeating (a live one would simply re-register on its\n * next beat), which arrives here as a 409. Job rows record the instance key as a plain string, so\n * removal never touches them.\n */\nexport const removeInstanceAction: ActionRoute = {\n kind: ActionKind.REMOVE_INSTANCE,\n summary: 'Remove a long-inactive instance row',\n handle: async ({ portQueue, action }) => {\n const instanceKey = requireInstanceKey(action);\n if (!instanceKey.ok) return instanceKey.response;\n try {\n const ok = await portQueue.removeInstance({ instanceKey: instanceKey.value });\n return json(200, { ok } satisfies ActionResultDto);\n } catch (err) {\n return conflict(err, 'Cannot remove instance');\n }\n },\n};\n","import { conflict, json } from '../../http';\nimport { requireQueue } from './validate';\nimport { ActionKind, type ActionResultDto } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `removeQueue` — delete a queue's row.\n *\n * Core refuses while any process still declares the queue, which arrives here as a 409 carrying its\n * message. Job rows link by name with no foreign key, so they are untouched either way.\n */\nexport const removeQueueAction: ActionRoute = {\n kind: ActionKind.REMOVE_QUEUE,\n summary: 'Delete a queue row',\n handle: async ({ portQueue, action }) => {\n const queue = requireQueue(action);\n if (!queue.ok) return queue.response;\n try {\n const ok = await portQueue.removeQueue({ name: queue.value });\n return json(200, { ok } satisfies ActionResultDto);\n } catch (err) {\n return conflict(err, 'Cannot remove queue');\n }\n },\n};\n","import { json } from '../../http';\nimport { requireScheduleIds } from './validate';\nimport { ActionKind, type ActionResultDto } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `removeSchedule` — stop one or many recurrences from producing new jobs.\n *\n * The client never has to know which queue a schedule belongs to: the row carries it, and the facade\n * returns it, so the whole set goes in one statement and each removal still names its queue in the\n * event it emits. Jobs the schedule already produced are untouched.\n */\nexport const removeScheduleAction: ActionRoute = {\n kind: ActionKind.REMOVE_SCHEDULE,\n summary: 'Delete one or many schedules',\n handle: async ({ portQueue, action }) => {\n const ids = requireScheduleIds(action);\n if (!ids.ok) return ids.response;\n const result = await portQueue._dashboard.removeSchedules({ scheduleIds: ids.value });\n return json(200, {\n ok: result.affected > 0,\n affected: result.affected,\n requested: result.requested,\n } satisfies ActionResultDto);\n },\n};\n","import { json } from '../../http';\nimport { requireQueue } from './validate';\nimport { ActionKind, type ActionResultDto } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/** `resume` — let instances claim this queue again, and accept new jobs. */\nexport const resumeAction: ActionRoute = {\n kind: ActionKind.RESUME,\n summary: 'Resume a paused queue',\n handle: async ({ portQueue, action }) => {\n const queue = requireQueue(action);\n if (!queue.ok) return queue.response;\n await portQueue.resumeQueue({ queue: queue.value });\n return json(200, { ok: true } satisfies ActionResultDto);\n },\n};\n","import { json } from '../../http';\nimport { requireInstanceKey } from './validate';\nimport { ActionKind, type ActionResultDto } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/** `resumeInstance` — let one named process claim jobs again. */\nexport const resumeInstanceAction: ActionRoute = {\n kind: ActionKind.RESUME_INSTANCE,\n summary: 'Let one instance claim jobs again',\n handle: async ({ portQueue, action }) => {\n const instanceKey = requireInstanceKey(action);\n if (!instanceKey.ok) return instanceKey.response;\n await portQueue.resumeInstance({ instanceKey: instanceKey.value });\n return json(200, { ok: true } satisfies ActionResultDto);\n },\n};\n","import { JobBatchAction } from '@portqueue/core';\nimport { runJobBatch } from './job-batch';\nimport { ActionKind } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `retry` — re-arm the selected jobs so they run again.\n *\n * A job that is still `ACTIVE` is left alone: clearing a running job's lock would let a second worker\n * claim it, so the same job would run twice at once. Those ids just don't count toward `affected`.\n */\nexport const retryAction: ActionRoute = {\n kind: ActionKind.RETRY,\n summary: 'Re-arm the selected jobs',\n handle: (ctx) => runJobBatch(ctx, JobBatchAction.RETRY),\n};\n","import { json } from '../../http';\nimport { requireScheduleId } from './validate';\nimport { ActionKind, type ActionResultDto } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\n/**\n * `setScheduleEnabled` — arm or disarm a schedule without deleting it.\n *\n * `enabled` must be sent explicitly. Treating a missing flag as a toggle would make the result depend\n * on state the client may not have refreshed, so two clicks could land as one no-op.\n */\nexport const setScheduleEnabledAction: ActionRoute = {\n kind: ActionKind.SET_SCHEDULE_ENABLED,\n summary: 'Arm or disarm a schedule',\n handle: async ({ portQueue, action }) => {\n const scheduleId = requireScheduleId(action);\n if (!scheduleId.ok) return scheduleId.response;\n if (typeof action.enabled !== 'boolean') return json(400, { error: 'Missing enabled' });\n const ok = await portQueue._dashboard.setScheduleEnabled({\n scheduleId: scheduleId.value,\n enabled: action.enabled,\n });\n return json(200, { ok } satisfies ActionResultDto);\n },\n};\n","/**\n * The action registry. One entry per mutation, each defined in its own file.\n *\n * Dispatch is a `Map` lookup on {@link ActionKind}, so an unknown kind is a miss rather than a\n * fall-through, and adding an action is adding a file plus one line here. Same shape as the CLI's\n * command registry, for the same reason: the list *is* the documentation of what the API can do.\n */\nimport { addAction } from './add';\nimport { cancelAction } from './cancel';\nimport { pauseAction } from './pause';\nimport { pauseInstanceAction } from './pause-instance';\nimport { removeAction } from './remove';\nimport { removeInstanceAction } from './remove-instance';\nimport { removeQueueAction } from './remove-queue';\nimport { removeScheduleAction } from './remove-schedule';\nimport { resumeAction } from './resume';\nimport { resumeInstanceAction } from './resume-instance';\nimport { retryAction } from './retry';\nimport { setScheduleEnabledAction } from './set-schedule-enabled';\nimport type { ActionKind } from '../../../../shared/dto';\nimport type { ActionRoute } from './types';\n\nexport const ACTIONS: readonly ActionRoute[] = [\n // Job-scoped (one id or many — the same single-statement batch either way)\n retryAction,\n cancelAction,\n removeAction,\n addAction,\n // Queue-scoped\n pauseAction,\n resumeAction,\n removeQueueAction,\n // Schedule-scoped (they resolve their own queue from the id)\n removeScheduleAction,\n setScheduleEnabledAction,\n // Instance-scoped (queue-less)\n pauseInstanceAction,\n resumeInstanceAction,\n removeInstanceAction,\n];\n\nexport const ACTIONS_BY_KIND: ReadonlyMap<ActionKind, ActionRoute> = new Map(\n ACTIONS.map((action) => [action.kind, action]),\n);\n\nexport type { ActionContext, ActionRoute } from './types';\n","import { json } from '../http';\nimport type { Route } from './types';\n\n/**\n * `GET /api/config` — a liveness probe with no payload of its own.\n *\n * It exists so a client can confirm it is talking to a PortQueue dashboard at all, which is a\n * different question from whether any particular page has data. Deliberately carries no\n * configuration: anything the SPA needs to render is baked into the shell it was served.\n */\nexport const configRoute: Route = {\n method: 'GET',\n path: '/api/config',\n summary: 'Confirm the mount is a PortQueue dashboard',\n handle: async () => json(200, { ok: true }),\n};\n","/**\n * Query-string parsing shared by the read routes. Every value a client can send arrives as a\n * string, so each reader here is the one place that decides what a missing, blank or nonsense\n * value means — and the answer is always \"don't narrow\", never \"guess\".\n */\nimport {\n DASHBOARD_MAX_PAGE_LIMIT,\n DEFAULT_PAGE_LIMIT,\n JobStatus,\n type GetJobsQuery,\n type JobInstanceFilter,\n} from '@portqueue/core';\n\n/** Read a paging window, clamped to the ceiling core's dashboard facade would clamp to anyway. */\nexport function paging(params: URLSearchParams): { limit: number; offset: number } {\n const rawLimit = Number(params.get('limit'));\n const rawOffset = Number(params.get('offset'));\n return {\n limit:\n Number.isFinite(rawLimit) && rawLimit > 0\n ? Math.min(Math.trunc(rawLimit), DASHBOARD_MAX_PAGE_LIMIT)\n : DEFAULT_PAGE_LIMIT,\n offset: Number.isFinite(rawOffset) && rawOffset > 0 ? Math.trunc(rawOffset) : 0,\n };\n}\n\n/** A tri-state boolean query param: `true`/`false` narrow, anything else means \"don't filter\". */\nexport function triBool(raw: string | null): boolean | undefined {\n if (raw === 'true') return true;\n if (raw === 'false') return false;\n return undefined;\n}\n\n/** A non-empty string param, or `undefined` — so `?search=` reads as \"no search\". */\nexport function text(params: URLSearchParams, key: string): string | undefined {\n const raw = params.get(key);\n return raw ? raw : undefined;\n}\n\n/**\n * Spread a named filter into an options object only when it is set. Keeps every route's query\n * assembly to one line per filter, instead of a conditional spread per filter.\n */\nexport function when<K extends string, V>(key: K, value: V | undefined): Partial<Record<K, V>> {\n return value === undefined ? {} : ({ [key]: value } as Record<K, V>);\n}\n\n/** A comma-separated status list, ignoring anything that isn't a `JobStatus`. */\nexport function statuses(raw: string | null): JobStatus[] | undefined {\n if (!raw) return undefined;\n const valid = new Set<string>(Object.values(JobStatus));\n const out = raw\n .split(',')\n .map((s) => s.trim().toUpperCase())\n .filter((s) => valid.has(s)) as JobStatus[];\n return out.length ? out : undefined;\n}\n\n/** The job filter both `/api/jobs` and the job detail route build from a query string. */\nexport function jobsQuery(params: URLSearchParams): GetJobsQuery & JobInstanceFilter {\n return {\n ...paging(params),\n ...when('queue', text(params, 'queue')),\n ...when('statuses', statuses(params.get('statuses'))),\n ...when('scheduleId', text(params, 'scheduleId')),\n ...when('instanceKey', text(params, 'instanceKey')),\n };\n}\n","/**\n * Maps PortQueue snapshots → wire DTOs. Pure functions, fully typed;\n * the single place Dates become ISO strings for the JSON boundary.\n */\nimport { INSTANCE_REMOVAL_STALE_SECONDS, secondsToMs } from '@portqueue/core';\nimport type { JobSnapshot, InstanceInfo, QueueInfo, QueueStats, Page } from '@portqueue/core';\nimport type {\n JobDto,\n JobPageDto,\n QueueDto,\n QueuePageDto,\n ScheduleDto,\n SchedulePageDto,\n StatsDto,\n InstanceDto,\n InstancePageDto,\n CountsDto,\n} from '../../shared/dto';\n\n/** A schedule as core's dashboard facade returns it: `ScheduleInfo` plus its queue. */\nexport interface ScheduleInfo {\n scheduleId: string;\n queue: string;\n cron?: string | null;\n /** For an interval schedule: the seconds between runs. */\n everySeconds?: number | null;\n timezone?: string | null;\n nextRunAt?: Date | null;\n lastRunAt?: Date | null;\n enabled: boolean;\n idempotencyKey?: string | null;\n}\n\nfunction iso(d: Date | null | undefined): string | null | undefined {\n if (d === null) return null;\n if (d === undefined) return undefined;\n return d.toISOString();\n}\n\nfunction counts(c: QueueInfo['counts']): CountsDto {\n return { ...c } as CountsDto;\n}\n\nexport function serializeJob(job: JobSnapshot): JobDto {\n return {\n id: job.id,\n queue: job.queue,\n status: job.status,\n data: job.data,\n returnValue: job.returnValue,\n priority: job.priority,\n retryAttempt: job.retryAttempt,\n retryMaxAttempts: job.retryMaxAttempts,\n createdAt: job.createdAt.toISOString(),\n updatedAt: job.updatedAt.toISOString(),\n startAfter: job.startAfter.toISOString(),\n startedAt: iso(job.startedAt),\n completedAt: iso(job.completedAt),\n failedAt: iso(job.failedAt),\n cancelledAt: iso(job.cancelledAt),\n expiredAt: iso(job.expiredAt),\n retriedAt: iso(job.retriedAt),\n stalledAt: iso(job.stalledAt),\n lockedUntil: iso(job.lockedUntil),\n preferredInstanceKeyPattern: job.preferredInstanceKeyPattern,\n processedOnInstanceKey: job.processedOnInstanceKey,\n failureMessage: job.failureMessage,\n idempotencyKey: job.idempotencyKey,\n scheduleId: job.scheduleId,\n stalled: job.stalled,\n };\n}\n\nexport function serializeQueue(q: QueueInfo): QueueDto {\n return {\n name: q.name,\n processingPaused: q.processingPaused,\n acceptingPaused: q.acceptingPaused,\n counts: counts(q.counts),\n };\n}\n\nexport function serializeQueuePage(page: Page<QueueInfo>): QueuePageDto {\n return { items: page.items.map(serializeQueue), total: page.total };\n}\n\nexport function serializeStats(s: QueueStats): StatsDto {\n return {\n ...(s.queue !== undefined ? { queue: s.queue } : {}),\n counts: counts(s.counts),\n };\n}\n\nexport function serializeJobPage(page: Page<JobSnapshot>): JobPageDto {\n return {\n items: page.items.map(serializeJob),\n total: page.total,\n };\n}\n\nexport function serializeSchedule(s: ScheduleInfo): ScheduleDto {\n return {\n scheduleId: s.scheduleId,\n queue: s.queue,\n cron: s.cron,\n everySeconds: s.everySeconds,\n timezone: s.timezone,\n nextRunAt: iso(s.nextRunAt),\n lastRunAt: iso(s.lastRunAt),\n enabled: s.enabled,\n idempotencyKey: s.idempotencyKey,\n };\n}\n\nexport function serializeSchedulePage(page: Page<ScheduleInfo>): SchedulePageDto {\n return { items: page.items.map(serializeSchedule), total: page.total };\n}\n\n/** Serialize an instance overview row. */\nexport function serializeInstance(i: InstanceInfo): InstanceDto {\n return {\n instanceKey: i.instanceKey,\n processingPaused: i.processingPaused,\n alive: i.alive,\n createdAt: i.createdAt.toISOString(),\n updatedAt: i.updatedAt.toISOString(),\n lastSeenAt: i.lastSeenAt.toISOString(),\n removableAfter: new Date(\n i.lastSeenAt.getTime() +\n secondsToMs(INSTANCE_REMOVAL_STALE_SECONDS, 'instance removal staleness window'),\n ).toISOString(),\n cpuPercent: i.cpuPercent,\n memoryPercent: i.memoryPercent,\n counts: counts(i.counts),\n };\n}\n\nexport function serializeInstancePage(page: Page<InstanceInfo>): InstancePageDto {\n return { items: page.items.map(serializeInstance), total: page.total };\n}\n","import { json } from '../http';\nimport { paging, text, triBool, when } from '../params';\nimport { serializeInstance, serializeInstancePage } from '../serialize';\nimport type { Route } from './types';\n\n/** `GET /api/instances` — a page of instances with liveness and per-instance job attribution. */\nexport const instancesRoute: Route = {\n method: 'GET',\n path: '/api/instances',\n summary: 'List instances with liveness and job attribution',\n handle: async ({ portQueue, query }) => {\n const page = await portQueue._dashboard.getInstances({\n ...paging(query),\n ...when('search', text(query, 'search')),\n ...when('processingPaused', triBool(query.get('processingPaused'))),\n ...when('alive', triBool(query.get('alive'))),\n });\n return json(200, serializeInstancePage(page));\n },\n};\n\n/** `GET /api/instances/:instanceKey` — the instance detail page's header. */\nexport const instanceRoute: Route = {\n method: 'GET',\n path: /^\\/api\\/instances\\/([^/]+)$/,\n summary: 'One instance by key',\n handle: async ({ portQueue, params }) => {\n const instance = await portQueue._dashboard.getInstance({ instanceKey: params[0]! });\n if (!instance) return json(404, { error: 'Instance not found' });\n return json(200, serializeInstance(instance));\n },\n};\n","import { json } from '../http';\nimport { jobsQuery, text, when } from '../params';\nimport { serializeJob, serializeJobPage } from '../serialize';\nimport type { Route } from './types';\n\n/**\n * `GET /api/jobs` — a page of jobs, newest first, optionally narrowed by a free-text search.\n *\n * The search is a `LIKE` in the database, so it is a paged query like any other read rather than a\n * scan of the table through this process.\n */\nexport const jobsRoute: Route = {\n method: 'GET',\n path: '/api/jobs',\n summary: 'List jobs, with filters and free-text search',\n handle: async ({ portQueue, query }) => {\n const page = await portQueue._dashboard.getJobs({\n ...jobsQuery(query),\n ...when('search', text(query, 'search')),\n });\n return json(200, serializeJobPage(page));\n },\n};\n\n/**\n * `GET /api/jobs/:jobId` — one job by id, from the public API.\n *\n * A job id already identifies exactly one row, so this needs no queue and takes none.\n */\nexport const jobRoute: Route = {\n method: 'GET',\n path: /^\\/api\\/jobs\\/([^/]+)$/,\n summary: 'One job by id',\n handle: async ({ portQueue, params }) => {\n const job = await portQueue.getJob({ jobId: params[0]! });\n if (!job) return json(404, { error: 'Job not found' });\n return json(200, serializeJob(job));\n },\n};\n","import { json } from '../http';\nimport { paging, text, triBool, when } from '../params';\nimport { serializeQueuePage } from '../serialize';\nimport type { Route } from './types';\n\n/**\n * `GET /api/queues` — a page of queues with their per-status counts.\n *\n * Filtering and paging both happen in the database; the counts arrive from one grouped query over\n * this page's names. There is no `inUse` filter: that flag means \"declared in the process that\n * produced this row\", and the dashboard runs on its own client, so it cannot know.\n */\nexport const queuesRoute: Route = {\n method: 'GET',\n path: '/api/queues',\n summary: 'List queues with their per-status counts',\n handle: async ({ portQueue, query }) => {\n const page = await portQueue._dashboard.getQueues({\n ...paging(query),\n ...when('search', text(query, 'search')),\n ...when('processingPaused', triBool(query.get('processingPaused'))),\n });\n return json(200, serializeQueuePage(page));\n },\n};\n","import { json } from '../http';\nimport { paging, text, triBool, when } from '../params';\nimport { serializeSchedule, serializeSchedulePage } from '../serialize';\nimport type { Route } from './types';\n\n/** `GET /api/schedules` — a page of schedules, across every queue unless `queue` narrows it. */\nexport const schedulesRoute: Route = {\n method: 'GET',\n path: '/api/schedules',\n summary: 'List recurring schedules',\n handle: async ({ portQueue, query }) => {\n const page = await portQueue._dashboard.getSchedules({\n ...paging(query),\n ...when('queue', text(query, 'queue')),\n ...when('search', text(query, 'search')),\n ...when('enabled', triBool(query.get('enabled'))),\n });\n return json(200, serializeSchedulePage(page));\n },\n};\n\n/** `GET /api/schedules/:scheduleId` — the schedule detail page's header. */\nexport const scheduleRoute: Route = {\n method: 'GET',\n path: /^\\/api\\/schedules\\/([^/]+)$/,\n summary: 'One schedule by id',\n handle: async ({ portQueue, params }) => {\n const schedule = await portQueue._dashboard.getSchedule({ scheduleId: params[0]! });\n if (!schedule) return json(404, { error: 'Schedule not found' });\n return json(200, serializeSchedule(schedule));\n },\n};\n","import { json } from '../http';\nimport { text, when } from '../params';\nimport { serializeStats } from '../serialize';\nimport type { Route } from './types';\n\n/**\n * `GET /api/stats` — per-status counts for one queue, or client-wide when `queue` is omitted.\n *\n * Counts only. The dashboard renders activity cards and nothing else, so there is deliberately no\n * throughput or failure-rate derivation here to disagree with the numbers on the tables.\n */\nexport const statsRoute: Route = {\n method: 'GET',\n path: '/api/stats',\n summary: 'Per-status counts, for one queue or the whole client',\n handle: async ({ portQueue, query }) => {\n const stats = await portQueue._dashboard.getStats({ ...when('queue', text(query, 'queue')) });\n return json(200, serializeStats(stats));\n },\n};\n","/** Constants shared between the dashboard client and server (avoid literal drift). */\n\n/**\n * The dashboard's name, in the browser tab and in the fallback shell. Fixed, not a host option:\n * the product has one name, and a host-set title only made the tab disagree with the header, the\n * docs and every screenshot.\n */\nexport const DASHBOARD_TITLE = 'PortQueue Dashboard';\n\n/**\n * Header + marker the client sends on every request, and the server **requires** on every mutation.\n *\n * This is the mount's CSRF defence, and it works because of what a browser will not do: a custom\n * request header cannot be set on a cross-origin request unless a preflight allows it, and the\n * dashboard answers no CORS preflight at all. So a form post or `fetch` from another page reaches\n * the mount without the marker and is refused — which matters because the mount is usually behind\n * cookie or basic auth, and a browser replays both on a cross-site request.\n *\n * It costs the host nothing: there is no option to set and nothing to configure.\n */\nexport const REQUESTED_WITH_HEADER = 'x-requested-with';\nexport const REQUESTED_WITH_MARKER = 'portqueue-dashboard';\n\n/**\n * The largest request body the mount reads, in bytes.\n *\n * Here rather than in the reader that enforces it, because it is a property of the API the client\n * talks to: the only mutation that carries a payload of any size is `add`, whose `data` this bounds.\n */\nexport const MAX_BODY_BYTES = 1024 * 1024;\n","/**\n * The route registry and the router built from it.\n *\n * Reads are dispatched by path against {@link ROUTES}. Mutations are too: each one owns\n * `POST /api/actions/<kind>` and is dispatched against `ACTIONS_BY_KIND` by that path segment, so a\n * request names exactly one operation. Both registries are plain lists of self-describing objects,\n * so the whole API surface is readable in one place and adding to it never means extending a\n * conditional chain.\n *\n * The one guard that lives here is the CSRF check: a mutation must carry\n * {@link REQUESTED_WITH_HEADER}. See that constant for why a custom header is the defence, and\n * {@link assertSameOrigin} for what it refuses.\n *\n * There is otherwise **no authentication and no read-only mode anywhere in here**: protecting the\n * mount belongs to whatever middleware the host puts in front of it (see `docs/docs/dashboard.mdx`).\n * Anyone who can reach these routes can perform every action.\n */\nimport { json, queryOf, relativePath, type HandlerInput, type HandlerResult } from '../http';\nimport { ACTIONS, ACTIONS_BY_KIND } from './actions';\nimport { configRoute } from './config';\nimport { instanceRoute, instancesRoute } from './instances';\nimport { jobRoute, jobsRoute } from './jobs';\nimport { queuesRoute } from './queues';\nimport { scheduleRoute, schedulesRoute } from './schedules';\nimport { statsRoute } from './stats';\nimport { REQUESTED_WITH_HEADER, REQUESTED_WITH_MARKER } from '../../../shared/constants';\nimport type { PortQueue } from '@portqueue/core';\nimport type { DashboardClient } from '../../client';\nimport type { ActionKind, ActionPayloadDto } from '../../../shared/dto';\nimport type { Route } from './types';\n\nexport type { HandlerInput, HandlerResult } from '../http';\nexport type { Route, RouteContext } from './types';\nexport type { ActionContext, ActionRoute } from './actions';\nexport { ACTIONS, ACTIONS_BY_KIND };\n\n/** The prefix every mutation posts under; the segment that follows names the action. */\nexport const ACTIONS_PATH_PREFIX = '/api/actions/';\n\n/**\n * Every read route. Literal paths are matched before patterns, so `/api/jobs` can sit beside\n * `/api/jobs/:id` without their order here mattering.\n */\nexport const ROUTES: readonly Route[] = [\n configRoute,\n queuesRoute,\n jobsRoute,\n jobRoute,\n schedulesRoute,\n scheduleRoute,\n instancesRoute,\n instanceRoute,\n statsRoute,\n];\n\nexport interface RouterOptions {\n /** Resolves (and, on the first call, connects) the dashboard's own headless client. */\n client: DashboardClient;\n basePath: string;\n}\n\n/**\n * Create the router. Returns the pure JSON handler plus the path predicate the adapters use to\n * decide between an API call and a static asset.\n */\nexport function createRouter(options: RouterOptions): {\n handle: (input: HandlerInput) => Promise<HandlerResult>;\n isApiPath: (url: string) => boolean;\n} {\n const { client, basePath } = options;\n\n const isApiPath = (url: string): boolean => relativePath(url, basePath).startsWith('/api/');\n\n async function handle(input: HandlerInput): Promise<HandlerResult> {\n const path = relativePath(input.url, basePath);\n const method = input.method.toUpperCase();\n\n // Checked before anything reaches the database, and before the body is even parsed.\n const rejection = assertSameOrigin(method, input.headers);\n if (rejection) return rejection;\n\n // Resolved per request: the first one connects, and a failure here is a 503 the client can retry\n // rather than a mount-time crash the host can do nothing about.\n let portQueue: PortQueue;\n try {\n portQueue = await client.get();\n } catch (err) {\n return json(503, {\n error: err instanceof Error ? err.message : 'Cannot reach the PortQueue database',\n });\n }\n\n if (method === 'POST' && path.startsWith(ACTIONS_PATH_PREFIX)) {\n return handleAction(portQueue, path.slice(ACTIONS_PATH_PREFIX.length), input.body);\n }\n if (method === 'GET') return handleRead(portQueue, path, queryOf(input.url));\n return json(404, { error: 'Not found' });\n }\n\n return { handle, isApiPath };\n}\n\n/**\n * Refuse a mutation that did not come from the dashboard's own client.\n *\n * A `GET` changes nothing and is left alone — reading the JSON API with `curl` should not need a\n * header. Everything else must carry the marker: a cross-origin page cannot set a custom header\n * without a preflight this mount never answers, so this is what stops another site purging a queue\n * with the operator's own cookies (or replayed basic credentials).\n */\nexport function assertSameOrigin(\n method: string,\n headers: Record<string, string | string[] | undefined>,\n): HandlerResult | null {\n if (method === 'GET' || method === 'HEAD') return null;\n const raw = headers[REQUESTED_WITH_HEADER];\n const value = Array.isArray(raw) ? raw[0] : raw;\n if (value === REQUESTED_WITH_MARKER) return null;\n return json(403, {\n error: `Missing or invalid ${REQUESTED_WITH_HEADER} header — a mutation must come from the dashboard client.`,\n });\n}\n\n/** Dispatch a read to the first route whose `path` matches. */\nasync function handleRead(\n portQueue: PortQueue,\n path: string,\n query: URLSearchParams,\n): Promise<HandlerResult> {\n for (const route of ROUTES) {\n const params = match(route, path);\n if (params) return route.handle({ portQueue, query, params });\n }\n return json(404, { error: 'Not found' });\n}\n\n/** The captured, decoded segments when `route` matches `path`, or `null` when it doesn't. */\nfunction match(route: Route, path: string): string[] | null {\n if (typeof route.path === 'string') return route.path === path ? [] : null;\n const found = route.path.exec(path);\n if (!found) return null;\n return found.slice(1).map((segment) => decodeURIComponent(segment));\n}\n\n/** Parse a mutation body and hand it to the action the URL segment names. */\nasync function handleAction(\n portQueue: PortQueue,\n segment: string,\n body: string | undefined,\n): Promise<HandlerResult> {\n const route = ACTIONS_BY_KIND.get(decodeURIComponent(segment) as ActionKind);\n if (!route) return json(404, { error: 'Unknown action' });\n let action: ActionPayloadDto;\n try {\n // An action with no fields of its own still posts `{}`, so an empty body is a malformed request\n // rather than a shorthand for \"no fields\".\n action = JSON.parse(body ?? '') as ActionPayloadDto;\n } catch {\n return json(400, { error: 'Invalid JSON body' });\n }\n if (!action || typeof action !== 'object') return json(400, { error: 'Invalid JSON body' });\n return route.handle({ portQueue, action });\n}\n","/**\n * Serves the built client bundle + index.html from the packaged `dist/client` directory. If that\n * directory is absent (the client hasn't been built), serves a minimal inline HTML shell so the\n * mount still responds and says why. No dependency beyond Node fs.\n */\nimport { randomBytes } from 'node:crypto';\nimport { readFile, stat } from 'node:fs/promises';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, extname, isAbsolute, join, relative, resolve } from 'node:path';\nimport { DASHBOARD_TITLE } from '../shared/constants';\nimport type { DashboardConfigDto } from '../shared/dto';\n\nconst HTML_MIME = 'text/html; charset=utf-8';\n\nconst MIME: Record<string, string> = {\n '.html': HTML_MIME,\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.map': 'application/json; charset=utf-8',\n};\n\n/**\n * Vite emits content-hashed asset filenames, so a given URL's bytes never change — those can be\n * cached indefinitely. HTML carries the injected runtime config and must always be revalidated.\n */\nconst IMMUTABLE_CACHE = 'public, max-age=31536000, immutable';\nconst NO_CACHE = 'no-cache';\n\nexport interface AssetResult {\n status: number;\n body: Buffer | string;\n contentType: string;\n /** Extra response headers — caching and, for HTML, the CSP naming the inline script's nonce. */\n headers?: Record<string, string>;\n}\n\n/** Resolve the packaged client bundle directory relative to this module. */\nfunction clientDistDir(): string {\n const here = dirname(fileURLToPath(import.meta.url));\n // At runtime the server lives at dist/index.{mjs,cjs}; the client bundle sits in dist/client.\n return resolve(here, 'client');\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n const s = await stat(path);\n return s.isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * True when a built client bundle is present in the package.\n *\n * Resolved **once** and memoized: the bundle ships inside the package and cannot appear or disappear\n * while the process runs, so asking the filesystem on every asset request was one `stat` per request\n * for an answer that never changes. `createEngine` awaits it at mount to warn about a missing\n * bundle, which is also what primes it.\n */\nexport function hasBuiltClient(): Promise<boolean> {\n builtClient ??= exists(join(clientDistDir(), 'index.html'));\n return builtClient;\n}\n\n/** The memoized answer. A promise, so concurrent first requests share one `stat`. */\nlet builtClient: Promise<boolean> | null = null;\n\n/** Clear the memo. Test-only: a suite that creates and removes a fake bundle needs to re-ask. */\nexport function resetBuiltClientCache(): void {\n builtClient = null;\n}\n\n/**\n * Resolve a request path inside the bundle directory, or null if it escapes.\n *\n * `resolve` + `relative`, not a string prefix test: a prefix check accepts a sibling directory\n * whose name merely starts with the root's (`…/client-evil` passes `startsWith('…/client')`), and\n * it mishandles an absolute request path. Here anything resolving outside the root — a `..`\n * segment, an absolute path — comes back as a relative path that starts with `..` or is itself\n * absolute, and is rejected.\n */\nexport function safeResolve(root: string, relPath: string): string | null {\n const target = resolve(root, `.${relPath.startsWith('/') ? relPath : `/${relPath}`}`);\n const rel = relative(root, target);\n if (rel === '') return target; // the root itself\n if (rel.startsWith('..') || isAbsolute(rel)) return null;\n return target;\n}\n\n/**\n * Serve a static asset by relative path (already stripped of basePath). SPA fallback: unknown\n * non-file paths resolve to index.html so client-side routing works.\n */\nexport async function serveAsset(\n relPath: string,\n config: DashboardConfigDto,\n): Promise<AssetResult> {\n const root = clientDistDir();\n const built = await hasBuiltClient();\n\n if (!built) {\n // No bundle: serve the inline shell for any navigation, 404 for asset-looking requests.\n if (extname(relPath) && relPath !== '/index.html') {\n return { status: 404, body: 'Not found', contentType: 'text/plain; charset=utf-8' };\n }\n return htmlResult(inlineShell(config), config);\n }\n\n const requested = relPath === '/' ? '/index.html' : relPath;\n const target = safeResolve(root, requested);\n if (target === null) {\n return { status: 403, body: 'Forbidden', contentType: 'text/plain; charset=utf-8' };\n }\n\n if (await exists(target)) {\n const ext = extname(target).toLowerCase();\n const body = await readFile(target);\n if (ext === '.html') {\n return htmlResult(rewriteAssetUrls(body.toString('utf8'), config.basePath), config);\n }\n return {\n status: 200,\n body,\n contentType: MIME[ext] ?? 'application/octet-stream',\n // Content-hashed filenames make this safe: the browser never re-requests a cached bundle.\n headers: { 'cache-control': IMMUTABLE_CACHE },\n };\n }\n\n // SPA fallback: any non-asset path → index.html with injected config.\n if (!extname(requested)) {\n const indexPath = join(root, 'index.html');\n if (await exists(indexPath)) {\n const raw = (await readFile(indexPath)).toString('utf8');\n return htmlResult(rewriteAssetUrls(raw, config.basePath), config);\n }\n }\n return { status: 404, body: 'Not found', contentType: 'text/plain; charset=utf-8' };\n}\n\n/**\n * Finish an HTML response: inject the runtime config under a fresh nonce, and emit the CSP that\n * authorizes exactly that one inline script. The nonce is per-response, so an injected `<script>`\n * without it is refused by the browser even if it does reach the page.\n */\nfunction htmlResult(html: string, config: DashboardConfigDto): AssetResult {\n const nonce = randomBytes(16).toString('base64');\n return {\n status: 200,\n body: injectConfig(html, config, nonce),\n contentType: HTML_MIME,\n headers: {\n 'cache-control': NO_CACHE,\n 'content-security-policy': contentSecurityPolicy(nonce),\n },\n };\n}\n\n/**\n * The dashboard's CSP. The SPA has exactly one inline script (the config blob), so it carries a\n * nonce and every other inline script is refused. `style-src` must allow `unsafe-inline`: the\n * SPA's own styles ship as a stylesheet, but `@ant-design/icons` injects its base icon rules into a\n * `<style>` element at runtime, and the shell carries a small inline `<style>` of its own.\n */\nfunction contentSecurityPolicy(nonce: string): string {\n return [\n \"default-src 'self'\",\n `script-src 'self' 'nonce-${nonce}'`,\n \"style-src 'self' 'unsafe-inline'\",\n \"img-src 'self' data:\",\n \"font-src 'self' data:\",\n \"connect-src 'self'\",\n \"frame-ancestors 'none'\",\n \"base-uri 'self'\",\n \"form-action 'self'\",\n \"object-src 'none'\",\n ].join('; ');\n}\n\n/**\n * The client is built with Vite `base: './'`, so `index.html` references its bundle relatively\n * (`./assets/app.js`). The browser would resolve that against the *current* URL, which breaks\n * for every mount-relative navigation: `/portqueue` → `/assets/app.js` (outside the mount) and\n * `/portqueue/jobs/1` → `/portqueue/jobs/assets/app.js`. Rewriting the references to absolute\n * paths under the mount makes them resolve identically from any URL, with or without a trailing\n * slash. A root mount (`/`) needs no prefix — `//assets/...` would read as protocol-relative.\n */\nexport function rewriteAssetUrls(html: string, basePath: string): string {\n const prefix = basePath === '/' ? '' : basePath;\n return html.replace(\n /(\\b(?:src|href)=\")\\.\\/([^\"]*)\"/g,\n (_match, attr: string, path: string) => `${attr}${prefix}/${path}\"`,\n );\n}\n\n/** Inject the runtime config as a global the SPA reads on boot. */\nfunction injectConfig(html: string, config: DashboardConfigDto, nonce: string): string {\n const tag = `<script nonce=\"${nonce}\">window.__PORTQUEUE_DASHBOARD__=${serializeConfig(config)};</script>`;\n if (html.includes('</head>')) return html.replace('</head>', `${tag}</head>`);\n return `${tag}${html}`;\n}\n\n/**\n * JSON for embedding inside a `<script>` element. `JSON.stringify` does not escape `<`, so a\n * developer-supplied `basePath` of `</script>…` would otherwise close the element early and let\n * what follows be parsed as markup. Escaping `<` and `>` — plus U+2028/U+2029, which are legal\n * inside a JSON string but count as line terminators to a JS parser — makes the value inert while\n * keeping it valid JSON.\n */\nexport function serializeConfig(config: DashboardConfigDto): string {\n return JSON.stringify(config)\n .replace(/</g, '\\\\u003c')\n .replace(/>/g, '\\\\u003e')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029');\n}\n\n/** A minimal, dependency-free HTML shell used when no built client is packaged. */\nfunction inlineShell(config: DashboardConfigDto): string {\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<title>${DASHBOARD_TITLE}</title>\n<style>\n :root { color-scheme: light dark; }\n body { margin:0; font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", system-ui, sans-serif; background:#f7f8fa; color:#1a1d23; }\n @media (prefers-color-scheme: dark){ body{ background:#0b0e14; color:#e6e8ec; } .card{ background:#131722 !important; } }\n .wrap{ max-width:720px; margin:12vh auto; padding:24px; }\n .card{ background:#fff; border-radius:16px; padding:32px; box-shadow:0 12px 32px rgba(16,24,40,0.12),0 6px 16px rgba(16,24,40,0.08); }\n code{ font-family: ui-monospace, \"SF Mono\", Menlo, monospace; background:rgba(127,127,127,0.15); padding:2px 6px; border-radius:6px; }\n h1{ font-size:22px; margin:0 0 8px; }\n</style>\n</head>\n<body>\n<div class=\"wrap\"><div class=\"card\">\n<h1>${DASHBOARD_TITLE}</h1>\n<p>The PortQueue dashboard server is mounted at <code>${escapeHtml(config.basePath)}</code>, but the client bundle has not been built into this package yet.</p>\n<p>Build it with <code>npm run build:client</code> in <code>@portqueue/dashboard</code>, then reload. The JSON API is already live at <code>${escapeHtml(config.basePath)}/api</code>.</p>\n</div></div>\n</body>\n</html>`;\n}\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\n}\n","/** Raw-Node request helpers shared by the engine and adapters. */\nimport type { IncomingMessage } from 'node:http';\nimport { MAX_BODY_BYTES } from '../shared/constants';\n\n/**\n * Read a request body to a string, rejecting anything over {@link MAX_BODY_BYTES}.\n *\n * On overflow it stops accumulating and **keeps reading** rather than destroying the socket. The\n * caller answers 413, and a client can only read that answer if the connection is still there —\n * `req.destroy()` mid-stream closed a keep-alive connection instead, so the client saw a transport\n * error where a clear status was available. The remaining bytes are discarded as they arrive, so\n * nothing accumulates in memory either way.\n */\nexport function readBody(req: IncomingMessage): Promise<string> {\n // A body parser mounted above the dashboard (`express.json()` is in most host apps) has already\n // drained the stream, so `end` has fired and will not fire again — waiting for it hung the request\n // forever. Recover what that parser left on `req.body` instead.\n if (req.readableEnded) return alreadyRead(req);\n return new Promise((resolveBody, reject) => {\n const chunks: Buffer[] = [];\n let size = 0;\n let tooLarge = false;\n req.on('data', (chunk: Buffer) => {\n size += chunk.length;\n if (tooLarge) return;\n if (size > MAX_BODY_BYTES) {\n tooLarge = true;\n chunks.length = 0;\n return;\n }\n chunks.push(chunk);\n });\n req.on('end', () => {\n if (tooLarge) {\n reject(new BodyTooLargeError());\n return;\n }\n resolveBody(Buffer.concat(chunks).toString('utf8'));\n });\n req.on('error', reject);\n });\n}\n\n/**\n * The body a host's parser already consumed, back as the string the router expects, under the same\n * cap. A parsed object is re-serialized — it came from JSON, so this round-trips — and nothing at all\n * reads as an empty body, which the router answers with a 400 rather than a hang.\n */\nfunction alreadyRead(req: IncomingMessage): Promise<string> {\n const parsed = (req as IncomingMessage & { body?: unknown }).body;\n let text: string;\n if (parsed === undefined || parsed === null) text = '';\n else if (typeof parsed === 'string') text = parsed;\n else if (Buffer.isBuffer(parsed)) text = parsed.toString('utf8');\n else text = JSON.stringify(parsed);\n if (Buffer.byteLength(text) > MAX_BODY_BYTES) return Promise.reject(new BodyTooLargeError());\n return Promise.resolve(text);\n}\n\n/** Why {@link readBody} rejected: the body passed the cap, and the answer is a 413. */\nexport class BodyTooLargeError extends Error {\n constructor() {\n super(`Request body exceeds the ${MAX_BODY_BYTES}-byte limit`);\n this.name = 'BodyTooLargeError';\n }\n}\n\nexport function toHeaders(req: IncomingMessage): Record<string, string | string[] | undefined> {\n return req.headers as Record<string, string | string[] | undefined>;\n}\n\n/** Normalize a mount path: ensure a leading slash, drop a trailing one. */\nexport function normalizeBase(basePath: string): string {\n let b = basePath.trim();\n if (!b.startsWith('/')) b = `/${b}`;\n if (b.length > 1 && b.endsWith('/')) b = b.slice(0, -1);\n return b;\n}\n","/**\n * The dashboard's own PortQueue.\n *\n * `createDashboard` takes a **driver**, not a running `PortQueue`. That is the whole point: the\n * dashboard is an operations console for a deployment, and in almost every real deployment it is a\n * different process from the workers — so being handed the app's client only ever worked in the one\n * case where they happened to share a process, and it quietly coupled the two.\n *\n * The client it builds is **headless** (`_headless: true`), which is what keeps an observer from\n * behaving like a participant:\n *\n * - it declares no queues and writes no queue rows, so browsing never creates anything;\n * - it registers no instance row, so the dashboard never shows up in its own instances list;\n * - it consumes no queue and runs no scheduler, retention sweep or health monitor — the app's processes own that\n * work, and a dashboard quietly firing the cluster's schedules would be a second producer nobody\n * asked for;\n * - it never migrates: pointing the dashboard at a database must not change its schema.\n *\n * `init()` is deferred to the first request and memoized, because `createDashboard` is synchronous\n * and a mount must not open a connection the host may never use.\n */\nimport { PortQueue } from '@portqueue/core';\nimport type { Driver, Logger } from '@portqueue/core';\n\nexport interface DashboardClient {\n /** The initialized client. Connects on the first call; every later call reuses it. */\n get(): Promise<PortQueue>;\n /** Disconnect, if a request ever caused a connection. Safe to call more than once. */\n close(): Promise<void>;\n}\n\nexport function createDashboardClient(options: {\n driver: Driver;\n logger?: Pick<Logger, 'warn'>;\n}): DashboardClient {\n let started: Promise<PortQueue> | null = null;\n let instance: PortQueue | null = null;\n\n return {\n get(): Promise<PortQueue> {\n if (!started) {\n started = (async () => {\n const pq = new PortQueue({ driver: options.driver, _headless: true });\n await pq.init();\n instance = pq;\n return pq;\n })().catch((err: unknown) => {\n // Don't cache a failed connection — the next request must be able to retry.\n started = null;\n throw err;\n });\n }\n return started;\n },\n async close(): Promise<void> {\n const pq = instance;\n started = null;\n instance = null;\n if (pq) await pq.shutdown();\n },\n };\n}\n","/**\n * The framework-agnostic serve core. Holds the router, config and path matching, and exposes\n * `serve`/`serveSafely` that every adapter drives with a raw Node `(req, res)` pair.\n *\n * It owns the dashboard's own headless client (see `client.ts`), built from the driver it was given.\n * Nothing connects at mount: the first API request opens the connection, and `close()` releases it.\n *\n * The dashboard has no authentication of its own — see `api/routes.ts` and the dashboard docs.\n */\nimport { MAX_BATCH_IDS } from '@portqueue/core';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { createRouter, type HandlerInput } from './api/routes';\nimport { hasBuiltClient, serveAsset } from './assets';\nimport { normalizeBase, readBody, toHeaders } from './request';\nimport { createDashboardClient, type DashboardClient } from './client';\nimport type { DashboardOptions } from './types';\nimport type { DashboardConfigDto } from '../shared/dto';\n\n/**\n * Headers on every response the dashboard writes. `nosniff` stops a browser second-guessing a\n * declared content type; the rest keep the UI out of frames and stop the referrer leaking a job\n * id (which URLs carry) to any external link a user follows.\n */\nconst SECURITY_HEADERS: Record<string, string> = {\n 'x-content-type-options': 'nosniff',\n 'x-frame-options': 'DENY',\n 'referrer-policy': 'no-referrer',\n};\n\nexport interface DashboardEngine {\n /** The resolved, normalized mount path. */\n readonly basePath: string;\n /** True when the URL falls under our mount. */\n owns(url: string | undefined): boolean;\n /** The core async serve routine — writes directly to the raw response. */\n serve(req: IncomingMessage, res: ServerResponse): Promise<void>;\n /** `serve` wrapped so any error becomes a 500 instead of an unhandled rejection. */\n serveSafely(req: IncomingMessage, res: ServerResponse): void;\n /** Release the dashboard's own client. */\n close(): Promise<void>;\n}\n\nexport function createEngine(\n options: DashboardOptions & { client?: DashboardClient },\n): DashboardEngine {\n const basePath = normalizeBase(options.basePath ?? '/portqueue');\n const config: DashboardConfigDto = { basePath, maxBatchIds: MAX_BATCH_IDS };\n const logger = options.logger ?? console;\n // The client is injectable so a test can drive the router without a driver; production always\n // builds it from the driver the host supplied.\n const client =\n options.client ??\n createDashboardClient({ driver: options.driver, ...(options.logger ? { logger } : {}) });\n const router = createRouter({ client, basePath });\n\n // A missing bundle makes every navigation serve the \"not built\" shell with a 200, which reads\n // as a working deploy. Say so once, at mount time, rather than letting it pass silently.\n void hasBuiltClient().then((built) => {\n if (!built) {\n logger.warn(\n `[@portqueue/dashboard] No client bundle found; serving the fallback shell at ${basePath}. ` +\n 'The package was published or built without its SPA — run `npm run build` in ' +\n '@portqueue/dashboard, or reinstall the package.',\n );\n }\n });\n\n /**\n * Whether a URL falls under the mount. The query string is stripped first, so this compares paths\n * — `/portqueue` exactly, or something below it. There is no third `basePath?` case: after the\n * split, a path cannot contain a `?`. A root mount (`/`) owns everything.\n */\n function owns(url: string | undefined): boolean {\n if (!url) return false;\n const path = url.split('?')[0] ?? '';\n // A root mount owns every path; `${basePath}/` would be `//` there and match nothing but `/`.\n if (basePath === '/') return path.startsWith('/');\n return path === basePath || path.startsWith(`${basePath}/`);\n }\n\n function relPath(url: string): string {\n const path = (url.split('?')[0] ?? '').slice(basePath.length);\n return path.startsWith('/') || path === '' ? path || '/' : `/${path}`;\n }\n\n /** Handle a JSON API request. */\n async function handleApi(\n req: IncomingMessage,\n res: ServerResponse,\n method: string,\n url: string,\n ): Promise<void> {\n let body: string | undefined;\n if (method === 'POST' || method === 'PUT' || method === 'PATCH') {\n try {\n body = await readBody(req);\n } catch {\n res.writeHead(413, { ...SECURITY_HEADERS, 'content-type': 'application/json' });\n res.end(JSON.stringify({ error: 'Request body too large' }));\n return;\n }\n }\n const input: HandlerInput = { method, url, body, headers: toHeaders(req) };\n const result = await router.handle(input);\n res.writeHead(result.status, { ...SECURITY_HEADERS, ...result.headers });\n res.end(result.body);\n }\n\n /** Serve the static SPA shell / assets. */\n async function handleAsset(res: ServerResponse, url: string): Promise<void> {\n const asset = await serveAsset(relPath(url), config);\n res.writeHead(asset.status, {\n ...SECURITY_HEADERS,\n 'content-type': asset.contentType,\n ...asset.headers,\n });\n res.end(asset.body);\n }\n\n async function serve(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const url = req.url ?? '';\n const method = (req.method ?? 'GET').toUpperCase();\n if (router.isApiPath(url)) return handleApi(req, res, method, url);\n return handleAsset(res, url);\n }\n\n function serveSafely(req: IncomingMessage, res: ServerResponse): void {\n void serve(req, res).catch(() => {\n if (!res.headersSent) {\n res.writeHead(500, { ...SECURITY_HEADERS, 'content-type': 'application/json' });\n }\n res.end(JSON.stringify({ error: 'Internal dashboard error' }));\n });\n }\n\n return { basePath, owns, serve, serveSafely, close: () => client.close() };\n}\n","/**\n * Express adapter. `app.use(basePath, expressAdapter(dashboard))` or\n * `app.use(dashboard.express())`.\n */\nimport type { DashboardEngine } from '../engine';\nimport type { Dashboard, ExpressMiddleware } from '../types';\n\nexport function createExpressMiddleware(engine: DashboardEngine): ExpressMiddleware {\n return (req, res, next) => {\n // Express strips the mount path from req.url; reconstruct so our router sees basePath.\n const original = req.url ?? '';\n const originalUrl = (req as unknown as { originalUrl?: string }).originalUrl;\n if (originalUrl) req.url = originalUrl;\n if (!engine.owns(req.url)) {\n req.url = original;\n next();\n return;\n }\n engine.serveSafely(req, res);\n };\n}\n\n/** Ergonomic named-import wrapper, equivalent to `dashboard.express()`. */\nexport function expressAdapter(dashboard: Dashboard): ExpressMiddleware {\n return dashboard.express();\n}\n","/**\n * Fastify adapter. `app.register(fastifyAdapter(dashboard))` or\n * `app.register(dashboard.fastify())`.\n *\n * **The plugin opts out of Fastify's encapsulation, and it has to.** `register` normally gives a\n * plugin its own child context, and a hook added inside one only runs for routes registered in that\n * context — of which the dashboard has none, because it serves the raw request itself rather than\n * declaring Fastify routes. So the hook never fired and every dashboard URL fell through to\n * Fastify's own 404. Setting `skip-override` (what `fastify-plugin` does, without the dependency)\n * makes `addHook` apply to the instance the host registered it on.\n */\nimport type { DashboardEngine } from '../engine';\nimport type { Dashboard, FastifyPlugin } from '../types';\n\n/** Fastify's marker for \"run me on the parent instance, not a child context\". */\nconst SKIP_OVERRIDE = Symbol.for('skip-override');\n\nexport function createFastifyPlugin(engine: DashboardEngine): FastifyPlugin {\n const plugin: FastifyPlugin = (fastify, _opts, done) => {\n // `async`, so Fastify sees a promise from a two-parameter hook rather than guessing whether the\n // hook is done — a bare `undefined` return leaves the request waiting for a `done` it never gets.\n fastify.addHook('onRequest', async (request, reply) => {\n if (!engine.owns(request.raw.url)) return;\n // Fastify owns the reply until this call; without it Fastify would answer too, and the second\n // write to the same response throws.\n reply.hijack();\n engine.serveSafely(request.raw, reply.raw);\n });\n done();\n };\n (plugin as unknown as Record<symbol, boolean>)[SKIP_OVERRIDE] = true;\n return plugin;\n}\n\n/** Ergonomic named-import wrapper, equivalent to `dashboard.fastify()`. */\nexport function fastifyAdapter(dashboard: Dashboard): FastifyPlugin {\n return dashboard.fastify();\n}\n","/**\n * Koa adapter. `app.use(koaAdapter(dashboard))` or\n * `app.use(dashboard.koa())`.\n */\nimport type { DashboardEngine } from '../engine';\nimport type { Dashboard, KoaMiddleware } from '../types';\n\nexport function createKoaMiddleware(engine: DashboardEngine): KoaMiddleware {\n return async (ctx, next) => {\n if (!engine.owns(ctx.req.url)) {\n await next();\n return;\n }\n ctx.respond = false; // we write to the raw response directly\n // A body parser above us (`koa-bodyparser`, `@koa/bodyparser`) drained the raw stream and left\n // the result on `ctx.request`; hand it to the reader, which looks for it on the raw request.\n const parsed = (ctx as { request?: { body?: unknown } }).request?.body;\n const raw = ctx.req as typeof ctx.req & { body?: unknown };\n if (parsed !== undefined && raw.body === undefined) raw.body = parsed;\n await engine.serve(ctx.req, ctx.res);\n };\n}\n\n/** Ergonomic named-import wrapper, equivalent to `dashboard.koa()`. */\nexport function koaAdapter(dashboard: Dashboard): KoaMiddleware {\n return dashboard.koa();\n}\n","/**\n * NestJS adapter. Nest's default platform is Express, so the dashboard mounts\n * as ordinary functional middleware — no `@nestjs/*` dependency is required. Wire it in a module:\n *\n * ```ts\n * @Module({})\n * export class DashboardModule implements NestModule {\n * constructor(private readonly dashboard: Dashboard) {}\n * configure(consumer: MiddlewareConsumer): void {\n * consumer.apply(nestAdapter(this.dashboard)).forRoutes('/portqueue');\n * }\n * }\n * ```\n *\n * The middleware reconstructs the full mount path from `req.originalUrl`, exactly like the\n * Express adapter, so it behaves identically under `@nestjs/platform-express`.\n */\nimport type { DashboardEngine } from '../engine';\nimport type { Dashboard, NestMiddleware } from '../types';\nimport { createExpressMiddleware } from './express';\n\nexport function createNestMiddleware(engine: DashboardEngine): NestMiddleware {\n // Nest (platform-express) middleware is Express middleware.\n return createExpressMiddleware(engine);\n}\n\n/** Ergonomic named-import wrapper, equivalent to `dashboard.nest()`. */\nexport function nestAdapter(dashboard: Dashboard): NestMiddleware {\n return dashboard.nest();\n}\n","/**\n * Raw-Node adapter. The `(req, res) => boolean` handler: returns true when\n * it served the request, so you can fall through to your own routing otherwise.\n */\nimport type { DashboardEngine } from '../engine';\nimport type { Dashboard, NodeHandler } from '../types';\n\nexport function createNodeHandler(engine: DashboardEngine): NodeHandler {\n return (req, res) => {\n if (!engine.owns(req.url)) return false;\n engine.serveSafely(req, res);\n return true;\n };\n}\n\n/** Ergonomic named-import wrapper, equivalent to `dashboard.node()`. */\nexport function nodeAdapter(dashboard: Dashboard): NodeHandler {\n return dashboard.node();\n}\n","/**\n * `createDashboard(options)` — the single named-options factory. Builds the framework-agnostic\n * engine (see `engine.ts`) once, then exposes per-framework handlers, each a thin wrapper defined in\n * `adapters/`.\n *\n * It takes a **driver** and builds its own headless client from it (see `client.ts`), rather than\n * riding on the application's `PortQueue`. Mounting opens no connection; the first API request does,\n * and `close()` releases it.\n */\nimport { createEngine } from './engine';\nimport { createExpressMiddleware } from './adapters/express';\nimport { createFastifyPlugin } from './adapters/fastify';\nimport { createKoaMiddleware } from './adapters/koa';\nimport { createNestMiddleware } from './adapters/nest';\nimport { createNodeHandler } from './adapters/node';\nimport type { DashboardClient } from './client';\nimport type { Dashboard, DashboardOptions } from './types';\n\nexport function createDashboard(\n /**\n * `client` is an internal seam: it lets a test drive the router without a database and is never\n * part of the documented option surface. Production always passes `driver` alone.\n */\n options: DashboardOptions & { client?: DashboardClient },\n): Dashboard {\n const engine = createEngine(options);\n return {\n basePath: engine.basePath,\n node: () => createNodeHandler(engine),\n express: () => createExpressMiddleware(engine),\n koa: () => createKoaMiddleware(engine),\n fastify: () => createFastifyPlugin(engine),\n nest: () => createNestMiddleware(engine),\n close: () => engine.close(),\n };\n}\n"],"names":["ActionKind","text"],"mappings":";;;;;AAsBA,MAAM,eAAuC,EAAE,gBAAgB,kCAAA;AAGxD,SAAS,KACd,QACA,SACA,OACe;AACf,SAAO,EAAE,QAAQ,MAAM,KAAK,UAAU,OAAO,GAAG,SAAS,EAAE,GAAG,cAAc,GAAG,QAAM;AACvF;AAMO,SAAS,SAAS,KAAc,UAAiC;AACtE,SAAO,KAAK,KAAK,EAAE,OAAO,eAAe,QAAQ,IAAI,UAAU,UAAU;AAC3E;AAGO,SAAS,aAAa,KAAa,UAA0B;AAClE,QAAM,SAAS,IAAI,QAAQ,GAAG;AAC9B,MAAI,OAAO,WAAW,KAAK,MAAM,IAAI,MAAM,GAAG,MAAM;AACpD,MAAI,YAAY,KAAK,WAAW,QAAQ,EAAG,QAAO,KAAK,MAAM,SAAS,MAAM;AAC5E,MAAI,CAAC,KAAK,WAAW,GAAG,EAAG,QAAO,IAAI,IAAI;AAC1C,SAAO;AACT;AAGO,SAAS,QAAQ,KAA8B;AACpD,QAAM,SAAS,IAAI,QAAQ,GAAG;AAC9B,SAAO,IAAI,gBAAgB,WAAW,KAAK,KAAK,IAAI,MAAM,SAAS,CAAC,CAAC;AACvE;ACvCA,MAAM,UAAU,CAAC,WAAmC,EAAE,IAAI,OAAO,UAAU,KAAK,KAAK,EAAE,MAAA,CAAO,EAAA;AAGvF,SAAS,aAAa,QAA2C;AACtE,MAAI,OAAO,OAAO,UAAU,YAAY,CAAC,OAAO,MAAO,QAAO,QAAQ,eAAe;AACrF,SAAO,EAAE,IA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