bunqueue-dashboard 0.0.31 → 0.0.32

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 (67) hide show
  1. package/agent/db.ts +163 -22
  2. package/agent/dbQueryWorker.ts +14 -6
  3. package/agent/index.ts +4 -1
  4. package/agent/manager.ts +97 -12
  5. package/agent/server.ts +7 -1
  6. package/dist/.vite/manifest.json +76 -75
  7. package/dist/assets/AddJob-Dvpp--yq.js +3 -0
  8. package/dist/assets/{Alerts-70bxf-PT.js → Alerts-CR9jgCCs.js} +1 -1
  9. package/dist/assets/Benchmark-CkL-Ee-M.js +1 -0
  10. package/dist/assets/BulkAddJobs-wI6cRZnX.js +5 -0
  11. package/dist/assets/{CopilotPanel-DZUGIf1q.js → CopilotPanel-DPZV9opm.js} +3 -3
  12. package/dist/assets/{Cron-ltjSoTjj.js → Cron-gWVkYWad.js} +1 -1
  13. package/dist/assets/CronManager-BvfW219u.js +1 -0
  14. package/dist/assets/Database-D2T_ZIGA.js +3 -0
  15. package/dist/assets/Diagnostics-C2goqq5h.js +1 -0
  16. package/dist/assets/{Dlq-fZAKwQoC.js → Dlq-Q4TmmZrK.js} +1 -1
  17. package/dist/assets/{DlqControl-eTrrQCrn.js → DlqControl-C5BfE7Gq.js} +1 -1
  18. package/dist/assets/{DlqPro-CF79339e.js → DlqPro-ClPNmw-X.js} +1 -1
  19. package/dist/assets/Flows-DbhMbvSG.js +1 -0
  20. package/dist/assets/JobInspector-CO_zKjSX.js +2 -0
  21. package/dist/assets/{Jobs-DEqAc1A5.js → Jobs-D2rDHPM_.js} +1 -1
  22. package/dist/assets/JobsPro-Drdgdj3s.js +1 -0
  23. package/dist/assets/{Logs-DBTukPIX.js → Logs-DjwGuRLi.js} +1 -1
  24. package/dist/assets/{LogsPro-Wl_e6hZM.js → LogsPro-7uTBjPWX.js} +1 -1
  25. package/dist/assets/{McpServer-CnWJsKw7.js → McpServer-DAklQDB5.js} +1 -1
  26. package/dist/assets/{Metrics-DzeIhNL-.js → Metrics-Dup9Zinh.js} +1 -1
  27. package/dist/assets/{MetricsPro-O9eVJSH0.js → MetricsPro-PP3TymeP.js} +1 -1
  28. package/dist/assets/{Overview-Bnu7rWqt.js → Overview-C7RCDE6r.js} +1 -1
  29. package/dist/assets/{Pagination-D4ki-pGz.js → Pagination-B9JDi5MI.js} +1 -1
  30. package/dist/assets/QueueActions-DJTw0h2g.js +1 -0
  31. package/dist/assets/{QueueControl-DKqEXnkM.js → QueueControl-CxKjUjF-.js} +1 -1
  32. package/dist/assets/{QueueDetail-DLRow04B.js → QueueDetail-bf2n-r2h.js} +1 -1
  33. package/dist/assets/{QueueDetailPro-BYmOVd4T.js → QueueDetailPro-C-XLWFBa.js} +1 -1
  34. package/dist/assets/{Queues-CoyjRFN7.js → Queues-CMQW89J9.js} +1 -1
  35. package/dist/assets/{QueuesOverview-BeWdJpKi.js → QueuesOverview-x7-akDzf.js} +1 -1
  36. package/dist/assets/{S3Backup-BaLFgl9d.js → S3Backup-1jAySC9R.js} +1 -1
  37. package/dist/assets/{S3BackupPro-DJB4oWgz.js → S3BackupPro-BG_0OHW7.js} +1 -1
  38. package/dist/assets/{ServerControl-_0lVB33E.js → ServerControl-DohTB--h.js} +3 -3
  39. package/dist/assets/{Settings-zKFJTtnq.js → Settings-CnS5PjNe.js} +1 -1
  40. package/dist/assets/{Usage-CKGkvl0j.js → Usage-C3H0hMSA.js} +1 -1
  41. package/dist/assets/{UsagePro-B-TJ6fp4.js → UsagePro-CdnQkP9o.js} +1 -1
  42. package/dist/assets/Webhooks-CAwVmIEZ.js +1 -0
  43. package/dist/assets/{Workers-jKhhXl3W.js → Workers-lvujKZwF.js} +1 -1
  44. package/dist/assets/{WorkersPro-mvY5VX8I.js → WorkersPro-CIJKl7U1.js} +1 -1
  45. package/dist/assets/{connectionStore-Ci04lJmR.js → connectionStore-DO6xQY7h.js} +1 -1
  46. package/dist/assets/{exportFile-tdUeW5m5.js → exportFile-C7xhE8Yh.js} +1 -1
  47. package/dist/assets/{index-DWV3tgrk.css → index-DcVOpnSj.css} +1 -1
  48. package/dist/assets/index-r1ZMLIZ9.js +8 -0
  49. package/dist/assets/{install-DhTYJCUC.js → install-BIVfix28.js} +1 -1
  50. package/dist/assets/useThroughputSeries-CVKzWzdv.js +1 -0
  51. package/dist/index.html +3 -3
  52. package/package.json +1 -1
  53. package/scripts/embedded.gen.ts +112 -112
  54. package/scripts/serve.ts +299 -98
  55. package/dist/assets/AddJob-CAhdg38n.js +0 -3
  56. package/dist/assets/Benchmark-CFZ3WCvj.js +0 -1
  57. package/dist/assets/BulkAddJobs-BzgzpGg_.js +0 -5
  58. package/dist/assets/CronManager-BcFALDeT.js +0 -1
  59. package/dist/assets/Database-CV2yt5O2.js +0 -3
  60. package/dist/assets/Diagnostics-D-EK4GEi.js +0 -1
  61. package/dist/assets/Flows-Ba8G7mcC.js +0 -1
  62. package/dist/assets/JobInspector--d_8ca9p.js +0 -2
  63. package/dist/assets/JobsPro-BcaokZIf.js +0 -1
  64. package/dist/assets/QueueActions-DHoSkWRz.js +0 -1
  65. package/dist/assets/Webhooks-C3zmvY-_.js +0 -1
  66. package/dist/assets/index-BOcegTHa.js +0 -8
  67. package/dist/assets/useThroughputSeries-Chp5OLx3.js +0 -1
package/scripts/serve.ts CHANGED
@@ -13,92 +13,100 @@
13
13
  * SPA finds the agent regardless of AGENT_PORT and even from a remote
14
14
  * browser, where loopback :6800 would be unreachable.
15
15
  *
16
+ * Control-plane exposure rule (the agent can spawn processes):
17
+ * - Loopback bind (the default): /agent/* is bridged, and the loopback :6800
18
+ * listener keeps its Host allowlist (DNS-rebinding defense).
19
+ * - Non-loopback bind (BIND_ADDR=0.0.0.0): the bridge would hand the whole
20
+ * LAN an unauthenticated process spawner (the agent's Origin gate lets an
21
+ * Origin-less curl through by design), so it is REFUSED with 403 unless the
22
+ * operator opts in with AGENT_TOKEN (recommended — it gates every mutation)
23
+ * or AGENT_ALLOW_REMOTE_CONTROL=1 (explicit, unauthenticated).
24
+ *
16
25
  * Env: PORT (dashboard, default 8080) · BIND_ADDR (default 127.0.0.1) ·
17
- * BUNQUEUE_URL · AGENT_PORT · AGENT_ALLOWED_ORIGINS · AGENT_TOKEN ·
18
- * BUNQUEUE_START_CMD · HTTP_PORT · TCP_PORT · BUNQUEUE_DATA_PATH ·
19
- * LOG_LEVEL (pino level, default info)
26
+ * BUNQUEUE_URL · AGENT_PORT · AGENT_ALLOWED_ORIGINS · AGENT_ALLOWED_HOSTS ·
27
+ * AGENT_TOKEN · AGENT_ALLOW_REMOTE_CONTROL · TRUST_PROXY · BUNQUEUE_START_CMD ·
28
+ * HTTP_PORT · TCP_PORT · BUNQUEUE_DATA_PATH · LOG_LEVEL (pino level, info)
20
29
  */
21
30
  import { logger } from '../agent/logger';
22
- import { ProcessManager } from '../agent/manager';
23
31
  import { setQueryWorkerUrl } from '../agent/db';
24
32
  import {
25
33
  createFetchHandler,
26
34
  isHostAllowed,
35
+ isOriginAllowed,
27
36
  resolveAllowedHosts,
28
37
  resolveAllowedOrigins,
29
38
  } from '../agent/server';
30
- import { ASSETS } from './embedded.gen';
31
-
32
- // Bun emits secondary TypeScript entrypoints under /$bunfs/root as JavaScript.
33
- // Point db.ts at that embedded path in a compiled executable; when this npm bin
34
- // runs from source, use the real TypeScript module beside agent/db.ts.
35
- const compiled = import.meta.url.includes('/$bunfs/');
36
- setQueryWorkerUrl(
37
- compiled
38
- ? new URL('/$bunfs/root/agent/dbQueryWorker.js', 'file:///').href
39
- : new URL('../agent/dbQueryWorker.ts', import.meta.url).href
40
- );
41
-
42
- const PORT = Number(process.env.PORT) || 8080;
43
- // Bind loopback by default: the /api proxy forwards to bunqueue's admin API, so
44
- // listening on all interfaces would expose it to the whole network. Set
45
- // BIND_ADDR=0.0.0.0 for direct LAN access (e.g. no reverse proxy in front).
46
- const HOST = process.env.BIND_ADDR || '127.0.0.1';
47
- const API = (process.env.BUNQUEUE_URL || 'http://localhost:6790').replace(/\/$/, '');
48
- const AGENT_PORT = Number(process.env.AGENT_PORT) || 6800;
49
-
50
- // Control agent — loopback only, allowlisted CORS; the origins this binary
51
- // serves the dashboard from are allowed automatically.
52
- const allowedOrigins = Array.from(
53
- new Set([
54
- ...resolveAllowedOrigins(),
55
- `http://localhost:${PORT}`,
56
- `http://127.0.0.1:${PORT}`,
57
- ])
58
- );
59
-
60
- // DNS-rebinding defense (see agent/server.ts). Only enforced when bound to
61
- // loopback — the common "looks safe" case where a rebound page could reach the
62
- // /api proxy and /agent inspector over same-origin GETs. When the user binds a
63
- // non-loopback interface (BIND_ADDR=0.0.0.0) they opted into network exposure,
64
- // where a fixed host allowlist would break legitimate LAN-IP access; leave it
65
- // off there (configure a reverse proxy / AGENT_ALLOWED_HOSTS instead).
66
- const loopbackBind = HOST === '127.0.0.1' || HOST === '::1' || HOST === 'localhost';
67
- const originHosts = allowedOrigins
68
- .map((o) => {
69
- try {
70
- return new URL(o).hostname;
71
- } catch {
72
- return '';
73
- }
74
- })
75
- .filter(Boolean);
76
- const allowedHosts = loopbackBind ? resolveAllowedHosts(process.env, originHosts) : undefined;
77
-
78
- const mgr = new ProcessManager();
79
- const agentHandle = createFetchHandler(mgr, {
80
- allowedOrigins,
81
- allowedHosts,
82
- token: process.env.AGENT_TOKEN || undefined,
83
- });
84
- Bun.serve({ port: AGENT_PORT, hostname: '127.0.0.1', fetch: agentHandle });
85
-
86
- // index.html with the runtime agent base injected, prepared once at startup.
87
- // The SPA's lib/bq.ts reads window.__BUNQUEUE_AGENT_URL__ before its baked-in
88
- // default, so Server Control works whatever AGENT_PORT is — the /agent/*
89
- // route below forwards to the in-process agent handler.
90
- const INDEX_HTML = (await Bun.file(ASSETS['/index.html']).text()).replace(
91
- '</head>',
92
- "<script>window.__BUNQUEUE_AGENT_URL__='/agent'</script></head>"
93
- );
94
- const indexResponse = () =>
95
- new Response(INDEX_HTML, { headers: { 'content-type': 'text/html; charset=utf-8' } });
96
-
97
- // Dashboard + /api proxy + same-origin /agent proxy.
98
- Bun.serve({
99
- port: PORT,
100
- hostname: HOST,
101
- async fetch(req) {
39
+
40
+ /** Hostnames that mean "only this machine can reach the listener". */
41
+ export function isLoopbackBind(host: string): boolean {
42
+ return host === '127.0.0.1' || host === '::1' || host === 'localhost';
43
+ }
44
+
45
+ /**
46
+ * May the process-spawning control plane be reachable over the network?
47
+ * Loopback always yes; a non-loopback bind requires an explicit opt-in.
48
+ */
49
+ export function remoteControlEnabled(
50
+ loopbackBind: boolean,
51
+ env: Record<string, string | undefined> = process.env
52
+ ): boolean {
53
+ if (loopbackBind) return true;
54
+ return Boolean(env.AGENT_TOKEN) || env.AGENT_ALLOW_REMOTE_CONTROL === '1';
55
+ }
56
+
57
+ /**
58
+ * Build the inner agent URL from the bridged path. `new URL(rest, base)` throws
59
+ * on a path like `//x:y/z` (it reads `//` as an authority); assigning .pathname
60
+ * never reinterprets it, so a hostile path can't crash the handler.
61
+ */
62
+ export function agentSubUrl(pathname: string, search: string): URL {
63
+ const rest = pathname.slice('/agent'.length) || '/';
64
+ const sub = new URL('http://agent.internal');
65
+ sub.pathname = rest.startsWith('/') ? rest : `/${rest}`;
66
+ sub.search = search;
67
+ return sub;
68
+ }
69
+
70
+ export interface ServeHandlerOptions {
71
+ /** bunqueue base URL the /api prefix proxies to (no trailing slash). */
72
+ api: string;
73
+ /** index.html with the agent base already injected. */
74
+ indexHtml: string;
75
+ /** embedded dist assets: request path → on-disk path. */
76
+ assets: Record<string, string>;
77
+ /** in-process control agent handler. */
78
+ agentHandle: (req: Request) => Response | Promise<Response>;
79
+ allowedOrigins: string[];
80
+ allowedHosts?: string[];
81
+ /** false → /agent/* is refused (non-loopback bind without opt-in). */
82
+ agentBridge: boolean;
83
+ /**
84
+ * TRUST_PROXY=1 — a reverse proxy in front of us owns X-Forwarded-Host, so it
85
+ * may be believed. Off by default: the header is otherwise client-settable
86
+ * and would let any direct caller declare itself same-origin.
87
+ */
88
+ trustProxy?: boolean;
89
+ }
90
+
91
+ /**
92
+ * The dashboard listener: static assets + /api proxy + same-origin /agent
93
+ * bridge. Factored out of the Bun.serve call so the policy is unit-testable.
94
+ */
95
+ export function createServeHandler(opts: ServeHandlerOptions) {
96
+ const {
97
+ api,
98
+ indexHtml,
99
+ assets,
100
+ agentHandle,
101
+ allowedOrigins,
102
+ allowedHosts,
103
+ agentBridge,
104
+ trustProxy = false,
105
+ } = opts;
106
+ const indexResponse = () =>
107
+ new Response(indexHtml, { headers: { 'content-type': 'text/html; charset=utf-8' } });
108
+
109
+ return async function handle(req: Request): Promise<Response> {
102
110
  const url = new URL(req.url);
103
111
 
104
112
  // DNS-rebinding defense across every route (/api proxy, /agent, assets):
@@ -108,25 +116,88 @@ Bun.serve({
108
116
  return new Response('Host not allowed', { status: 403 });
109
117
  }
110
118
 
119
+ // A request whose Origin is the origin this listener serves from is by
120
+ // definition not the cross-site case the allowlist exists for. It is what a
121
+ // LAN browser sends (http://<lan-ip>:PORT), which no static allowlist can
122
+ // predict — treat it as allowed everywhere below.
123
+ //
124
+ // Compared by HOST, not by full origin: this listener only ever speaks
125
+ // plain http, so behind a TLS-terminating reverse proxy the browser sends
126
+ // `https://dash.example.com` while req.url reads `http://dash.example.com`.
127
+ // A full-origin compare would 403 every mutation on a proxied deployment
128
+ // while read-only GETs (which carry no Origin) kept working — a dashboard
129
+ // that looks healthy and fails on click. The host is the part that
130
+ // identifies a cross-site page (its Origin carries its OWN host), so it is
131
+ // the part worth comparing. x-forwarded-host is honoured for proxies that
132
+ // rewrite Host.
133
+ const origin = req.headers.get('origin');
134
+ let originHost = '';
135
+ try {
136
+ originHost = origin ? new URL(origin).host.toLowerCase() : '';
137
+ } catch {
138
+ originHost = ''; // unparseable Origin — treat as cross-site
139
+ }
140
+ // X-Forwarded-Host is attacker-controlled unless something in front of us
141
+ // is guaranteed to overwrite it: a direct caller can send
142
+ // `Origin: https://evil.example` + `x-forwarded-host: evil.example` and
143
+ // declare ITSELF same-origin. So it is consulted only when the operator
144
+ // sets TRUST_PROXY=1, which asserts a reverse proxy owns that header.
145
+ // Without it, a proxy that preserves Host still works (the Host compare
146
+ // below covers it); only a Host-REWRITING proxy needs the opt-in.
147
+ const fwd = trustProxy ? req.headers.get('x-forwarded-host')?.split(',') : undefined;
148
+ const forwardedHost = fwd?.[fwd.length - 1]?.trim().toLowerCase();
149
+ const sameOrigin =
150
+ originHost !== '' &&
151
+ (originHost === url.host.toLowerCase() || originHost === forwardedHost);
152
+
111
153
  // Same-origin bridge to the control agent: strip the /agent prefix and
112
154
  // hand the request to the in-process agent handler (no loopback hop).
113
155
  // The agent's own Origin allowlist + optional AGENT_TOKEN still apply —
114
156
  // this changes reachability, not authorization.
115
157
  if (url.pathname === '/agent' || url.pathname.startsWith('/agent/')) {
116
- const sub = new URL(url.pathname.slice('/agent'.length) || '/', 'http://agent.internal');
117
- sub.search = url.search;
118
- return agentHandle(new Request(sub.href, req));
158
+ if (!agentBridge) {
159
+ return Response.json(
160
+ {
161
+ ok: false,
162
+ error:
163
+ 'Control agent disabled on a non-loopback bind. Set AGENT_TOKEN (recommended) or AGENT_ALLOW_REMOTE_CONTROL=1 to expose it.',
164
+ },
165
+ { status: 403 }
166
+ );
167
+ }
168
+ const sub = agentSubUrl(url.pathname, url.search);
169
+ const headers = new Headers(req.headers);
170
+ // Drop a same-origin Origin the agent's static allowlist cannot know
171
+ // (a LAN IP / hostname alias). Loopback origins are already allowlisted,
172
+ // so they are forwarded untouched and CORS behaviour is unchanged.
173
+ if (sameOrigin && origin && !isOriginAllowed(origin, allowedOrigins)) headers.delete('origin');
174
+ return agentHandle(new Request(sub.href, { method: req.method, headers, body: req.body }));
119
175
  }
120
176
 
121
177
  // Same-origin proxy to the bunqueue server (mirrors the Vite dev proxy).
122
178
  if (url.pathname === '/api' || url.pathname.startsWith('/api/')) {
123
- const target = API + (url.pathname.slice(4) || '/') + url.search;
124
- const res = await fetch(target, {
125
- method: req.method,
126
- headers: req.headers,
127
- body: req.body,
128
- redirect: 'manual',
129
- });
179
+ // The proxy talks to bunqueue's admin API, so it needs the same drive-by
180
+ // CSRF gate as the agent: a cross-site page must not reach it.
181
+ if (!sameOrigin && !isOriginAllowed(origin, allowedOrigins)) {
182
+ return Response.json({ ok: false, error: 'Origin not allowed' }, { status: 403 });
183
+ }
184
+ const target = api + (url.pathname.slice(4) || '/') + url.search;
185
+ let res: Response;
186
+ try {
187
+ res = await fetch(target, {
188
+ method: req.method,
189
+ headers: req.headers,
190
+ body: req.body,
191
+ redirect: 'manual',
192
+ });
193
+ } catch (err) {
194
+ // bunqueue not running / wrong BUNQUEUE_URL: answer in the shape the
195
+ // dashboard parses instead of letting Bun render an HTML error page.
196
+ return Response.json(
197
+ { ok: false, error: `bunqueue unreachable at ${api}: ${(err as Error).message}` },
198
+ { status: 502 }
199
+ );
200
+ }
130
201
  // Bun's fetch advertises accept-encoding upstream and transparently
131
202
  // DECOMPRESSES the body, but leaves the upstream headers intact. If the
132
203
  // bunqueue server sits behind any gzip-compressing proxy, forwarding
@@ -145,18 +216,148 @@ Bun.serve({
145
216
  // index.html (direct or via fallback) is served from the injected copy.
146
217
  const key = url.pathname === '/' ? '/index.html' : url.pathname;
147
218
  if (key === '/index.html') return indexResponse();
148
- const asset = ASSETS[key];
219
+ const asset = assets[key];
149
220
  if (asset) return new Response(Bun.file(asset));
150
221
  if (url.pathname.startsWith('/assets/')) return new Response('Not found', { status: 404 });
151
222
  return indexResponse();
152
- },
153
- });
154
-
155
- logger.info(
156
- {
157
- dashboard: `http://${HOST}:${PORT}`,
158
- apiProxy: API,
159
- agent: `http://127.0.0.1:${AGENT_PORT}/control`,
160
- },
161
- 'bunqueue dashboard (standalone) ready'
162
- );
223
+ };
224
+ }
225
+
226
+ async function main(): Promise<void> {
227
+ // Bun emits secondary TypeScript entrypoints under /$bunfs/root as JavaScript.
228
+ // Point db.ts at that embedded path in a compiled executable; when this npm bin
229
+ // runs from source, use the real TypeScript module beside agent/db.ts.
230
+ const compiled = import.meta.url.includes('/$bunfs/');
231
+ setQueryWorkerUrl(
232
+ compiled
233
+ ? new URL('/$bunfs/root/agent/dbQueryWorker.js', 'file:///').href
234
+ : new URL('../agent/dbQueryWorker.ts', import.meta.url).href
235
+ );
236
+
237
+ const PORT = Number(process.env.PORT) || 8080;
238
+ // Bind loopback by default: the /api proxy forwards to bunqueue's admin API, so
239
+ // listening on all interfaces would expose it to the whole network. Set
240
+ // BIND_ADDR=0.0.0.0 for direct LAN access (e.g. no reverse proxy in front).
241
+ const HOST = process.env.BIND_ADDR || '127.0.0.1';
242
+ const API = (process.env.BUNQUEUE_URL || 'http://localhost:6790').replace(/\/$/, '');
243
+ const AGENT_PORT = Number(process.env.AGENT_PORT) || 6800;
244
+
245
+ // Control agent — loopback only, allowlisted CORS; the origins this binary
246
+ // serves the dashboard from are allowed automatically.
247
+ const allowedOrigins = Array.from(
248
+ new Set([
249
+ ...resolveAllowedOrigins(),
250
+ `http://localhost:${PORT}`,
251
+ `http://127.0.0.1:${PORT}`,
252
+ ])
253
+ );
254
+
255
+ // DNS-rebinding defense (see agent/server.ts). Always enforced on the loopback
256
+ // :6800 listener. On the public dashboard listener it is only enforced for a
257
+ // loopback bind — when the user binds a non-loopback interface
258
+ // (BIND_ADDR=0.0.0.0) a fixed host allowlist would break legitimate LAN-IP
259
+ // access, and the control plane there is gated by remoteControlEnabled()
260
+ // instead (AGENT_TOKEN / AGENT_ALLOW_REMOTE_CONTROL).
261
+ const loopbackBind = isLoopbackBind(HOST);
262
+ const originHosts = allowedOrigins
263
+ .map((o) => {
264
+ try {
265
+ return new URL(o).hostname;
266
+ } catch {
267
+ return '';
268
+ }
269
+ })
270
+ .filter(Boolean);
271
+ const agentHosts = resolveAllowedHosts(process.env, originHosts);
272
+ const allowedHosts = loopbackBind ? agentHosts : undefined;
273
+
274
+ // Imported here rather than at module scope: this file's exported policy
275
+ // helpers are unit-tested, and a top-level import would pull the whole
276
+ // ProcessManager into every test that touches them — which, besides being
277
+ // wasteful, makes Bun attribute a barely-executed copy of agent/manager.ts to
278
+ // the coverage report and hides that module's real coverage.
279
+ const { ProcessManager } = await import('../agent/manager');
280
+ const mgr = new ProcessManager();
281
+ const token = process.env.AGENT_TOKEN || undefined;
282
+ // Two handlers, same manager: the loopback :6800 listener keeps the Host gate
283
+ // unconditionally (it is always reached as localhost/127.0.0.1), while the
284
+ // bridged one sees the dashboard client's Host and follows `allowedHosts`.
285
+ const agentHandle = createFetchHandler(mgr, { allowedOrigins, allowedHosts, token });
286
+ const loopbackAgentHandle = createFetchHandler(mgr, {
287
+ allowedOrigins,
288
+ allowedHosts: agentHosts,
289
+ token,
290
+ });
291
+ // `error` is a backstop: without it an unexpected throw renders Bun's HTML
292
+ // error page (with a stack trace) to the client instead of a plain 500.
293
+ const onError = () => new Response('Internal error', { status: 500 });
294
+ Bun.serve({
295
+ port: AGENT_PORT,
296
+ hostname: '127.0.0.1',
297
+ fetch: loopbackAgentHandle,
298
+ error: onError,
299
+ });
300
+
301
+ const agentBridge = remoteControlEnabled(loopbackBind, process.env);
302
+ if (!agentBridge) {
303
+ logger.warn(
304
+ { bind: HOST },
305
+ 'non-loopback bind without AGENT_TOKEN / AGENT_ALLOW_REMOTE_CONTROL=1 — /agent is disabled (403)'
306
+ );
307
+ }
308
+
309
+ // index.html with the runtime agent base injected, prepared once at startup.
310
+ // The SPA's lib/bq.ts reads window.__BUNQUEUE_AGENT_URL__ before its baked-in
311
+ // default, so Server Control works whatever AGENT_PORT is — the /agent/*
312
+ // route below forwards to the in-process agent handler.
313
+ const { ASSETS } = await import('./embedded.gen');
314
+ const indexHtml = (await Bun.file(ASSETS['/index.html']).text()).replace(
315
+ '</head>',
316
+ "<script>window.__BUNQUEUE_AGENT_URL__='/agent'</script></head>"
317
+ );
318
+
319
+ // Dashboard + /api proxy + same-origin /agent proxy.
320
+ Bun.serve({
321
+ port: PORT,
322
+ hostname: HOST,
323
+ fetch: createServeHandler({
324
+ api: API,
325
+ indexHtml,
326
+ assets: ASSETS,
327
+ agentHandle,
328
+ allowedOrigins,
329
+ allowedHosts,
330
+ agentBridge,
331
+ trustProxy: process.env.TRUST_PROXY === '1',
332
+ }),
333
+ error: onError,
334
+ });
335
+
336
+ // Stop the managed server before exiting — without this, Ctrl-C / SIGTERM on
337
+ // the binary orphans the spawned bunqueue child (it reparents to PID 1 and
338
+ // keeps holding the ports and the SQLite db, so the next start fails).
339
+ let shuttingDown = false;
340
+ const shutdown = (signal: string) => {
341
+ if (shuttingDown) return;
342
+ shuttingDown = true;
343
+ logger.info({ signal }, 'signal received, stopping managed server');
344
+ // shutdown(), not stop(): it latches, so a restart() already in flight
345
+ // can't spawn a fresh child after we've stopped the old one (mirrors
346
+ // agent/index.ts).
347
+ void mgr.shutdown().finally(() => process.exit(0));
348
+ };
349
+ process.on('SIGINT', () => shutdown('SIGINT'));
350
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
351
+
352
+ logger.info(
353
+ {
354
+ dashboard: `http://${HOST}:${PORT}`,
355
+ apiProxy: API,
356
+ agent: `http://127.0.0.1:${AGENT_PORT}/control`,
357
+ agentBridge,
358
+ },
359
+ 'bunqueue dashboard (standalone) ready'
360
+ );
361
+ }
362
+
363
+ if (import.meta.main) await main();
@@ -1,3 +0,0 @@
1
- import{r as e}from"./cn-CMFYpumL.js";import{h as t,l as n,r,t as i}from"./react-vendor-BcouBxpZ.js";import{A as a,C as o,S as s,h as c,nt as l,rt as u,w as d}from"./index-BOcegTHa.js";import{a as f,n as p,o as m,t as h}from"./form-DGinTEEb.js";var g=e(t(),1),_=i(),v=e=>e==null?``:String(e);function y(){let{data:e}=a(()=>l.queues(),[],{intervalMs:3e4}),t=n().state?.clone,i=t?.options??{},[m,y]=(0,g.useState)(t?.queue??``),[x,ee]=(0,g.useState)(t?.dataText??`{
2
- "hello": "world"
3
- }`),[S,te]=(0,g.useState)(`1`),[C,ne]=(0,g.useState)(v(i.priority)),[w,re]=(0,g.useState)(``),[T,E]=(0,g.useState)(``),[D,ie]=(0,g.useState)(v(i.maxAttempts)),[O,k]=(0,g.useState)(v(typeof i.backoff==`number`?i.backoff:void 0)),[A,j]=(0,g.useState)(v(i.timeout)),[M,ae]=(0,g.useState)(``),[N,oe]=(0,g.useState)(i.removeOnComplete??!1),[P,se]=(0,g.useState)(i.removeOnFail??!1),[F,I]=(0,g.useState)(!1),[L,R]=(0,g.useState)(!1),[z,B]=(0,g.useState)(``),[V,H]=(0,g.useState)(``),[U,W]=(0,g.useState)(``),[G,ce]=(0,g.useState)(``),[K,le]=(0,g.useState)(``),[q,J]=(0,g.useState)(!1),[Y,X]=(0,g.useState)(null),[Z,Q]=(0,g.useState)(null),$=e=>{let t=Number(e);return e.trim()!==``&&Number.isFinite(t)?t:void 0},ue=async()=>{if(X(null),Q(null),!m.trim()){X({ok:!1,msg:`Choose a queue`});return}let e;try{e=JSON.parse(x)}catch(e){Q(`Invalid JSON: ${e.message}`);return}let t=$(w);if(T.trim()){let e=new Date(T).getTime();if(!Number.isFinite(e)){X({ok:!1,msg:`Run at is not a valid date/time`});return}t=Math.max(0,e-Date.now())}let n=$(O),r=n==null?void 0:z?{type:z,delay:n}:n,i=V.split(`,`).map(e=>e.trim()).filter(Boolean),a=G.split(`,`).map(e=>e.trim()).filter(Boolean),o={data:e,priority:$(C),delay:t,maxAttempts:$(D),backoff:r,timeout:$(A),jobId:M.trim()||void 0,removeOnComplete:N||void 0,removeOnFail:P||void 0,durable:F||void 0,lifo:L||void 0,tags:i.length?i:void 0,groupId:U.trim()||void 0,dependsOn:a.length?a:void 0,uniqueKey:K.trim()||void 0},s=$(S)??1;if(!Number.isInteger(s)||s<1){X({ok:!1,msg:`Count must be an integer of at least 1`});return}if(s>1e4){X({ok:!1,msg:`Count must be 10000 or fewer`});return}J(!0);try{if(s===1){let e=await l.addJob(m,o);X({ok:!0,msg:`Created job ${e.id}`}),u.success(`Job created`,`${m} · ${e.id}`)}else{let e=await l.addJobsBulk(m,Array.from({length:s},()=>o)),t=new Set(e.ids).size;X({ok:!0,msg:`Created ${t} job${t===1?``:`s`}`}),u.success(`Created ${t} job${t===1?``:`s`}`,`in ${m}`)}}catch(e){X({ok:!1,msg:e.message}),u.error(`Add job failed`,e.message)}finally{J(!1)}};return(0,_.jsxs)(`div`,{children:[(0,_.jsx)(c,{title:`Add Job`,description:`Enqueue a job with full options.`,actions:(0,_.jsx)(r,{to:`/jobs/bulk-add`,className:`rounded-lg border border-line px-3 py-1.5 text-sm text-muted hover:bg-surface-2 hover:text-fg`,children:`Bulk import`})}),t&&(0,_.jsx)(`div`,{className:`mb-4 flex items-center gap-2 rounded-lg border border-accent/30 bg-accent/[0.06] px-4 py-2 text-sm text-accent`,children:`Pre-filled from an existing job. Review the data and options, then enqueue a fresh job.`}),(0,_.jsxs)(`form`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-2`,onSubmit:e=>{e.preventDefault(),ue()},children:[(0,_.jsxs)(s,{children:[(0,_.jsx)(o,{title:`Job`}),(0,_.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,_.jsxs)(h,{label:`Queue`,children:[(0,_.jsx)(p,{list:`queue-options`,value:m,onChange:e=>y(e.target.value),placeholder:`queue name (existing or new)`}),(0,_.jsx)(`datalist`,{id:`queue-options`,children:(e?.queues??[]).map(e=>(0,_.jsx)(`option`,{value:e.name},e.name))})]}),(0,_.jsxs)(`div`,{children:[(0,_.jsx)(h,{label:`Data (JSON)`,children:(0,_.jsx)(`textarea`,{value:x,onChange:e=>ee(e.target.value),onBlur:()=>{try{JSON.parse(x),Q(null)}catch(e){Q(`Invalid JSON: ${e.message}`)}},spellCheck:!1,rows:7,className:`w-full rounded-lg border border-line bg-surface-2 p-3 font-mono text-sm text-fg focus:border-accent/60 focus:outline-none focus:ring-2 focus:ring-accent/30`})}),Z&&(0,_.jsx)(`p`,{className:`mt-2 text-xs text-danger`,children:Z})]})]})]}),(0,_.jsxs)(s,{children:[(0,_.jsx)(o,{title:`Options`}),(0,_.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 md:grid-cols-3`,children:[(0,_.jsx)(h,{label:`Priority`,children:(0,_.jsx)(p,{type:`number`,value:C,onChange:e=>ne(e.target.value),placeholder:`0`})}),(0,_.jsx)(h,{label:`Delay (ms)`,children:(0,_.jsx)(p,{type:`number`,min:0,value:w,onChange:e=>re(e.target.value),placeholder:`0`,disabled:T.trim()!==``})}),(0,_.jsx)(h,{label:`Run at`,hint:T.trim()?`Overrides Delay — derived from this time (local time).`:`(local time)`,children:(0,_.jsx)(p,{type:`datetime-local`,value:T,onChange:e=>E(e.target.value)})}),(0,_.jsx)(h,{label:`Max attempts`,hint:`blank = server default`,children:(0,_.jsx)(p,{type:`number`,min:1,value:D,onChange:e=>ie(e.target.value),placeholder:`3`})}),(0,_.jsx)(h,{label:`Backoff (ms)`,hint:`blank = server default`,children:(0,_.jsx)(p,{type:`number`,min:0,value:O,onChange:e=>k(e.target.value),placeholder:`1000`})}),(0,_.jsx)(h,{label:`Backoff strategy`,hint:`flat delay unless set`,children:(0,_.jsxs)(f,{value:z,onChange:e=>B(e.target.value),children:[(0,_.jsx)(`option`,{value:``,children:`flat`}),(0,_.jsx)(`option`,{value:`fixed`,children:`fixed`}),(0,_.jsx)(`option`,{value:`exponential`,children:`exponential`})]})}),(0,_.jsx)(h,{label:`Timeout (ms)`,children:(0,_.jsx)(p,{type:`number`,min:0,value:A,onChange:e=>j(e.target.value),placeholder:`—`})}),(0,_.jsx)(h,{label:`Custom job ID`,children:(0,_.jsx)(p,{value:M,onChange:e=>ae(e.target.value),placeholder:`idempotency key`})})]}),(0,_.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-6`,children:[(0,_.jsx)(b,{label:`removeOnComplete`,checked:N,onChange:oe}),(0,_.jsx)(b,{label:`removeOnFail`,checked:P,onChange:se}),(0,_.jsx)(b,{label:`durable`,checked:F,onChange:I}),(0,_.jsx)(b,{label:`lifo`,checked:L,onChange:R})]}),(0,_.jsxs)(`div`,{className:`mt-4 border-t border-line pt-4`,children:[(0,_.jsx)(`div`,{className:`mb-3 text-[11px] uppercase tracking-wider text-faint`,children:`Advanced`}),(0,_.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 md:grid-cols-3`,children:[(0,_.jsx)(h,{label:`Tags`,hint:`comma-separated`,children:(0,_.jsx)(p,{value:V,onChange:e=>H(e.target.value),placeholder:`email, urgent`})}),(0,_.jsx)(h,{label:`Group ID`,children:(0,_.jsx)(p,{value:U,onChange:e=>W(e.target.value),placeholder:`—`})}),(0,_.jsx)(h,{label:`Unique key`,hint:`dedup key`,children:(0,_.jsx)(p,{value:K,onChange:e=>le(e.target.value),placeholder:`—`})}),(0,_.jsx)(h,{label:`Depends on`,hint:`parent job ids, comma-separated`,children:(0,_.jsx)(p,{value:G,onChange:e=>ce(e.target.value),placeholder:`job-id-1, job-id-2`})})]})]})]}),(0,_.jsxs)(`div`,{className:`flex flex-wrap items-end gap-3 lg:col-span-2`,children:[(0,_.jsx)(`div`,{className:`w-28`,children:(0,_.jsx)(h,{label:`Count`,hint:`1–10000`,children:(0,_.jsx)(p,{type:`number`,min:1,value:S,onChange:e=>te(e.target.value)})})}),(0,_.jsx)(d,{type:`submit`,variant:`accent`,disabled:q,children:q?`Adding…`:`Add job`}),Y&&(0,_.jsx)(`span`,{role:`status`,className:Y.ok?`text-sm text-success`:`text-sm text-danger`,children:Y.msg})]})]})]})}function b({label:e,checked:t,onChange:n}){return(0,_.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,_.jsx)(m,{checked:t,onChange:n,label:e}),(0,_.jsx)(`span`,{className:`font-mono text-xs text-muted`,children:e})]})}export{y as AddJob};
@@ -1 +0,0 @@
1
- import{r as e,t}from"./cn-CMFYpumL.js";import{h as n,t as r}from"./react-vendor-BcouBxpZ.js";import{r as i}from"./connectionStore-Ci04lJmR.js";import{A as a,C as o,O as s,S as c,U as l,W as u,c as d,h as f,m as p,nt as m,r as h,s as g,w as _}from"./index-BOcegTHa.js";import{i as v,n as y,o as b,t as x}from"./form-DGinTEEb.js";import{t as S}from"./AreaChart-2gM0YoZT.js";var C=e(n(),1),w={total:1e6,batch:5e3,producers:64,payload:65536,workers:64,workerBatch:1e3,processMs:6e4,durationS:600},T={queue:`benchmark`,mode:`count`,total:5e3,durationS:30,batch:100,producers:4,payload:128,workers:4,workerBatch:100,processMs:5,durable:!1,removeOnComplete:!0},E={Smoke:{mode:`count`,total:200,batch:50,producers:2,workers:1,workerBatch:50,processMs:0},Standard:{mode:`count`,total:5e3,batch:100,producers:4,workers:4,workerBatch:100,processMs:5},Stress:{mode:`count`,total:5e4,batch:500,producers:16,workers:16,workerBatch:200,processMs:0},Soak:{mode:`duration`,durationS:30,batch:100,producers:4,workers:8,workerBatch:100,processMs:10}},D=(e,t,n)=>Number.isFinite(e)?Math.max(t,Math.min(n,Math.floor(e))):t,O=(e,t)=>e.length?e[Math.min(e.length-1,Math.floor(t/100*e.length))]:0,k=(e,t,n,r,i)=>Array.from({length:t},(t,a)=>({data:{i:e+a,blob:n},durable:r,removeOnComplete:i})),A=e=>new Promise(t=>setTimeout(t,e)),j=async(e,t)=>{let n=performance.now()+e;for(;t()&&performance.now()<n;)await A(Math.min(100,Math.max(0,n-performance.now())))},M=e=>e instanceof Error?e.message:String(e),N=e=>e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:`${Math.round(e)}`,P=r();function F({history:e,onClear:t}){if(!e.length)return null;let n=JSON.stringify(e,null,2);return(0,P.jsxs)(c,{padded:!1,className:`mt-6 overflow-hidden`,children:[(0,P.jsxs)(`div`,{className:`flex items-center justify-between border-b border-line px-5 py-3`,children:[(0,P.jsx)(`h3`,{className:`text-base font-semibold text-fg`,children:`Run history`}),(0,P.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,P.jsx)(s,{value:n}),(0,P.jsx)(_,{size:`sm`,variant:`ghost`,onClick:()=>{let e=new Blob([n],{type:`application/json`}),t=URL.createObjectURL(e),r=document.createElement(`a`);r.href=t,r.download=`benchmark-history-${Date.now()}.json`,r.click(),URL.revokeObjectURL(t)},children:`Export JSON`}),(0,P.jsx)(_,{size:`sm`,variant:`ghost`,onClick:t,children:`Clear`})]})]}),(0,P.jsx)(`div`,{className:`overflow-x-auto`,children:(0,P.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,P.jsx)(`thead`,{children:(0,P.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,P.jsx)(`th`,{className:`px-5 py-2 font-medium`,children:`Mode`}),(0,P.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Prod`}),(0,P.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Wkr`}),(0,P.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Pushed`}),(0,P.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Done`}),(0,P.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Push/s`}),(0,P.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Done/s`}),(0,P.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`p95`}),(0,P.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Dur`})]})}),(0,P.jsx)(`tbody`,{children:e.map(e=>(0,P.jsxs)(`tr`,{className:`border-b border-line last:border-0 hover:bg-surface-2/40`,children:[(0,P.jsx)(`td`,{className:`px-5 py-2 capitalize text-muted`,children:e.mode}),(0,P.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-muted`,children:e.producers}),(0,P.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-muted`,children:e.workers}),(0,P.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-fg`,children:d(e.pushed)}),(0,P.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-success`,children:d(e.completed)}),(0,P.jsxs)(`td`,{className:`px-5 py-2 text-right tnum text-accent`,children:[N(e.pushPerSec),`/s`]}),(0,P.jsxs)(`td`,{className:`px-5 py-2 text-right tnum text-success`,children:[N(e.donePerSec),`/s`]}),(0,P.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-muted`,children:g(e.p95)}),(0,P.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-muted`,children:g(e.durationMs)})]},e.id))})]})})]})}var I={pushed:0,completed:0,pushFailed:0,ackFailed:0,bytes:0,elapsedMs:0,pushPerSec:0,donePerSec:0,activeWorkers:0,pushSeries:[],doneSeries:[],etaMs:null,error:null},L=()=>({pushed:0,completed:0,pushFailed:0,ackFailed:0,bytes:0,assigned:0,startedAt:0,pushLat:[],activeWorkers:0,error:null,lastAt:0,lastPushed:0,lastDone:0,pushSeries:[],doneSeries:[]}),R=0;function z(){let[e,t]=(0,C.useState)(`idle`),[n,r]=(0,C.useState)(I),[i,a]=(0,C.useState)(null),[o,s]=(0,C.useState)([]),[c,l]=(0,C.useState)(null),u=(0,C.useRef)(!1),d=(0,C.useRef)(!1),f=(0,C.useRef)(!1),p=(0,C.useRef)(null),h=(0,C.useRef)(`idle`);h.current=e;let g=(0,C.useRef)(L());return(0,C.useEffect)(()=>()=>{u.current=!0},[]),(0,C.useEffect)(()=>{if(e!==`running`&&e!==`draining`)return;let t=setInterval(()=>{let e=g.current,t=performance.now(),n=t-e.startedAt,i=(t-e.lastAt)/1e3,a=i>0?Math.max(0,(e.pushed-e.lastPushed)/i):0,o=i>0?Math.max(0,(e.completed-e.lastDone)/i):0;e.lastAt=t,e.lastPushed=e.pushed,e.lastDone=e.completed,e.pushSeries=[...e.pushSeries,a].slice(-60),e.doneSeries=[...e.doneSeries,o].slice(-60);let s=null,c=p.current;if(c&&c.mode===`count`){let t=D(c.total,1,w.total);if(h.current===`draining`){let r=e.doneSeries.slice(-10),i=r.length?r.reduce((e,t)=>e+t,0)/r.length:0;i<=0&&n>0&&(i=e.completed/(n/1e3)),i>0&&(s=Math.max(0,t-e.completed)/i*1e3)}else a>0&&(s=Math.max(0,t-e.pushed)/a*1e3)}else c&&c.mode===`duration`&&(s=Math.max(0,D(c.durationS,1,w.durationS)*1e3-n));r({pushed:e.pushed,completed:e.completed,pushFailed:e.pushFailed,ackFailed:e.ackFailed,bytes:e.bytes,elapsedMs:n,pushPerSec:a,donePerSec:o,activeWorkers:e.activeWorkers,pushSeries:e.pushSeries,doneSeries:e.doneSeries,etaMs:s,error:e.error})},200);return()=>clearInterval(t)},[e]),{phase:e,live:n,summary:i,history:o,runCfg:c,run:async e=>{if(!d.current){d.current=!0;try{a(null);let n=e.queue.trim();if(!n){r({...I,error:`Queue name is required.`}),t(`error`);return}try{await m.overview()}catch(e){r({...I,error:`Server unreachable — start it on the Server page first. (${M(e)})`}),t(`error`);return}let i=D(e.total,1,w.total),o=D(e.durationS,1,w.durationS)*1e3,c=D(e.batch,1,w.batch),d=D(e.producers,e.mode===`duration`?0:1,w.producers),_=D(e.payload,0,w.payload),v=D(e.workers,0,w.workers),y=D(e.workerBatch,1,w.workerBatch),b=D(e.processMs,0,w.processMs);u.current=!1,f.current=!1,p.current=e,l(e),g.current=L(),g.current.startedAt=performance.now(),g.current.lastAt=performance.now(),r({...I}),t(`running`);let x=`x`.repeat(_),S=performance.now()+o,C=async()=>{for(;!u.current;){let t;if(e.mode===`count`){if(g.current.assigned>=i)break;t=Math.min(c,i-g.current.assigned)}else{if(performance.now()>=S)break;t=c}let r=g.current.assigned;g.current.assigned+=t;let a=k(r,t,x,e.durable,e.removeOnComplete),o=performance.now();try{await m.addJobsBulk(n,a),g.current.pushed+=t,g.current.bytes+=t*_}catch(e){g.current.pushFailed+=t,g.current.error??=M(e)}g.current.pushLat.push(performance.now()-o)}},T=async()=>{for(;!u.current&&!(e.mode===`duration`&&performance.now()>=S||e.mode===`count`&&g.current.completed>=i);){g.current.activeWorkers++;let t=[];try{try{t=(await m.pullBatch(n,y)).jobs??[]}catch(e){g.current.error??=M(e)}if(t.length>0){b>0&&await j(b,()=>!u.current);try{await m.ackBatch(t.map(e=>e.id)),g.current.completed+=t.length}catch(e){g.current.ackFailed+=t.length,g.current.error??=M(e)}}}finally{g.current.activeWorkers--}if(t.length===0){if(e.mode===`count`&&f.current)break;await A(50)}}},E=Array.from({length:d},C),N=Array.from({length:v},T),P=Promise.all(E).then(()=>{f.current=!0,!u.current&&e.mode===`count`&&v>0&&h.current===`running`&&t(`draining`)});await Promise.all([P,...N]);let F=g.current,z=performance.now()-F.startedAt,B=z/1e3||1,V=[...F.pushLat].sort((e,t)=>e-t),H={pushed:F.pushed,completed:F.completed,pushFailed:F.pushFailed,ackFailed:F.ackFailed,bytes:F.bytes,durationMs:z,pushPerSec:F.pushed/B,donePerSec:F.completed/B,mbPerSec:F.bytes/B,avg:V.length?V.reduce((e,t)=>e+t,0)/V.length:0,p50:O(V,50),p95:O(V,95),p99:O(V,99),max:V.length?V[V.length-1]:0,error:F.error};a(H),r(e=>({...e,pushed:F.pushed,completed:F.completed,elapsedMs:z,pushPerSec:0,donePerSec:0,activeWorkers:0,etaMs:0})),s(t=>[{...H,id:++R,at:Date.now(),mode:e.mode,producers:d,workers:v},...t].slice(0,12)),t(u.current?`stopped`:`done`)}finally{d.current=!1}}},stop:()=>{u.current=!0,(h.current===`running`||h.current===`draining`)&&t(`stopping`)},reset:()=>{u.current=!0,a(null),r(I),t(`idle`)},clearHistory:()=>s([])}}var B=[`count`,`duration`],V=[`total`,`durationS`,`batch`,`producers`,`payload`,`workers`,`workerBatch`,`processMs`],H=e=>({...e,total:String(e.total),durationS:String(e.durationS),batch:String(e.batch),producers:String(e.producers),payload:String(e.payload),workers:String(e.workers),workerBatch:String(e.workerBatch),processMs:String(e.processMs)}),U=e=>({...e,total:Number(e.total),durationS:Number(e.durationS),batch:Number(e.batch),producers:Number(e.producers),payload:Number(e.payload),workers:Number(e.workers),workerBatch:Number(e.workerBatch),processMs:Number(e.processMs)});function W(){let[e,n]=(0,C.useState)(()=>H(T)),r=z(),{phase:s,live:O,summary:k,history:A}=r,j=s===`running`||s===`draining`||s===`stopping`,M=(e,t)=>n(n=>({...n,[e]:t})),I=e=>t=>M(e,t.target.value),L=e=>n(t=>{let n={...t};for(let[t,r]of Object.entries(e))n[t]=V.includes(t)?String(r):r;return n}),[R,W]=(0,C.useState)(T.queue);(0,C.useEffect)(()=>{let t=setTimeout(()=>W(e.queue.trim()||T.queue),400);return()=>clearTimeout(t)},[e.queue]);let{data:ee,error:te}=a(()=>m.counts(R),[R],{intervalMs:1e3}),q=ee?.counts??null,[J,Y]=(0,C.useState)(!1),[X,Z]=(0,C.useState)(null),ne=async()=>{let t=e.queue.trim();if(J||!t)return;let n=q&&R===t?` Currently ${d(q.waiting??0)} waiting / ${d(q.completed??0)} completed.`:``;if(window.confirm(`Remove benchmark jobs from "${t}"?${n}`)){Y(!0),Z(null);try{let e=null;for(let n of[`waiting`,`completed`,`failed`,`delayed`])try{await m.clean(t,{state:n,limit:w.total})}catch(t){e=t.message}let n=await m.counts(t).catch(t=>(e=t.message,null));Z(n==null?{error:e??`server unreachable — could not verify`}:{remaining:n.counts?.active??0})}finally{Y(!1)}}},Q=r.runCfg??U(e),$=D(Q.total,1,w.total),re=D(Q.workers,0,w.workers),ie=Q.mode===`count`&&(j||k)?Math.min(100,O.pushed/$*100):0,ae=Q.mode===`count`&&(j||k)?Math.min(100,O.completed/$*100):0,oe=Q.mode===`duration`?Math.min(100,O.elapsedMs/(D(Q.durationS,1,w.durationS)*1e3)*100):0,se=s===`running`?Q.mode===`duration`?`Running…`:`Producing…`:s===`draining`?`Draining…`:s===`stopping`?`Stopping…`:s===`error`?`Error`:k?`Result`:`Ready`,ce=(s===`running`||s===`draining`)&&O.etaMs!=null?O.etaMs>0?`ETA ${g(O.etaMs)}`:`finishing…`:s===`stopped`?`stopped early`:s===`done`?`complete`:``;return(0,P.jsxs)(`div`,{children:[(0,P.jsx)(f,{title:`Benchmark`,description:`Drive real load against the server — producers bulk-enqueue jobs while simulated workers pull, process and ack them. Throughput is measured client-side; the queue genuinely fills and drains.`,actions:s===`stopping`?(0,P.jsxs)(_,{variant:`warning`,size:`sm`,disabled:!0,children:[(0,P.jsx)(l,{className:`size-3.5`}),` Stopping…`]}):j?(0,P.jsxs)(_,{variant:`warning`,size:`sm`,onClick:r.stop,children:[(0,P.jsx)(l,{className:`size-3.5`}),` Stop`]}):(0,P.jsxs)(_,{variant:`success`,size:`sm`,onClick:()=>{let t=U(e),n=t.queue.trim()||T.queue;window.confirm(`Enqueue real jobs into "${n}" on ${i()}?`)&&r.run(t)},children:[(0,P.jsx)(u,{className:`size-3.5`}),` Run benchmark`]})}),O.error&&(0,P.jsx)(`div`,{className:`mb-4 rounded-lg border border-red-500/20 bg-red-500/5 px-4 py-2 text-sm text-danger`,children:O.error}),(0,P.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-center gap-2`,children:[(0,P.jsx)(`span`,{className:`text-xs font-medium uppercase tracking-wider text-faint`,children:`Presets`}),Object.keys(E).map(e=>(0,P.jsx)(`button`,{type:`button`,disabled:j,onClick:()=>L(E[e]),className:`rounded-md border border-line bg-surface-2 px-2.5 py-1 text-xs text-muted transition-colors hover:border-line-strong hover:text-fg disabled:opacity-40`,children:e},e))]}),(0,P.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-3`,children:[(0,P.jsxs)(c,{className:`lg:col-span-1`,children:[(0,P.jsx)(o,{title:`Configuration`}),(0,P.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,P.jsx)(x,{label:`Queue`,hint:`Jobs are enqueued here (created on first push).`,children:(0,P.jsx)(y,{value:e.queue,disabled:j,onChange:e=>M(`queue`,e.target.value)})}),(0,P.jsx)(x,{label:`Mode`,hint:e.mode===`count`?`Push a fixed number of jobs.`:`Run producers + workers for a fixed time.`,children:(0,P.jsx)(v,{options:B,value:e.mode,onChange:e=>M(`mode`,e),disabled:j})}),e.mode===`count`?(0,P.jsx)(x,{label:`Total jobs`,hint:`max ${d(w.total)}`,children:(0,P.jsx)(y,{type:`number`,min:1,max:w.total,value:e.total,disabled:j,onChange:I(`total`)})}):(0,P.jsx)(x,{label:`Duration (s)`,hint:`max ${w.durationS}s`,children:(0,P.jsx)(y,{type:`number`,min:1,max:w.durationS,value:e.durationS,disabled:j,onChange:I(`durationS`)})}),(0,P.jsx)(`div`,{className:`mt-1 text-[11px] font-semibold uppercase tracking-wider text-faint`,children:`Producers`}),(0,P.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,P.jsx)(x,{label:`Producers`,hint:`parallel, max ${w.producers}`,children:(0,P.jsx)(y,{type:`number`,min:e.mode===`duration`?0:1,max:w.producers,value:e.producers,disabled:j,onChange:I(`producers`)})}),(0,P.jsx)(x,{label:`Push batch`,hint:`jobs/req, max ${w.batch}`,children:(0,P.jsx)(y,{type:`number`,min:1,max:w.batch,value:e.batch,disabled:j,onChange:I(`batch`)})}),(0,P.jsx)(x,{label:`Payload`,hint:`bytes/job, max ${d(w.payload)}`,children:(0,P.jsx)(y,{type:`number`,min:0,max:w.payload,value:e.payload,disabled:j,onChange:I(`payload`)})})]}),(0,P.jsx)(`div`,{className:`mt-1 text-[11px] font-semibold uppercase tracking-wider text-faint`,children:`Workers (simulated)`}),(0,P.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,P.jsx)(x,{label:`Workers`,hint:`0 = produce only, max ${w.workers}`,children:(0,P.jsx)(y,{type:`number`,min:0,max:w.workers,value:e.workers,disabled:j,onChange:I(`workers`)})}),(0,P.jsx)(x,{label:`Pull batch`,hint:`jobs/pull, max ${w.workerBatch}`,children:(0,P.jsx)(y,{type:`number`,min:1,max:w.workerBatch,value:e.workerBatch,disabled:j,onChange:I(`workerBatch`)})}),(0,P.jsx)(x,{label:`Process (ms)`,hint:`simulated work per pull`,children:(0,P.jsx)(y,{type:`number`,min:0,max:w.processMs,value:e.processMs,disabled:j,onChange:I(`processMs`)})})]}),(0,P.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2`,children:[(0,P.jsx)(b,{checked:e.durable,onChange:e=>M(`durable`,e),disabled:j}),(0,P.jsx)(`span`,{className:`text-sm text-muted`,children:`Durable (fsync each job)`})]}),(0,P.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2`,children:[(0,P.jsx)(b,{checked:e.removeOnComplete,onChange:e=>M(`removeOnComplete`,e),disabled:j}),(0,P.jsx)(`span`,{className:`text-sm text-muted`,children:`Remove on complete`})]}),(0,P.jsxs)(`div`,{className:`flex items-center gap-3 pt-1`,children:[(0,P.jsx)(_,{variant:`ghost`,size:`sm`,disabled:j||J,onClick:ne,children:J?`Cleaning…`:`Clean queue`}),X&&(`error`in X?(0,P.jsxs)(`span`,{className:`text-xs text-danger`,children:[`Clean unverified — `,X.error]}):(0,P.jsx)(`span`,{className:t(`text-xs`,X.remaining>0?`text-warning`:`text-success`),children:X.remaining>0?`Cleaned — ${d(X.remaining)} active job(s) remain (requeued after the stall timeout)`:`Cleaned — 0 jobs remain`}))]})]})]}),(0,P.jsxs)(`div`,{className:`flex flex-col gap-6 lg:col-span-2`,children:[(0,P.jsxs)(c,{children:[(0,P.jsxs)(`div`,{className:`mb-3 flex items-center justify-between`,children:[(0,P.jsx)(`h3`,{className:`text-base font-semibold text-fg`,children:se}),(0,P.jsx)(`span`,{className:`text-xs text-faint`,children:ce})]}),(0,P.jsx)(G,{label:Q.mode===`duration`?`Elapsed`:`Produced`,pct:Q.mode===`duration`?oe:ie,tone:`accent`}),re>0&&Q.mode===`count`&&(0,P.jsx)(G,{label:`Completed`,pct:ae,tone:`emerald`}),(0,P.jsxs)(`div`,{className:`mt-4 grid grid-cols-2 gap-4 md:grid-cols-4`,children:[(0,P.jsx)(p,{label:`Pushed`,value:d(O.pushed),tone:`accent`,compact:!0}),(0,P.jsx)(p,{label:`Completed`,value:d(O.completed),tone:`green`,compact:!0}),(0,P.jsx)(p,{label:`Push/sec`,value:N(O.pushPerSec),compact:!0}),(0,P.jsx)(p,{label:`Done/sec`,value:N(O.donePerSec),tone:`green`,compact:!0}),(0,P.jsx)(p,{label:`Elapsed`,value:g(O.elapsedMs),compact:!0}),(0,P.jsx)(p,{label:`Active workers`,value:`${O.activeWorkers}/${re}`,tone:`blue`,compact:!0}),(0,P.jsx)(p,{label:`Data`,value:h(k?.bytes??O.bytes),compact:!0}),(0,P.jsx)(p,{label:`Errors`,value:d((k?.pushFailed??O.pushFailed)+(k?.ackFailed??O.ackFailed)),tone:O.pushFailed+O.ackFailed?`red`:`default`,compact:!0})]})]}),(0,P.jsxs)(c,{children:[(0,P.jsx)(o,{title:`Throughput`}),(0,P.jsx)(`p`,{className:`-mt-3 mb-4 text-xs text-faint`,children:`Enqueue (client → server) vs completion (workers) per second`}),(0,P.jsx)(S,{series:[{label:`Push/sec`,color:`#38bdf8`,points:O.pushSeries,area:!0},{label:`Done/sec`,color:`#34d399`,points:O.doneSeries,area:!0}]}),(0,P.jsxs)(`div`,{className:`mt-2 flex items-center gap-4 font-mono text-[11px] text-faint`,children:[(0,P.jsx)(K,{color:`#38bdf8`,label:`Push/sec`,value:O.pushPerSec}),(0,P.jsx)(K,{color:`#34d399`,label:`Done/sec`,value:O.donePerSec})]})]})]})]}),k&&(0,P.jsxs)(c,{className:`mt-6`,children:[(0,P.jsx)(o,{title:`Summary`}),(0,P.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 md:grid-cols-4 xl:grid-cols-8`,children:[(0,P.jsx)(p,{label:`Pushed`,value:d(k.pushed),tone:`accent`,compact:!0}),(0,P.jsx)(p,{label:`Completed`,value:d(k.completed),tone:`green`,compact:!0}),(0,P.jsx)(p,{label:`Duration`,value:g(k.durationMs),compact:!0}),(0,P.jsx)(p,{label:`Avg push/s`,value:N(k.pushPerSec),tone:`accent`,compact:!0}),(0,P.jsx)(p,{label:`Avg done/s`,value:N(k.donePerSec),tone:`green`,compact:!0}),(0,P.jsx)(p,{label:`Data rate`,value:`${h(k.mbPerSec)}/s`,compact:!0}),(0,P.jsx)(p,{label:`Push p95`,value:g(k.p95),compact:!0}),(0,P.jsx)(p,{label:`Push p99`,value:g(k.p99),compact:!0})]}),(0,P.jsxs)(`p`,{className:`mt-3 text-xs text-faint`,children:[`Push-batch latency avg `,g(k.avg),` · p50 `,g(k.p50),` · p95`,` `,g(k.p95),` · p99 `,g(k.p99),` · max `,g(k.max),`.`,k.error?` First error: ${k.error}`:``]})]}),(0,P.jsxs)(c,{className:`mt-6`,children:[(0,P.jsx)(o,{title:`Server queue: ${R}`,action:te?(0,P.jsx)(`span`,{className:`text-xs font-medium text-warning`,children:`stale — server unreachable`}):void 0}),(0,P.jsx)(`p`,{className:`-mt-3 mb-4 text-xs text-faint`,children:`Live counts from the server (poll 1s).`}),q?(0,P.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 md:grid-cols-5`,children:[(0,P.jsx)(p,{label:`Waiting`,value:d(q.waiting??0),tone:`amber`,compact:!0}),(0,P.jsx)(p,{label:`Active`,value:d(q.active??0),tone:`blue`,compact:!0}),(0,P.jsx)(p,{label:`Completed`,value:d(q.completed??0),tone:`green`,compact:!0}),(0,P.jsx)(p,{label:`Failed`,value:d(q.failed??0),tone:q.failed?`red`:`default`,compact:!0}),(0,P.jsx)(p,{label:`Delayed`,value:d(q.delayed??0),compact:!0})]}):(0,P.jsx)(`p`,{className:`text-sm text-faint`,children:`No counts yet — waiting for the server to answer for this queue.`})]}),(0,P.jsx)(F,{history:A,onClear:r.clearHistory})]})}function G({label:e,pct:n,tone:r}){return(0,P.jsxs)(`div`,{className:`mb-2`,children:[(0,P.jsxs)(`div`,{className:`mb-1 flex items-center justify-between text-[11px] text-faint`,children:[(0,P.jsx)(`span`,{children:e}),(0,P.jsxs)(`span`,{className:`tnum`,children:[n.toFixed(0),`%`]})]}),(0,P.jsx)(`div`,{className:`h-1.5 overflow-hidden rounded-full bg-surface-2`,children:(0,P.jsx)(`div`,{className:t(`h-full rounded-full transition-all`,r===`accent`?`bg-accent`:`bg-emerald-500`),style:{width:`${n}%`}})})]})}function K({color:e,label:t,value:n}){return(0,P.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,P.jsx)(`span`,{className:`size-2 rounded-full`,style:{background:e}}),t,` `,(0,P.jsxs)(`span`,{className:`text-fg`,children:[N(n),`/s`]})]})}export{W as Benchmark};
@@ -1,5 +0,0 @@
1
- import{r as e}from"./cn-CMFYpumL.js";import{h as t,t as n}from"./react-vendor-BcouBxpZ.js";import{A as r,C as i,S as a,h as o,nt as s,rt as c,w as l}from"./index-BOcegTHa.js";import{i as u,n as d,t as f}from"./form-DGinTEEb.js";var p=e(t(),1),m=n(),h=1e4,g=`[
2
- { "data": { "to": "a@example.com", "template": "welcome" }, "priority": 1 },
3
- { "data": { "to": "b@example.com", "template": "welcome" } }
4
- ]`,_=e=>{let t=Number(e);return e.trim()!==``&&Number.isFinite(t)?t:void 0},v=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,y=e=>typeof e==`boolean`?e:void 0,b=e=>typeof e==`string`&&e!==``?e:void 0;function x(e,t,n){if(n===`spec`&&e&&typeof e==`object`&&!Array.isArray(e)&&`data`in e){let n=e;return{data:n.data,priority:v(n.priority)??t.priority,delay:v(n.delay),maxAttempts:v(n.maxAttempts)??t.maxAttempts,backoff:v(n.backoff)??t.backoff,timeout:v(n.timeout)??t.timeout,jobId:b(n.jobId),removeOnComplete:y(n.removeOnComplete),removeOnFail:y(n.removeOnFail),durable:y(n.durable),lifo:y(n.lifo),ttl:v(n.ttl),uniqueKey:b(n.uniqueKey)}}return{data:e,...t}}var S=new Set([`data`,`priority`,`delay`,`maxAttempts`,`backoff`,`timeout`,`jobId`,`removeOnComplete`,`removeOnFail`,`durable`,`lifo`,`ttl`,`uniqueKey`]);function C(e){return e.some(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`data`in e&&Object.keys(e).some(e=>!S.has(e)))}function w(e){let t=e.trim();if(!t)return{items:[],error:null};try{let e=JSON.parse(t);return Array.isArray(e)?{items:e,error:null}:{items:[e],error:null}}catch{}let n=[],r=t.split(`
5
- `);for(let e=0;e<r.length;e++){let t=r[e].trim();if(t)try{n.push(JSON.parse(t))}catch(t){return{items:[],error:`Line ${e+1}: ${t.message}`}}}return{items:n,error:null}}function T(){let{data:e}=r(()=>s.queues(),[],{intervalMs:3e4}),[t,n]=(0,p.useState)(``),[v,y]=(0,p.useState)(``),[b,S]=(0,p.useState)(`spec`),[T,E]=(0,p.useState)(``),[D,O]=(0,p.useState)(``),[k,A]=(0,p.useState)(``),[j,M]=(0,p.useState)(``),[N,P]=(0,p.useState)(!1),[F,I]=(0,p.useState)(null),{items:L,error:R}=(0,p.useMemo)(()=>w(v),[v]),z=b===`spec`&&!R&&C(L);return(0,m.jsxs)(`div`,{children:[(0,m.jsx)(o,{title:`Bulk Add Jobs`,description:`Import many distinct jobs at once from a JSON array, NDJSON, or a file.`}),(0,m.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-3`,children:[(0,m.jsxs)(a,{className:`lg:col-span-2`,children:[(0,m.jsx)(i,{title:`Jobs`,action:(0,m.jsxs)(`label`,{className:`cursor-pointer rounded-lg border border-line px-3 py-1.5 text-xs text-muted hover:bg-surface-2 hover:text-fg`,children:[`Upload file`,(0,m.jsx)(`input`,{type:`file`,accept:`.json,.ndjson,.txt,application/json`,onChange:e=>{let t=e.target.files?.[0];if(!t)return;if(v.trim()!==``&&!window.confirm(`Replace the current input with "${t.name}"?`)){e.target.value=``;return}let n=new FileReader;n.onload=()=>y(String(n.result??``)),n.onerror=()=>I({ok:!1,msg:`Could not read file`}),n.readAsText(t),e.target.value=``},className:`hidden`})]})}),(0,m.jsx)(`textarea`,{value:v,onChange:e=>y(e.target.value),spellCheck:!1,rows:16,placeholder:g,"aria-label":`Jobs JSON`,className:`w-full rounded-lg border border-line bg-surface-2 p-3 font-mono text-xs text-fg placeholder:text-faint focus:border-accent/60 focus:outline-none focus:ring-2 focus:ring-accent/30`}),(0,m.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3`,children:[(0,m.jsx)(`span`,{className:`text-xs font-medium text-faint`,children:`Interpret each item as`}),(0,m.jsx)(u,{options:[`spec`,`raw`],value:b,onChange:S}),(0,m.jsx)(`span`,{className:`text-xs text-faint`,children:b===`spec`?`job spec: an object with a "data" key sets options from its sibling fields.`:`raw data: the whole item becomes the job payload, untouched.`})]}),(0,m.jsx)(`p`,{className:`mt-2 text-xs text-faint`,children:`Accepts a JSON array, a single object, or newline-delimited JSON.`}),(0,m.jsx)(`div`,{className:`mt-2 text-sm`,children:R?(0,m.jsx)(`span`,{className:`text-danger`,children:R}):L.length>0?(0,m.jsxs)(`span`,{className:`text-success`,children:[L.length,` job(s) parsed ✓`]}):(0,m.jsx)(`span`,{className:`text-faint`,children:`Nothing parsed yet.`})}),z&&(0,m.jsx)(`p`,{className:`mt-2 text-xs text-warning`,children:`Some items carry keys beyond the known job options — in “spec” mode those keys are dropped. Switch to “raw” to keep every field as the job's data.`})]}),(0,m.jsxs)(a,{children:[(0,m.jsx)(i,{title:`Target & defaults`}),(0,m.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,m.jsxs)(f,{label:`Queue`,children:[(0,m.jsx)(d,{list:`bulk-queue-options`,value:t,onChange:e=>n(e.target.value),placeholder:`queue name (existing or new)`}),(0,m.jsx)(`datalist`,{id:`bulk-queue-options`,children:(e?.queues??[]).map(e=>(0,m.jsx)(`option`,{value:e.name},e.name))})]}),(0,m.jsx)(`p`,{className:`-mt-2 text-xs text-faint`,children:`Defaults below fill any field an item omits.`}),(0,m.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,m.jsx)(f,{label:`Priority`,children:(0,m.jsx)(d,{type:`number`,value:T,onChange:e=>E(e.target.value),placeholder:`0`})}),(0,m.jsx)(f,{label:`Max attempts`,children:(0,m.jsx)(d,{type:`number`,min:0,value:D,onChange:e=>O(e.target.value),placeholder:`3`})}),(0,m.jsx)(f,{label:`Backoff (ms)`,children:(0,m.jsx)(d,{type:`number`,min:0,value:k,onChange:e=>A(e.target.value),placeholder:`1000`})}),(0,m.jsx)(f,{label:`Timeout (ms)`,children:(0,m.jsx)(d,{type:`number`,min:0,value:j,onChange:e=>M(e.target.value),placeholder:`—`})})]}),(0,m.jsx)(`div`,{className:`flex items-center gap-3`,children:(0,m.jsx)(l,{variant:`accent`,disabled:N||L.length===0||R!=null,onClick:async()=>{if(I(null),!t.trim()){I({ok:!1,msg:`Choose a queue`});return}if(R){I({ok:!1,msg:R});return}if(L.length===0){I({ok:!1,msg:`Nothing to enqueue — paste a JSON array or NDJSON.`});return}if(L.length>h){I({ok:!1,msg:`Too many jobs (${L.length}). Limit is ${h}.`});return}let e=e=>e!=null&&e<0?0:e,n={priority:_(T),maxAttempts:e(_(D)),backoff:e(_(k)),timeout:e(_(j))},r=L.map(e=>x(e,n,b));P(!0);try{let e=await s.addJobsBulk(t,r),n=new Set(e.ids).size,i=`Created ${n} job${n===1?``:`s`} in ${t}`;I({ok:!0,msg:i}),c.success(i)}catch(e){let t=e.message;I({ok:!1,msg:t}),c.error(`Bulk import failed`,t)}finally{P(!1)}},children:N?`Importing…`:`Import ${L.length||``}`})}),F&&(0,m.jsx)(`span`,{role:`status`,className:F.ok?`text-sm text-success`:`text-sm text-danger`,children:F.msg})]})]})]})]})}export{T as BulkAddJobs};
@@ -1 +0,0 @@
1
- import{r as e,t}from"./cn-CMFYpumL.js";import{h as n,t as r}from"./react-vendor-BcouBxpZ.js";import{A as i,C as a,L as o,S as s,T as c,Y as l,a as u,b as d,c as f,h as p,nt as m,rt as h,v as g,w as _,x as v}from"./index-BOcegTHa.js";import{i as y,n as b,o as x,t as S}from"./form-DGinTEEb.js";import{t as C}from"./Pagination-D4ki-pGz.js";var w=e(n(),1),T=[``,`jan`,`feb`,`mar`,`apr`,`may`,`jun`,`jul`,`aug`,`sep`,`oct`,`nov`,`dec`],E=[`sun`,`mon`,`tue`,`wed`,`thu`,`fri`,`sat`];function D(e,t,n,r){let i=e===`*`||/^\*\/\d+$/.test(e),a=new Set;for(let i of e.split(`,`)){let e=i.trim().toLowerCase();if(e===``)return null;let o=e.match(/^(.+)\/(\d+)$/),s=o?Number(o[2]):1,c=o?o[1]:e;if(s<1)return null;let l,u;if(c===`*`)l=t,u=n;else if(c.includes(`-`)){let[e,t]=c.split(`-`),n=O(e,r),i=O(t,r);if(n==null||i==null)return null;l=n,u=i}else{let e=O(c,r);if(e==null)return null;l=e,u=o?n:e}if(l<t||u>n||l>u)return null;for(let e=l;e<=u;e+=s)a.add(e)}return a.size?{values:a,star:i}:null}function O(e,t){let n=e.trim().toLowerCase();if(n===``)return null;if(t){let e=t.indexOf(n.slice(0,3));if(e!==-1)return e}return/^\d+$/.test(n)?Number(n):null}function k(e,t,n){let r=e.trim().split(/\s+/);if(r.length!==5)return{valid:!1,error:`Expected 5 fields (min hour day month weekday), got ${r.length}.`,runs:[]};let i=D(r[0],0,59),a=D(r[1],0,23),o=D(r[2],1,31),s=D(r[3],1,12,T),c=D(r[4],0,7,E);if(!i||!a||!o||!s||!c)return{valid:!1,error:`Invalid field syntax.`,runs:[]};let l=new Set;for(let e of c.values)l.add(e===7?0:e);let u={values:l,star:c.star},d=e=>{let t=o.values.has(e.getDate()),n=u.values.has(e.getDay());return o.star||u.star?t&&n:t||n},f=[],p=new Date(n);p.setSeconds(0,0),p.setMinutes(p.getMinutes()+1);for(let e=0;e<22e5&&f.length<t;e++){if(!s.values.has(p.getMonth()+1)){p.setMonth(p.getMonth()+1,1),p.setHours(0,0,0,0);continue}if(!d(p)){p.setDate(p.getDate()+1),p.setHours(0,0,0,0);continue}if(!a.values.has(p.getHours())){p.setHours(p.getHours()+1,0,0,0);continue}if(!i.values.has(p.getMinutes())){p.setMinutes(p.getMinutes()+1,0,0);continue}f.push(p.getTime()),p.setMinutes(p.getMinutes()+1,0,0)}return{valid:!0,runs:f}}var A=r();function j(){let{data:e,error:t,loading:n,refetch:r}=i(()=>m.crons(),[]),_=e?.crons??[],[y,b]=(0,w.useState)(0),x=Math.max(1,Math.ceil(_.length/15)),S=Math.min(y,x-1),[T,E]=(0,w.useState)(null),D=async e=>{if(window.confirm(`Delete cron "${e}"?`)){E(null);try{await m.deleteCron(e),h.success(`Cron deleted`,e),r()}catch(e){E(e.message),h.error(`Delete cron failed`,e.message)}}};return(0,A.jsxs)(`div`,{children:[t&&(0,A.jsx)(v,{onRetry:r}),(0,A.jsx)(p,{title:`Cron Manager`,description:`Schedule and manage repeatable jobs.`,live:!0}),T&&(0,A.jsx)(`div`,{role:`status`,className:`mb-4 rounded-lg border border-red-500/20 bg-red-500/5 px-4 py-2 text-sm text-danger`,children:T}),(0,A.jsxs)(s,{className:`mb-6`,children:[(0,A.jsx)(a,{title:`Create schedule`}),(0,A.jsx)(N,{onCreate:async e=>{await m.createCron(e),h.success(`Cron created`,e.name),r()}})]}),n&&!e&&!t?(0,A.jsx)(d,{label:`Loading crons…`}):_.length===0?(0,A.jsx)(g,{icon:(0,A.jsx)(o,{}),title:`No scheduled jobs`,hint:`Create one above.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`overflow-x-auto rounded-xl border border-line bg-surface`,children:(0,A.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,A.jsx)(`thead`,{children:(0,A.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,A.jsx)(`th`,{scope:`col`,className:`px-5 py-3 font-medium`,children:`Name`}),(0,A.jsx)(`th`,{scope:`col`,className:`px-5 py-3 font-medium`,children:`Queue`}),(0,A.jsx)(`th`,{scope:`col`,className:`px-5 py-3 font-medium`,children:`Schedule`}),(0,A.jsx)(`th`,{scope:`col`,className:`px-5 py-3 font-medium`,children:`Next Run`}),(0,A.jsx)(`th`,{scope:`col`,className:`px-5 py-3 text-right font-medium`,children:`Runs`}),(0,A.jsx)(`th`,{scope:`col`,className:`w-12 px-5 py-3`})]})}),(0,A.jsx)(`tbody`,{children:_.slice(S*15,S*15+15).map(e=>(0,A.jsxs)(`tr`,{className:`border-b border-line last:border-0 hover:bg-surface-2/40`,children:[(0,A.jsx)(`td`,{className:`px-5 py-3 font-medium text-fg`,children:e.name}),(0,A.jsx)(`td`,{className:`px-5 py-3 font-mono text-xs text-muted`,children:e.queue}),(0,A.jsx)(`td`,{className:`px-5 py-3 font-mono text-xs text-muted`,children:e.schedule??(e.repeatEvery?`every ${e.repeatEvery}ms`:`—`)}),(0,A.jsx)(`td`,{className:`px-5 py-3 text-faint`,children:u(e.nextRun)}),(0,A.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-muted`,children:f(e.executions)}),(0,A.jsx)(`td`,{className:`px-5 py-3 text-right`,children:(0,A.jsx)(c,{"aria-label":`Delete cron`,onClick:()=>D(e.name),children:(0,A.jsx)(l,{className:`size-3.5`})})})]},e.name))})]})}),(0,A.jsx)(C,{page:S,pageSize:15,total:_.length,onPageChange:b,label:`crons`})]})]})}function M(e){let t=Number(e);if(!Number.isInteger(t)||t<=0)return null;if(t<1e3)return`every ${t}ms`;for(let[e,n]of[[864e5,`d`],[36e5,`h`],[6e4,`m`],[1e3,`s`]])if(t>=e){let r=t/e;return`${Number.isInteger(r)?``:`≈ `}every ${Math.round(r*10)/10}${n}`}return null}function N({onCreate:e}){let[n,r]=(0,w.useState)(``),[i,a]=(0,w.useState)(``),[o,s]=(0,w.useState)(`cron`),[c,l]=(0,w.useState)(``),[d,f]=(0,w.useState)(``),[p,m]=(0,w.useState)(`{}`),[h,g]=(0,w.useState)(!1),[v,C]=(0,w.useState)(``),[T,E]=(0,w.useState)(``),[D,O]=(0,w.useState)(!1),[j,N]=(0,w.useState)(!1),[P,F]=(0,w.useState)(``),[I,L]=(0,w.useState)(!1),[R,z]=(0,w.useState)(!1),[B,V]=(0,w.useState)(``),[H,U]=(0,w.useState)(``),[W,G]=(0,w.useState)(``),[K,q]=(0,w.useState)(null),[J,Y]=(0,w.useState)(!1),[X,Z]=(0,w.useState)(!1),Q=(0,w.useMemo)(()=>o!==`cron`||!c.trim()?null:k(c.trim(),3,Date.now()),[o,c]),$=async()=>{if(J)return;if(q(null),Z(!1),!n.trim()||!i.trim()){q(`Name and queue are required`);return}let t={};try{t=p.trim()?JSON.parse(p):{}}catch{q(`Data is not valid JSON`);return}let a={name:n,queue:i,data:t};if(o===`cron`){if(!c.trim()){q(`Cron expression required`);return}if(Q&&!Q.valid){q(Q.error??`Invalid cron expression`);return}a.schedule=c.trim()}else{let e=Number(d);if(!Number.isInteger(e)||e<=0){q(`Interval must be a whole number of milliseconds greater than 0`);return}a.repeatEvery=e}v.trim()&&(a.timezone=v.trim());let s=Number(T);T.trim()!==``&&Number.isFinite(s)&&(a.priority=s),D&&(a.preventOverlap=!0),j&&(a.skipIfNoWorker=!0);let u=Number(P);P.trim()!==``&&Number.isInteger(u)&&u>0&&(a.maxLimit=u),I&&(a.immediately=!0),R&&(a.skipMissedOnRestart=!0);let m={},h=Number(B);B.trim()!==``&&Number.isFinite(h)&&(m.maxAttempts=h);let g=Number(H);H.trim()!==``&&Number.isFinite(g)&&(m.backoff=g);let _=Number(W);W.trim()!==``&&Number.isFinite(_)&&(m.timeout=_),Object.keys(m).length>0&&(a.jobOptions=m),Y(!0);try{await e(a),r(``),l(``),f(``),Z(!0),setTimeout(()=>Z(!1),3e3)}catch(e){q(e.message)}finally{Y(!1)}};return(0,A.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),$()},children:[(0,A.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,A.jsx)(S,{label:`Name`,children:(0,A.jsx)(b,{value:n,onChange:e=>r(e.target.value),placeholder:`daily-report`})}),(0,A.jsx)(S,{label:`Queue`,children:(0,A.jsx)(b,{value:i,onChange:e=>a(e.target.value),placeholder:`reports`})})]}),(0,A.jsxs)(`div`,{className:`flex flex-wrap items-end gap-3`,children:[(0,A.jsx)(y,{options:[`cron`,`every`],value:o,onChange:s}),o===`cron`?(0,A.jsx)(`div`,{className:`min-w-56 flex-1`,children:(0,A.jsx)(S,{label:`Cron expression`,children:(0,A.jsx)(b,{value:c,onChange:e=>l(e.target.value),placeholder:`0 9 * * *`})})}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`w-40`,children:(0,A.jsx)(S,{label:`Every (ms)`,children:(0,A.jsx)(b,{type:`number`,value:d,onChange:e=>f(e.target.value),placeholder:`30000`})})}),d.trim()!==``&&(0,A.jsx)(`span`,{className:t(`pb-2 text-xs`,M(d)?`text-muted`:`text-danger`),children:M(d)??`not a valid interval`})]})]}),o===`cron`&&c.trim()&&Q&&(0,A.jsx)(`div`,{className:`rounded-lg border border-line bg-surface-2 px-3 py-2 text-xs`,children:Q.valid?Q.runs.length?(0,A.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,A.jsxs)(`span`,{className:`text-faint`,children:[`Next runs`,v.trim()?` (local)`:``,`:`]}),Q.runs.map(e=>(0,A.jsx)(`span`,{className:`font-mono text-muted`,children:u(e)},e)),v.trim()&&(0,A.jsxs)(`span`,{className:`text-faint`,children:[`— server evaluates in `,v.trim()]})]}):(0,A.jsx)(`span`,{className:`text-warning`,children:`Valid, but no runs in the next few years.`}):(0,A.jsx)(`span`,{className:`text-danger`,children:Q.error})}),(0,A.jsx)(S,{label:`Data (JSON)`,children:(0,A.jsx)(`textarea`,{value:p,onChange:e=>m(e.target.value),rows:3,spellCheck:!1,className:`w-full rounded-lg border border-line bg-surface-2 px-3 py-2 font-mono text-sm text-fg placeholder:text-faint transition-colors focus:border-accent/60 focus:outline-none focus:ring-2 focus:ring-accent/30`})}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>g(e=>!e),className:`text-xs font-medium text-muted hover:text-fg`,children:h?`− Hide advanced`:`+ Advanced options`}),h&&(0,A.jsxs)(`div`,{className:`mt-3 grid grid-cols-2 gap-3`,children:[(0,A.jsx)(S,{label:`Timezone (IANA)`,hint:`e.g. Europe/Rome. Default: server timezone.`,children:(0,A.jsx)(b,{value:v,onChange:e=>C(e.target.value),placeholder:`Europe/Rome`})}),(0,A.jsx)(S,{label:`Priority`,children:(0,A.jsx)(b,{type:`number`,value:T,onChange:e=>E(e.target.value),placeholder:`0`})}),(0,A.jsx)(S,{label:`Max executions`,hint:`blank = unlimited`,children:(0,A.jsx)(b,{type:`number`,min:1,value:P,onChange:e=>F(e.target.value),placeholder:`∞`})}),(0,A.jsxs)(`div`,{className:`col-span-2 flex flex-wrap gap-6`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(x,{checked:D,onChange:O,label:`prevent overlap`}),(0,A.jsx)(`span`,{className:`text-sm text-muted`,children:`prevent overlap`})]}),(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(x,{checked:j,onChange:N,label:`skip if no worker`}),(0,A.jsx)(`span`,{className:`text-sm text-muted`,children:`skip if no worker`})]}),(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(x,{checked:I,onChange:L,label:`run immediately`}),(0,A.jsx)(`span`,{className:`text-sm text-muted`,children:`run immediately`})]}),(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(x,{checked:R,onChange:z,label:`skip missed on restart`}),(0,A.jsx)(`span`,{className:`text-sm text-muted`,children:`skip missed on restart`})]})]}),(0,A.jsxs)(`div`,{className:`col-span-2`,children:[(0,A.jsx)(`div`,{className:`mb-2 text-[11px] uppercase tracking-wider text-faint`,children:`Spawned-job options`}),(0,A.jsxs)(`div`,{className:`grid grid-cols-3 gap-3`,children:[(0,A.jsx)(S,{label:`Max attempts`,children:(0,A.jsx)(b,{type:`number`,min:1,value:B,onChange:e=>V(e.target.value),placeholder:`3`})}),(0,A.jsx)(S,{label:`Backoff (ms)`,children:(0,A.jsx)(b,{type:`number`,min:0,value:H,onChange:e=>U(e.target.value),placeholder:`1000`})}),(0,A.jsx)(S,{label:`Timeout (ms)`,children:(0,A.jsx)(b,{type:`number`,min:0,value:W,onChange:e=>G(e.target.value),placeholder:`—`})})]})]})]})]}),(0,A.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,A.jsx)(_,{type:`submit`,variant:`accent`,size:`sm`,disabled:J,children:J?`Creating…`:`Create`}),K&&(0,A.jsx)(`span`,{role:`status`,className:`text-xs text-danger`,children:K}),X&&(0,A.jsx)(`span`,{role:`status`,className:`text-xs text-success`,children:`Cron created ✓`})]})]})}export{j as CronManager};
@@ -1,3 +0,0 @@
1
- import{r as e,t}from"./cn-CMFYpumL.js";import{h as n,t as r}from"./react-vendor-BcouBxpZ.js";import{A as i,C as a,I as o,J as s,O as c,S as l,b as u,c as d,et as f,h as p,m,nt as h,r as g,rt as _,v,w as y,x as ee}from"./index-BOcegTHa.js";import{a as b}from"./form-DGinTEEb.js";import{t as x}from"./Pagination-D4ki-pGz.js";var S=e(n(),1),C=r(),w=50,T=500,E=2e5,D=`bq-dash-db-history`,O=10;function k(e){let t=e==null?``:String(e),n=typeof e==`string`&&/^[=+\-@]/.test(e)?`'${e}`:t;return/[",\r\n]/.test(n)?`"${n.replaceAll(`"`,`""`)}"`:n}function A(e,t){return[e.map(k).join(`,`),...t.map(e=>e.map(k).join(`,`))].join(`
2
- `)}function j(e,t,n){let r=URL.createObjectURL(new Blob([n],{type:t})),i=document.createElement(`a`);i.href=r,i.download=e,i.click(),URL.revokeObjectURL(r)}function M(){try{let e=JSON.parse(localStorage.getItem(D)??`[]`);return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}catch{return[]}}function N(e){try{localStorage.setItem(D,JSON.stringify(e))}catch{}return e}function P(e){return N([e,...M().filter(t=>t!==e)].slice(0,O))}function F(e){if(e==null)return`NULL`;let t=typeof e==`string`?e:String(e);try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}}function I({value:e,align:n}){if(e==null)return(0,C.jsx)(`span`,{className:`italic text-faint`,children:`NULL`});let r=typeof e==`string`?e:String(e);return(0,C.jsx)(`span`,{className:t(`block max-w-[24rem] truncate`,n===`right`&&`text-right tabular-nums`),title:r,children:r})}function L({columns:e,rows:n,truncatedCells:r,colMeta:i,sort:a,onSort:o,onRowClick:s,dimmed:c}){let l=(0,S.useMemo)(()=>e.map((e,t)=>{let r=i?.[e]?.type?.toUpperCase()??``;if(/INT|REAL|NUM|DEC|DOUB|FLOA/.test(r))return!0;let a=!1;for(let e of n){let n=e[t];if(n!=null&&(a=!0,typeof n!=`number`))return!1}return a}),[e,n,i]);return(0,C.jsx)(`div`,{className:t(`max-h-[70vh] overflow-auto rounded-xl border border-line bg-surface transition-opacity`,c&&`pointer-events-none opacity-50`),children:(0,C.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,C.jsx)(`thead`,{children:(0,C.jsx)(`tr`,{className:`text-left text-[11px] uppercase tracking-wider text-faint`,children:e.map((e,n)=>{let r=i?.[e];return(0,C.jsx)(`th`,{className:t(`sticky top-0 z-10 whitespace-nowrap border-b border-line bg-surface px-4 py-3 font-medium`,l[n]&&`text-right`),"aria-sort":a?.col===e?a.dir===`asc`?`ascending`:`descending`:o?`none`:void 0,children:o?(0,C.jsxs)(`button`,{type:`button`,onClick:()=>o(e),"aria-label":`Sort by ${e}`,className:`inline-flex items-center gap-1 uppercase tracking-wider hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50`,children:[e,r?.primaryKey&&(0,C.jsx)(`span`,{className:`rounded bg-accent/15 px-1 py-0.5 text-[9px] font-semibold text-accent`,children:`PK`}),r?.type&&(0,C.jsx)(`span`,{className:`text-faint/70`,children:r.type.toLowerCase()}),(0,C.jsx)(`span`,{"aria-hidden":`true`,className:a?.col===e?`text-accent`:`text-faint/60`,children:a?.col===e?a.dir===`asc`?`▲`:`▼`:`↕`})]}):e},e)})})}),(0,C.jsx)(`tbody`,{children:n.map((e,n)=>(0,C.jsx)(`tr`,{onClick:s?()=>s(n):void 0,onKeyDown:s?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),s(n))}:void 0,tabIndex:s?0:void 0,className:t(`border-b border-line font-mono text-xs last:border-0 hover:bg-surface-2/40`,s&&`cursor-pointer`),children:e.map((e,t)=>(0,C.jsx)(`td`,{className:`whitespace-nowrap px-4 py-2 text-muted`,children:(0,C.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,C.jsx)(I,{value:e,align:l[t]?`right`:`left`}),r?.[n]?.[t]&&(0,C.jsx)(`span`,{title:`Value truncated — click the row to view it in full`,className:`shrink-0 rounded bg-warning/15 px-1 text-[9px] font-semibold text-warning`,children:`…`})]})},t))},n))})]})})}function R(){let[e,n]=(0,S.useState)(``),[r,a]=(0,S.useState)(0),[o,s]=(0,S.useState)(null),[c,b]=(0,S.useState)(`data`),[D,O]=(0,S.useState)(null),[k,M]=(0,S.useState)(null),[N,P]=(0,S.useState)(`SELECT name FROM sqlite_master WHERE type = 'table'`),F=(0,S.useRef)(null),{data:I,error:R,loading:ie,refetch:ae}=i(()=>h.db.tables(),[],{intervalMs:1e4}),B=(0,S.useMemo)(()=>I?.tables??[],[I]),V=R instanceof f&&R.status===404,{data:H}=i(()=>V?Promise.resolve(null):h.db.info(),[V],{intervalMs:15e3}),U=e||B[0]?.name||``;(0,S.useEffect)(()=>{!e&&B[0]&&n(B[0].name)},[e,B]);let{data:W}=i(()=>U?h.db.schema(U):Promise.resolve(null),[U],{intervalMs:3e4}),oe=(0,S.useMemo)(()=>{let e={};if(W?.table===U)for(let t of W.columns)e[t.name]={type:t.type,primaryKey:t.primaryKey};return e},[W,U]),G=D?`${D.column}|${D.op}|${D.value}`:``,{data:K,error:q,loading:J}=i((0,S.useCallback)(async()=>U?{...await h.db.rows(U,w,r*w,o?.col,o?.dir,D??void 0),page:r,filterKey:G}:null,[U,r,o,D,G]),[U,r,o,G],{intervalMs:6e3}),Y=K&&K.table===U&&K.page===r&&K.orderBy===(o?.col??null)&&(!o||K.dir===o.dir)&&K.filterKey===G?K:null;(0,S.useEffect)(()=>{Y&&Y.total>0&&Y.rows.length===0&&r>0&&a(Math.max(0,Math.ceil(Y.total/w)-1))},[Y,r]);let[X,Z]=(0,S.useState)(!1),[Q,$]=(0,S.useState)(null),se=()=>{a(0),s(null),O(null),M(null)},ce=e=>{n(e),b(`data`),se()},le=e=>{a(0),M(null),s(t=>t?.col===e?t.dir===`asc`?{col:e,dir:`desc`}:null:{col:e,dir:`asc`})},ue=()=>{Y&&j(`${Y.table}-page${r+1}.csv`,`text/csv`,A(Y.columns,Y.rows))},de=async()=>{if(!(!U||X)){Z(!0),$(null);try{let e=[],t=[],n=0,r=!1;for(;;){let i=await h.db.rows(U,T,n,o?.col,o?.dir,D??void 0);if(t=i.columns,e.push(...i.rows),n+=T,e.length>=E){r=!0;break}if(i.rows.length<T||n>=i.total)break}j(`${U}.csv`,`text/csv`,A(t,e));let i=r?`Exported the first ${d(e.length)} rows (export cap reached)`:`Exported ${d(e.length)} rows`;$(i),_.success(`Export of ${U} complete`,i)}catch(e){$(`Export failed: ${e.message}`),_.error(`Export of ${U} failed`,e.message)}finally{Z(!1)}}},fe=()=>{let e=`SELECT * FROM "${U.replaceAll(`"`,`""`)}" LIMIT 100`;P(e),requestAnimationFrame(()=>{F.current?.focus(),F.current?.scrollIntoView({behavior:`smooth`,block:`center`})})},pe=!!Y?.truncatedCells.some(e=>e.some(Boolean));return(0,C.jsxs)(`div`,{children:[(0,C.jsx)(p,{title:`Database`,description:`SQLite inspector — schema, data and queries over a read-only connection.`,actions:(0,C.jsx)(`span`,{className:`rounded-full bg-emerald-500/10 px-2.5 py-1 text-[11px] font-medium text-success`,children:`read-only`})}),R&&!V&&(0,C.jsx)(ee,{message:`Could not read the database — ${R.message}`,onRetry:ae}),H&&(0,C.jsxs)(`div`,{className:`mb-6 grid grid-cols-2 gap-4 md:grid-cols-3 xl:grid-cols-5`,children:[(0,C.jsx)(m,{label:`SQLite`,value:H.sqliteVersion,compact:!0}),(0,C.jsx)(m,{label:`On disk`,value:g(H.fileSize+H.walSize),compact:!0}),(0,C.jsx)(m,{label:`Journal`,value:H.journalMode.toUpperCase(),compact:!0}),(0,C.jsx)(m,{label:`Tables`,value:d(H.tables),compact:!0}),(0,C.jsx)(m,{label:`Indexes`,value:d(H.indexes),compact:!0})]}),V?(0,C.jsx)(v,{title:`No database yet`,hint:R.message}):ie&&B.length===0?(0,C.jsx)(u,{label:`Reading database…`}):(0,C.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-4`,children:[(0,C.jsxs)(l,{padded:!1,className:`self-start overflow-hidden`,children:[(0,C.jsxs)(`div`,{className:`border-b border-line px-4 py-3 text-[11px] font-medium uppercase tracking-wider text-faint`,children:[`Tables (`,B.length,`)`]}),(0,C.jsxs)(`ul`,{className:`max-h-[28rem] overflow-y-auto`,children:[B.map(e=>(0,C.jsx)(`li`,{children:(0,C.jsxs)(`button`,{type:`button`,onClick:()=>ce(e.name),className:t(`flex w-full items-center justify-between gap-2 px-4 py-2 text-left text-sm transition-colors`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50`,U===e.name?`bg-surface-2 text-fg`:`text-muted hover:bg-surface-2/60 hover:text-fg`),children:[(0,C.jsx)(`span`,{className:`min-w-0 truncate font-mono text-xs`,children:e.name}),(0,C.jsx)(`span`,{className:`shrink-0 text-[11px] text-faint tabular-nums`,children:d(e.rows)})]})},e.name)),B.length===0&&(0,C.jsx)(`li`,{className:`px-4 py-6 text-center text-xs text-faint`,children:`No tables.`})]})]}),(0,C.jsx)(`div`,{className:`min-w-0 lg:col-span-3`,children:B.length===0?(0,C.jsx)(v,{title:`No tables`,hint:`This database has no user tables yet.`}):(0,C.jsxs)(C.Fragment,{children:[U&&(0,C.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center gap-2`,children:[(0,C.jsx)(`span`,{className:`mr-auto min-w-0 truncate font-mono text-sm text-fg`,title:U,children:U}),(0,C.jsx)(y,{size:`sm`,variant:`ghost`,onClick:fe,children:`Query`}),(0,C.jsx)(`div`,{className:`inline-flex items-center gap-1 rounded-lg border border-line bg-surface p-1`,children:[`data`,`schema`].map(e=>(0,C.jsx)(`button`,{type:`button`,onClick:()=>b(e),"aria-pressed":c===e,className:t(`rounded-md px-3 py-1 text-xs font-medium capitalize transition-colors`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50`,c===e?`bg-surface-2 text-fg`:`text-muted hover:text-fg`),children:e},e))}),c===`data`&&(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(y,{size:`sm`,disabled:!Y||Y.rows.length===0,title:Y?`Exports the ${Y.rows.length} rows on this page only`:void 0,onClick:ue,children:[`Export page`,Y?` (${Y.rows.length})`:``]}),(0,C.jsx)(y,{size:`sm`,variant:`accent`,disabled:X||!Y||Y.total===0,onClick:de,children:X?`Exporting…`:`Export table${Y?` (${d(Y.total)})`:``}`})]})]}),c===`data`&&U&&(0,C.jsx)(z,{columns:Y?.columns??W?.columns.map(e=>e.name)??[],filter:D,onChange:e=>{O(e),a(0),M(null)}},U),Q&&(0,C.jsx)(`p`,{className:`mb-3 text-xs text-muted`,children:Q}),c===`schema`?W?.table===U?(0,C.jsx)(ne,{schema:W}):(0,C.jsx)(u,{label:`Reading schema of ${U}…`}):q&&!Y?(0,C.jsx)(v,{title:`Could not read table`,hint:q.message}):J&&!Y&&K?.table!==U?(0,C.jsx)(u,{label:`Reading ${U}…`}):!Y&&!K?(0,C.jsx)(v,{title:`Select a table`,hint:`Pick a table on the left to browse its rows.`}):(Y??K)&&(Y??K)?.total===0?(0,C.jsx)(v,{title:D?`No matching rows`:`Empty table`,hint:D?`No rows match the current filter.`:`"${(Y??K)?.table}" has no rows.`}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(L,{columns:(Y??K)?.columns??[],rows:(Y??K)?.rows??[],truncatedCells:(Y??K)?.truncatedCells,colMeta:oe,sort:o,onSort:le,onRowClick:e=>M(e),dimmed:J&&!Y}),pe&&(0,C.jsx)(`p`,{className:`mt-2 text-[11px] text-faint`,children:`Cells over 2000 chars and BLOBs are abbreviated in the grid and CSV — click a row to view the full value.`}),(0,C.jsx)(x,{page:r,pageSize:w,total:(Y??K)?.total??0,onPageChange:e=>{a(e),M(null)},label:`rows`})]}),(0,C.jsx)(re,{sql:N,setSql:P,editorRef:F})]})})]}),Y&&k!=null&&Y.rows[k]&&(0,C.jsx)(te,{table:Y.table,columns:Y.columns,row:Y.rows[k],rowid:Y.rowids[k],truncated:Y.truncatedCells[k],onClose:()=>M(null)})]})}function z({columns:e,filter:t,onChange:n}){let[r,i]=(0,S.useState)(t?.column??``),[a,o]=(0,S.useState)(t?.op??`contains`),[c,l]=(0,S.useState)(t?.value??``),u=r||e[0]||``,d=()=>n(c.trim()?{column:u,op:a,value:c.trim()}:null);return e.length===0?null:(0,C.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-center gap-2`,children:[(0,C.jsx)(`div`,{className:`w-40`,children:(0,C.jsx)(b,{value:u,"aria-label":`Filter column`,onChange:e=>i(e.target.value),children:e.map(e=>(0,C.jsx)(`option`,{value:e,children:e},e))})}),(0,C.jsx)(`div`,{className:`w-32`,children:(0,C.jsxs)(b,{value:a,"aria-label":`Filter operator`,onChange:e=>o(e.target.value),children:[(0,C.jsx)(`option`,{value:`contains`,children:`contains`}),(0,C.jsx)(`option`,{value:`eq`,children:`=`}),(0,C.jsx)(`option`,{value:`ne`,children:`≠`})]})}),(0,C.jsxs)(`div`,{className:`relative min-w-40 flex-1`,children:[(0,C.jsx)(s,{className:`pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-faint`}),(0,C.jsx)(`input`,{value:c,onChange:e=>l(e.target.value),onKeyDown:e=>e.key===`Enter`&&d(),"aria-label":`Filter value`,placeholder:`value — Enter to filter`,className:`h-9 w-full rounded-lg border border-line bg-surface pl-8 pr-3 text-sm text-fg placeholder:text-faint focus:border-accent/60 focus:outline-none focus:ring-2 focus:ring-accent/30`})]}),(0,C.jsx)(y,{size:`sm`,onClick:d,disabled:!c.trim(),children:`Filter`}),t&&(0,C.jsx)(y,{size:`sm`,variant:`ghost`,onClick:()=>{l(``),n(null)},children:`Clear`}),(0,C.jsx)(`span`,{className:`text-[11px] text-faint`,children:`filters the whole table, server-side`})]})}function te({table:e,columns:t,row:n,rowid:r,truncated:i,onClose:a}){let[s,l]=(0,S.useState)({}),u=(0,S.useRef)(null);(0,S.useEffect)(()=>{let e=e=>e.key===`Escape`&&a();return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[a]),(0,S.useEffect)(()=>{let e=document.activeElement;return u.current?.focus(),()=>{e?.isConnected&&e.focus()}},[]);let d=t.filter((e,t)=>i[t]).join(``);return(0,S.useEffect)(()=>{if(r==null||!d)return;let t=d.split(``),n=!1;return(async()=>{for(let i of t)try{let t=await h.db.cell(e,r,i);n||l(e=>({...e,[i]:t.value}))}catch{}})(),()=>{n=!0}},[e,r,d]),(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(`button`,{type:`button`,"aria-label":`Close row detail`,onClick:a,className:`fixed inset-0 z-40 bg-black/50`}),(0,C.jsxs)(`aside`,{ref:u,role:`dialog`,"aria-modal":`true`,"aria-label":`${e} row ${r??`detail`}`,tabIndex:-1,className:`fixed inset-y-0 right-0 z-50 flex w-full max-w-xl flex-col border-l border-line bg-surface shadow-xl focus-visible:outline-none`,children:[(0,C.jsxs)(`div`,{className:`flex items-center justify-between border-b border-line px-5 py-4`,children:[(0,C.jsxs)(`h2`,{className:`font-mono text-sm text-fg`,children:[e,` · row detail`]}),(0,C.jsx)(`button`,{type:`button`,"aria-label":`Close`,onClick:a,className:`flex size-8 items-center justify-center rounded-lg text-muted hover:bg-surface-2 hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50`,children:(0,C.jsx)(o,{className:`size-4`})})]}),(0,C.jsx)(`div`,{className:`flex-1 overflow-y-auto p-5`,children:(0,C.jsx)(`dl`,{className:`flex flex-col gap-4`,children:t.map((e,t)=>{let r=e in s?s[e]:n[t],a=F(r),o=a.includes(`
3
- `)||a.length>80;return(0,C.jsxs)(`div`,{children:[(0,C.jsxs)(`dt`,{className:`mb-1 flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-faint`,children:[e,r!=null&&(0,C.jsx)(c,{value:String(r)}),i[t]&&!(e in s)&&(0,C.jsx)(`span`,{className:`text-warning`,children:`(loading full value…)`})]}),(0,C.jsx)(`dd`,{children:r==null?(0,C.jsx)(`span`,{className:`italic text-faint`,children:`NULL`}):o?(0,C.jsx)(`pre`,{className:`max-h-80 overflow-auto whitespace-pre-wrap break-words rounded-lg bg-surface-2 p-3 font-mono text-xs text-muted`,children:a}):(0,C.jsx)(`span`,{className:`break-words font-mono text-sm text-fg`,children:a})})]},e)})})})]})]})}function ne({schema:e}){return(0,C.jsxs)(`div`,{className:`flex flex-col gap-6`,children:[(0,C.jsx)(`div`,{className:`overflow-x-auto rounded-xl border border-line bg-surface`,children:(0,C.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,C.jsx)(`thead`,{children:(0,C.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,C.jsx)(`th`,{className:`px-4 py-3 font-medium`,children:`Column`}),(0,C.jsx)(`th`,{className:`px-4 py-3 font-medium`,children:`Type`}),(0,C.jsx)(`th`,{className:`px-4 py-3 font-medium`,children:`Constraints`}),(0,C.jsx)(`th`,{className:`px-4 py-3 font-medium`,children:`Default`})]})}),(0,C.jsx)(`tbody`,{children:e.columns.map(e=>(0,C.jsxs)(`tr`,{className:`border-b border-line last:border-0`,children:[(0,C.jsx)(`td`,{className:`px-4 py-2 font-mono text-xs text-fg`,children:e.name}),(0,C.jsx)(`td`,{className:`px-4 py-2 font-mono text-xs text-muted`,children:e.type}),(0,C.jsxs)(`td`,{className:`px-4 py-2 text-xs`,children:[e.primaryKey&&(0,C.jsx)(`span`,{className:`mr-1 rounded-md bg-accent/15 px-1.5 py-0.5 text-[10px] font-semibold text-accent`,children:`PK`}),e.notNull&&(0,C.jsx)(`span`,{className:`rounded-md bg-surface-2 px-1.5 py-0.5 text-[10px] font-semibold text-muted`,children:`NOT NULL`})]}),(0,C.jsx)(`td`,{className:`px-4 py-2 font-mono text-xs text-faint`,children:e.defaultValue??`—`})]},e.name))})]})}),(0,C.jsxs)(l,{children:[(0,C.jsx)(a,{title:`Indexes (${e.indexes.length})`}),e.indexes.length===0?(0,C.jsx)(`p`,{className:`text-xs text-faint`,children:`No indexes on this table.`}):(0,C.jsx)(`ul`,{className:`flex flex-col gap-1.5`,children:e.indexes.map(e=>(0,C.jsxs)(`li`,{className:`flex flex-wrap items-center gap-2 font-mono text-xs`,children:[(0,C.jsx)(`span`,{className:`text-fg`,children:e.name}),e.unique&&(0,C.jsx)(`span`,{className:`rounded-md bg-accent/15 px-1.5 py-0.5 text-[10px] font-semibold text-accent`,children:`UNIQUE`}),(0,C.jsxs)(`span`,{className:`text-faint`,children:[`(`,e.columns.join(`, `),`)`]})]},e.name))})]}),e.sql&&(0,C.jsxs)(l,{children:[(0,C.jsxs)(`div`,{className:`mb-2 flex items-center justify-between`,children:[(0,C.jsx)(`h3`,{className:`text-base font-semibold text-fg`,children:`DDL`}),(0,C.jsx)(c,{value:e.sql})]}),(0,C.jsx)(`pre`,{className:`overflow-x-auto rounded-lg bg-surface-2 p-3 font-mono text-xs text-muted`,children:e.sql})]})]})}function re({sql:e,setSql:t,editorRef:n}){let[r,i]=(0,S.useState)(!1),[o,s]=(0,S.useState)(null),[c,u]=(0,S.useState)(M),[f,p]=(0,S.useState)(null),m=(0,S.useRef)(0);(0,S.useEffect)(()=>()=>{m.current++},[]);let g=async(t=e,n=!0)=>{if(!t.trim()||r)return;let a=++m.current;i(!0),s(null);try{let r=await h.db.query(t);if(a!==m.current)return;p(r),n&&u(P(e.trim()))}catch(e){if(a!==m.current)return;p(null),s(e.message)}finally{a===m.current&&i(!1)}};return(0,C.jsxs)(l,{className:`mt-6`,children:[(0,C.jsx)(a,{title:`Query`,action:(0,C.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,C.jsx)(y,{size:`sm`,disabled:r||!e.trim(),onClick:()=>{let t=e.trim();t&&g(`EXPLAIN QUERY PLAN ${t}`,!1)},children:`Explain`}),(0,C.jsx)(y,{size:`sm`,variant:`accent`,disabled:r||!e.trim(),onClick:()=>g(),children:r?`Running…`:`Run`})]})}),(0,C.jsx)(`textarea`,{ref:n,value:e,onChange:e=>t(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&g()},rows:3,spellCheck:!1,"aria-label":`SQL query`,placeholder:`SELECT … — read-only: writes are rejected by the engine`,className:`w-full resize-y rounded-lg border border-line bg-surface-2 p-3 font-mono text-xs text-fg placeholder:text-faint focus:border-accent/60 focus:outline-none focus:ring-2 focus:ring-accent/30`}),(0,C.jsx)(`p`,{className:`mt-1 text-[11px] text-faint`,children:`⌘/Ctrl+Enter runs. Connection is read-only.`}),c.length>0&&(0,C.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-1.5`,children:[(0,C.jsx)(`span`,{className:`text-[11px] uppercase tracking-wider text-faint`,children:`History`}),c.map(e=>(0,C.jsx)(`button`,{type:`button`,onClick:()=>t(e),title:e,className:`max-w-56 truncate rounded-md border border-line bg-surface-2 px-2 py-1 font-mono text-[11px] text-muted transition-colors hover:border-line-strong hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50`,children:e},e)),(0,C.jsx)(`button`,{type:`button`,onClick:()=>{N([]),u([])},className:`rounded-md px-2 py-1 text-[11px] text-faint transition-colors hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50`,children:`Clear`})]}),(0,C.jsxs)(`div`,{"aria-live":`polite`,children:[o&&(0,C.jsx)(`p`,{role:`alert`,className:`mt-3 text-xs text-danger`,children:o}),f&&!o&&(0,C.jsxs)(`div`,{className:`mt-4`,children:[(0,C.jsxs)(`div`,{className:`mb-2 flex flex-wrap items-center gap-3`,children:[(0,C.jsxs)(`p`,{className:`text-xs text-faint`,children:[f.truncated?`≥ `:``,d(f.rowCount),` row`,f.rowCount===1?``:`s`,` ·`,` `,d(f.ms),` ms`,f.truncated&&(0,C.jsxs)(`span`,{className:`text-warning`,children:[` — showing first `,f.rows.length]})]}),f.rows.length>0&&(0,C.jsxs)(`div`,{className:`ml-auto flex gap-2`,children:[(0,C.jsx)(y,{size:`sm`,onClick:()=>j(`query-results.csv`,`text/csv`,A(f.columns,f.rows)),children:`CSV`}),(0,C.jsx)(y,{size:`sm`,onClick:()=>j(`query-results.json`,`application/json`,JSON.stringify(f.rows.map(e=>Object.fromEntries(f.columns.map((t,n)=>[t,e[n]]))),null,2)),children:`JSON`})]})]}),f.rows.length>0?(0,C.jsx)(L,{columns:f.columns,rows:f.rows}):(0,C.jsx)(`p`,{className:`text-xs text-faint`,children:`Query returned no rows.`})]})]})]})}export{R as Database};
@@ -1 +0,0 @@
1
- import{r as e}from"./cn-CMFYpumL.js";import{h as t,t as n}from"./react-vendor-BcouBxpZ.js";import{A as r,C as i,O as a,S as o,b as s,c,d as l,h as u,m as d,nt as f,r as p,rt as m,w as h,x as g}from"./index-BOcegTHa.js";var _=e(t(),1),v=n(),y={health:{},storage:null,stats:null};function b(){let{data:e,error:t,loading:n,refetch:b}=r(async()=>{let[e,t,n]=await Promise.all([f.health(),f.storage().catch(()=>null),f.stats().catch(()=>null)]);return{health:e,storage:t,stats:n}},[]),[C,w]=(0,_.useState)(null),T=async()=>{w(`…`);let e=performance.now();try{await f.ping(),w(`${Math.round(performance.now()-e)} ms`)}catch{w(`unreachable`)}},[E,D]=(0,_.useState)(!1),[O,k]=(0,_.useState)(null),A=async()=>{D(!0),k(null);try{let e=await f.gc(),t=e.before.rss-e.after.rss,n=t>0?`Freed ${t} MB (RSS ${e.before.rss}→${e.after.rss})`:`No memory reclaimed`;k(n),m.success(`Memory compacted`,n),b()}catch(e){m.error(`GC failed`,e.message),k(e.message)}finally{D(!1)}},[j,M]=(0,_.useState)(null),[N,P]=(0,_.useState)(!1),F=async()=>{P(!0);try{M(await f.heapStats())}catch(e){m.error(`Heap stats failed`,e.message)}finally{P(!1)}};if(n&&!e&&!t)return(0,v.jsx)(s,{label:`Loading diagnostics…`});let I=e??y,L=I.health,R=I.storage?.data,z=I.stats?.stats;return(0,v.jsxs)(`div`,{children:[(0,v.jsx)(u,{title:`Diagnostics`,description:`Server health, storage, memory and connections.`,live:!t}),t&&(0,v.jsx)(g,{onRetry:b}),(0,v.jsxs)(`div`,{className:`mb-6 grid grid-cols-2 gap-4 md:grid-cols-4`,children:[(0,v.jsx)(d,{label:`Status`,value:L.status??(L.ok?`healthy`:`degraded`),tone:L.ok?`green`:`red`,compact:!0}),(0,v.jsx)(d,{label:`Version`,value:L.version?`v${L.version}`:`—`,compact:!0}),(0,v.jsx)(d,{label:`Uptime`,value:l(L.uptime),compact:!0}),(0,v.jsx)(d,{label:`Disk`,value:R?.diskFull?`Full`:`Healthy`,tone:R?.diskFull?`red`:`green`,compact:!0})]}),(0,v.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-2`,children:[(0,v.jsxs)(o,{children:[(0,v.jsx)(i,{title:`Connectivity`,action:(0,v.jsxs)(h,{size:`sm`,onClick:T,children:[`Ping`,C?` · ${C}`:``]})}),(0,v.jsxs)(`dl`,{className:`divide-y divide-line text-sm`,children:[(0,v.jsx)(x,{k:`WebSocket clients`,v:String(L.connections?.ws??0)}),(0,v.jsx)(x,{k:`SSE clients`,v:String(L.connections?.sse??0)}),(0,v.jsx)(x,{k:`Storage error`,v:R?.error?String(R.error):`none`})]})]}),(0,v.jsxs)(o,{children:[(0,v.jsx)(i,{title:`Memory`,action:(0,v.jsx)(h,{size:`sm`,disabled:E,onClick:A,children:E?`Compacting…`:`Compact (GC)`})}),(0,v.jsxs)(`div`,{className:`grid grid-cols-3 gap-4`,children:[(0,v.jsx)(S,{k:`Heap used`,v:p((L.memory?.heapUsed??0)*1024*1024)}),(0,v.jsx)(S,{k:`Heap total`,v:p((L.memory?.heapTotal??0)*1024*1024)}),(0,v.jsx)(S,{k:`RSS`,v:p((L.memory?.rss??0)*1024*1024)})]}),O&&(0,v.jsx)(`p`,{className:`mt-3 text-xs text-muted`,children:O})]})]}),(0,v.jsxs)(o,{className:`mt-6`,children:[(0,v.jsx)(i,{title:`Heap statistics`,action:(0,v.jsx)(h,{size:`sm`,disabled:N,onClick:F,children:N?`Loading…`:j?`Refresh`:`Load`})}),j?(0,v.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-2`,children:[(0,v.jsxs)(`div`,{className:`grid grid-cols-3 gap-4`,children:[(0,v.jsx)(S,{k:`Objects`,v:c(j.heap?.objectCount??0)}),(0,v.jsx)(S,{k:`Protected`,v:c(j.heap?.protectedCount??0)}),(0,v.jsx)(S,{k:`Global`,v:c(j.heap?.globalCount??0)})]}),(0,v.jsxs)(`div`,{children:[(0,v.jsx)(`div`,{className:`mb-2 text-[11px] uppercase tracking-wider text-faint`,children:`Top object types`}),(0,v.jsx)(`div`,{className:`max-h-52 overflow-y-auto rounded-lg border border-line`,children:(0,v.jsx)(`table`,{className:`w-full text-xs`,children:(0,v.jsx)(`tbody`,{children:(j.topObjectTypes??[]).map(e=>(0,v.jsxs)(`tr`,{className:`border-b border-line last:border-0`,children:[(0,v.jsx)(`td`,{className:`px-3 py-1.5 font-mono text-muted`,children:e.type}),(0,v.jsx)(`td`,{className:`px-3 py-1.5 text-right tnum text-fg`,children:c(e.count)})]},e.type))})})})]})]}):(0,v.jsxs)(`p`,{className:`text-sm text-muted`,children:[`On-demand `,(0,v.jsx)(`code`,{className:`font-mono text-xs`,children:`bun:jsc`}),` heap breakdown (forces a GC first). Use it to spot which internal object type is growing when chasing a leak.`]})]}),(0,v.jsxs)(o,{className:`mt-6`,children:[(0,v.jsx)(i,{title:`Prometheus`}),(0,v.jsxs)(`p`,{className:`mb-3 text-sm text-muted`,children:[`Scrape endpoint (text exposition) for Grafana / Alertmanager. Auth is required only if the server sets `,(0,v.jsx)(`code`,{className:`font-mono text-xs`,children:`requireAuthForMetrics`}),`.`]}),(0,v.jsxs)(`div`,{className:`flex items-center gap-2 rounded-lg border border-line bg-surface-2 px-3 py-2`,children:[(0,v.jsx)(`code`,{className:`min-w-0 flex-1 truncate font-mono text-xs text-fg`,children:f.prometheusUrl()}),(0,v.jsx)(a,{value:f.prometheusUrl()})]})]}),z&&(0,v.jsxs)(o,{className:`mt-6`,children:[(0,v.jsx)(i,{title:`Totals since restart`}),(0,v.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 md:grid-cols-4`,children:[(0,v.jsx)(S,{k:`Pushed`,v:c(z.totalPushed)}),(0,v.jsx)(S,{k:`Pulled`,v:c(z.totalPulled)}),(0,v.jsx)(S,{k:`Completed`,v:c(z.totalCompleted)}),(0,v.jsx)(S,{k:`Failed`,v:c(z.totalFailed)})]})]})]})}function x({k:e,v:t}){return(0,v.jsxs)(`div`,{className:`flex items-center justify-between py-2.5`,children:[(0,v.jsx)(`dt`,{className:`text-muted`,children:e}),(0,v.jsx)(`dd`,{className:`font-medium text-fg`,children:t})]})}function S({k:e,v:t}){return(0,v.jsxs)(`div`,{children:[(0,v.jsx)(`div`,{className:`text-[11px] uppercase tracking-wider text-faint`,children:e}),(0,v.jsx)(`div`,{className:`mt-1 text-lg font-semibold tnum text-fg`,children:t})]})}export{b as Diagnostics};