@portqueue/dashboard 0.0.0-stage → 1.0.1

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.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +23 -2
  3. package/dist/client/assets/index-Bi6fyaCo.js +111 -0
  4. package/dist/client/assets/index-rcTsR9lz.css +1 -0
  5. package/dist/client/index.html +24 -0
  6. package/dist/index.cjs +922 -0
  7. package/dist/index.cjs.map +1 -0
  8. package/dist/index.d.ts +18 -0
  9. package/dist/index.mjs +921 -0
  10. package/dist/index.mjs.map +1 -0
  11. package/dist/server/adapters/express.d.ts +5 -0
  12. package/dist/server/adapters/fastify.d.ts +5 -0
  13. package/dist/server/adapters/koa.d.ts +5 -0
  14. package/dist/server/adapters/nest.d.ts +5 -0
  15. package/dist/server/adapters/node.d.ts +5 -0
  16. package/dist/server/api/http.d.ts +30 -0
  17. package/dist/server/api/params.d.ts +19 -0
  18. package/dist/server/api/routes/actions/add.d.ts +9 -0
  19. package/dist/server/api/routes/actions/cancel.d.ts +8 -0
  20. package/dist/server/api/routes/actions/index.d.ts +5 -0
  21. package/dist/server/api/routes/actions/job-batch.d.ts +4 -0
  22. package/dist/server/api/routes/actions/pause-instance.d.ts +8 -0
  23. package/dist/server/api/routes/actions/pause.d.ts +8 -0
  24. package/dist/server/api/routes/actions/remove-instance.d.ts +9 -0
  25. package/dist/server/api/routes/actions/remove-queue.d.ts +8 -0
  26. package/dist/server/api/routes/actions/remove-schedule.d.ts +9 -0
  27. package/dist/server/api/routes/actions/remove.d.ts +8 -0
  28. package/dist/server/api/routes/actions/resume-instance.d.ts +3 -0
  29. package/dist/server/api/routes/actions/resume.d.ts +3 -0
  30. package/dist/server/api/routes/actions/retry.d.ts +8 -0
  31. package/dist/server/api/routes/actions/set-schedule-enabled.d.ts +8 -0
  32. package/dist/server/api/routes/actions/types.d.ts +16 -0
  33. package/dist/server/api/routes/actions/validate.d.ts +24 -0
  34. package/dist/server/api/routes/config.d.ts +9 -0
  35. package/dist/server/api/routes/index.d.ts +37 -0
  36. package/dist/server/api/routes/instances.d.ts +5 -0
  37. package/dist/server/api/routes/jobs.d.ts +14 -0
  38. package/dist/server/api/routes/queues.d.ts +9 -0
  39. package/dist/server/api/routes/schedules.d.ts +5 -0
  40. package/dist/server/api/routes/stats.d.ts +8 -0
  41. package/dist/server/api/routes/types.d.ts +22 -0
  42. package/dist/server/api/serialize.d.ts +25 -0
  43. package/dist/server/assets.d.ts +51 -0
  44. package/dist/server/client.d.ts +11 -0
  45. package/dist/server/create-dashboard.d.ts +10 -0
  46. package/dist/server/engine.d.ts +18 -0
  47. package/dist/server/request.d.ts +18 -0
  48. package/dist/server/types.d.ts +74 -0
  49. package/dist/shared/constants.d.ts +27 -0
  50. package/dist/shared/dto/action.d.ts +88 -0
  51. package/dist/shared/dto/config.d.ts +20 -0
  52. package/dist/shared/dto/job.d.ts +37 -0
  53. package/dist/shared/dto/queue.d.ts +50 -0
  54. package/dist/shared/dto/schedule.d.ts +15 -0
  55. package/dist/shared/dto.d.ts +7 -0
  56. package/package.json +84 -4
package/dist/index.mjs ADDED
@@ -0,0 +1,921 @@
1
+ import { MAX_BATCH_IDS, JobBatchAction, PauseMode, DEFAULT_PAGE_LIMIT, DASHBOARD_MAX_PAGE_LIMIT, JobStatus, PortQueue } from "@portqueue/core";
2
+ import { randomBytes } from "node:crypto";
3
+ import { stat, readFile } from "node:fs/promises";
4
+ import { fileURLToPath } from "node:url";
5
+ import { join, dirname, resolve, extname, relative, isAbsolute } from "node:path";
6
+ const JSON_HEADERS = { "content-type": "application/json; charset=utf-8" };
7
+ function json(status, payload, extra) {
8
+ return { status, body: JSON.stringify(payload), headers: { ...JSON_HEADERS, ...extra } };
9
+ }
10
+ function conflict(err, fallback) {
11
+ return json(409, { error: err instanceof Error ? err.message : fallback });
12
+ }
13
+ function relativePath(url, basePath) {
14
+ const qIndex = url.indexOf("?");
15
+ let path = qIndex === -1 ? url : url.slice(0, qIndex);
16
+ if (basePath && path.startsWith(basePath)) path = path.slice(basePath.length);
17
+ if (!path.startsWith("/")) path = `/${path}`;
18
+ return path;
19
+ }
20
+ function queryOf(url) {
21
+ const qIndex = url.indexOf("?");
22
+ return new URLSearchParams(qIndex === -1 ? "" : url.slice(qIndex + 1));
23
+ }
24
+ const invalid = (error) => ({ ok: false, response: json(400, { error }) });
25
+ function requireQueue(action) {
26
+ if (typeof action.queue !== "string" || !action.queue) return invalid("Missing queue");
27
+ return { ok: true, value: action.queue };
28
+ }
29
+ function requireInstanceKey(action) {
30
+ if (typeof action.instanceKey !== "string" || !action.instanceKey) {
31
+ return invalid("Missing instanceKey");
32
+ }
33
+ return { ok: true, value: action.instanceKey };
34
+ }
35
+ function requireJobIds(action) {
36
+ const ids = action.jobIds?.length ? action.jobIds : action.jobId ? [action.jobId] : [];
37
+ return checkIds(ids, "jobId(s)");
38
+ }
39
+ function requireScheduleIds(action) {
40
+ const ids = action.scheduleIds?.length ? action.scheduleIds : action.scheduleId ? [action.scheduleId] : [];
41
+ return checkIds(ids, "scheduleId(s)");
42
+ }
43
+ function requireScheduleId(action) {
44
+ if (typeof action.scheduleId !== "string" || !action.scheduleId) {
45
+ return invalid("Missing scheduleId");
46
+ }
47
+ return { ok: true, value: action.scheduleId };
48
+ }
49
+ function checkIds(ids, what) {
50
+ if (!ids.length) return invalid(`Missing ${what}`);
51
+ if (ids.length > MAX_BATCH_IDS) {
52
+ return invalid(`Too many ids: ${ids.length} — the limit is ${MAX_BATCH_IDS} per request`);
53
+ }
54
+ return { ok: true, value: ids };
55
+ }
56
+ var ActionKind = /* @__PURE__ */ ((ActionKind2) => {
57
+ ActionKind2["PAUSE"] = "pause";
58
+ ActionKind2["RESUME"] = "resume";
59
+ ActionKind2["RETRY"] = "retry";
60
+ ActionKind2["REMOVE"] = "remove";
61
+ ActionKind2["CANCEL"] = "cancel";
62
+ ActionKind2["ADD"] = "add";
63
+ ActionKind2["REMOVE_SCHEDULE"] = "removeSchedule";
64
+ ActionKind2["SET_SCHEDULE_ENABLED"] = "setScheduleEnabled";
65
+ ActionKind2["REMOVE_QUEUE"] = "removeQueue";
66
+ ActionKind2["PAUSE_INSTANCE"] = "pauseInstance";
67
+ ActionKind2["RESUME_INSTANCE"] = "resumeInstance";
68
+ ActionKind2["REMOVE_INSTANCE"] = "removeInstance";
69
+ return ActionKind2;
70
+ })(ActionKind || {});
71
+ const addAction = {
72
+ kind: ActionKind.ADD,
73
+ summary: "Enqueue a job, or create a recurring schedule",
74
+ handle: async ({ portQueue, action }) => {
75
+ const queue = requireQueue(action);
76
+ if (!queue.ok) return queue.response;
77
+ if (!action.add || typeof action.add !== "object") {
78
+ return json(400, { error: "Missing add payload" });
79
+ }
80
+ try {
81
+ const result = await portQueue.addJob({
82
+ queue: queue.value,
83
+ ...buildAddOptions(action.add)
84
+ });
85
+ return json(200, {
86
+ ok: true,
87
+ ...result.jobId ? { jobId: result.jobId } : {},
88
+ ...result.scheduleId ? { scheduleId: result.scheduleId } : {}
89
+ });
90
+ } catch (err) {
91
+ return json(400, { error: err instanceof Error ? err.message : "Cannot add job" });
92
+ }
93
+ }
94
+ };
95
+ function buildAddOptions(add) {
96
+ const opts = { data: add.data };
97
+ if (typeof add.priority === "number") opts.priority = add.priority;
98
+ if (add.idempotencyKey) opts.idempotencyKey = add.idempotencyKey;
99
+ if (add.singletonKey) opts.singletonKey = add.singletonKey;
100
+ if (typeof add.retryMaxAttempts === "number") opts.retry = { maxAttempts: add.retryMaxAttempts };
101
+ if (add.preferredInstanceKeyPattern) {
102
+ opts.preferredInstanceKeyPattern = add.preferredInstanceKeyPattern;
103
+ }
104
+ const schedule = {};
105
+ if (add.startAfterSeconds != null) schedule.startAfterSeconds = add.startAfterSeconds;
106
+ if (add.cron != null) schedule.cron = add.cron;
107
+ else if (add.startEverySeconds != null) schedule.startEverySeconds = add.startEverySeconds;
108
+ if (Object.keys(schedule).length > 0) opts.schedule = schedule;
109
+ return opts;
110
+ }
111
+ async function runJobBatch({ portQueue, action }, verb) {
112
+ const jobIds = requireJobIds(action);
113
+ if (!jobIds.ok) return jobIds.response;
114
+ const result = await portQueue._dashboard.runJobBatch({
115
+ jobIds: jobIds.value,
116
+ action: verb
117
+ });
118
+ const signalled = result.signalled ?? 0;
119
+ return json(200, {
120
+ ok: result.affected > 0 || signalled > 0,
121
+ affected: result.affected,
122
+ requested: result.requested,
123
+ ...signalled ? { signalled } : {}
124
+ });
125
+ }
126
+ const cancelAction = {
127
+ kind: ActionKind.CANCEL,
128
+ summary: "Cancel the selected jobs",
129
+ handle: (ctx) => runJobBatch(ctx, JobBatchAction.CANCEL)
130
+ };
131
+ const pauseAction = {
132
+ kind: ActionKind.PAUSE,
133
+ summary: "Pause a queue (processing, or everything)",
134
+ handle: async ({ portQueue, action }) => {
135
+ const queue = requireQueue(action);
136
+ if (!queue.ok) return queue.response;
137
+ const mode = action.mode === PauseMode.ALL ? PauseMode.ALL : PauseMode.PROCESSING;
138
+ await portQueue.pauseQueue({ queue: queue.value, mode });
139
+ return json(200, { ok: true });
140
+ }
141
+ };
142
+ const pauseInstanceAction = {
143
+ kind: ActionKind.PAUSE_INSTANCE,
144
+ summary: "Stop one instance from claiming jobs",
145
+ handle: async ({ portQueue, action }) => {
146
+ const instanceKey = requireInstanceKey(action);
147
+ if (!instanceKey.ok) return instanceKey.response;
148
+ await portQueue.pauseInstance({ instanceKey: instanceKey.value });
149
+ return json(200, { ok: true });
150
+ }
151
+ };
152
+ const removeAction = {
153
+ kind: ActionKind.REMOVE,
154
+ summary: "Delete the selected job rows",
155
+ handle: (ctx) => runJobBatch(ctx, JobBatchAction.REMOVE)
156
+ };
157
+ const removeInstanceAction = {
158
+ kind: ActionKind.REMOVE_INSTANCE,
159
+ summary: "Remove a long-inactive instance row",
160
+ handle: async ({ portQueue, action }) => {
161
+ const instanceKey = requireInstanceKey(action);
162
+ if (!instanceKey.ok) return instanceKey.response;
163
+ try {
164
+ const ok = await portQueue.removeInstance({ instanceKey: instanceKey.value });
165
+ return json(200, { ok });
166
+ } catch (err) {
167
+ return conflict(err, "Cannot remove instance");
168
+ }
169
+ }
170
+ };
171
+ const removeQueueAction = {
172
+ kind: ActionKind.REMOVE_QUEUE,
173
+ summary: "Delete a queue row",
174
+ handle: async ({ portQueue, action }) => {
175
+ const queue = requireQueue(action);
176
+ if (!queue.ok) return queue.response;
177
+ try {
178
+ const ok = await portQueue.removeQueue({ name: queue.value });
179
+ return json(200, { ok });
180
+ } catch (err) {
181
+ return conflict(err, "Cannot remove queue");
182
+ }
183
+ }
184
+ };
185
+ const removeScheduleAction = {
186
+ kind: ActionKind.REMOVE_SCHEDULE,
187
+ summary: "Delete one or many schedules",
188
+ handle: async ({ portQueue, action }) => {
189
+ const ids = requireScheduleIds(action);
190
+ if (!ids.ok) return ids.response;
191
+ const result = await portQueue._dashboard.removeSchedules({ scheduleIds: ids.value });
192
+ return json(200, {
193
+ ok: result.affected > 0,
194
+ affected: result.affected,
195
+ requested: result.requested
196
+ });
197
+ }
198
+ };
199
+ const resumeAction = {
200
+ kind: ActionKind.RESUME,
201
+ summary: "Resume a paused queue",
202
+ handle: async ({ portQueue, action }) => {
203
+ const queue = requireQueue(action);
204
+ if (!queue.ok) return queue.response;
205
+ await portQueue.resumeQueue({ queue: queue.value });
206
+ return json(200, { ok: true });
207
+ }
208
+ };
209
+ const resumeInstanceAction = {
210
+ kind: ActionKind.RESUME_INSTANCE,
211
+ summary: "Let one instance claim jobs again",
212
+ handle: async ({ portQueue, action }) => {
213
+ const instanceKey = requireInstanceKey(action);
214
+ if (!instanceKey.ok) return instanceKey.response;
215
+ await portQueue.resumeInstance({ instanceKey: instanceKey.value });
216
+ return json(200, { ok: true });
217
+ }
218
+ };
219
+ const retryAction = {
220
+ kind: ActionKind.RETRY,
221
+ summary: "Re-arm the selected jobs",
222
+ handle: (ctx) => runJobBatch(ctx, JobBatchAction.RETRY)
223
+ };
224
+ const setScheduleEnabledAction = {
225
+ kind: ActionKind.SET_SCHEDULE_ENABLED,
226
+ summary: "Arm or disarm a schedule",
227
+ handle: async ({ portQueue, action }) => {
228
+ const scheduleId = requireScheduleId(action);
229
+ if (!scheduleId.ok) return scheduleId.response;
230
+ if (typeof action.enabled !== "boolean") return json(400, { error: "Missing enabled" });
231
+ const ok = await portQueue._dashboard.setScheduleEnabled({
232
+ scheduleId: scheduleId.value,
233
+ enabled: action.enabled
234
+ });
235
+ return json(200, { ok });
236
+ }
237
+ };
238
+ const ACTIONS = [
239
+ // Job-scoped (one id or many — the same single-statement batch either way)
240
+ retryAction,
241
+ cancelAction,
242
+ removeAction,
243
+ addAction,
244
+ // Queue-scoped
245
+ pauseAction,
246
+ resumeAction,
247
+ removeQueueAction,
248
+ // Schedule-scoped (they resolve their own queue from the id)
249
+ removeScheduleAction,
250
+ setScheduleEnabledAction,
251
+ // Instance-scoped (queue-less)
252
+ pauseInstanceAction,
253
+ resumeInstanceAction,
254
+ removeInstanceAction
255
+ ];
256
+ const ACTIONS_BY_KIND = new Map(
257
+ ACTIONS.map((action) => [action.kind, action])
258
+ );
259
+ const configRoute = {
260
+ method: "GET",
261
+ path: "/api/config",
262
+ summary: "Confirm the mount is a PortQueue dashboard",
263
+ handle: async () => json(200, { ok: true })
264
+ };
265
+ function paging(params) {
266
+ const rawLimit = Number(params.get("limit"));
267
+ const rawOffset = Number(params.get("offset"));
268
+ return {
269
+ limit: Number.isFinite(rawLimit) && rawLimit > 0 ? Math.min(Math.trunc(rawLimit), DASHBOARD_MAX_PAGE_LIMIT) : DEFAULT_PAGE_LIMIT,
270
+ offset: Number.isFinite(rawOffset) && rawOffset > 0 ? Math.trunc(rawOffset) : 0
271
+ };
272
+ }
273
+ function triBool(raw) {
274
+ if (raw === "true") return true;
275
+ if (raw === "false") return false;
276
+ return void 0;
277
+ }
278
+ function text(params, key) {
279
+ const raw = params.get(key);
280
+ return raw ? raw : void 0;
281
+ }
282
+ function when(key, value) {
283
+ return value === void 0 ? {} : { [key]: value };
284
+ }
285
+ function statuses(raw) {
286
+ if (!raw) return void 0;
287
+ const valid = new Set(Object.values(JobStatus));
288
+ const out = raw.split(",").map((s) => s.trim().toUpperCase()).filter((s) => valid.has(s));
289
+ return out.length ? out : void 0;
290
+ }
291
+ function jobsQuery(params) {
292
+ return {
293
+ ...paging(params),
294
+ ...when("queue", text(params, "queue")),
295
+ ...when("statuses", statuses(params.get("statuses"))),
296
+ ...when("scheduleId", text(params, "scheduleId")),
297
+ ...when("instanceKey", text(params, "instanceKey"))
298
+ };
299
+ }
300
+ function iso(d) {
301
+ if (d === null) return null;
302
+ if (d === void 0) return void 0;
303
+ return d.toISOString();
304
+ }
305
+ function counts(c) {
306
+ return { ...c };
307
+ }
308
+ function serializeJob(job) {
309
+ return {
310
+ id: job.id,
311
+ queue: job.queue,
312
+ status: job.status,
313
+ data: job.data,
314
+ returnValue: job.returnValue,
315
+ priority: job.priority,
316
+ retryAttempt: job.retryAttempt,
317
+ retryMaxAttempts: job.retryMaxAttempts,
318
+ createdAt: job.createdAt.toISOString(),
319
+ updatedAt: job.updatedAt.toISOString(),
320
+ startAfter: job.startAfter.toISOString(),
321
+ startedAt: iso(job.startedAt),
322
+ completedAt: iso(job.completedAt),
323
+ failedAt: iso(job.failedAt),
324
+ cancelledAt: iso(job.cancelledAt),
325
+ expiredAt: iso(job.expiredAt),
326
+ retriedAt: iso(job.retriedAt),
327
+ stalledAt: iso(job.stalledAt),
328
+ lockedUntil: iso(job.lockedUntil),
329
+ preferredInstanceKeyPattern: job.preferredInstanceKeyPattern,
330
+ processedOnInstanceKey: job.processedOnInstanceKey,
331
+ failureMessage: job.failureMessage,
332
+ idempotencyKey: job.idempotencyKey,
333
+ scheduleId: job.scheduleId,
334
+ stalled: job.stalled
335
+ };
336
+ }
337
+ function serializeQueue(q) {
338
+ return {
339
+ name: q.name,
340
+ processingPaused: q.processingPaused,
341
+ acceptingPaused: q.acceptingPaused,
342
+ counts: counts(q.counts)
343
+ };
344
+ }
345
+ function serializeQueuePage(page) {
346
+ return { items: page.items.map(serializeQueue), total: page.total };
347
+ }
348
+ function serializeStats(s) {
349
+ return {
350
+ ...s.queue !== void 0 ? { queue: s.queue } : {},
351
+ counts: counts(s.counts)
352
+ };
353
+ }
354
+ function serializeJobPage(page) {
355
+ return {
356
+ items: page.items.map(serializeJob),
357
+ total: page.total
358
+ };
359
+ }
360
+ function serializeSchedule(s) {
361
+ return {
362
+ scheduleId: s.scheduleId,
363
+ queue: s.queue,
364
+ cron: s.cron,
365
+ everySeconds: s.everySeconds,
366
+ timezone: s.timezone,
367
+ nextRunAt: iso(s.nextRunAt),
368
+ lastRunAt: iso(s.lastRunAt),
369
+ enabled: s.enabled,
370
+ idempotencyKey: s.idempotencyKey
371
+ };
372
+ }
373
+ function serializeSchedulePage(page) {
374
+ return { items: page.items.map(serializeSchedule), total: page.total };
375
+ }
376
+ function serializeInstance(i) {
377
+ return {
378
+ instanceKey: i.instanceKey,
379
+ processingPaused: i.processingPaused,
380
+ alive: i.alive,
381
+ createdAt: i.createdAt.toISOString(),
382
+ updatedAt: i.updatedAt.toISOString(),
383
+ lastSeenAt: i.lastSeenAt.toISOString(),
384
+ cpuPercent: i.cpuPercent,
385
+ memoryPercent: i.memoryPercent,
386
+ counts: counts(i.counts)
387
+ };
388
+ }
389
+ function serializeInstancePage(page) {
390
+ return { items: page.items.map(serializeInstance), total: page.total };
391
+ }
392
+ const instancesRoute = {
393
+ method: "GET",
394
+ path: "/api/instances",
395
+ summary: "List instances with liveness and job attribution",
396
+ handle: async ({ portQueue, query }) => {
397
+ const page = await portQueue._dashboard.getInstances({
398
+ ...paging(query),
399
+ ...when("search", text(query, "search")),
400
+ ...when("processingPaused", triBool(query.get("processingPaused"))),
401
+ ...when("alive", triBool(query.get("alive")))
402
+ });
403
+ return json(200, serializeInstancePage(page));
404
+ }
405
+ };
406
+ const instanceRoute = {
407
+ method: "GET",
408
+ path: /^\/api\/instances\/([^/]+)$/,
409
+ summary: "One instance by key",
410
+ handle: async ({ portQueue, params }) => {
411
+ const instance = await portQueue._dashboard.getInstance({ instanceKey: params[0] });
412
+ if (!instance) return json(404, { error: "Instance not found" });
413
+ return json(200, serializeInstance(instance));
414
+ }
415
+ };
416
+ const jobsRoute = {
417
+ method: "GET",
418
+ path: "/api/jobs",
419
+ summary: "List jobs, with filters and free-text search",
420
+ handle: async ({ portQueue, query }) => {
421
+ const page = await portQueue._dashboard.getJobs({
422
+ ...jobsQuery(query),
423
+ ...when("search", text(query, "search"))
424
+ });
425
+ return json(200, serializeJobPage(page));
426
+ }
427
+ };
428
+ const jobRoute = {
429
+ method: "GET",
430
+ path: /^\/api\/jobs\/([^/]+)$/,
431
+ summary: "One job by id",
432
+ handle: async ({ portQueue, params }) => {
433
+ const job = await portQueue.getJob({ jobId: params[0] });
434
+ if (!job) return json(404, { error: "Job not found" });
435
+ return json(200, serializeJob(job));
436
+ }
437
+ };
438
+ const queuesRoute = {
439
+ method: "GET",
440
+ path: "/api/queues",
441
+ summary: "List queues with their per-status counts",
442
+ handle: async ({ portQueue, query }) => {
443
+ const page = await portQueue._dashboard.getQueues({
444
+ ...paging(query),
445
+ ...when("search", text(query, "search")),
446
+ ...when("processingPaused", triBool(query.get("processingPaused")))
447
+ });
448
+ return json(200, serializeQueuePage(page));
449
+ }
450
+ };
451
+ const schedulesRoute = {
452
+ method: "GET",
453
+ path: "/api/schedules",
454
+ summary: "List recurring schedules",
455
+ handle: async ({ portQueue, query }) => {
456
+ const page = await portQueue._dashboard.getSchedules({
457
+ ...paging(query),
458
+ ...when("queue", text(query, "queue")),
459
+ ...when("search", text(query, "search")),
460
+ ...when("enabled", triBool(query.get("enabled")))
461
+ });
462
+ return json(200, serializeSchedulePage(page));
463
+ }
464
+ };
465
+ const scheduleRoute = {
466
+ method: "GET",
467
+ path: /^\/api\/schedules\/([^/]+)$/,
468
+ summary: "One schedule by id",
469
+ handle: async ({ portQueue, params }) => {
470
+ const schedule = await portQueue._dashboard.getSchedule({ scheduleId: params[0] });
471
+ if (!schedule) return json(404, { error: "Schedule not found" });
472
+ return json(200, serializeSchedule(schedule));
473
+ }
474
+ };
475
+ const statsRoute = {
476
+ method: "GET",
477
+ path: "/api/stats",
478
+ summary: "Per-status counts, for one queue or the whole client",
479
+ handle: async ({ portQueue, query }) => {
480
+ const stats = await portQueue._dashboard.getStats({ ...when("queue", text(query, "queue")) });
481
+ return json(200, serializeStats(stats));
482
+ }
483
+ };
484
+ const DASHBOARD_TITLE = "PortQueue Dashboard";
485
+ const REQUESTED_WITH_HEADER = "x-requested-with";
486
+ const REQUESTED_WITH_MARKER = "portqueue-dashboard";
487
+ const MAX_BODY_BYTES = 1024 * 1024;
488
+ const ACTIONS_PATH_PREFIX = "/api/actions/";
489
+ const ROUTES = [
490
+ configRoute,
491
+ queuesRoute,
492
+ jobsRoute,
493
+ jobRoute,
494
+ schedulesRoute,
495
+ scheduleRoute,
496
+ instancesRoute,
497
+ instanceRoute,
498
+ statsRoute
499
+ ];
500
+ function createRouter(options) {
501
+ const { client, basePath } = options;
502
+ const isApiPath = (url) => relativePath(url, basePath).startsWith("/api/");
503
+ async function handle(input) {
504
+ const path = relativePath(input.url, basePath);
505
+ const method = input.method.toUpperCase();
506
+ const rejection = assertSameOrigin(method, input.headers);
507
+ if (rejection) return rejection;
508
+ let portQueue;
509
+ try {
510
+ portQueue = await client.get();
511
+ } catch (err) {
512
+ return json(503, {
513
+ error: err instanceof Error ? err.message : "Cannot reach the PortQueue database"
514
+ });
515
+ }
516
+ if (method === "POST" && path.startsWith(ACTIONS_PATH_PREFIX)) {
517
+ return handleAction(portQueue, path.slice(ACTIONS_PATH_PREFIX.length), input.body);
518
+ }
519
+ if (method === "GET") return handleRead(portQueue, path, queryOf(input.url));
520
+ return json(404, { error: "Not found" });
521
+ }
522
+ return { handle, isApiPath };
523
+ }
524
+ function assertSameOrigin(method, headers) {
525
+ if (method === "GET" || method === "HEAD") return null;
526
+ const raw = headers[REQUESTED_WITH_HEADER];
527
+ const value = Array.isArray(raw) ? raw[0] : raw;
528
+ if (value === REQUESTED_WITH_MARKER) return null;
529
+ return json(403, {
530
+ error: `Missing or invalid ${REQUESTED_WITH_HEADER} header — a mutation must come from the dashboard client.`
531
+ });
532
+ }
533
+ async function handleRead(portQueue, path, query) {
534
+ for (const route of ROUTES) {
535
+ const params = match(route, path);
536
+ if (params) return route.handle({ portQueue, query, params });
537
+ }
538
+ return json(404, { error: "Not found" });
539
+ }
540
+ function match(route, path) {
541
+ if (typeof route.path === "string") return route.path === path ? [] : null;
542
+ const found = route.path.exec(path);
543
+ if (!found) return null;
544
+ return found.slice(1).map((segment) => decodeURIComponent(segment));
545
+ }
546
+ async function handleAction(portQueue, segment, body) {
547
+ const route = ACTIONS_BY_KIND.get(decodeURIComponent(segment));
548
+ if (!route) return json(404, { error: "Unknown action" });
549
+ let action;
550
+ try {
551
+ action = JSON.parse(body ?? "");
552
+ } catch {
553
+ return json(400, { error: "Invalid JSON body" });
554
+ }
555
+ if (!action || typeof action !== "object") return json(400, { error: "Invalid JSON body" });
556
+ return route.handle({ portQueue, action });
557
+ }
558
+ const HTML_MIME = "text/html; charset=utf-8";
559
+ const MIME = {
560
+ ".html": HTML_MIME,
561
+ ".js": "text/javascript; charset=utf-8",
562
+ ".mjs": "text/javascript; charset=utf-8",
563
+ ".css": "text/css; charset=utf-8",
564
+ ".json": "application/json; charset=utf-8",
565
+ ".svg": "image/svg+xml",
566
+ ".png": "image/png",
567
+ ".ico": "image/x-icon",
568
+ ".woff": "font/woff",
569
+ ".woff2": "font/woff2",
570
+ ".map": "application/json; charset=utf-8"
571
+ };
572
+ const IMMUTABLE_CACHE = "public, max-age=31536000, immutable";
573
+ const NO_CACHE = "no-cache";
574
+ function clientDistDir() {
575
+ const here = dirname(fileURLToPath(import.meta.url));
576
+ return resolve(here, "client");
577
+ }
578
+ async function exists(path) {
579
+ try {
580
+ const s = await stat(path);
581
+ return s.isFile();
582
+ } catch {
583
+ return false;
584
+ }
585
+ }
586
+ function hasBuiltClient() {
587
+ builtClient ??= exists(join(clientDistDir(), "index.html"));
588
+ return builtClient;
589
+ }
590
+ let builtClient = null;
591
+ function safeResolve(root, relPath) {
592
+ const target = resolve(root, `.${relPath.startsWith("/") ? relPath : `/${relPath}`}`);
593
+ const rel = relative(root, target);
594
+ if (rel === "") return target;
595
+ if (rel.startsWith("..") || isAbsolute(rel)) return null;
596
+ return target;
597
+ }
598
+ async function serveAsset(relPath, config) {
599
+ const root = clientDistDir();
600
+ const built = await hasBuiltClient();
601
+ if (!built) {
602
+ if (extname(relPath) && relPath !== "/index.html") {
603
+ return { status: 404, body: "Not found", contentType: "text/plain; charset=utf-8" };
604
+ }
605
+ return htmlResult(inlineShell(config), config);
606
+ }
607
+ const requested = relPath === "/" ? "/index.html" : relPath;
608
+ const target = safeResolve(root, requested);
609
+ if (target === null) {
610
+ return { status: 403, body: "Forbidden", contentType: "text/plain; charset=utf-8" };
611
+ }
612
+ if (await exists(target)) {
613
+ const ext = extname(target).toLowerCase();
614
+ const body = await readFile(target);
615
+ if (ext === ".html") {
616
+ return htmlResult(rewriteAssetUrls(body.toString("utf8"), config.basePath), config);
617
+ }
618
+ return {
619
+ status: 200,
620
+ body,
621
+ contentType: MIME[ext] ?? "application/octet-stream",
622
+ // Content-hashed filenames make this safe: the browser never re-requests a cached bundle.
623
+ headers: { "cache-control": IMMUTABLE_CACHE }
624
+ };
625
+ }
626
+ if (!extname(requested)) {
627
+ const indexPath = join(root, "index.html");
628
+ if (await exists(indexPath)) {
629
+ const raw = (await readFile(indexPath)).toString("utf8");
630
+ return htmlResult(rewriteAssetUrls(raw, config.basePath), config);
631
+ }
632
+ }
633
+ return { status: 404, body: "Not found", contentType: "text/plain; charset=utf-8" };
634
+ }
635
+ function htmlResult(html, config) {
636
+ const nonce = randomBytes(16).toString("base64");
637
+ return {
638
+ status: 200,
639
+ body: injectConfig(html, config, nonce),
640
+ contentType: HTML_MIME,
641
+ headers: {
642
+ "cache-control": NO_CACHE,
643
+ "content-security-policy": contentSecurityPolicy(nonce)
644
+ }
645
+ };
646
+ }
647
+ function contentSecurityPolicy(nonce) {
648
+ return [
649
+ "default-src 'self'",
650
+ `script-src 'self' 'nonce-${nonce}'`,
651
+ "style-src 'self' 'unsafe-inline'",
652
+ "img-src 'self' data:",
653
+ "font-src 'self' data:",
654
+ "connect-src 'self'",
655
+ "frame-ancestors 'none'",
656
+ "base-uri 'self'",
657
+ "form-action 'self'",
658
+ "object-src 'none'"
659
+ ].join("; ");
660
+ }
661
+ function rewriteAssetUrls(html, basePath) {
662
+ const prefix = basePath === "/" ? "" : basePath;
663
+ return html.replace(
664
+ /(\b(?:src|href)=")\.\/([^"]*)"/g,
665
+ (_match, attr, path) => `${attr}${prefix}/${path}"`
666
+ );
667
+ }
668
+ function injectConfig(html, config, nonce) {
669
+ const tag = `<script nonce="${nonce}">window.__PORTQUEUE_DASHBOARD__=${serializeConfig(config)};<\/script>`;
670
+ if (html.includes("</head>")) return html.replace("</head>", `${tag}</head>`);
671
+ return `${tag}${html}`;
672
+ }
673
+ function serializeConfig(config) {
674
+ return JSON.stringify(config).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
675
+ }
676
+ function inlineShell(config) {
677
+ return `<!doctype html>
678
+ <html lang="en">
679
+ <head>
680
+ <meta charset="utf-8" />
681
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
682
+ <title>${DASHBOARD_TITLE}</title>
683
+ <style>
684
+ :root { color-scheme: light dark; }
685
+ body { margin:0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif; background:#f7f8fa; color:#1a1d23; }
686
+ @media (prefers-color-scheme: dark){ body{ background:#0b0e14; color:#e6e8ec; } .card{ background:#131722 !important; } }
687
+ .wrap{ max-width:720px; margin:12vh auto; padding:24px; }
688
+ .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); }
689
+ code{ font-family: ui-monospace, "SF Mono", Menlo, monospace; background:rgba(127,127,127,0.15); padding:2px 6px; border-radius:6px; }
690
+ h1{ font-size:22px; margin:0 0 8px; }
691
+ </style>
692
+ </head>
693
+ <body>
694
+ <div class="wrap"><div class="card">
695
+ <h1>${DASHBOARD_TITLE}</h1>
696
+ <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>
697
+ <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>
698
+ </div></div>
699
+ </body>
700
+ </html>`;
701
+ }
702
+ function escapeHtml(s) {
703
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
704
+ }
705
+ function readBody(req) {
706
+ return new Promise((resolveBody, reject) => {
707
+ const chunks = [];
708
+ let size = 0;
709
+ let tooLarge = false;
710
+ req.on("data", (chunk) => {
711
+ size += chunk.length;
712
+ if (tooLarge) return;
713
+ if (size > MAX_BODY_BYTES) {
714
+ tooLarge = true;
715
+ chunks.length = 0;
716
+ return;
717
+ }
718
+ chunks.push(chunk);
719
+ });
720
+ req.on("end", () => {
721
+ if (tooLarge) {
722
+ reject(new BodyTooLargeError());
723
+ return;
724
+ }
725
+ resolveBody(Buffer.concat(chunks).toString("utf8"));
726
+ });
727
+ req.on("error", reject);
728
+ });
729
+ }
730
+ class BodyTooLargeError extends Error {
731
+ constructor() {
732
+ super(`Request body exceeds the ${MAX_BODY_BYTES}-byte limit`);
733
+ this.name = "BodyTooLargeError";
734
+ }
735
+ }
736
+ function toHeaders(req) {
737
+ return req.headers;
738
+ }
739
+ function normalizeBase(basePath) {
740
+ let b = basePath.trim();
741
+ if (!b.startsWith("/")) b = `/${b}`;
742
+ if (b.length > 1 && b.endsWith("/")) b = b.slice(0, -1);
743
+ return b;
744
+ }
745
+ function createDashboardClient(options) {
746
+ let started = null;
747
+ let instance = null;
748
+ return {
749
+ get() {
750
+ if (!started) {
751
+ started = (async () => {
752
+ const pq = new PortQueue({ driver: options.driver, _headless: true });
753
+ await pq.init();
754
+ instance = pq;
755
+ return pq;
756
+ })().catch((err) => {
757
+ started = null;
758
+ throw err;
759
+ });
760
+ }
761
+ return started;
762
+ },
763
+ async close() {
764
+ const pq = instance;
765
+ started = null;
766
+ instance = null;
767
+ if (pq) await pq.shutdown();
768
+ }
769
+ };
770
+ }
771
+ const SECURITY_HEADERS = {
772
+ "x-content-type-options": "nosniff",
773
+ "x-frame-options": "DENY",
774
+ "referrer-policy": "no-referrer"
775
+ };
776
+ function createEngine(options) {
777
+ const basePath = normalizeBase(options.basePath ?? "/portqueue");
778
+ const config = { basePath, maxBatchIds: MAX_BATCH_IDS };
779
+ const logger = options.logger ?? console;
780
+ const client = options.client ?? createDashboardClient({ driver: options.driver, ...options.logger ? { logger } : {} });
781
+ const router = createRouter({ client, basePath });
782
+ void hasBuiltClient().then((built) => {
783
+ if (!built) {
784
+ logger.warn(
785
+ `[@portqueue/dashboard] No client bundle found; serving the fallback shell at ${basePath}. The package was published or built without its SPA — run \`npm run build\` in @portqueue/dashboard, or reinstall the package.`
786
+ );
787
+ }
788
+ });
789
+ function owns(url) {
790
+ if (!url) return false;
791
+ const path = url.split("?")[0] ?? "";
792
+ return path === basePath || path.startsWith(`${basePath}/`);
793
+ }
794
+ function relPath(url) {
795
+ const path = (url.split("?")[0] ?? "").slice(basePath.length);
796
+ return path.startsWith("/") || path === "" ? path || "/" : `/${path}`;
797
+ }
798
+ async function handleApi(req, res, method, url) {
799
+ let body;
800
+ if (method === "POST" || method === "PUT" || method === "PATCH") {
801
+ try {
802
+ body = await readBody(req);
803
+ } catch {
804
+ res.writeHead(413, { ...SECURITY_HEADERS, "content-type": "application/json" });
805
+ res.end(JSON.stringify({ error: "Request body too large" }));
806
+ return;
807
+ }
808
+ }
809
+ const input = { method, url, body, headers: toHeaders(req) };
810
+ const result = await router.handle(input);
811
+ res.writeHead(result.status, { ...SECURITY_HEADERS, ...result.headers });
812
+ res.end(result.body);
813
+ }
814
+ async function handleAsset(res, url) {
815
+ const asset = await serveAsset(relPath(url), config);
816
+ res.writeHead(asset.status, {
817
+ ...SECURITY_HEADERS,
818
+ "content-type": asset.contentType,
819
+ ...asset.headers
820
+ });
821
+ res.end(asset.body);
822
+ }
823
+ async function serve(req, res) {
824
+ const url = req.url ?? "";
825
+ const method = (req.method ?? "GET").toUpperCase();
826
+ if (router.isApiPath(url)) return handleApi(req, res, method, url);
827
+ return handleAsset(res, url);
828
+ }
829
+ function serveSafely(req, res) {
830
+ void serve(req, res).catch(() => {
831
+ if (!res.headersSent) {
832
+ res.writeHead(500, { ...SECURITY_HEADERS, "content-type": "application/json" });
833
+ }
834
+ res.end(JSON.stringify({ error: "Internal dashboard error" }));
835
+ });
836
+ }
837
+ return { basePath, owns, serve, serveSafely, close: () => client.close() };
838
+ }
839
+ function createExpressMiddleware(engine) {
840
+ return (req, res, next) => {
841
+ const original = req.url ?? "";
842
+ const originalUrl = req.originalUrl;
843
+ if (originalUrl) req.url = originalUrl;
844
+ if (!engine.owns(req.url)) {
845
+ req.url = original;
846
+ next();
847
+ return;
848
+ }
849
+ engine.serveSafely(req, res);
850
+ };
851
+ }
852
+ function expressAdapter(dashboard) {
853
+ return dashboard.express();
854
+ }
855
+ const SKIP_OVERRIDE = Symbol.for("skip-override");
856
+ function createFastifyPlugin(engine) {
857
+ const plugin = (fastify, _opts, done) => {
858
+ fastify.addHook("onRequest", async (request, reply) => {
859
+ if (!engine.owns(request.raw.url)) return;
860
+ reply.hijack();
861
+ engine.serveSafely(request.raw, reply.raw);
862
+ });
863
+ done();
864
+ };
865
+ plugin[SKIP_OVERRIDE] = true;
866
+ return plugin;
867
+ }
868
+ function fastifyAdapter(dashboard) {
869
+ return dashboard.fastify();
870
+ }
871
+ function createKoaMiddleware(engine) {
872
+ return async (ctx, next) => {
873
+ if (!engine.owns(ctx.req.url)) {
874
+ await next();
875
+ return;
876
+ }
877
+ ctx.respond = false;
878
+ await engine.serve(ctx.req, ctx.res);
879
+ };
880
+ }
881
+ function koaAdapter(dashboard) {
882
+ return dashboard.koa();
883
+ }
884
+ function createNestMiddleware(engine) {
885
+ return createExpressMiddleware(engine);
886
+ }
887
+ function nestAdapter(dashboard) {
888
+ return dashboard.nest();
889
+ }
890
+ function createNodeHandler(engine) {
891
+ return (req, res) => {
892
+ if (!engine.owns(req.url)) return false;
893
+ engine.serveSafely(req, res);
894
+ return true;
895
+ };
896
+ }
897
+ function nodeAdapter(dashboard) {
898
+ return dashboard.node();
899
+ }
900
+ function createDashboard(options) {
901
+ const engine = createEngine(options);
902
+ return {
903
+ basePath: engine.basePath,
904
+ node: () => createNodeHandler(engine),
905
+ express: () => createExpressMiddleware(engine),
906
+ koa: () => createKoaMiddleware(engine),
907
+ fastify: () => createFastifyPlugin(engine),
908
+ nest: () => createNestMiddleware(engine),
909
+ close: () => engine.close()
910
+ };
911
+ }
912
+ export {
913
+ ActionKind,
914
+ createDashboard,
915
+ expressAdapter,
916
+ fastifyAdapter,
917
+ koaAdapter,
918
+ nestAdapter,
919
+ nodeAdapter
920
+ };
921
+ //# sourceMappingURL=index.mjs.map