@azlib/scheduler 1.0.5 → 1.2.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.
Files changed (48) hide show
  1. package/Dockerfile +14 -0
  2. package/README.md +53 -0
  3. package/compose.yaml +28 -0
  4. package/dist/cli-config-6u8AzSdw.mjs +542 -0
  5. package/dist/cli-config-6u8AzSdw.mjs.map +1 -0
  6. package/dist/cli-config-CFBl-YOh.cjs +628 -0
  7. package/dist/dashboard/cli.cjs +30 -0
  8. package/dist/dashboard/cli.d.cts +6 -0
  9. package/dist/dashboard/cli.d.cts.map +1 -0
  10. package/dist/dashboard/cli.d.mts +6 -0
  11. package/dist/dashboard/cli.d.mts.map +1 -0
  12. package/dist/dashboard/cli.mjs +31 -0
  13. package/dist/dashboard/cli.mjs.map +1 -0
  14. package/dist/dashboard/public/assets/index-CbmpG6_w.css +2 -0
  15. package/dist/dashboard/public/assets/index-DczjtqRn.js +12 -0
  16. package/dist/dashboard/public/index.html +13 -0
  17. package/dist/dashboard-types-BHjRLcxJ.d.cts +127 -0
  18. package/dist/dashboard-types-BHjRLcxJ.d.cts.map +1 -0
  19. package/dist/dashboard-types-BHjRLcxJ.d.mts +127 -0
  20. package/dist/dashboard-types-BHjRLcxJ.d.mts.map +1 -0
  21. package/dist/dashboard.cjs +15 -0
  22. package/dist/dashboard.d.cts +31 -0
  23. package/dist/dashboard.d.cts.map +1 -0
  24. package/dist/dashboard.d.mts +31 -0
  25. package/dist/dashboard.d.mts.map +1 -0
  26. package/dist/dashboard.mjs +4 -0
  27. package/dist/http-server-Cme4XKyH.d.mts +34 -0
  28. package/dist/http-server-Cme4XKyH.d.mts.map +1 -0
  29. package/dist/http-server-u1BnbkAK.d.cts +34 -0
  30. package/dist/http-server-u1BnbkAK.d.cts.map +1 -0
  31. package/dist/index.cjs +49 -442
  32. package/dist/index.d.cts +3 -158
  33. package/dist/index.d.cts.map +1 -1
  34. package/dist/index.d.mts +3 -158
  35. package/dist/index.d.mts.map +1 -1
  36. package/dist/index.mjs +44 -439
  37. package/dist/index.mjs.map +1 -1
  38. package/dist/queue-dashboard-service-BFXcnfUr.cjs +55 -0
  39. package/dist/queue-dashboard-service-C0QapgOg.mjs +52 -0
  40. package/dist/queue-dashboard-service-C0QapgOg.mjs.map +1 -0
  41. package/dist/store-dashboard-C44d7sdh.d.cts +59 -0
  42. package/dist/store-dashboard-C44d7sdh.d.cts.map +1 -0
  43. package/dist/store-dashboard-Cyf_JILa.mjs +515 -0
  44. package/dist/store-dashboard-Cyf_JILa.mjs.map +1 -0
  45. package/dist/store-dashboard-D-yIxXxL.d.mts +59 -0
  46. package/dist/store-dashboard-D-yIxXxL.d.mts.map +1 -0
  47. package/dist/store-dashboard-Sg4BBWiJ.cjs +554 -0
  48. package/package.json +54 -6
package/Dockerfile ADDED
@@ -0,0 +1,14 @@
1
+ FROM node:22-alpine
2
+
3
+ WORKDIR /app
4
+
5
+ RUN npm install --omit=dev @azlib/scheduler pg
6
+
7
+ ENV HOST=0.0.0.0
8
+ ENV PORT=9100
9
+ ENV SCHEDULER_DIALECT=postgres
10
+ ENV SCHEDULER_NAMESPACE=azlib
11
+
12
+ EXPOSE 9100
13
+
14
+ CMD ["node", "node_modules/@azlib/scheduler/dist/dashboard/cli.mjs"]
package/README.md CHANGED
@@ -11,6 +11,7 @@ Cron-style job scheduler for Node.js, supporting timezone normalization, overlap
11
11
  - Queue-backed execution dispatch through `@azlib/queue`
12
12
  - Cache coordination using `@azlib/cache`
13
13
  - Structured database state persistence (SQL persistence)
14
+ - Operator dashboard (HTTP + React UI) for monitoring and controlling jobs
14
15
 
15
16
  ## AI Agent Quick Reference
16
17
 
@@ -22,6 +23,58 @@ Cron-style job scheduler for Node.js, supporting timezone normalization, overlap
22
23
  | `createCronExpression(): CronExpressionBuilder` | Function | Fluent helper to construct standard 5-field cron strings. |
23
24
  | `bindSchedulerToHost(service: SchedulerService, adapter: SchedulerHostAdapter)` | Function | Automatically starts/stops the scheduler based on custom server bindings. |
24
25
  | `CronWeekday` | Enum | Monday through Sunday utility enum values. |
26
+ | `createSchedulerDashboardService(scheduler, options?)` | Function | Operator API: health, list, pause/resume, run-now, retry, CRUD. |
27
+ | `createSchedulerDashboardFromPersistence(persistence)` | Function | Sidecar dashboard against the same SQL tables (does not start the engine). |
28
+ | `createSchedulerDashboardServer(options)` | Function | Serves the React UI and JSON API (`@azlib/scheduler/dashboard`). |
29
+ | `createSchedulerDashboardNodeHandler(options)` | Function | Same monitor as the standalone server, for Express/`http` hosts. |
30
+
31
+ ### Dashboard
32
+
33
+ The dashboard can run **in-process** next to a live `SchedulerService`, or as a **sidecar / Docker** process that shares SQL persistence. The sidecar never starts a second scheduler engine. Pause/resume writes `enabled` on the job row; the worker re-reads that on every tick.
34
+
35
+ ```ts
36
+ import {
37
+ createSchedulerDashboardServer,
38
+ createSchedulerDashboardService,
39
+ createSchedulerDashboardNodeHandler,
40
+ } from "@azlib/scheduler/dashboard";
41
+
42
+ const dashboard = createSchedulerDashboardService(service, { handlers });
43
+ const server = createSchedulerDashboardServer({
44
+ dashboard,
45
+ port: 9100,
46
+ host: "127.0.0.1",
47
+ });
48
+ await server.listen();
49
+
50
+ // Or mount the same monitor on an existing Node/Express server:
51
+ app.use(
52
+ createSchedulerDashboardNodeHandler({
53
+ dashboard,
54
+ basePath: "/scheduler",
55
+ authorize: async ({ authorization }) => {
56
+ // throw DashboardHttpError(401 | 403, message) to reject
57
+ },
58
+ }),
59
+ );
60
+ ```
61
+
62
+ Sidecar CLI (`azlib-scheduler-dashboard`) and Docker (`packages/scheduler/Dockerfile`, `compose.yaml`):
63
+
64
+ | Env | Default | Notes |
65
+ | --- | --- | --- |
66
+ | `DATABASE_URL` | required | Same database as the worker |
67
+ | `SCHEDULER_DIALECT` | inferred from URL | `postgres` (default), `mysql`, `sqlite`, `mssql` |
68
+ | `SCHEDULER_NAMESPACE` | `azlib` | Table prefix (`azlib__scheduler_jobs`, …) |
69
+ | `HOST` | `127.0.0.1` | Use `0.0.0.0` in Docker |
70
+ | `PORT` | `9100` | |
71
+ | `DASHBOARD_TOKEN` | required when HOST is not loopback | `Authorization: Bearer …` on `/api/*` |
72
+
73
+ Install the matching SQL driver (`pg`, `mysql2`, `better-sqlite3`, or `mssql`) next to `@azlib/scheduler`. Run-now and retry enqueue only when the worker’s queue is reachable; pause, resume, update, and delete work from SQL alone.
74
+
75
+ ```bash
76
+ DASHBOARD_TOKEN=secret docker compose -f packages/scheduler/compose.yaml up --build
77
+ ```
25
78
 
26
79
  ### Core Types & Signatures
27
80
 
package/compose.yaml ADDED
@@ -0,0 +1,28 @@
1
+ services:
2
+ postgres:
3
+ image: postgres:16-alpine
4
+ environment:
5
+ POSTGRES_DB: scheduler
6
+ POSTGRES_PASSWORD: scheduler
7
+ ports:
8
+ - "5432:5432"
9
+ healthcheck:
10
+ test: ["CMD-SHELL", "pg_isready -U postgres -d scheduler"]
11
+ interval: 5s
12
+ timeout: 5s
13
+ retries: 10
14
+
15
+ scheduler-dashboard:
16
+ build: .
17
+ ports:
18
+ - "9100:9100"
19
+ environment:
20
+ DATABASE_URL: postgres://postgres:scheduler@postgres:5432/scheduler
21
+ SCHEDULER_DIALECT: postgres
22
+ SCHEDULER_NAMESPACE: azlib
23
+ HOST: 0.0.0.0
24
+ PORT: "9100"
25
+ DASHBOARD_TOKEN: ${DASHBOARD_TOKEN}
26
+ depends_on:
27
+ postgres:
28
+ condition: service_healthy
@@ -0,0 +1,542 @@
1
+ import { s as parseSchedule } from "./store-dashboard-Cyf_JILa.mjs";
2
+ import { asBoolean, asRecord, asString } from "@azlib/std";
3
+ import * as http from "node:http";
4
+ import { createReadStream, existsSync, statSync } from "node:fs";
5
+ import { dirname, extname, join, relative, resolve, sep } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { AsyncLocalStorage } from "node:async_hooks";
8
+ import { createMySqlDialectAdapter, createPostgresDialectAdapter, createSqlClientAdapter, createSqlServerDialectAdapter, createSqliteDialectAdapter } from "@azlib/persistence";
9
+ //#region src/dashboard/http-auth.ts
10
+ var DashboardHttpError = class extends Error {
11
+ status;
12
+ constructor(status, message) {
13
+ super(message);
14
+ this.name = "DashboardHttpError";
15
+ this.status = status;
16
+ }
17
+ };
18
+ function isLoopbackHost(host) {
19
+ const normalized = host.trim().toLowerCase();
20
+ return normalized === "127.0.0.1" || normalized === "localhost" || normalized === "::1" || normalized === "[::1]";
21
+ }
22
+ function authorizeDashboardRequest(input) {
23
+ if (!input.token) return;
24
+ if ((Array.isArray(input.authorization) ? input.authorization[0] : input.authorization) !== `Bearer ${input.token}`) throw new DashboardHttpError(401, "Unauthorized");
25
+ }
26
+ function assertDashboardBindSafety(input) {
27
+ if (!isLoopbackHost(input.host) && !input.token) throw new Error("DASHBOARD_TOKEN is required when HOST is not a loopback address");
28
+ }
29
+ //#endregion
30
+ //#region src/dashboard/http-parse.ts
31
+ const DEFAULT_TIMEZONE = "UTC";
32
+ function requiredText(value, field) {
33
+ const text = asString(value)?.trim();
34
+ if (!text) throw new DashboardHttpError(400, `${field} is required.`);
35
+ return text;
36
+ }
37
+ function parseConfig(value) {
38
+ if (value === void 0 || value === null || value === "") return {};
39
+ if (typeof value === "string") try {
40
+ return JSON.parse(value);
41
+ } catch {
42
+ throw new DashboardHttpError(400, "config must be valid JSON.");
43
+ }
44
+ return value;
45
+ }
46
+ function parseScheduleFromRecord(record) {
47
+ const nested = asRecord(record.schedule);
48
+ const scheduleType = asString(record.scheduleType)?.trim() || asString(nested?.scheduleType)?.trim() || "cron";
49
+ if (scheduleType !== "cron" && scheduleType !== "once") throw new DashboardHttpError(400, "scheduleType must be cron or once.");
50
+ const expression = requiredText(record.expression ?? nested?.expression, "expression");
51
+ const timezone = asString(record.timezone)?.trim() || asString(nested?.timezone)?.trim() || DEFAULT_TIMEZONE;
52
+ parseSchedule(scheduleType, expression, timezone);
53
+ return {
54
+ scheduleType,
55
+ expression,
56
+ timezone
57
+ };
58
+ }
59
+ function parseCreateJobBody(body) {
60
+ const record = asRecord(body);
61
+ if (!record) throw new DashboardHttpError(400, "Request body must be a JSON object.");
62
+ return {
63
+ name: requiredText(record.name, "name"),
64
+ handlerKey: requiredText(record.handlerKey, "handlerKey"),
65
+ schedule: parseScheduleFromRecord(record),
66
+ config: parseConfig(record.config),
67
+ enabled: asBoolean(record.enabled) ?? true
68
+ };
69
+ }
70
+ function parseUpdateJobBody(body) {
71
+ const record = asRecord(body);
72
+ if (!record) throw new DashboardHttpError(400, "Request body must be a JSON object.");
73
+ const patch = {};
74
+ if (record.name !== void 0) patch.name = requiredText(record.name, "name");
75
+ if (record.handlerKey !== void 0) patch.handlerKey = requiredText(record.handlerKey, "handlerKey");
76
+ if (record.expression !== void 0 || record.timezone !== void 0 || record.scheduleType !== void 0 || record.schedule !== void 0) patch.schedule = parseScheduleFromRecord(record);
77
+ if (record.config !== void 0) patch.config = parseConfig(record.config);
78
+ if (record.enabled !== void 0) patch.enabled = asBoolean(record.enabled) ?? true;
79
+ return patch;
80
+ }
81
+ //#endregion
82
+ //#region src/dashboard/http-path.ts
83
+ function normalizeDashboardBasePath(basePath) {
84
+ const trimmed = basePath?.trim();
85
+ if (!trimmed || trimmed === "/") return "";
86
+ return (trimmed.startsWith("/") ? trimmed : `/${trimmed}`).replace(/\/+$/, "");
87
+ }
88
+ function stripDashboardBasePath(pathname, basePath) {
89
+ const base = normalizeDashboardBasePath(basePath);
90
+ const path = pathname || "/";
91
+ if (!base) return path.startsWith("/") ? path : `/${path}`;
92
+ if (path === base || path === `${base}/`) return "/";
93
+ if (path.startsWith(`${base}/`)) {
94
+ const rest = path.slice(base.length);
95
+ return rest.startsWith("/") ? rest : `/${rest}`;
96
+ }
97
+ return null;
98
+ }
99
+ function resolveDashboardApiBase(pathname) {
100
+ const trimmed = (pathname.split("?")[0] || "/").replace(/\/index\.html$/i, "/").replace(/\/[^/]+\.[a-z0-9]+$/i, "/").replace(/\/+$/, "");
101
+ return trimmed === "" ? "/api" : `${trimmed}/api`;
102
+ }
103
+ function requestPathname(url, originalUrl) {
104
+ const raw = originalUrl || url || "/";
105
+ try {
106
+ return new URL(raw, "http://127.0.0.1").pathname;
107
+ } catch {
108
+ return raw.split("?")[0] || "/";
109
+ }
110
+ }
111
+ //#endregion
112
+ //#region src/dashboard/public-dir.ts
113
+ function resolveDashboardPublicDir(fromFileUrl) {
114
+ const dir = dirname(fileURLToPath(fromFileUrl));
115
+ const nested = join(dir, "public");
116
+ const sibling = join(dir, "dashboard", "public");
117
+ if (existsSync(join(nested, "index.html"))) return nested;
118
+ if (existsSync(join(sibling, "index.html"))) return sibling;
119
+ return nested;
120
+ }
121
+ //#endregion
122
+ //#region src/dashboard/http-handler.ts
123
+ const MIME_TYPES = {
124
+ ".css": "text/css; charset=utf-8",
125
+ ".html": "text/html; charset=utf-8",
126
+ ".js": "text/javascript; charset=utf-8",
127
+ ".json": "application/json; charset=utf-8",
128
+ ".map": "application/json; charset=utf-8",
129
+ ".svg": "image/svg+xml",
130
+ ".woff2": "font/woff2"
131
+ };
132
+ function sendJson(res, status, body) {
133
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
134
+ res.end(JSON.stringify(body));
135
+ }
136
+ function sendDashboardError(res, error) {
137
+ if (error instanceof DashboardHttpError) {
138
+ sendJson(res, error.status, { error: error.message });
139
+ return;
140
+ }
141
+ const message = error instanceof Error ? error.message : "Unknown error";
142
+ sendJson(res, message.includes("not found") ? 404 : message.includes("Only failed") ? 400 : message.includes("Unknown handlerKey") ? 400 : 500, { error: message });
143
+ }
144
+ function hasParsedBody(req) {
145
+ return Object.prototype.hasOwnProperty.call(req, "body");
146
+ }
147
+ async function readJsonBody(req) {
148
+ if (req.readableEnded && hasParsedBody(req)) return req.body ?? {};
149
+ const chunks = [];
150
+ for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
151
+ if (chunks.length === 0) {
152
+ if (hasParsedBody(req)) return req.body ?? {};
153
+ return {};
154
+ }
155
+ const raw = Buffer.concat(chunks).toString("utf8");
156
+ if (!raw.trim()) return {};
157
+ try {
158
+ return JSON.parse(raw);
159
+ } catch {
160
+ throw new DashboardHttpError(400, "Request body must be valid JSON.");
161
+ }
162
+ }
163
+ function matchPath(pathname, pattern) {
164
+ const pathParts = pathname.split("/").filter(Boolean);
165
+ const patternParts = pattern.split("/").filter(Boolean);
166
+ if (pathParts.length !== patternParts.length) return null;
167
+ const params = {};
168
+ for (let i = 0; i < patternParts.length; i += 1) {
169
+ const expected = patternParts[i] ?? "";
170
+ const actual = pathParts[i] ?? "";
171
+ if (expected.startsWith(":")) {
172
+ params[expected.slice(1)] = decodeURIComponent(actual);
173
+ continue;
174
+ }
175
+ if (expected !== actual) return null;
176
+ }
177
+ return params;
178
+ }
179
+ function servePublicFile(publicDir, urlPath, res) {
180
+ if (!existsSync(publicDir)) return false;
181
+ const pathname = decodeURIComponent(urlPath.split("?")[0] ?? "/");
182
+ const abs = resolve(publicDir, `.${pathname === "/" ? "/index.html" : pathname}`);
183
+ const rel = relative(resolve(publicDir), abs);
184
+ if (rel.startsWith("..") || rel.includes(`..${sep}`)) return false;
185
+ const filePath = existsSync(abs) && statSync(abs).isFile() ? abs : join(publicDir, "index.html");
186
+ if (!existsSync(filePath) || !statSync(filePath).isFile()) return false;
187
+ const type = MIME_TYPES[extname(filePath)] ?? "application/octet-stream";
188
+ res.writeHead(200, { "Content-Type": type });
189
+ createReadStream(filePath).pipe(res);
190
+ return true;
191
+ }
192
+ async function authorizeApi(options, method, pathname, req) {
193
+ if (options.authorize) {
194
+ await options.authorize({
195
+ method,
196
+ pathname,
197
+ authorization: req.headers.authorization
198
+ });
199
+ return;
200
+ }
201
+ authorizeDashboardRequest({
202
+ token: options.token,
203
+ authorization: req.headers.authorization
204
+ });
205
+ }
206
+ async function handleApi(dashboard, method, pathname, req, res) {
207
+ if (method === "GET" && pathname === "/api/health") {
208
+ sendJson(res, 200, await dashboard.getHealth());
209
+ return;
210
+ }
211
+ if (method === "GET" && pathname === "/api/handlers") {
212
+ sendJson(res, 200, { handlers: dashboard.listHandlerKeys() });
213
+ return;
214
+ }
215
+ if (method === "GET" && pathname === "/api/jobs") {
216
+ sendJson(res, 200, { items: await dashboard.listItems() });
217
+ return;
218
+ }
219
+ if (method === "POST" && pathname === "/api/jobs") {
220
+ sendJson(res, 201, await dashboard.createJob(parseCreateJobBody(await readJsonBody(req))));
221
+ return;
222
+ }
223
+ const jobExec = matchPath(pathname, "/api/jobs/:jobId/executions");
224
+ if (jobExec && method === "GET") {
225
+ sendJson(res, 200, { executions: await dashboard.listExecutions(jobExec.jobId ?? "") });
226
+ return;
227
+ }
228
+ const jobAction = matchPath(pathname, "/api/jobs/:jobId/:action");
229
+ if (jobAction && method === "POST") {
230
+ const jobId = jobAction.jobId ?? "";
231
+ if (jobAction.action === "pause") {
232
+ await dashboard.pauseJob(jobId);
233
+ res.writeHead(204);
234
+ res.end();
235
+ return;
236
+ }
237
+ if (jobAction.action === "resume") {
238
+ await dashboard.resumeJob(jobId);
239
+ res.writeHead(204);
240
+ res.end();
241
+ return;
242
+ }
243
+ if (jobAction.action === "run") {
244
+ await dashboard.runJob(jobId);
245
+ res.writeHead(204);
246
+ res.end();
247
+ return;
248
+ }
249
+ }
250
+ const retry = matchPath(pathname, "/api/executions/:executionId/retry");
251
+ if (retry && method === "POST") {
252
+ await dashboard.retryExecution(retry.executionId ?? "");
253
+ res.writeHead(204);
254
+ res.end();
255
+ return;
256
+ }
257
+ const job = matchPath(pathname, "/api/jobs/:jobId");
258
+ if (job) {
259
+ const jobId = job.jobId ?? "";
260
+ if (method === "GET") {
261
+ const item = await dashboard.getJob(jobId);
262
+ if (!item) throw new DashboardHttpError(404, `Job not found: ${jobId}`);
263
+ sendJson(res, 200, item);
264
+ return;
265
+ }
266
+ if (method === "PATCH") {
267
+ await dashboard.updateJob(jobId, parseUpdateJobBody(await readJsonBody(req)));
268
+ res.writeHead(204);
269
+ res.end();
270
+ return;
271
+ }
272
+ if (method === "DELETE") {
273
+ await dashboard.deleteJob(jobId);
274
+ res.writeHead(204);
275
+ res.end();
276
+ return;
277
+ }
278
+ }
279
+ sendJson(res, 404, { error: "Not Found" });
280
+ }
281
+ async function handleSchedulerDashboardRequest(req, res, options) {
282
+ const method = req.method ?? "GET";
283
+ const originalUrl = "originalUrl" in req && typeof req.originalUrl === "string" ? req.originalUrl : void 0;
284
+ const pathname = requestPathname(req.url, originalUrl);
285
+ const basePath = normalizeDashboardBasePath(options.basePath);
286
+ const relative = stripDashboardBasePath(pathname, basePath);
287
+ if (relative === null) return false;
288
+ if (method === "GET" && basePath && pathname === basePath) {
289
+ res.writeHead(302, { Location: `${basePath}/` });
290
+ res.end();
291
+ return true;
292
+ }
293
+ const publicDir = options.publicDir ?? resolveDashboardPublicDir(import.meta.url);
294
+ try {
295
+ if (method === "GET" && relative === "/health") {
296
+ res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
297
+ res.end("ok");
298
+ return true;
299
+ }
300
+ if (relative === "/api" || relative.startsWith("/api/")) {
301
+ await authorizeApi(options, method, relative, req);
302
+ await handleApi(options.dashboard, method, relative, req, res);
303
+ return true;
304
+ }
305
+ if (method === "GET" && servePublicFile(publicDir, relative, res)) return true;
306
+ res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
307
+ res.end("Not Found");
308
+ return true;
309
+ } catch (error) {
310
+ sendDashboardError(res, error);
311
+ return true;
312
+ }
313
+ }
314
+ function createSchedulerDashboardNodeHandler(options) {
315
+ return (req, res, next) => {
316
+ handleSchedulerDashboardRequest(req, res, options).then((handled) => {
317
+ if (!handled) next?.();
318
+ }).catch((error) => {
319
+ if (next) {
320
+ next(error);
321
+ return;
322
+ }
323
+ if (!res.headersSent) sendDashboardError(res, error);
324
+ });
325
+ };
326
+ }
327
+ //#endregion
328
+ //#region src/dashboard/http-server.ts
329
+ function createSchedulerDashboardServer(options) {
330
+ const port = options.port ?? 9100;
331
+ const host = options.host ?? "127.0.0.1";
332
+ const handler = createSchedulerDashboardNodeHandler({
333
+ ...options,
334
+ publicDir: options.publicDir ?? resolveDashboardPublicDir(import.meta.url)
335
+ });
336
+ const server = http.createServer((req, res) => {
337
+ handler(req, res, () => {
338
+ if (!res.headersSent) {
339
+ res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
340
+ res.end("Not Found");
341
+ }
342
+ });
343
+ });
344
+ return {
345
+ get port() {
346
+ return port;
347
+ },
348
+ get host() {
349
+ return host;
350
+ },
351
+ listen() {
352
+ return new Promise((resolveListen, reject) => {
353
+ server.once("error", reject);
354
+ server.listen(port, host, () => {
355
+ server.off("error", reject);
356
+ resolveListen();
357
+ });
358
+ });
359
+ },
360
+ close() {
361
+ return new Promise((resolveClose, reject) => {
362
+ server.close((err) => err ? reject(err) : resolveClose());
363
+ });
364
+ }
365
+ };
366
+ }
367
+ //#endregion
368
+ //#region src/dashboard/sql-drivers.ts
369
+ function rewriteQuestionParams(sql, style) {
370
+ if (style === "?") return sql;
371
+ let index = 0;
372
+ return sql.replaceAll("?", () => {
373
+ index += 1;
374
+ return style === "$n" ? `$${index}` : `@p${index}`;
375
+ });
376
+ }
377
+ function inferDashboardDialect(databaseUrl) {
378
+ const scheme = databaseUrl.split(":")[0]?.toLowerCase() ?? "";
379
+ if (scheme === "postgres" || scheme === "postgresql") return "postgres";
380
+ if (scheme === "mysql" || scheme === "mariadb") return "mysql";
381
+ if (scheme === "mssql" || scheme === "sqlserver") return "mssql";
382
+ if (scheme === "sqlite" || scheme === "file") return "sqlite";
383
+ return "postgres";
384
+ }
385
+ function dialectAdapterFor(dialect) {
386
+ if (dialect === "mysql") return createMySqlDialectAdapter();
387
+ if (dialect === "sqlite") return createSqliteDialectAdapter();
388
+ if (dialect === "mssql") return createSqlServerDialectAdapter();
389
+ return createPostgresDialectAdapter();
390
+ }
391
+ function sqlitePathFromUrl(databaseUrl) {
392
+ if (databaseUrl.startsWith("file:")) return databaseUrl.slice(5);
393
+ if (databaseUrl.startsWith("sqlite:")) return databaseUrl.slice(7);
394
+ return databaseUrl;
395
+ }
396
+ function bindMssqlParams(request, params) {
397
+ (params ?? []).forEach((value, index) => {
398
+ request.input(`p${index + 1}`, value);
399
+ });
400
+ }
401
+ function createPgDriver(pool) {
402
+ const txStore = new AsyncLocalStorage();
403
+ const active = () => txStore.getStore() ?? pool;
404
+ const runQuery = async (sql, params) => active().query(rewriteQuestionParams(sql, "$n"), [...params ?? []]);
405
+ return {
406
+ query: async (sql, params) => {
407
+ return (await runQuery(sql, params)).rows;
408
+ },
409
+ execute: async (sql, params) => {
410
+ await runQuery(sql, params);
411
+ },
412
+ transaction: async (run) => {
413
+ if (txStore.getStore()) return run();
414
+ const conn = await pool.connect();
415
+ try {
416
+ await conn.query("BEGIN");
417
+ const result = await txStore.run(conn, run);
418
+ await conn.query("COMMIT");
419
+ return result;
420
+ } catch (error) {
421
+ await conn.query("ROLLBACK");
422
+ throw error;
423
+ } finally {
424
+ conn.release();
425
+ }
426
+ }
427
+ };
428
+ }
429
+ function createMysqlDriver(pool) {
430
+ const txStore = new AsyncLocalStorage();
431
+ const active = () => txStore.getStore() ?? pool;
432
+ return {
433
+ query: async (sql, params) => {
434
+ const [rows] = await active().execute(sql, [...params ?? []]);
435
+ return rows;
436
+ },
437
+ execute: async (sql, params) => {
438
+ await active().execute(sql, [...params ?? []]);
439
+ },
440
+ transaction: async (run) => {
441
+ if (txStore.getStore()) return run();
442
+ const conn = await pool.getConnection();
443
+ try {
444
+ await conn.beginTransaction();
445
+ const result = await txStore.run(conn, run);
446
+ await conn.commit();
447
+ return result;
448
+ } catch (error) {
449
+ await conn.rollback();
450
+ throw error;
451
+ } finally {
452
+ conn.release();
453
+ }
454
+ }
455
+ };
456
+ }
457
+ async function createDashboardSqlDriver(databaseUrl, dialect) {
458
+ if (dialect === "postgres") {
459
+ const pg = await import("pg");
460
+ const Pool = pg.Pool ?? pg.default?.Pool;
461
+ if (!Pool) throw new Error("The pg package is required for postgres dashboards.");
462
+ return createPgDriver(new Pool({ connectionString: databaseUrl }));
463
+ }
464
+ if (dialect === "mysql") {
465
+ const mysql = await import("mysql2/promise");
466
+ const createPool = mysql.createPool ?? mysql.default?.createPool;
467
+ if (!createPool) throw new Error("The mysql2 package is required for mysql dashboards.");
468
+ return createMysqlDriver(createPool(databaseUrl));
469
+ }
470
+ if (dialect === "sqlite") {
471
+ const Database = (await import("better-sqlite3")).default;
472
+ if (!Database) throw new Error("The better-sqlite3 package is required for sqlite dashboards.");
473
+ const db = new Database(sqlitePathFromUrl(databaseUrl));
474
+ return {
475
+ query: async (sql, params) => db.prepare(sql).all(...params ?? []),
476
+ execute: async (sql, params) => {
477
+ db.prepare(sql).run(...params ?? []);
478
+ },
479
+ transaction: async (run) => run()
480
+ };
481
+ }
482
+ const mssql = await import("mssql");
483
+ const connect = mssql.connect ?? mssql.default?.connect;
484
+ if (!connect) throw new Error("The mssql package is required for mssql dashboards.");
485
+ const pool = await connect(databaseUrl);
486
+ return {
487
+ query: async (sql, params) => {
488
+ const request = pool.request();
489
+ bindMssqlParams(request, params);
490
+ return (await request.query(rewriteQuestionParams(sql, "@pn"))).recordset;
491
+ },
492
+ execute: async (sql, params) => {
493
+ const request = pool.request();
494
+ bindMssqlParams(request, params);
495
+ await request.query(rewriteQuestionParams(sql, "@pn"));
496
+ },
497
+ transaction: async (run) => run()
498
+ };
499
+ }
500
+ function createDashboardPersistenceConfig(input) {
501
+ return {
502
+ client: createSqlClientAdapter(input.driver),
503
+ dialect: dialectAdapterFor(input.dialect),
504
+ namespace: input.namespace
505
+ };
506
+ }
507
+ //#endregion
508
+ //#region src/dashboard/cli-config.ts
509
+ function parsePort(value, fallback) {
510
+ if (!value) return fallback;
511
+ const port = Number(value);
512
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) throw new Error(`Invalid PORT: ${value}`);
513
+ return port;
514
+ }
515
+ function parseDialect(value, databaseUrl) {
516
+ const explicit = value?.trim().toLowerCase();
517
+ if (!explicit) return inferDashboardDialect(databaseUrl);
518
+ if (explicit === "postgres" || explicit === "mysql" || explicit === "sqlite" || explicit === "mssql") return explicit;
519
+ throw new Error(`Invalid SCHEDULER_DIALECT: ${value}. Use postgres, mysql, sqlite, or mssql.`);
520
+ }
521
+ function parseDashboardCliEnv(env) {
522
+ const databaseUrl = asString(env.DATABASE_URL)?.trim();
523
+ if (!databaseUrl) throw new Error("DATABASE_URL is required");
524
+ const host = asString(env.HOST)?.trim() || "127.0.0.1";
525
+ const token = asString(env.DASHBOARD_TOKEN)?.trim() || void 0;
526
+ assertDashboardBindSafety({
527
+ host,
528
+ token
529
+ });
530
+ return {
531
+ databaseUrl,
532
+ dialect: parseDialect(env.SCHEDULER_DIALECT, databaseUrl),
533
+ namespace: asString(env.SCHEDULER_NAMESPACE)?.trim() || "azlib",
534
+ port: parsePort(env.PORT, 9100),
535
+ host,
536
+ token
537
+ };
538
+ }
539
+ //#endregion
540
+ export { createSchedulerDashboardNodeHandler as a, normalizeDashboardBasePath as c, DashboardHttpError as d, createSchedulerDashboardServer as i, resolveDashboardApiBase as l, createDashboardPersistenceConfig as n, handleSchedulerDashboardRequest as o, createDashboardSqlDriver as r, resolveDashboardPublicDir as s, parseDashboardCliEnv as t, stripDashboardBasePath as u };
541
+
542
+ //# sourceMappingURL=cli-config-6u8AzSdw.mjs.map