bunqueue-dashboard 0.0.47 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/README.md +6 -6
  2. package/agent/managedTarget.ts +3 -1
  3. package/agent/manager/commandLine.ts +33 -0
  4. package/agent/manager/errors.ts +4 -0
  5. package/agent/manager/process.ts +4 -2
  6. package/agent/manager.ts +1 -0
  7. package/agent/server/controlRoutes.ts +10 -0
  8. package/agent/server/controlStatus.ts +26 -5
  9. package/agent/server/errors.ts +3 -0
  10. package/agent/server/router.ts +2 -1
  11. package/agent/shutdown.ts +3 -2
  12. package/dist/.vite/manifest.json +537 -575
  13. package/dist/assets/AddJob-CiwWycYG.js +3 -0
  14. package/dist/assets/Alerts-DzKKoA9U.js +1 -0
  15. package/dist/assets/AreaChart-Db2UVnaK.js +1 -0
  16. package/dist/assets/Benchmark-CHYDL31K.js +1 -0
  17. package/dist/assets/BulkAddJobs-GRMVnf0j.js +5 -0
  18. package/dist/assets/Button-_aSJvRoW.js +1 -0
  19. package/dist/assets/Card-egIDLwVk.js +1 -0
  20. package/dist/assets/Cron-XL0PdUEc.js +1 -0
  21. package/dist/assets/CronManager-Cqtg9Zr8.js +1 -0
  22. package/dist/assets/{Database-DV2pcDLL.js → Database-BoxVpjts.js} +3 -3
  23. package/dist/assets/Diagnostics-B3QSQuFF.js +1 -0
  24. package/dist/assets/Dlq-DHOfgORa.js +1 -0
  25. package/dist/assets/DlqControl-BY1e55-x.js +1 -0
  26. package/dist/assets/DlqPro-CfwKDcpc.js +1 -0
  27. package/dist/assets/Fleet-Bkbq0dFB.js +1 -0
  28. package/dist/assets/Flows-CDCQrPit.js +2 -0
  29. package/dist/assets/JobInspector-Bw3Gs1Iy.js +2 -0
  30. package/dist/assets/Jobs-IrlneOy6.js +1 -0
  31. package/dist/assets/JobsPro-vlPd6Ows.js +1 -0
  32. package/dist/assets/Logs-DG7cK-tF.js +1 -0
  33. package/dist/assets/LogsPro-ClSqFKys.js +1 -0
  34. package/dist/assets/{McpServer-fVy27Mof.js → McpServer-DoNFY0Pj.js} +1 -1
  35. package/dist/assets/{Metrics-Ba46pdzT.js → Metrics-BkePZiCZ.js} +1 -1
  36. package/dist/assets/MetricsPro-ooSvpQ3H.js +1 -0
  37. package/dist/assets/{Overview-DV2qo5v3.js → Overview-CuWmPRra.js} +1 -1
  38. package/dist/assets/{PageHeader-CvIyaFOO.js → PageHeader-CQzNsw8r.js} +1 -1
  39. package/dist/assets/Pagination-CSkzhNW6.js +1 -0
  40. package/dist/assets/QueueActions-BBxRt-t0.js +1 -0
  41. package/dist/assets/QueueControl-C01l6bBJ.js +1 -0
  42. package/dist/assets/QueueDetail-gSf9Tb7G.js +1 -0
  43. package/dist/assets/QueueDetailPro-BKszqI0M.js +1 -0
  44. package/dist/assets/Queues-BAg2nSz0.js +1 -0
  45. package/dist/assets/QueuesOverview-BLSjiYsA.js +1 -0
  46. package/dist/assets/{S3Backup-DNABHR2Q.js → S3Backup-Ci4dJPP_.js} +1 -1
  47. package/dist/assets/S3BackupPro-DcjlrzC5.js +3 -0
  48. package/dist/assets/ServerControl-SiZBNo9P.js +3 -0
  49. package/dist/assets/Settings-DR_iqW0T.js +1 -0
  50. package/dist/assets/StatusBadge-DereLzOj.js +1 -0
  51. package/dist/assets/{Usage-1KxG1mJ9.js → Usage-ZWfB7PcR.js} +1 -1
  52. package/dist/assets/UsagePro-BjdeS2zb.js +1 -0
  53. package/dist/assets/Webhooks-BonYUgMo.js +1 -0
  54. package/dist/assets/Workers-C1h6hCPp.js +1 -0
  55. package/dist/assets/WorkersPro-B0f_Nfdz.js +1 -0
  56. package/dist/assets/Workflows-CqZZ96EK.js +1 -0
  57. package/dist/assets/{api-BgWE-705.js → api-D9aT0ND7.js} +1 -1
  58. package/dist/assets/bq-DR2BTISO.js +1 -0
  59. package/dist/assets/classicJobsData-Csj4iihY.js +1 -0
  60. package/dist/assets/connectionStore-CVjQyIZv.js +1 -0
  61. package/dist/assets/controlConnectionEpoch-ChAeMMLk.js +1 -0
  62. package/dist/assets/feedback-CtGN_kqB.js +1 -0
  63. package/dist/assets/form-DG3X6cLL.js +1 -0
  64. package/dist/assets/{icons-BVzwsfbG.js → icons-DH9SS1DA.js} +1 -1
  65. package/dist/assets/index-Bat1DN5U.js +8 -0
  66. package/dist/assets/react-vendor-CFL9l8LK.js +11 -0
  67. package/dist/assets/{cn-zFEt5SO8.js → rolldown-runtime-QTnfLwEv.js} +1 -1
  68. package/dist/assets/{toastStore-IZn6OPLZ.js → toastStore-XmMX7A5W.js} +1 -1
  69. package/dist/assets/useControlActionGuard-1i7aFA7E.js +1 -0
  70. package/dist/assets/usePolledData-CEyyLRYa.js +1 -0
  71. package/dist/assets/useServerActionGuard-CUx8TOAC.js +1 -0
  72. package/dist/assets/useThroughputSeries-CeFx-Mwq.js +1 -0
  73. package/dist/index.html +14 -14
  74. package/package.json +10 -7
  75. package/scripts/embedded.gen.ts +152 -162
  76. package/scripts/serveHandler.ts +28 -1
  77. package/dist/assets/AddJob-FNaPbs_V.js +0 -3
  78. package/dist/assets/Alerts-vzIYtFpW.js +0 -1
  79. package/dist/assets/AreaChart-DEAalJ6P.js +0 -1
  80. package/dist/assets/Benchmark-C16tT4pF.js +0 -1
  81. package/dist/assets/BulkAddJobs-IiL1uud0.js +0 -5
  82. package/dist/assets/Button-Ch1W94fJ.js +0 -1
  83. package/dist/assets/Card-CWxrC8OY.js +0 -1
  84. package/dist/assets/CopilotPanel-FlAW3RlL.js +0 -44
  85. package/dist/assets/Cron-1DZTZWXO.js +0 -1
  86. package/dist/assets/CronManager-B6xLLgI5.js +0 -1
  87. package/dist/assets/Diagnostics-B6apZrC5.js +0 -1
  88. package/dist/assets/Dlq-MRmkQrNC.js +0 -1
  89. package/dist/assets/DlqControl-DNJPVOTF.js +0 -1
  90. package/dist/assets/DlqPro-CwtTDwGN.js +0 -1
  91. package/dist/assets/Fleet-Bdrj9bLI.js +0 -1
  92. package/dist/assets/Flows-1dC8F_wx.js +0 -2
  93. package/dist/assets/JobInspector-Ct9Ga-UT.js +0 -2
  94. package/dist/assets/Jobs-Chqv0RuL.js +0 -1
  95. package/dist/assets/JobsPro-CLzOhKAL.js +0 -1
  96. package/dist/assets/Logs-C5PNP9Wq.js +0 -1
  97. package/dist/assets/LogsPro-B3KwTSsn.js +0 -1
  98. package/dist/assets/MetricsPro-B9rD_KQc.js +0 -1
  99. package/dist/assets/Pagination-x-Cwgrul.js +0 -1
  100. package/dist/assets/QueueActions-BWnmNEqV.js +0 -1
  101. package/dist/assets/QueueControl-DqBvuDnF.js +0 -1
  102. package/dist/assets/QueueDetail-COSH9bJl.js +0 -1
  103. package/dist/assets/QueueDetailPro-ClKtyHIf.js +0 -1
  104. package/dist/assets/Queues-D2-R8nYh.js +0 -1
  105. package/dist/assets/QueuesOverview-tokquA3g.js +0 -1
  106. package/dist/assets/S3BackupPro-CDX5WQUY.js +0 -3
  107. package/dist/assets/ServerControl-BmccMNW9.js +0 -3
  108. package/dist/assets/Settings-UcujwvKv.js +0 -1
  109. package/dist/assets/StatusBadge-BoOVTnKu.js +0 -1
  110. package/dist/assets/UsagePro-BGLufsE7.js +0 -1
  111. package/dist/assets/Webhooks-DT2LK17V.js +0 -1
  112. package/dist/assets/Workers-BX1qspaQ.js +0 -1
  113. package/dist/assets/WorkersPro-BsUQVgQZ.js +0 -1
  114. package/dist/assets/Workflows-DZZA6aGW.js +0 -1
  115. package/dist/assets/bq-F5BbTG1T.js +0 -1
  116. package/dist/assets/connectionStore-BJLihGaC.js +0 -1
  117. package/dist/assets/controlConnectionEpoch-CZsS0wAb.js +0 -1
  118. package/dist/assets/dist-1f1fMHVO.js +0 -11
  119. package/dist/assets/dist-BlWBaCN6.js +0 -11
  120. package/dist/assets/dist-DZL8soAh.js +0 -79
  121. package/dist/assets/dist-DjvZiKhB.js +0 -2
  122. package/dist/assets/dist-DpZcbP9W.js +0 -11
  123. package/dist/assets/feedback-QDN1AsYt.js +0 -1
  124. package/dist/assets/form-C4oby9pI.js +0 -1
  125. package/dist/assets/index-8Ii-_Rml.js +0 -8
  126. package/dist/assets/react-vendor-CvwrP0tU.js +0 -11
  127. package/dist/assets/useControlActionGuard-B-bzKZKI.js +0 -1
  128. package/dist/assets/usePolledData-0CVelkl2.js +0 -1
  129. package/dist/assets/useServerActionGuard-uGePilQQ.js +0 -1
  130. package/dist/assets/useThroughputSeries-DgO8uicf.js +0 -1
@@ -0,0 +1,3 @@
1
+ import{n as e,r as t}from"./rolldown-runtime-QTnfLwEv.js";import{g as n,l as r,r as i,t as a}from"./react-vendor-CFL9l8LK.js";import{i as o}from"./upstreamPaths-DQeKSxGc.js";import{r as s,t as c}from"./bq-DR2BTISO.js";import{t as l}from"./toastStore-XmMX7A5W.js";import{n as u}from"./usePolledData-CEyyLRYa.js";import{t as d}from"./Button-_aSJvRoW.js";import{n as f,t as p}from"./Card-egIDLwVk.js";import{t as m}from"./PageHeader-CQzNsw8r.js";import{a as h,n as g,o as _,t as v}from"./form-DG3X6cLL.js";import{r as y}from"./useServerActionGuard-CUx8TOAC.js";import{a as b,c as x,d as S,f as C,h as w,i as T,l as E,m as D,n as O,o as k,r as A,s as j,t as M,u as N}from"./responses-BkR2JTH9.js";var P=t(n(),1),F=a();function I({values:e,setValue:t,queueNames:n,queueDiscoveryError:r,onRetryQueues:i,jsonError:a,setJsonError:o}){return(0,F.jsxs)(p,{children:[(0,F.jsx)(f,{title:`Job`}),(0,F.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,F.jsxs)(v,{label:`Queue`,children:[(0,F.jsx)(g,{list:`queue-options`,"aria-label":`Queue`,name:`target-queue`,autoComplete:`off`,value:e.queue,onChange:e=>t(`queue`,e.target.value),placeholder:`queue name (existing or new)`}),(0,F.jsx)(`datalist`,{id:`queue-options`,children:n.map(e=>(0,F.jsx)(`option`,{value:e},e))})]}),(0,F.jsx)(v,{label:`Job name`,hint:`Worker routing name in Bunqueue 2.9.3; separate from the JSON payload.`,children:(0,F.jsx)(g,{name:`job-name`,autoComplete:`off`,maxLength:256,value:e.name,onChange:e=>t(`name`,e.target.value),placeholder:`default`})}),r&&(0,F.jsxs)(`p`,{role:`status`,className:`-mt-2 text-xs text-warning`,children:[`Existing queue suggestions unavailable — `,r.message,`. You can still enter a queue name manually.`,` `,(0,F.jsx)(`button`,{type:`button`,onClick:i,className:`font-medium underline underline-offset-2 hover:text-fg`,children:`Retry`})]}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(v,{label:`Data (JSON)`,children:(0,F.jsx)(`textarea`,{name:`job-data`,value:e.dataText,onChange:e=>t(`dataText`,e.target.value),onBlur:()=>{let t=w(e.dataText);o(t.ok?null:t.msg)},maxLength:D,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`})}),a&&(0,F.jsx)(`p`,{role:`alert`,className:`mt-2 text-xs text-danger`,children:a})]})]})]})}function L({values:e,setValue:t}){return(0,F.jsxs)(p,{children:[(0,F.jsx)(f,{title:`Options`}),(0,F.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 md:grid-cols-3`,children:[(0,F.jsx)(B,{label:e.groupId.trim()?`Group priority`:`Priority`,hint:e.groupId.trim()?`0 is highest within this group`:void 0,name:`priority`,value:e.priority,min:e.groupId.trim()?0:-1e6,max:e.groupId.trim()?k:1e6,placeholder:`0`,onChange:e=>t(`priority`,e)}),(0,F.jsx)(B,{label:`Delay (ms)`,name:`delay`,value:e.delay,min:0,max:T,placeholder:`0`,disabled:e.runAt.trim()!==``,onChange:e=>t(`delay`,e)}),(0,F.jsx)(v,{label:`Run at`,hint:e.runAt.trim()?`Overrides Delay — derived from this time (local time).`:`(local time)`,children:(0,F.jsx)(g,{type:`datetime-local`,name:`run-at`,value:e.runAt,onChange:e=>t(`runAt`,e.target.value)})}),(0,F.jsx)(B,{label:`Max attempts`,hint:`blank = server default`,name:`max-attempts`,value:e.maxAttempts,min:1,max:1e3,placeholder:`3`,onChange:e=>t(`maxAttempts`,e)}),(0,F.jsx)(B,{label:`Backoff (ms)`,hint:`blank = server default`,name:`backoff`,value:e.backoff,min:0,max:b,placeholder:`1000`,onChange:e=>t(`backoff`,e)}),(0,F.jsx)(v,{label:`Backoff strategy`,hint:`flat delay unless set`,children:(0,F.jsxs)(h,{name:`backoff-strategy`,value:e.backoffType,onChange:e=>t(`backoffType`,e.target.value),children:[(0,F.jsx)(`option`,{value:``,children:`flat`}),(0,F.jsx)(`option`,{value:`fixed`,children:`fixed`}),(0,F.jsx)(`option`,{value:`exponential`,children:`exponential`})]})}),(0,F.jsx)(B,{label:`Timeout (ms)`,name:`timeout`,value:e.timeout,min:0,max:b,placeholder:`—`,onChange:e=>t(`timeout`,e)}),(0,F.jsx)(B,{label:`TTL (ms)`,hint:`blank = no expiry`,name:`ttl`,value:e.ttl,min:0,max:T,placeholder:`—`,onChange:e=>t(`ttl`,e)}),(0,F.jsx)(v,{label:`Custom job ID`,children:(0,F.jsx)(g,{name:`custom-job-id`,value:e.jobId,onChange:e=>t(`jobId`,e.target.value),placeholder:`idempotency key`})})]}),(0,F.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-6`,children:[(0,F.jsx)(V,{label:`removeOnComplete`,checked:e.removeOnComplete,onChange:e=>t(`removeOnComplete`,e)}),(0,F.jsx)(V,{label:`removeOnFail`,checked:e.removeOnFail,onChange:e=>t(`removeOnFail`,e)}),(0,F.jsx)(V,{label:`durable`,checked:e.durable,onChange:e=>t(`durable`,e)}),(0,F.jsx)(V,{label:`lifo`,checked:e.lifo,onChange:e=>t(`lifo`,e)})]}),(0,F.jsx)(R,{values:e,setValue:t})]})}function R({values:e,setValue:t}){return(0,F.jsxs)(`div`,{className:`mt-4 border-t border-line pt-4`,children:[(0,F.jsx)(`div`,{className:`mb-3 text-[11px] uppercase tracking-wider text-faint`,children:`Advanced`}),(0,F.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 md:grid-cols-3`,children:[(0,F.jsx)(z,{label:`Tags`,hint:`comma-separated`,name:`tags`,value:e.tags,placeholder:`email, urgent`,onChange:e=>t(`tags`,e)}),(0,F.jsx)(z,{label:`Group ID`,name:`group-id`,value:e.groupId,placeholder:`—`,onChange:e=>t(`groupId`,e)}),(0,F.jsx)(B,{label:`Group max size`,hint:`Atomic pending-job cap (2.9.3)`,name:`group-max-size`,value:e.groupMaxSize,min:1,max:2**53-1,placeholder:`—`,onChange:e=>t(`groupMaxSize`,e)}),(0,F.jsx)(z,{label:`Unique key`,hint:`dedup key`,name:`unique-key`,value:e.uniqueKey,placeholder:`—`,onChange:e=>t(`uniqueKey`,e)}),(0,F.jsx)(z,{label:`Depends on`,hint:`parent job ids, comma-separated`,name:`depends-on`,value:e.dependsOn,placeholder:`job-id-1, job-id-2`,onChange:e=>t(`dependsOn`,e)}),(0,F.jsx)(`div`,{className:`col-span-2 md:col-span-3`,children:(0,F.jsx)(v,{label:`Repeat policy (JSON)`,hint:`v2.9.3-safe form: e.g. {"every":60000,"limit":10}. Use Cron Manager for cron patterns.`,children:(0,F.jsx)(`textarea`,{name:`repeat-policy`,value:e.repeatText,onChange:e=>t(`repeatText`,e.target.value),rows:2,spellCheck:!1,placeholder:`{"every": 60000}`,className:`w-full rounded-lg border border-line bg-surface-2 px-3 py-2 font-mono text-xs text-fg placeholder:text-faint focus:border-accent/60 focus:outline-none focus:ring-2 focus:ring-accent/30`})})})]})]})}function z({label:e,hint:t,name:n,value:r,placeholder:i,onChange:a}){return(0,F.jsx)(v,{label:e,hint:t,children:(0,F.jsx)(g,{name:n,value:r,onChange:e=>a(e.target.value),placeholder:i})})}function B({label:e,hint:t,name:n,value:r,min:i,max:a,placeholder:o,disabled:s,onChange:c}){return(0,F.jsx)(v,{label:e,hint:t,children:(0,F.jsx)(g,{type:`number`,min:i,max:a,step:1,name:n,value:r,onChange:e=>c(e.target.value),placeholder:o,disabled:s})})}function V({label:e,checked:t,onChange:n}){return(0,F.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,F.jsx)(_,{checked:t,onChange:n,label:e}),(0,F.jsx)(`span`,{className:`font-mono text-xs text-muted`,children:e})]})}function H(e){let t=e?.options??{},n=j(t);return{queue:e?.queue??``,name:e?.name??`default`,dataText:e?.dataText??`{
2
+ "hello": "world"
3
+ }`,count:`1`,priority:x(t.priority),delay:``,runAt:``,maxAttempts:x(t.maxAttempts),backoff:n.backoff,timeout:x(t.timeout),ttl:n.ttl,jobId:``,removeOnComplete:t.removeOnComplete??!1,removeOnFail:t.removeOnFail??!1,durable:!1,lifo:!1,backoffType:n.backoffType,tags:n.tags,groupId:n.groupId,groupMaxSize:``,dependsOn:``,uniqueKey:``,repeatText:``}}function U(e,t=Date.now()){let n=e.queue.trim(),r=S(n);if(r)return W(r);let i=e.name.trim();if(!i||i.length>256)return W(`Job name must be a non-empty string of at most 256 characters`);let a=w(e.dataText);if(!a.ok)return{ok:!1,msg:a.msg,field:a.kind===`json`?`data`:`result`};let s=e.groupId.trim();if(s.length>256||s.includes(`\0`))return W(`Group ID must contain 1–256 characters and no NUL`);let c=E({priority:e.priority,delay:e.runAt.trim()?``:e.delay,maxAttempts:e.maxAttempts,backoff:e.backoff,timeout:e.timeout,ttl:e.ttl,groupMaxSize:e.groupMaxSize},!!s);if(!c.ok)return W(c.msg);if(c.options.groupMaxSize!==void 0&&!s)return W(`Group max size requires a Group ID`);let l=c.options.delay;if(e.runAt.trim()){let n=new Date(e.runAt).getTime();if(!Number.isFinite(n))return W(`Run at is not a valid date/time`);if(l=Math.max(0,n-t),l>31536e6)return W(`Run at must be within the next 365 days`)}let u=C(c.options.backoff,e.backoffType);if(!u.ok)return W(u.msg);let d=G(e.tags),f=G(e.dependsOn),p=e.jobId.trim();if(p){let e=o(p);if(e)return W(`Job ID: ${e}`)}for(let e of f){let t=o(e);if(t)return W(`Dependency ID "${e}": ${t}`)}let m=N(e.repeatText);if(!m.ok)return W(m.msg);let h=Number(e.count);return!Number.isSafeInteger(h)||h<1||h>1e4?W(`Count must be a whole number from 1 to 10000`):{ok:!0,target:n,count:h,body:{name:i,data:a.data,priority:c.options.priority,delay:l,maxAttempts:c.options.maxAttempts,backoff:u.backoff,timeout:c.options.timeout,ttl:c.options.ttl,jobId:p||void 0,removeOnComplete:e.removeOnComplete||void 0,removeOnFail:e.removeOnFail||void 0,durable:e.durable||void 0,lifo:e.lifo||void 0,tags:d.length?d:void 0,groupId:s||void 0,groupMaxSize:c.options.groupMaxSize,dependsOn:f.length?f:void 0,uniqueKey:e.uniqueKey.trim()||void 0,repeat:m.repeat}}}var W=e=>({ok:!1,msg:e,field:`result`}),G=e=>e.split(`,`).map(e=>e.trim()).filter(Boolean),K=e({AddJob:()=>q,MAX_JOB_DATA_BYTES:()=>MAX_JOB_DATA_BYTES,MAX_JOB_DATA_CHARS:()=>D});function q(){let{data:e,error:t,refetch:n}=u(()=>c.queues(),[],{intervalMs:3e4}),a=r().state?.clone,[o,f]=(0,P.useState)(()=>H(a)),[p,h]=(0,P.useState)(!1),[_,b]=(0,P.useState)(null),[x,S]=(0,P.useState)(null),C=y(`add-job`),w=(e,t)=>f(n=>({...n,[e]:t}));(0,P.useEffect)(()=>{h(!1),b(null),S(null)},[C.scopeKey]);let T=async()=>{b(null),S(null);let e=U(o);if(!e.ok){e.field===`data`?S(e.msg):b({ok:!1,msg:e.msg});return}let t=C.begin();if(!t)return;h(!0);let{target:n,body:r,count:i}=e;try{if(i===1&&r.groupMaxSize===void 0){let e=O(await c.addJob(n,r));if(!t.isCurrent())return;b({ok:!0,msg:`Accepted job ID ${e} (it may be an existing deduplicated job)`}),l.success(`Job submission accepted`,`${n} · ${e}`)}else{let e=Array.from({length:i},()=>r),a=s(e);if(a){t.isCurrent()&&b({ok:!1,msg:a});return}let o=M(await c.addJobsBulk(n,e),i);if(!t.isCurrent())return;let u=A(new Set(o).size,i);b(u),l.success(u.msg,`in ${n}`)}}catch(e){if(!t.isCurrent())return;b({ok:!1,msg:e.message}),l.error(`Add job failed`,e.message)}finally{t.finish()&&h(!1)}};return(0,F.jsxs)(`div`,{children:[(0,F.jsx)(m,{title:`Add Job`,description:`Enqueue a job with full options.`,actions:(0,F.jsx)(i,{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`})}),a&&(0,F.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,F.jsxs)(`form`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-2`,onSubmit:e=>{e.preventDefault(),T()},children:[(0,F.jsx)(I,{values:o,setValue:w,queueNames:(e?.queues??[]).map(e=>e.name),queueDiscoveryError:t,onRetryQueues:()=>void n(),jsonError:x,setJsonError:S}),(0,F.jsx)(L,{values:o,setValue:w}),(0,F.jsxs)(`div`,{className:`flex flex-wrap items-end gap-3 lg:col-span-2`,children:[(0,F.jsx)(`div`,{className:`w-28`,children:(0,F.jsx)(v,{label:`Count`,hint:`1–10000`,children:(0,F.jsx)(g,{type:`number`,min:1,max:1e4,step:1,name:`count`,value:o.count,onChange:e=>w(`count`,e.target.value)})})}),(0,F.jsx)(d,{type:`submit`,variant:`accent`,disabled:p,children:p?`Adding…`:`Add job`}),_&&(0,F.jsx)(`span`,{role:_.ok?`status`:`alert`,className:_.ok?`text-sm text-success`:`text-sm text-danger`,children:_.msg})]})]})]})}export{K as t};
@@ -0,0 +1 @@
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{g as t,t as n}from"./react-vendor-CFL9l8LK.js";import{o as r}from"./connectionStore-CVjQyIZv.js";import{O as i,r as a}from"./icons-DH9SS1DA.js";import{n as o,t as s}from"./Button-_aSJvRoW.js";import{t as c}from"./Card-egIDLwVk.js";import{i as l,t as u}from"./feedback-CtGN_kqB.js";import{t as d}from"./PageHeader-CQzNsw8r.js";import{l as f}from"./format-Cg7VCIZW.js";import{d as p,f as m,l as h,p as g,u as _}from"./index-Bat1DN5U.js";import{a as v,n as y,o as b,t as x}from"./form-DG3X6cLL.js";var S=e(t(),1),C=[`error_rate`,`p99_latency`,`waiting`,`failed`,`dlq`],w=[`>=`,`>`,`<=`,`<`],T=[`email`,`webhook`,`slack`],E=/^[a-zA-Z0-9_\-.:]+$/,D={error_rate:{unit:`% (0–100)`,placeholder:`e.g. 5`},p99_latency:{unit:`ms`,placeholder:`e.g. 250`},waiting:{unit:`jobs`,placeholder:`e.g. 100`},failed:{unit:`jobs`,placeholder:`e.g. 10`},dlq:{unit:`jobs`,placeholder:`e.g. 1`}};function O(e){let t=e.name.trim();if(!C.includes(e.metric))return{ok:!1,error:`Invalid metric`,field:`metric`};if(!w.includes(e.operator))return{ok:!1,error:`Invalid operator`,field:`operator`};let n=e.metric===`p99_latency`?``:e.queue.trim();if(!t)return{ok:!1,error:`Rule name is required`,field:`name`};if(t.length>200)return{ok:!1,error:`Rule name must be 200 characters or fewer`,field:`name`};if(!e.threshold.trim())return{ok:!1,error:`Threshold is required`,field:`threshold`};let r=Number(e.threshold);return!Number.isFinite(r)||r<0?{ok:!1,error:`Threshold must be a non-negative number`,field:`threshold`}:e.metric===`error_rate`&&r>100?{ok:!1,error:`Error-rate threshold must be between 0 and 100%`,field:`threshold`}:[`waiting`,`failed`,`dlq`].includes(e.metric)&&!Number.isSafeInteger(r)?{ok:!1,error:`Job-count thresholds must be whole numbers`,field:`threshold`}:n&&(n.length>256||!E.test(n))?{ok:!1,error:`Queue contains unsupported characters or is too long`,field:`queue`}:T.includes(e.channel)?{ok:!0,rule:{name:t,metric:e.metric,operator:e.operator,threshold:r,queue:n,channel:e.channel,enabled:!0}}:{ok:!1,error:`Invalid channel type`,field:`channel`}}var k=n();function A({onAdd:e}){let[t,n]=(0,S.useState)(``),[r,i]=(0,S.useState)(`error_rate`),[a,o]=(0,S.useState)(`>=`),[c,l]=(0,S.useState)(``),[u,d]=(0,S.useState)(``),[f,p]=(0,S.useState)(null),h=(0,S.useRef)(!1),g=(0,S.useId)(),_=e=>f?.field===e;return(0,k.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-5`,children:[(0,k.jsx)(x,{label:`Name`,children:(0,k.jsx)(y,{name:`alert-rule-name`,autoComplete:`off`,maxLength:200,value:t,"aria-invalid":_(`name`),"aria-describedby":_(`name`)?g:void 0,onChange:e=>{n(e.target.value),p(null)},placeholder:`High error rate`})}),(0,k.jsx)(x,{label:`Metric`,children:(0,k.jsx)(v,{name:`alert-rule-metric`,value:r,"aria-invalid":_(`metric`),"aria-describedby":_(`metric`)?g:void 0,onChange:e=>{i(e.target.value),p(null)},children:C.map(e=>(0,k.jsx)(`option`,{value:e,children:m[e]},e))})}),(0,k.jsx)(x,{label:`Operator`,children:(0,k.jsx)(v,{name:`alert-rule-operator`,value:a,"aria-invalid":_(`operator`),"aria-describedby":_(`operator`)?g:void 0,onChange:e=>{o(e.target.value),p(null)},children:w.map(e=>(0,k.jsx)(`option`,{value:e,children:e},e))})}),(0,k.jsx)(x,{label:`Threshold`,hint:D[r].unit,children:(0,k.jsx)(y,{name:`alert-rule-threshold`,autoComplete:`off`,type:`number`,min:0,max:r===`error_rate`?100:void 0,step:[`waiting`,`failed`,`dlq`].includes(r)?1:`any`,value:c,"aria-invalid":_(`threshold`),"aria-describedby":_(`threshold`)?g:void 0,onChange:e=>{l(e.target.value),p(null)},placeholder:D[r].placeholder})}),(0,k.jsx)(x,{label:`Queue (optional)`,hint:r===`p99_latency`?`global only — latency is not per queue`:void 0,children:(0,k.jsx)(y,{name:`alert-rule-queue`,autoComplete:`off`,spellCheck:!1,maxLength:256,value:u,"aria-invalid":_(`queue`),"aria-describedby":_(`queue`)?g:void 0,onChange:e=>{d(e.target.value),p(null)},disabled:r===`p99_latency`,placeholder:r===`p99_latency`?`Global`:`All queues`,className:`disabled:cursor-not-allowed disabled:opacity-40`})}),(0,k.jsxs)(`div`,{className:`col-span-full`,children:[(0,k.jsx)(s,{variant:`accent`,disabled:!t.trim()||!c.trim(),onClick:()=>{if(h.current)return;let n=O({name:t,metric:r,operator:a,threshold:c,queue:u,channel:`email`});if(!n.ok)return p({field:n.field,message:n.error});h.current=!0;try{let t=e(n.rule);t.ok||(h.current=!1,p({field:`name`,message:t.error}))}catch(e){h.current=!1,p({field:`name`,message:e.message})}},children:`Save rule`}),f&&(0,k.jsx)(`span`,{id:g,role:`alert`,className:`ml-3 text-xs text-danger`,children:f.message})]})]})}function j(){return typeof Notification>`u`?`unsupported`:Notification.permission}function M(){let{rules:e,addRule:t,removeRule:n,toggleRule:v}=g(),y=_(e=>e.breaching),x=_(e=>e.status),C=_(e=>e.error),w=_(e=>e.connectionIdentity),T=r(e=>p(e.baseUrl,e.token)),E=e.some(e=>e.enabled),D=w===T,O=D?y:[],M=D?x:E?`checking`:`idle`,N=D?C:null,[P,F]=(0,S.useState)(!1),[I,L]=(0,S.useState)(j);return(0,k.jsxs)(`div`,{children:[(0,k.jsx)(d,{title:`Alerts`,description:`Threshold rules evaluated live in your browser.`,live:E&&M===`live`,actions:(0,k.jsxs)(k.Fragment,{children:[I===`granted`?(0,k.jsxs)(`span`,{className:`flex items-center gap-1.5 text-sm text-success`,children:[(0,k.jsx)(a,{className:`size-4`}),` Desktop alerts on`]}):I===`unsupported`?(0,k.jsx)(`span`,{className:`text-sm text-faint`,children:`Notifications unsupported`}):I===`denied`?(0,k.jsx)(`span`,{className:`text-sm text-faint`,children:`Desktop alerts blocked — allow notifications in browser settings`}):(0,k.jsx)(s,{size:`sm`,onClick:async()=>{L(await h())},children:`Enable desktop notifications`}),(0,k.jsx)(s,{variant:`accent`,size:`sm`,"aria-expanded":P,"aria-controls":`alert-rule-form`,onClick:()=>F(e=>!e),children:`+ Create Alert Rule`})]})}),E&&M===`checking`&&(0,k.jsx)(`p`,{role:`status`,className:`mb-4 text-sm text-muted`,children:`Checking alert metrics for the connected server…`}),E&&M===`degraded`&&(0,k.jsx)(l,{message:N??`Alert metrics are unavailable; current rule results may be stale.`}),(0,k.jsx)(`div`,{className:`mb-6 rounded-lg border border-amber-500/20 bg-amber-500/5 px-4 py-3 text-sm text-amber-400/90`,children:`Rules are evaluated in this browser while a tab is open (even backgrounded), raising an in-app toast and — if enabled — a desktop notification. bunqueue OSS has no alerting backend, so email/webhook/slack delivery still needs your own monitoring or hosted bunqueue Cloud.`}),(0,k.jsxs)(`section`,{className:`mb-8`,children:[(0,k.jsx)(`h2`,{className:`mb-3 text-lg font-semibold text-fg`,children:`Triggered Alerts`}),O.length===0?(0,k.jsx)(u,{icon:(0,k.jsx)(a,{}),title:`No triggered alerts`,hint:E?M===`live`?`All enabled rules are within their thresholds.`:M===`checking`?`Alert metrics are still being checked.`:`Alert metrics are unavailable; no all-clear result is available.`:`No enabled rules yet. Create one below.`}):(0,k.jsx)(`div`,{className:`overflow-x-auto rounded-xl border border-danger/30 bg-red-500/5`,children:(0,k.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,k.jsx)(`thead`,{children:(0,k.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,k.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Rule`}),(0,k.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Condition`}),(0,k.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Queue`}),(0,k.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Current`}),(0,k.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Since`})]})}),(0,k.jsx)(`tbody`,{children:O.map(e=>(0,k.jsxs)(`tr`,{className:`border-b border-line last:border-0`,children:[(0,k.jsx)(`td`,{className:`px-5 py-3 font-medium text-danger`,children:e.ruleName}),(0,k.jsxs)(`td`,{className:`px-5 py-3 text-muted`,children:[e.metricLabel,` `,e.operator,` `,(0,k.jsx)(`span`,{className:`font-semibold text-fg`,children:e.threshold})]}),(0,k.jsx)(`td`,{className:`px-5 py-3 text-muted`,children:e.queue||`All queues`}),(0,k.jsx)(`td`,{className:`px-5 py-3 text-right tnum font-semibold text-danger`,children:Math.round(e.value*100)/100}),(0,k.jsx)(`td`,{className:`px-5 py-3 text-right text-faint`,children:f(e.at)})]},e.ruleId))})]})})]}),(0,k.jsxs)(`section`,{children:[(0,k.jsx)(`h2`,{className:`mb-3 text-lg font-semibold text-fg`,children:`Alert Rules`}),P&&(0,k.jsx)(`div`,{id:`alert-rule-form`,children:(0,k.jsx)(c,{className:`mb-4`,children:(0,k.jsx)(A,{onAdd:e=>{let n=t(e);return n.ok&&F(!1),n}})})}),e.length===0?(0,k.jsx)(u,{title:`No alert rules`,hint:`Create a rule to be notified when a threshold is crossed.`}):(0,k.jsx)(`div`,{className:`overflow-x-auto rounded-xl border border-line bg-surface`,children:(0,k.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,k.jsx)(`thead`,{children:(0,k.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,k.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Rule`}),(0,k.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Condition`}),(0,k.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Queue`}),(0,k.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Delivery`}),(0,k.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Status`}),(0,k.jsx)(`th`,{className:`w-12 px-5 py-3`})]})}),(0,k.jsx)(`tbody`,{children:e.map(e=>(0,k.jsxs)(`tr`,{className:`border-b border-line last:border-0`,children:[(0,k.jsx)(`td`,{className:`px-5 py-3 font-medium text-fg`,children:e.name}),(0,k.jsxs)(`td`,{className:`px-5 py-3 text-muted`,children:[m[e.metric],` `,e.operator,` `,(0,k.jsx)(`span`,{className:`font-semibold text-accent`,children:e.threshold})]}),(0,k.jsx)(`td`,{className:`px-5 py-3 text-muted`,children:e.queue||`All queues`}),(0,k.jsx)(`td`,{className:`px-5 py-3`,children:(0,k.jsx)(`span`,{className:`rounded-md bg-surface-2 px-2 py-0.5 text-xs text-muted`,children:`Browser`})}),(0,k.jsx)(`td`,{className:`px-5 py-3`,children:(0,k.jsx)(b,{checked:e.enabled,onChange:()=>v(e.id),label:`Enabled`})}),(0,k.jsx)(`td`,{className:`px-5 py-3 text-right`,children:(0,k.jsx)(o,{"aria-label":`Delete rule ${e.name}`,onClick:()=>window.confirm(`Delete alert rule "${e.name}"?`)&&n(e.id),children:(0,k.jsx)(i,{className:`size-3.5`})})})]},e.id))})]})})]})]})}export{M as Alerts};
@@ -0,0 +1 @@
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{g as t,t as n}from"./react-vendor-CFL9l8LK.js";var r=e(t(),1),i=n();function a({series:e,height:t=180,xLabels:n,ariaLabel:a=`throughput chart`,formatValue:o}){let s=(0,r.useId)().replace(/:/g,``),c=`${s}-desc`,l=t,u=e=>Number.isFinite(e)?e:0,d=Math.max(1,...e.map(e=>e.points.length)),f=Math.max(1,...e.flatMap(e=>e.points.map(u))),p=e=>d<=1?0:e/(d-1)*600,m=e=>l-10-u(e)/f*(l-20),h=[0,.25,.5,.75,1].map(e=>10+e*(l-20)),g=o??(e=>Number.isInteger(e)?String(e):e.toFixed(1)),_=e.some(e=>e.points.length>0),v=e.find(e=>e.points.length>0),y=v?u(v.points[v.points.length-1]):0;return(0,i.jsxs)(`div`,{className:`w-full`,children:[(0,i.jsxs)(`div`,{className:`relative`,children:[(0,i.jsxs)(`svg`,{viewBox:`0 0 600 ${l}`,preserveAspectRatio:`none`,className:`block w-full`,style:{height:t},role:`img`,"aria-label":a,"aria-describedby":c,children:[(0,i.jsx)(`defs`,{children:e.map((e,t)=>(0,i.jsxs)(`linearGradient`,{id:`${s}-g${t}`,x1:`0`,y1:`0`,x2:`0`,y2:`1`,children:[(0,i.jsx)(`stop`,{offset:`0%`,stopColor:e.color,stopOpacity:`0.28`}),(0,i.jsx)(`stop`,{offset:`100%`,stopColor:e.color,stopOpacity:`0`})]},e.label))}),h.map(e=>(0,i.jsx)(`line`,{x1:`0`,y1:e,x2:600,y2:e,stroke:`var(--line)`,strokeWidth:`1`},e)),e.map((e,t)=>{if(e.points.length===0)return null;let n=e.points.length===1?`M0,${m(e.points[0])} L600,${m(e.points[0])}`:e.points.map((e,t)=>`${t===0?`M`:`L`}${p(t)},${m(e)}`).join(` `),r=e.points.length===1?`${n} L600,${l} L0,${l} Z`:`${n} L${p(e.points.length-1)},${l} L${p(0)},${l} Z`;return(0,i.jsxs)(`g`,{children:[e.area&&(0,i.jsx)(`path`,{d:r,fill:`url(#${s}-g${t})`}),(0,i.jsx)(`path`,{d:n,fill:`none`,stroke:e.color,strokeWidth:`2`,strokeLinejoin:`round`,vectorEffect:`non-scaling-stroke`})]},e.label)})]}),_&&(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(`span`,{className:`pointer-events-none absolute left-1 -translate-y-full font-mono text-[10px] leading-none text-faint`,style:{top:10},children:g(f)}),(0,i.jsx)(`span`,{className:`pointer-events-none absolute left-1 top-1/2 -translate-y-1/2 font-mono text-[10px] leading-none text-faint`,children:g(f/2)})]})]}),n&&(0,i.jsx)(`div`,{className:`mt-1 flex justify-between px-1 font-mono text-[10px] text-faint`,children:n.map(e=>(0,i.jsx)(`span`,{children:e},e))}),(0,i.jsx)(`p`,{id:c,className:`sr-only`,children:_?`latest ${g(y)}, max ${g(f)}`:`no data yet`})]})}export{a as t};
@@ -0,0 +1 @@
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{g as t,t as n}from"./react-vendor-CFL9l8LK.js";import{o as r}from"./connectionStore-CVjQyIZv.js";import{t as i}from"./bq-DR2BTISO.js";import{b as a,x as o}from"./icons-DH9SS1DA.js";import{r as s}from"./StatusBadge-DereLzOj.js";import{n as c}from"./usePolledData-CEyyLRYa.js";import{t as l}from"./Button-_aSJvRoW.js";import{n as u,t as d}from"./Card-egIDLwVk.js";import{t as f}from"./PageHeader-CQzNsw8r.js";import{n as p,o as m,s as h}from"./format-Cg7VCIZW.js";import{a as g,r as _}from"./index-Bat1DN5U.js";import{i as v,n as y,o as b,t as x}from"./form-DG3X6cLL.js";import{t as S}from"./AreaChart-Db2UVnaK.js";var C=e(t(),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=`bq-dashboard-benchmark-`;function D(){if(typeof globalThis.crypto?.randomUUID!=`function`)throw Error(`A cryptographically secure browser is required to create a benchmark queue.`);return`${E}${globalThis.crypto.randomUUID()}`}function O(e){return RegExp(`^${E}[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`,`i`).test(e)}var k={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}},A=(e,t,n)=>Number.isFinite(e)?Math.max(t,Math.min(n,Math.floor(e))):t;function j(e){return e?e.length>256?`Queue name is too long (maximum 256 characters).`:/^[a-zA-Z0-9_\-.:]+$/.test(e)?null:`Queue name contains unsupported characters.`:`Queue name is required.`}var M=(e,t)=>e.length?e[Math.min(e.length-1,Math.max(0,Math.ceil(t/100*e.length)-1))]:0,N=(e,t,n,r,i,a,o)=>Array.from({length:t},(t,s)=>({data:{i:e+s,blob:n},durable:r,removeOnComplete:i,...o===void 0?{}:{stallTimeout:o},...a?{jobId:`${a}-${e+s}`,tags:[`bunqueue-dashboard-benchmark`,a]}:{}})),P=e=>new Promise(t=>setTimeout(t,e)),F=async(e,t)=>{let n=performance.now()+e;for(;t()&&performance.now()<n;)await P(Math.min(100,Math.max(0,n-performance.now())))},I=e=>e instanceof Error?e.message:String(e),L=e=>e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:`${Math.round(e)}`,R=[`count`,`duration`],z=[`waiting`,`completed`,`failed`],B=null;function ee(){return B??=D(),B}var te=[`total`,`durationS`,`batch`,`producers`,`payload`,`workers`,`workerBatch`,`processMs`],ne=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)}),V=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)}),H=n();function re({draft:e,active:t,cleaning:n,cleanResult:r,setField:i,numberInput:a,onClean:o}){return(0,H.jsxs)(d,{className:`lg:col-span-1`,children:[(0,H.jsx)(u,{title:`Configuration`}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,H.jsx)(x,{label:`Dedicated queue`,hint:`Cryptographically generated for this browser tab; production queue names cannot be entered here.`,children:(0,H.jsx)(y,{name:`benchmark-queue`,autoComplete:`off`,value:e.queue,readOnly:!0,"aria-readonly":`true`})}),(0,H.jsx)(x,{label:`Mode`,hint:e.mode===`count`?`Push a fixed number of jobs.`:`Run producers + workers for a fixed time.`,children:(0,H.jsx)(v,{options:R,value:e.mode,onChange:e=>i(`mode`,e),disabled:t})}),e.mode===`count`?(0,H.jsx)(x,{label:`Total jobs`,hint:`max ${h(w.total)}`,children:(0,H.jsx)(y,{name:`benchmark-total`,autoComplete:`off`,type:`number`,min:1,max:w.total,value:e.total,disabled:t,onChange:a(`total`)})}):(0,H.jsx)(x,{label:`Duration (s)`,hint:`max ${w.durationS}s`,children:(0,H.jsx)(y,{name:`benchmark-duration-seconds`,autoComplete:`off`,type:`number`,min:1,max:w.durationS,value:e.durationS,disabled:t,onChange:a(`durationS`)})}),(0,H.jsx)(`div`,{className:`mt-1 text-[11px] font-semibold uppercase tracking-wider text-faint`,children:`Producers`}),(0,H.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,H.jsx)(x,{label:`Producers`,hint:`parallel, max ${w.producers}`,children:(0,H.jsx)(y,{name:`benchmark-producers`,autoComplete:`off`,type:`number`,min:1,max:w.producers,value:e.producers,disabled:t,onChange:a(`producers`)})}),(0,H.jsx)(x,{label:`Push batch`,hint:`jobs/req, max ${w.batch}`,children:(0,H.jsx)(y,{name:`benchmark-push-batch`,autoComplete:`off`,type:`number`,min:1,max:w.batch,value:e.batch,disabled:t,onChange:a(`batch`)})}),(0,H.jsx)(x,{label:`Payload`,hint:`bytes/job, max ${h(w.payload)}`,children:(0,H.jsx)(y,{name:`benchmark-payload-bytes`,autoComplete:`off`,type:`number`,min:0,max:w.payload,value:e.payload,disabled:t,onChange:a(`payload`)})})]}),(0,H.jsx)(`div`,{className:`mt-1 text-[11px] font-semibold uppercase tracking-wider text-faint`,children:`Workers (simulated)`}),(0,H.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,H.jsx)(x,{label:`Workers`,hint:`0 = produce only, max ${w.workers}`,children:(0,H.jsx)(y,{name:`benchmark-workers`,autoComplete:`off`,type:`number`,min:0,max:w.workers,value:e.workers,disabled:t,onChange:a(`workers`)})}),(0,H.jsx)(x,{label:`Pull batch`,hint:`jobs/pull, max ${w.workerBatch}`,children:(0,H.jsx)(y,{name:`benchmark-pull-batch`,autoComplete:`off`,type:`number`,min:1,max:w.workerBatch,value:e.workerBatch,disabled:t,onChange:a(`workerBatch`)})}),(0,H.jsx)(x,{label:`Process (ms)`,hint:`simulated work per pull`,children:(0,H.jsx)(y,{name:`benchmark-process-ms`,autoComplete:`off`,type:`number`,min:0,max:w.processMs,value:e.processMs,disabled:t,onChange:a(`processMs`)})})]}),(0,H.jsx)(U,{label:`Durable (fsync each job)`,checked:e.durable,active:t,onChange:e=>i(`durable`,e)}),(0,H.jsx)(U,{label:`Remove on complete`,checked:e.removeOnComplete,active:t,onChange:e=>i(`removeOnComplete`,e)}),(0,H.jsxs)(`div`,{className:`flex items-center gap-3 pt-1`,children:[(0,H.jsx)(l,{variant:`ghost`,size:`sm`,disabled:t||n,onClick:o,children:n?`Cleaning…`:`Clean queue`}),r&&(`error`in r?(0,H.jsxs)(`span`,{className:`text-xs text-danger`,children:[`Clean unverified — `,r.error]}):(0,H.jsx)(`span`,{className:s(`text-xs`,r.remaining>0?`text-warning`:`text-success`),children:r.remaining>0?`Cleaned — ${h(r.remaining)} active job(s) remain (requeued after the stall timeout)`:`Cleaned — 0 jobs remain`}))]})]})]})}function U({label:e,checked:t,active:n,onChange:r}){return(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(b,{checked:t,onChange:r,disabled:n,label:e}),(0,H.jsx)(`span`,{className:`text-sm text-muted`,children:e})]})}function ie({heading:e,pollBaseUrl:t,etaText:n,shown:r,shownWorkers:i,producePct:a,drainPct:o,durationPct:s,live:c,summary:l}){return(0,H.jsxs)(`div`,{className:`flex flex-col gap-6 lg:col-span-2`,children:[(0,H.jsxs)(d,{children:[(0,H.jsxs)(`div`,{className:`mb-3 flex items-center justify-between`,children:[(0,H.jsx)(`h3`,{className:`text-base font-semibold text-fg`,children:e}),(0,H.jsxs)(`span`,{className:`text-right text-xs text-faint`,children:[(0,H.jsxs)(`span`,{className:`block`,children:[`Benchmark target: `,t]}),n&&(0,H.jsx)(`span`,{className:`block`,children:n})]})]}),(0,H.jsx)(W,{label:r.mode===`duration`?`Elapsed`:`Produced`,pct:r.mode===`duration`?s:a,tone:`accent`}),i>0&&r.mode===`count`&&(0,H.jsx)(W,{label:`Completed`,pct:o,tone:`emerald`}),(0,H.jsxs)(`div`,{className:`mt-4 grid grid-cols-2 gap-4 md:grid-cols-4`,children:[(0,H.jsx)(_,{label:`Pushed`,value:h(c.pushed),tone:`accent`,compact:!0}),(0,H.jsx)(_,{label:`Completed`,value:h(c.completed),tone:`green`,compact:!0}),(0,H.jsx)(_,{label:`Push/sec`,value:L(c.pushPerSec),compact:!0}),(0,H.jsx)(_,{label:`Done/sec`,value:L(c.donePerSec),tone:`green`,compact:!0}),(0,H.jsx)(_,{label:`Elapsed`,value:m(c.elapsedMs),compact:!0}),(0,H.jsx)(_,{label:`Active workers`,value:`${c.activeWorkers}/${i}`,tone:`blue`,compact:!0}),(0,H.jsx)(_,{label:`Data`,value:p(l?.bytes??c.bytes),compact:!0}),(0,H.jsx)(_,{label:`Errors`,value:h((l?.pushFailed??c.pushFailed)+(l?.ackFailed??c.ackFailed)),tone:c.pushFailed+c.ackFailed?`red`:`default`,compact:!0})]})]}),(0,H.jsxs)(d,{children:[(0,H.jsx)(u,{title:`Throughput`}),(0,H.jsx)(`p`,{className:`-mt-3 mb-4 text-xs text-faint`,children:`Enqueue (client → server) vs completion (workers) per second`}),(0,H.jsx)(S,{series:[{label:`Push/sec`,color:`#38bdf8`,points:c.pushSeries,area:!0},{label:`Done/sec`,color:`#34d399`,points:c.doneSeries,area:!0}]}),(0,H.jsxs)(`div`,{className:`mt-2 flex items-center gap-4 font-mono text-[11px] text-faint`,children:[(0,H.jsx)(G,{color:`#38bdf8`,label:`Push/sec`,value:c.pushPerSec}),(0,H.jsx)(G,{color:`#34d399`,label:`Done/sec`,value:c.donePerSec})]})]})]})}function ae({summary:e}){return e?(0,H.jsxs)(d,{className:`mt-6`,children:[(0,H.jsx)(u,{title:`Summary`}),(0,H.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 md:grid-cols-4 xl:grid-cols-8`,children:[(0,H.jsx)(_,{label:`Pushed`,value:h(e.pushed),tone:`accent`,compact:!0}),(0,H.jsx)(_,{label:`Completed`,value:h(e.completed),tone:`green`,compact:!0}),(0,H.jsx)(_,{label:`Duration`,value:m(e.durationMs),compact:!0}),(0,H.jsx)(_,{label:`Avg push/s`,value:L(e.pushPerSec),tone:`accent`,compact:!0}),(0,H.jsx)(_,{label:`Avg done/s`,value:L(e.donePerSec),tone:`green`,compact:!0}),(0,H.jsx)(_,{label:`Data rate`,value:`${p(e.mbPerSec)}/s`,compact:!0}),(0,H.jsx)(_,{label:`Push p95`,value:m(e.p95),compact:!0}),(0,H.jsx)(_,{label:`Push p99`,value:m(e.p99),compact:!0})]}),(0,H.jsxs)(`p`,{className:`mt-3 text-xs text-faint`,children:[`Push-batch latency avg `,m(e.avg),` · p50 `,m(e.p50),` · p95`,` `,m(e.p95),` · p99 `,m(e.p99),` · max `,m(e.max),`.`,e.error?` First error: ${e.error}`:``]})]}):null}function oe({pollQueue:e,pollBaseUrl:t,pinned:n,counts:r,error:i}){return(0,H.jsxs)(d,{className:`mt-6`,children:[(0,H.jsx)(u,{title:`Server queue: ${e}`,action:i?(0,H.jsx)(`span`,{className:`text-xs font-medium text-warning`,children:`stale — server unreachable`}):void 0}),(0,H.jsxs)(`p`,{className:`-mt-3 mb-4 text-xs text-faint`,children:[`Live counts from `,t,` (poll 1s).`,n?` Pinned to the current or last benchmark run.`:``]}),r?(0,H.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 md:grid-cols-5`,children:[(0,H.jsx)(_,{label:`Waiting`,value:h(r.waiting??0),tone:`amber`,compact:!0}),(0,H.jsx)(_,{label:`Active`,value:h(r.active??0),tone:`blue`,compact:!0}),(0,H.jsx)(_,{label:`Completed`,value:h(r.completed??0),tone:`green`,compact:!0}),(0,H.jsx)(_,{label:`Failed`,value:h(r.failed??0),tone:r.failed?`red`:`default`,compact:!0}),(0,H.jsx)(_,{label:`Delayed`,value:h(r.delayed??0),compact:!0})]}):(0,H.jsx)(`p`,{className:`text-sm text-faint`,children:`No counts yet — waiting for the server to answer for this queue.`})]})}function W({label:e,pct:t,tone:n}){return(0,H.jsxs)(`div`,{className:`mb-2`,children:[(0,H.jsxs)(`div`,{className:`mb-1 flex items-center justify-between text-[11px] text-faint`,children:[(0,H.jsx)(`span`,{children:e}),(0,H.jsxs)(`span`,{className:`tnum`,children:[t.toFixed(0),`%`]})]}),(0,H.jsx)(`div`,{className:`h-1.5 overflow-hidden rounded-full bg-surface-2`,role:`progressbar`,"aria-label":e,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(t),children:(0,H.jsx)(`div`,{className:s(`h-full rounded-full transition-[width] motion-reduce:transition-none`,n===`accent`?`bg-accent`:`bg-emerald-500`),style:{width:`${t}%`}})})]})}function G({color:e,label:t,value:n}){return(0,H.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,H.jsx)(`span`,{className:`size-2 rounded-full`,style:{background:e}}),t,` `,(0,H.jsxs)(`span`,{className:`text-fg`,children:[L(n),`/s`]})]})}function se({history:e,onClear:t}){if(!e.length)return null;let n=JSON.stringify(e,null,2);return(0,H.jsxs)(d,{padded:!1,className:`mt-6 overflow-hidden`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between border-b border-line px-5 py-3`,children:[(0,H.jsx)(`h3`,{className:`text-base font-semibold text-fg`,children:`Run history`}),(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(g,{value:n}),(0,H.jsx)(l,{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,H.jsx)(l,{size:`sm`,variant:`ghost`,onClick:t,children:`Clear`})]})]}),(0,H.jsx)(`div`,{className:`overflow-x-auto`,children:(0,H.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,H.jsx)(`thead`,{children:(0,H.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,H.jsx)(`th`,{className:`px-5 py-2 font-medium`,children:`Mode`}),(0,H.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Prod`}),(0,H.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Wkr`}),(0,H.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Pushed`}),(0,H.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Done`}),(0,H.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Push/s`}),(0,H.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Done/s`}),(0,H.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`p95`}),(0,H.jsx)(`th`,{className:`px-5 py-2 text-right font-medium`,children:`Dur`})]})}),(0,H.jsx)(`tbody`,{children:e.map(e=>(0,H.jsxs)(`tr`,{className:`border-b border-line last:border-0 hover:bg-surface-2/40`,children:[(0,H.jsx)(`td`,{className:`px-5 py-2 capitalize text-muted`,children:e.mode}),(0,H.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-muted`,children:e.producers}),(0,H.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-muted`,children:e.workers}),(0,H.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-fg`,children:h(e.pushed)}),(0,H.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-success`,children:h(e.completed)}),(0,H.jsxs)(`td`,{className:`px-5 py-2 text-right tnum text-accent`,children:[L(e.pushPerSec),`/s`]}),(0,H.jsxs)(`td`,{className:`px-5 py-2 text-right tnum text-success`,children:[L(e.donePerSec),`/s`]}),(0,H.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-muted`,children:m(e.p95)}),(0,H.jsx)(`td`,{className:`px-5 py-2 text-right tnum text-muted`,children:m(e.durationMs)})]},e.id))})]})})]})}function ce(e=8){if(!Number.isSafeInteger(e)||e<1)throw RangeError(`Benchmark compensation concurrency must be a positive whole number`);let t=0,n=[],r=()=>{--t,n.shift()?.()};return Object.freeze({run(i){return new Promise((a,o)=>{let s=()=>{t+=1,Promise.resolve().then(i).then(a,o).finally(r)};t<e?s():n.push(s)})}})}var le=[`waiting`,`prioritized`,`delayed`,`active`,`paused`,`waiting-children`,`completed`,`failed`];function K(e){return le.reduce((t,n)=>{let r=e[n];if(!Number.isSafeInteger(r)||r<0)throw Error(`Malformed queue count for "${n}".`);return t+r},0)}function q(e,t){if(!e||typeof e!=`object`||e.ok!==!0)throw Error(`${t} returned a malformed success response.`)}var J={pushed:0,completed:0,pushFailed:0,ackFailed:0,bytes:0,elapsedMs:0,pushPerSec:0,donePerSec:0,activeWorkers:0,pushSeries:[],doneSeries:[],etaMs:null,error:null},Y=()=>({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:[]});function ue(e,t,n,r){let i=r-e.startedAt,a=(r-e.lastAt)/1e3,o=a>0?Math.max(0,(e.pushed-e.lastPushed)/a):0,s=a>0?Math.max(0,(e.completed-e.lastDone)/a):0;e.lastAt=r,e.lastPushed=e.pushed,e.lastDone=e.completed,e.pushSeries=[...e.pushSeries,o].slice(-60),e.doneSeries=[...e.doneSeries,s].slice(-60);let c=null;if(t?.mode===`count`){let r=A(t.total,1,w.total);if(n===`draining`){let t=e.doneSeries.slice(-10),n=t.length?t.reduce((e,t)=>e+t,0)/t.length:0;n<=0&&i>0&&(n=e.completed/(i/1e3)),n>0&&(c=Math.max(0,r-e.completed)/n*1e3)}else o>0&&(c=Math.max(0,r-e.pushed)/o*1e3)}else t?.mode===`duration`&&(c=Math.max(0,A(t.durationS,1,w.durationS)*1e3-i));return{pushed:e.pushed,completed:e.completed,pushFailed:e.pushFailed,ackFailed:e.ackFailed,bytes:e.bytes,elapsedMs:i,pushPerSec:o,donePerSec:s,activeWorkers:e.activeWorkers,pushSeries:e.pushSeries,doneSeries:e.doneSeries,etaMs:c,error:e.error}}function de(e,t){let n=t/1e3||1,r=[...e.pushLat].sort((e,t)=>e-t);return{pushed:e.pushed,completed:e.completed,pushFailed:e.pushFailed,ackFailed:e.ackFailed,bytes:e.bytes,durationMs:t,pushPerSec:e.pushed/n,donePerSec:e.completed/n,mbPerSec:e.bytes/n,avg:r.length?r.reduce((e,t)=>e+t,0)/r.length:0,p50:M(r,50),p95:M(r,95),p99:M(r,99),max:r.length?r[r.length-1]:0,error:e.error}}function fe(e){let t=e.queue.trim(),n=j(t);return n?{ok:!1,error:n}:[`count`,`duration`].includes(e.mode)?typeof e.durable!=`boolean`||typeof e.removeOnComplete!=`boolean`?{ok:!1,error:`Benchmark job options are invalid.`}:{ok:!0,config:Object.freeze({...e,queue:t,total:A(e.total,1,w.total),durationS:A(e.durationS,1,w.durationS),batch:A(e.batch,1,w.batch),producers:A(e.producers,1,w.producers),payload:A(e.payload,0,w.payload),workers:A(e.workers,0,w.workers),workerBatch:A(e.workerBatch,1,w.workerBatch),processMs:A(e.processMs,0,w.processMs)})}:{ok:!1,error:`Benchmark mode is invalid.`}}async function pe(e,t,n){try{q(await e.overview(),`Dashboard preflight`)}catch(e){return{ok:!1,live:{...J,error:`Server unreachable — start it on the Server page first. (${I(e)})`}}}if(!n())return{ok:!0};try{let r=await e.counts(t);if(!n())return{ok:!0};if(q(r,`Queue-count preflight`),!r.counts||typeof r.counts!=`object`||Array.isArray(r.counts))throw Error(`Malformed queue-count response.`);let i=K(r.counts);if(i>0)return{ok:!1,live:{...J,error:`Dedicated benchmark queue "${t}" is not empty (${i} job(s) across all states). Clean it before running so no external work can be consumed or deleted.`}}}catch(e){return{ok:!1,live:{...J,error:`Could not verify that dedicated queue "${t}" is empty. (${I(e)})`}}}return{ok:!0}}var X=new WeakMap;function me(e){let t=X.get(e);return t||(t={next:0,inFlight:new Set},X.set(e,t)),t}function he(e){return async()=>{let{stats:t}=e;for(;e.shouldContinue();){let n;if(e.runConfig.mode===`count`){if(t.assigned>=e.total)break;n=Math.min(e.batch,e.total-t.assigned)}else{if(performance.now()>=e.deadline)break;n=e.batch}let r=t.assigned;t.assigned+=n;let i=N(r,n,e.blob,e.runConfig.durable,e.runConfig.removeOnComplete,e.runId,Math.max(12e4,e.processMs+6e4)),a=performance.now(),o=e.client.addJobsBulk(e.queue,i).then(r=>{if(!e.isCurrent())return;if(q(r,`Bulk enqueue`),!Array.isArray(r.ids)||r.ids.length!==n||r.ids.some(e=>typeof e!=`string`||e.length===0)||new Set(r.ids).size!==r.ids.length)throw Error(`Bulk enqueue returned invalid job IDs.`);let i=r.ids;for(let t of i)e.ownJobIds.add(t);t.pushed+=i.length,t.bytes+=i.length*e.payload;let a=Math.max(0,n-i.length);a>0&&(t.pushFailed+=a,t.error??=`Server created ${i.length} of ${n} jobs in a benchmark batch.`)}).catch(r=>{e.isCurrent()&&(t.pushFailed+=n,t.error??=I(r))});e.pendingPushes.add(o);try{await o}finally{e.pendingPushes.delete(o)}e.isCurrent()&&t.pushLat.push(performance.now()-a)}}}function ge(e){return async()=>{let{stats:t}=e,n=me(e);for(;e.shouldContinue()&&!(e.runConfig.mode===`duration`&&performance.now()>=e.deadline||e.runConfig.mode===`count`&&t.completed>=e.total);){t.activeWorkers++;let r=++n.next;n.inFlight.add(r);let i=[];try{if(i=await _e(e),!e.shouldContinue()){await Z(e,i);break}i.length>0&&await ve(e,i)}finally{n.inFlight.delete(r),e.isCurrent()&&t.activeWorkers--}if(!e.shouldContinue())break;if(i.length===0){if(e.runConfig.mode===`count`&&e.producersDone()){let r=n.next;for(;e.ownJobIds.size>0&&e.shouldContinue()&&[...n.inFlight].some(e=>e<=r);)await F(50,e.shouldContinue);if(!e.shouldContinue())break;e.ownJobIds.size>0&&(t.error??=`${e.ownJobIds.size} benchmark job(s) could not be drained.`);break}await F(50,e.shouldContinue)}}}}async function _e(e){try{let t=await e.client.pullBatch(e.queue,e.workerBatch,`dashboard-benchmark:${e.runId}`);if(t?.ok!==!0||!Array.isArray(t.jobs)||t.jobs.length>e.workerBatch||t.jobs.some(e=>!e||typeof e!=`object`||typeof e.id!=`string`||e.id.length===0)||!Array.isArray(t.tokens)||t.tokens.length!==t.jobs.length||t.tokens.some(e=>typeof e!=`string`||e.length===0)||new Set(t.jobs.map(e=>e.id)).size!==t.jobs.length)throw Error(`Malformed pull-batch response.`);let n=t.jobs.map((e,n)=>({id:e.id,token:t.tokens?.[n]}));return e.shouldContinue()?n:(await Z(e,n),[])}catch(t){return e.isCurrent()&&(e.stats.error??=I(t)),[]}}async function ve(e,t){if(t.some(t=>!e.ownJobIds.has(t.id))&&e.pendingPushes.size>0&&await Promise.allSettled([...e.pendingPushes]),!e.shouldContinue())return Z(e,t);let n=t.filter(t=>e.ownJobIds.has(t.id)),r=t.filter(t=>!e.ownJobIds.has(t.id));if(r.length>0){await ye(e,t,r.length);return}if(n.length===0)return;if(!e.shouldContinue()||(e.processMs>0&&await F(e.processMs,e.shouldContinue),!e.shouldContinue()))return Z(e,n);let i=!1;try{let t=n.map(e=>e.id),r=n.map(e=>e.token),a=await e.client.heartbeatBatch(t,r);q(a,`Heartbeat benchmark jobs`);let o=a.data;if(!o||typeof o!=`object`||o.ok!==!0||!Number.isSafeInteger(o.count)||o.count!==n.length)throw Error(`Heartbeat confirmed ${String(o?.count)} of ${n.length} benchmark jobs; refusing a lossy batch ACK.`);if(!e.shouldContinue())return Z(e,n);if(i=!0,q(await e.client.ackBatch(t,r),`Acknowledge benchmark jobs`),!e.isCurrent())return;e.stats.completed+=n.length;for(let t of n)e.ownJobIds.delete(t.id)}catch(t){e.isCurrent()&&(e.stats.ackFailed+=n.length,e.stats.error??=I(t)),i||await Z(e,n)}}async function ye(e,t,n){let r=await Q(e,t);e.isCurrent()&&(e.stats.error??=r>0?`Detected ${n} foreign job(s); ${r} pulled job(s) could not be returned to waiting. Benchmark stopped.`:`Detected ${n} foreign job(s); returned the complete pulled batch to waiting and stopped without counting it.`),e.stop()}async function Z(e,t){if(t.length===0)return;let n=await Q(e,t);n>0&&e.isCurrent()&&(e.stats.error??=`${n} interrupted benchmark job(s) could not be returned to waiting.`)}async function Q(e,t){return(await Promise.allSettled(t.map(t=>e.compensationQueue.run(async()=>{q(await e.client.retryJob(t.id,t.token),`Restore job ${t.id}`),e.ownJobIds.delete(t.id)})))).filter(e=>e.status===`rejected`).length}var be=0;async function xe(e,t,n){if(e.runningRef.current||!e.mountedRef.current)return;e.runningRef.current=!0;let r=++e.runGenerationRef.current,a=n??i.createServerTargetClient(i.captureServerRequestTarget()),o=()=>e.mountedRef.current&&e.runGenerationRef.current===r,s=()=>o()&&!e.stopRef.current;e.stopRef.current=!1;try{e.setSummary(null);let n=fe(t);if(!n.ok){e.setLive({...J,error:n.error}),$(e,`error`);return}let r=n.config,i=await pe(a,r.queue,s);if(!o())return;if(!i.ok){e.setLive(i.live),$(e,`error`);return}if(!s())return;e.producersDoneRef.current=!1,e.configRef.current=r,e.setRunConfig(r);let c=Y();c.startedAt=performance.now(),c.lastAt=performance.now(),e.statsRef.current=c,e.setLive({...J}),$(e,`running`);let l={batch:r.batch,blob:`x`.repeat(r.payload),client:a,compensationQueue:ce(),deadline:performance.now()+r.durationS*1e3,isCurrent:o,ownJobIds:new Set,payload:r.payload,pendingPushes:new Set,processMs:r.processMs,producersDone:()=>e.producersDoneRef.current,queue:r.queue,runConfig:r,runId:`bqbench-${globalThis.crypto.randomUUID()}`,shouldContinue:s,stats:c,stop:()=>{e.stopRef.current=!0},total:r.total,workerBatch:r.workerBatch},u=he(l),d=ge(l),f=Array.from({length:r.producers},u),p=Array.from({length:r.workers},d),m=Promise.all(f).then(()=>{o()&&(e.producersDoneRef.current=!0,s()&&r.mode===`count`&&r.workers>0&&e.phaseRef.current===`running`&&$(e,`draining`))});if(await Promise.all([m,...p]),!o())return;Se(e,r,c)}finally{e.runningRef.current=!1}}function Se(e,t,n){let r=performance.now()-n.startedAt,i=de(n,r);e.setSummary(i),e.setLive(e=>({...e,pushed:n.pushed,completed:n.completed,pushFailed:n.pushFailed,ackFailed:n.ackFailed,bytes:n.bytes,elapsedMs:r,pushPerSec:0,donePerSec:0,activeWorkers:0,etaMs:0,error:n.error})),e.setHistory(e=>[{...i,id:++be,at:Date.now(),mode:t.mode,producers:t.producers,workers:t.workers},...e].slice(0,12)),$(e,e.stopRef.current?`stopped`:n.error?`error`:`done`)}function $(e,t){e.phaseRef.current=t,e.setPhase(t)}function Ce(){let[e,t]=(0,C.useState)(`idle`),[n,r]=(0,C.useState)(J),[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)(!0),f=(0,C.useRef)(0),p=(0,C.useRef)(!1),m=(0,C.useRef)(!1),h=(0,C.useRef)(null),g=(0,C.useRef)(`idle`),_=(0,C.useRef)(Y());return g.current=e,(0,C.useEffect)(()=>{let e=d,t=u,n=f;return d.current=!0,()=>{e.current=!1,t.current=!0,n.current++}},[]),(0,C.useEffect)(()=>{if(e!==`running`&&e!==`draining`)return;let t=setInterval(()=>{r(ue(_.current,h.current,g.current,performance.now()))},200);return()=>clearInterval(t)},[e]),{phase:e,live:n,summary:i,history:o,runCfg:c,run:(e,n)=>xe({configRef:h,mountedRef:d,phaseRef:g,producersDoneRef:m,runningRef:p,runGenerationRef:f,setHistory:s,setLive:r,setPhase:t,setRunConfig:l,setSummary:a,statsRef:_,stopRef:u},e,n),stop:()=>{u.current=!0,(g.current===`running`||g.current===`draining`)&&(g.current=`stopping`,t(`stopping`))},reset:()=>{u.current=!0,f.current++,g.current=`idle`,a(null),r(J),t(`idle`)},clearHistory:()=>s([])}}function we({benchmark:e,counts:t,dedicatedQueue:n,draft:r,pollQueue:i,runTarget:a,setRunTarget:o}){let s=(0,C.useRef)(null),c=(0,C.useRef)(!0),[l,u]=(0,C.useState)(!1),[d,f]=(0,C.useState)(null);(0,C.useEffect)(()=>(c.current=!0,()=>{c.current=!1,s.current=null}),[]);let p=async()=>{let e=r.queue.trim();if(s.current||!e)return;if(!O(e)||e!==n){f({error:`refusing to clean a queue not owned by this dashboard session`});return}s.current=`clean`;let o=a??Te(),l=t&&i===e?` Currently ${h(t.waiting??0)} waiting / ${h(t.completed??0)} completed.`:``;if(!window.confirm(`Clean every cleanable job from the dedicated dashboard benchmark queue "${e}" on ${o.target.baseUrl}? This is queue-wide; the cryptographic queue name is owned by this browser session.${l}`)){s.current=null;return}u(!0),f(null);try{let t=null;for(let n of z){if(!c.current)return;try{let t=await o.client.clean(e,{state:n,limit:w.total});if(q(t,`Clean ${n} jobs`),!Number.isSafeInteger(t.count)||t.count<0)throw Error(`Clean ${n} jobs returned an invalid count.`)}catch(e){t=e.message}}if(!c.current)return;let n=await o.client.counts(e).catch(e=>(t=e.message,null));if(!c.current)return;if(!n)f({error:t??`server unreachable — could not verify`});else if(n.ok!==!0||!n.counts||typeof n.counts!=`object`||Array.isArray(n.counts))f({error:`server returned a malformed queue-count response`});else try{let e=K(n.counts);f(t||e>0?{error:t??`${h(e)} job(s) still present`}:{remaining:0})}catch{f({error:`server returned malformed queue counts`})}}finally{c.current&&u(!1),s.current===`clean`&&(s.current=null)}},m=()=>{if(s.current)return;s.current=`run`;let n=V(r),c=n.queue.trim(),l=Te();if(j(c)){e.run({...n,queue:c},l.client).finally(g);return}let u=0;if(!a&&t&&i===c)try{u=K(t)}catch{}let d=u>0?` Warning: it already holds ${h(u)} job(s) across all states; the safety preflight will refuse the run until the dedicated queue is empty.`:``;if(!window.confirm(`Enqueue real jobs into "${c}" on ${l.target.baseUrl}?${d}`)){s.current=null;return}o(l),e.run(n,l.client).finally(g)},g=()=>{s.current===`run`&&(s.current=null)};return{cleaning:l,cleanResult:d,cleanup:p,start:m}}function Te(){let e=i.captureServerRequestTarget();return{target:e,client:i.createServerTargetClient(e)}}function Ee(){let[e]=(0,C.useState)(ee),[t,n]=(0,C.useState)(()=>ne({...T,queue:e})),s=Ce(),u=r(e=>e.baseUrl),[d,p]=(0,C.useState)(null),m=(e,t)=>n(n=>({...n,[e]:t})),h=e=>t=>m(e,t.target.value),g=e=>n(t=>{let n={...t};for(let[t,r]of Object.entries(e))n[t]=te.includes(t)?String(r):r;return n}),[_,v]=(0,C.useState)(e);(0,C.useEffect)(()=>{let e=setTimeout(()=>v(t.queue.trim()||T.queue),400);return()=>clearTimeout(e)},[t.queue]);let y=d?.target.baseUrl??u,{data:b,error:x}=c(()=>d?d.client.counts(_):i.counts(_),[_,d],{intervalMs:1e3}),S=b?.counts??null,E=we({benchmark:s,counts:S,dedicatedQueue:e,draft:t,pollQueue:_,runTarget:d,setRunTarget:p}),{phase:D,live:O,summary:j,history:M}=s,N=D===`running`||D===`draining`||D===`stopping`,P=s.runCfg??V(t),F=A(P.total,1,w.total),I=A(P.workers,0,w.workers),L=P.mode===`count`&&(N||j)?Math.min(100,O.pushed/F*100):0,R=P.mode===`count`&&(N||j)?Math.min(100,O.completed/F*100):0,z=P.mode===`duration`?Math.min(100,O.elapsedMs/(A(P.durationS,1,w.durationS)*1e3)*100):0,B=De(D,P.mode,!!j),U=Oe(D,O.etaMs);return(0,H.jsxs)(`div`,{children:[(0,H.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:D===`stopping`?(0,H.jsxs)(l,{variant:`warning`,size:`sm`,disabled:!0,children:[(0,H.jsx)(a,{className:`size-3.5`}),` Stopping…`]}):N?(0,H.jsxs)(l,{variant:`warning`,size:`sm`,onClick:s.stop,children:[(0,H.jsx)(a,{className:`size-3.5`}),` Stop`]}):(0,H.jsxs)(l,{variant:`success`,size:`sm`,disabled:E.cleaning,onClick:E.start,children:[(0,H.jsx)(o,{className:`size-3.5`}),` Run benchmark`]})}),O.error&&(0,H.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,H.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-center gap-2`,children:[(0,H.jsx)(`span`,{className:`text-xs font-medium uppercase tracking-wider text-faint`,children:`Presets`}),Object.keys(k).map(e=>(0,H.jsx)(`button`,{type:`button`,disabled:N,onClick:()=>g(k[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,H.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-3`,children:[(0,H.jsx)(re,{draft:t,active:N,cleaning:E.cleaning,cleanResult:E.cleanResult,setField:m,numberInput:h,onClean:()=>void E.cleanup()}),(0,H.jsx)(ie,{heading:B,pollBaseUrl:y,etaText:U,shown:P,shownWorkers:I,producePct:L,drainPct:R,durationPct:z,live:O,summary:j})]}),(0,H.jsx)(ae,{summary:j}),(0,H.jsx)(oe,{pollQueue:_,pollBaseUrl:y,pinned:!!d,counts:S,error:x}),(0,H.jsx)(se,{history:M,onClear:s.clearHistory})]})}function De(e,t,n){return e===`running`?t===`duration`?`Running…`:`Producing…`:e===`draining`?`Draining…`:e===`stopping`?`Stopping…`:e===`error`?`Error`:n?`Result`:`Ready`}function Oe(e,t){return(e===`running`||e===`draining`)&&t!=null?t>0?`ETA ${m(t)}`:`finishing…`:e===`stopped`?`stopped early`:e===`done`?`complete`:``}export{Ee as Benchmark};
@@ -0,0 +1,5 @@
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{g as t,t as n}from"./react-vendor-CFL9l8LK.js";import{i as r}from"./upstreamPaths-DQeKSxGc.js";import{r as i,t as a}from"./bq-DR2BTISO.js";import{t as o}from"./toastStore-XmMX7A5W.js";import{n as s}from"./usePolledData-CEyyLRYa.js";import{t as c}from"./Button-_aSJvRoW.js";import{n as l,t as u}from"./Card-egIDLwVk.js";import{t as d}from"./PageHeader-CQzNsw8r.js";import{i as f,n as p,t as m}from"./form-DG3X6cLL.js";import{r as h}from"./useServerActionGuard-CUx8TOAC.js";import{d as g,g as _,o as v,p as y,t as b,u as x}from"./responses-BkR2JTH9.js";var S=e(t(),1),C=1e4,w=365*24*60*60*1e3,T=1440*60*1e3,E=64*1024*1024,D=64*1024*1024,O=`[
2
+ { "data": { "to": "a@example.com", "template": "welcome" }, "groupId": "tenant-a", "priority": 1, "groupMaxSize": 100 },
3
+ { "data": { "to": "b@example.com", "template": "welcome" }, "groupId": "tenant-b" }
4
+ ]`,k=n();function A({values:e,setValue:t,parsedCount:n,parseError:r,validation:i,onFile:a,onBeforeTextChange:o}){return(0,k.jsxs)(u,{className:`lg:col-span-2`,children:[(0,k.jsx)(l,{title:`Jobs`,action:(0,k.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,k.jsx)(`input`,{type:`file`,name:`jobs-file`,accept:`.json,.ndjson,.txt,application/json`,onChange:a,className:`hidden`})]})}),(0,k.jsx)(`textarea`,{name:`jobs-json`,value:e.text,onChange:e=>{o(),t(`text`,e.target.value)},maxLength:E,spellCheck:!1,rows:16,placeholder:O,"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,k.jsxs)(`fieldset`,{className:`mt-3 flex flex-wrap items-center gap-3`,children:[(0,k.jsx)(`legend`,{className:`sr-only`,children:`Import interpretation`}),(0,k.jsx)(`span`,{"aria-hidden":`true`,className:`text-xs font-medium text-faint`,children:`Interpret each item as`}),(0,k.jsx)(f,{options:[`spec`,`raw`],value:e.mode,onChange:e=>t(`mode`,e)}),(0,k.jsx)(`span`,{className:`text-xs text-faint`,children:e.mode===`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,k.jsx)(`p`,{className:`mt-2 text-xs text-faint`,children:`Accepts a JSON array, a single object, or newline-delimited JSON.`}),(0,k.jsx)(`div`,{className:`mt-2 text-sm`,children:r?(0,k.jsx)(`span`,{role:`alert`,className:`text-danger`,children:r}):n>1e4?(0,k.jsxs)(`span`,{role:`alert`,className:`text-danger`,children:[`Too many jobs (`,n,`). Limit is `,C,`.`]}):n>0?(0,k.jsxs)(`span`,{className:`text-success`,children:[n,` job(s) parsed ✓`]}):(0,k.jsx)(`span`,{className:`text-faint`,children:`Nothing parsed yet.`})}),!r&&n>0&&!i.ok&&(0,k.jsxs)(`p`,{role:`alert`,className:`mt-2 text-xs text-danger`,children:[`Import blocked — `,i.msg,`. Fix the spec or switch to “raw” when the whole object is job data.`]})]})}function j({values:e,setValue:t,queueNames:n,queueDiscoveryError:r,onRetryQueues:i,busy:a,parsedCount:o,parseError:s,validationOk:d,result:f,onSubmit:h}){return(0,k.jsxs)(u,{children:[(0,k.jsx)(l,{title:`Target & defaults`}),(0,k.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,k.jsxs)(m,{label:`Queue`,children:[(0,k.jsx)(p,{list:`bulk-queue-options`,"aria-label":`Queue`,name:`bulk-target-queue`,autoComplete:`off`,value:e.queue,onChange:e=>t(`queue`,e.target.value),placeholder:`queue name (existing or new)`}),(0,k.jsx)(`datalist`,{id:`bulk-queue-options`,children:n.map(e=>(0,k.jsx)(`option`,{value:e},e))})]}),r&&(0,k.jsxs)(`p`,{role:`status`,className:`-mt-2 text-xs text-warning`,children:[`Existing queue suggestions unavailable — `,r.message,`. You can still enter a queue name manually.`,` `,(0,k.jsx)(`button`,{type:`button`,onClick:i,className:`font-medium underline underline-offset-2 hover:text-fg`,children:`Retry`})]}),(0,k.jsx)(`p`,{className:`-mt-2 text-xs text-faint`,children:`Defaults below fill any field an item omits.`}),(0,k.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,k.jsx)(M,{label:`Priority`,name:`default-priority`,value:e.priority,min:-1e6,max:1e6,placeholder:`0`,onChange:e=>t(`priority`,e)}),(0,k.jsx)(M,{label:`Max attempts`,name:`default-max-attempts`,value:e.maxAttempts,min:1,max:1e3,placeholder:`3`,onChange:e=>t(`maxAttempts`,e)}),(0,k.jsx)(M,{label:`Backoff (ms)`,name:`default-backoff`,value:e.backoff,min:0,max:T,placeholder:`1000`,onChange:e=>t(`backoff`,e)}),(0,k.jsx)(M,{label:`Timeout (ms)`,name:`default-timeout`,value:e.timeout,min:0,max:T,placeholder:`—`,onChange:e=>t(`timeout`,e)})]}),(0,k.jsx)(`div`,{className:`flex items-center gap-3`,children:(0,k.jsx)(c,{variant:`accent`,disabled:a||o===0||o>1e4||s!=null||!d,onClick:h,children:a?`Importing…`:`Import ${o||``}`})}),f&&(0,k.jsx)(`span`,{role:f.ok?`status`:`alert`,className:f.ok?`text-sm text-success`:`text-sm text-danger`,children:f.msg})]})]})}function M({label:e,name:t,value:n,min:r,max:i,placeholder:a,onChange:o}){return(0,k.jsx)(m,{label:e,children:(0,k.jsx)(p,{type:`number`,min:r,max:i,step:1,name:t,value:n,onChange:e=>o(e.target.value),placeholder:a})})}function N(e){return e.length>67108864||_(e,67108864)>67108864?`Import text exceeds the 64 MiB UTF-8 safety limit`:null}function P(e,t=D){return i(e,t)}function F(e,t,n){return{ok:!0,msg:`Accepted ${t} job submission${t===1?``:`s`} in ${n}; server returned ${e} distinct job ID${e===1?``:`s`} (deduplication may reuse existing jobs)`}}function I(e){let t=N(e);if(t)return{items:[],error:t};let n=e.trim();if(!n)return{items:[],error:null};let r;try{let e=JSON.parse(n);return{items:Array.isArray(e)?e:[e],error:null}}catch(e){r=e.message}let i=[],a=e.split(`
5
+ `);for(let e=0;e<a.length;e++){let t=a[e].trim();if(t)try{i.push(JSON.parse(t))}catch(t){return i.length===0?{items:[],error:`Invalid JSON: ${r}`}:{items:[],error:`Line ${e+1}: ${t.message}`}}}return{items:i,error:null}}function L({text:e,setText:t,setResult:n}){let r=(0,S.useRef)(null),i=(0,S.useRef)(0),a=(0,S.useCallback)(()=>{i.current+=1;let e=r.current;r.current=null;try{e?.abort()}catch{}},[]);return(0,S.useEffect)(()=>a,[a]),{cancelPending:a,onFile:a=>{let o=a.currentTarget,s=o.files?.[0];if(!s)return;let c=i.current+1;i.current=c;let l=r.current;r.current=null;try{l?.abort()}catch{}if(o.value=``,!Number.isSafeInteger(s.size)||s.size<0||s.size>67108864){n({ok:!1,msg:`File is too large; maximum is 64 MiB (${s.name})`});return}if(e.trim()!==``&&!window.confirm(`Replace the current input with "${s.name}"?`))return;let u=new FileReader,d=()=>i.current===c&&r.current===u,f=()=>{d()&&(r.current=null)};u.onload=()=>{if(!d())return;if(typeof u.result!=`string`){n({ok:!1,msg:`Could not decode file as text (${s.name})`}),f();return}let e=N(u.result);e?n({ok:!1,msg:`${e} (${s.name})`}):(t(u.result),n(null)),f()},u.onerror=()=>{d()&&(n({ok:!1,msg:`Could not read file (${s.name})`}),f())},u.onabort=f,r.current=u,n(null);try{u.readAsText(s)}catch{if(!d())return;n({ok:!1,msg:`Could not read file (${s.name})`}),f()}}}}var R=e=>{let t=typeof e==`string`&&e.trim()!==``?Number(e.trim()):e;return typeof t==`number`&&Number.isFinite(t)?t:void 0},z=e=>typeof e==`boolean`?e:void 0,B=e=>typeof e==`string`?e.trim()===``?void 0:e.trim():typeof e==`number`&&Number.isFinite(e)?String(e):void 0,V=e=>{if(!Array.isArray(e))return;let t=e.map(B);return t.every(e=>e!==void 0)?t:void 0},H=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:void 0,U=e=>{let t=R(e);if(t!==void 0)return t;let n=H(e);if(!n||n.type!==`fixed`&&n.type!==`exponential`||Object.keys(n).some(e=>e!==`type`&&e!==`delay`))return;let r=R(n.delay);return r===void 0?void 0:{type:n.type,delay:r}},W=e=>{let t=H(e);if(!t)return;let n=x(JSON.stringify(t));return n.ok?n.repeat:void 0};function G(e){let t=H(e);if(!t)return{ok:!1,msg:`must be an object`};let n=new Set([`ttl`,`extend`,`replace`]),r=Object.keys(t).filter(e=>!n.has(e));if(r.length)return{ok:!1,msg:`has unknown option(s): ${r.join(`, `)}`};if(t.ttl!==void 0&&(!Number.isSafeInteger(t.ttl)||t.ttl<=0||t.ttl>31536e6))return{ok:!1,msg:`ttl must be a whole number from 1 to ${w} ms`};for(let e of[`extend`,`replace`])if(t[e]!==void 0&&typeof t[e]!=`boolean`)return{ok:!1,msg:`${e} must be a boolean`};return t.extend===!0&&t.replace===!0?{ok:!1,msg:`extend and replace are mutually exclusive`}:t.extend===!0&&t.ttl===void 0?{ok:!1,msg:`extend requires ttl`}:{ok:!0,dedup:{...typeof t.ttl==`number`?{ttl:t.ttl}:{},...typeof t.extend==`boolean`?{extend:t.extend}:{},...typeof t.replace==`boolean`?{replace:t.replace}:{}}}}var K=e=>{let t=G(e);return t.ok?t.dedup:void 0};function q(e,t,n){if(n===`spec`&&e&&typeof e==`object`&&!Array.isArray(e)&&`data`in e){let n=e;return{name:B(n.name),data:n.data,priority:R(n.priority)??t.priority,delay:R(n.delay),maxAttempts:R(n.maxAttempts)??t.maxAttempts,backoff:U(n.backoff)??t.backoff,timeout:R(n.timeout)??t.timeout,jobId:B(n.jobId)??B(n.customId),removeOnComplete:z(n.removeOnComplete),removeOnFail:z(n.removeOnFail),durable:z(n.durable),lifo:z(n.lifo),ttl:R(n.ttl),uniqueKey:B(n.uniqueKey),tags:V(n.tags),groupId:B(n.groupId),groupMaxSize:R(n.groupMaxSize),dependsOn:V(n.dependsOn),stallTimeout:R(n.stallTimeout),repeat:W(n.repeat),dedup:K(n.dedup),stackTraceLimit:R(n.stackTraceLimit),timestamp:R(n.timestamp)}}return{data:e,...t}}var J=new Set([`name`,`data`,`priority`,`delay`,`maxAttempts`,`backoff`,`timeout`,`jobId`,`customId`,`removeOnComplete`,`removeOnFail`,`durable`,`lifo`,`ttl`,`uniqueKey`,`tags`,`groupId`,`groupMaxSize`,`dependsOn`,`stallTimeout`,`repeat`,`dedup`,`stackTraceLimit`,`timestamp`]);function Y(e,t,n,r){if(e===void 0)return null;let i=R(e);return i===void 0?`${t} must be a number`:Number.isSafeInteger(i)?i<n||i>r?`${t} must be between ${n} and ${r}`:null:`${t} must be a whole, safe integer`}function X(e){let t={priority:e.priority.trim()||void 0,maxAttempts:e.maxAttempts.trim()||void 0,backoff:e.backoff.trim()||void 0,timeout:e.timeout.trim()||void 0},n=[[`priority`,`Default priority`,-1e6,1e6],[`maxAttempts`,`Default max attempts`,1,1e3],[`backoff`,`Default backoff`,0,T],[`timeout`,`Default timeout`,0,T]],r={};for(let[e,i,a,o]of n){let n=Y(t[e],i,a,o);if(n)return{ok:!1,msg:n};let s=R(t[e]);s!==void 0&&(r[e]=s)}return{ok:!0,defaults:r}}function Z(e){let t=Object.keys(e).filter(e=>!J.has(e));if(t.length)return`unknown job option(s): ${t.join(`, `)}`;let n=[[`delay`,`delay`,0,w],[`maxAttempts`,`maxAttempts`,1,1e3],[`timeout`,`timeout`,0,T],[`ttl`,`ttl`,0,w],[`stallTimeout`,`stallTimeout`,0,T],[`stackTraceLimit`,`stackTraceLimit`,0,1e4],[`timestamp`,`timestamp`,0,2**53-1],[`groupMaxSize`,`groupMaxSize`,1,2**53-1]];for(let[t,r,i,a]of n){let n=Y(e[t],r,i,a);if(n)return n}if(e.backoff!==void 0){let t=U(e.backoff);if(t===void 0)return`backoff must be a number or {"type":"fixed|exponential","delay":number} with no extra keys`;let n=Y(typeof t==`number`?t:t.delay,`backoff delay`,0,T);if(n)return n}if(e.repeat!==void 0){let t=H(e.repeat);if(!t)return`repeat must be an object`;let n=x(JSON.stringify(t));if(!n.ok)return n.msg}if(e.dedup!==void 0){let t=G(e.dedup);if(!t.ok)return`dedup ${t.msg}`;if(B(e.uniqueKey)===void 0)return`dedup requires a non-empty uniqueKey`}if(e.name!==void 0){let t=B(e.name);if(t===void 0||t.length>256)return`name must be a non-empty string (or finite number) of at most 256 characters`}for(let t of[`removeOnComplete`,`removeOnFail`,`durable`,`lifo`])if(e[t]!==void 0&&typeof e[t]!=`boolean`)return`${t} must be a boolean`;for(let t of[`jobId`,`customId`,`uniqueKey`]){let n=e[t];if(n===void 0)continue;let i=B(n);if(i===void 0||i.length>1024)return`${t} must be a non-empty string (or finite numeric id) of at most 1024 characters`;if((t===`jobId`||t===`customId`)&&r(i))return`${t}: ${r(i)}`}let i=B(e.jobId),a=B(e.customId);if(i!==void 0&&a!==void 0&&i!==a)return`jobId and customId disagree; provide only one spelling`;if(e.groupId!==void 0){let t=B(e.groupId);if(t===void 0||t.length>256||t.includes(`\0`))return`groupId must be a non-empty string of at most 256 characters without NUL`}if(e.groupMaxSize!==void 0&&e.groupId===void 0)return`groupMaxSize requires groupId`;let o=Y(e.priority,e.groupId===void 0?`priority`:`group priority`,e.groupId===void 0?-1e6:0,e.groupId===void 0?1e6:v);if(o)return o;for(let t of[`tags`,`dependsOn`]){if(e[t]===void 0)continue;let n=V(e[t]),i=t===`tags`?256:1024;if(!n||n.some(e=>e.length>i))return`${t} must be an array of non-empty strings of at most ${i} characters`;if(t===`dependsOn`){let e=n.find(e=>r(e));if(e)return`dependsOn ID "${e}": ${r(e)}`}}return null}function Q(e){let t=new Map;for(let n of e)if(n.jobId){if(t.has(n.jobId))return`duplicate jobId/customId "${n.jobId}" makes dependency resolution ambiguous`;t.set(n.jobId,n)}let n=new Set,r=new Set,i=e=>{if(n.has(e))return!0;if(r.has(e))return!1;n.add(e);for(let n of t.get(e)?.dependsOn??[])if(t.has(n)&&i(n))return!0;return n.delete(e),r.add(e),!1};for(let e of t.keys())if(i(e))return`dependency cycle detected in this batch (involving "${e}")`;return null}function $(e,t,n){if(e.length>1e4)return{ok:!1,msg:`Too many jobs (${e.length}). Limit is ${C}.`};let r=[],i=0;for(let a=0;a<e.length;a++){let o=e[a];if(n===`spec`&&ee(o)){let e=Z(o);if(e)return{ok:!1,msg:`Job ${a+1}: ${e}`}}let s=q(o,t,n);if(s.groupId!==void 0){let e=Y(s.priority,`group priority`,0,v);if(e)return{ok:!1,msg:`Job ${a+1}: ${e}`}}if(s.groupMaxSize!==void 0&&s.groupId===void 0)return{ok:!1,msg:`Job ${a+1}: groupMaxSize requires groupId`};let c;try{c=JSON.stringify(s.data)}catch{return{ok:!1,msg:`Job ${a+1}: data must be JSON serializable`}}if(c===void 0)return{ok:!1,msg:`Job ${a+1}: data must be JSON serializable`};if(c.length>10485760)return{ok:!1,msg:`Job ${a+1}: data exceeds the 10 MiB UTF-8 limit`};let l=_(c,y);if(l>10485760)return{ok:!1,msg:`Job ${a+1}: data exceeds the 10 MiB UTF-8 limit`};if(i+=l,i>67108864)return{ok:!1,msg:`Combined job data exceeds the 64 MiB import safety limit`};r.push(s)}let a=Q(r);return a?{ok:!1,msg:a}:{ok:!0,bodies:r}}var ee=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&`data`in e,te={queue:``,text:``,mode:`spec`,priority:``,maxAttempts:``,backoff:``,timeout:``};function ne(){let{data:e,error:t,refetch:n}=s(()=>a.queues(),[],{intervalMs:3e4}),[r,i]=(0,S.useState)(te),[c,l]=(0,S.useState)(!1),[u,f]=(0,S.useState)(null),p=h(`bulk-add-jobs`),m=(e,t)=>i(n=>({...n,[e]:t})),_=L({text:r.text,setText:e=>m(`text`,e),setResult:f});(0,S.useEffect)(()=>{l(!1),f(null)},[p.scopeKey]);let v=(0,S.useMemo)(()=>I(r.text),[r.text]),y=(0,S.useMemo)(()=>{if(v.error)return{ok:!1,msg:v.error};if(v.items.length>1e4)return{ok:!1,msg:`Too many jobs (${v.items.length}). Limit is ${C}.`};let e=X(r);return e.ok?$(v.items,e.defaults,r.mode):e},[v,r]),x=async()=>{f(null);let e=r.queue.trim(),t=g(e);if(t){f({ok:!1,msg:t});return}let n=N(r.text);if(n){f({ok:!1,msg:n});return}if(v.error){f({ok:!1,msg:v.error});return}if(v.items.length===0){f({ok:!1,msg:`Nothing to enqueue — paste a JSON array or NDJSON.`});return}if(v.items.length>1e4){f({ok:!1,msg:`Too many jobs (${v.items.length}). Limit is ${C}.`});return}if(!y.ok){f({ok:!1,msg:y.msg});return}let i=P(y.bodies);if(i){f({ok:!1,msg:i});return}let s=p.begin();if(s){l(!0);try{let t=b(await a.addJobsBulk(e,y.bodies),y.bodies.length);if(!s.isCurrent())return;let n=F(new Set(t).size,y.bodies.length,e);f(n),o.success(n.msg)}catch(e){if(!s.isCurrent())return;let t=e.message;f({ok:!1,msg:t}),o.error(`Bulk import failed`,t)}finally{s.finish()&&l(!1)}}};return(0,k.jsxs)(`div`,{children:[(0,k.jsx)(d,{title:`Bulk Add Jobs`,description:`Import many distinct jobs at once from a JSON array, NDJSON, or a file.`}),(0,k.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-3`,children:[(0,k.jsx)(A,{values:r,setValue:m,parsedCount:v.items.length,parseError:v.error,validation:y,onFile:_.onFile,onBeforeTextChange:_.cancelPending}),(0,k.jsx)(j,{values:r,setValue:m,queueNames:(e?.queues??[]).map(e=>e.name),queueDiscoveryError:t,onRetryQueues:()=>void n(),busy:c,parsedCount:v.items.length,parseError:v.error,validationOk:y.ok,result:u,onSubmit:()=>void x()})]})]})}export{ne as BulkAddJobs};
@@ -0,0 +1 @@
1
+ import{t as e}from"./react-vendor-CFL9l8LK.js";import{r as t}from"./StatusBadge-DereLzOj.js";var n=e(),r={default:`border border-line bg-surface-2 text-fg hover:bg-surface-2/70 hover:border-line-strong`,ghost:`text-muted hover:text-fg hover:bg-surface-2`,accent:`bg-accent text-accent-fg hover:opacity-90 border border-transparent`,danger:`border border-red-500/30 text-danger hover:bg-red-500/10 hover:border-red-500/50`,warning:`border border-amber-500/30 text-warning hover:bg-amber-500/10 hover:border-amber-500/50`,success:`bg-emerald-500 text-white hover:bg-emerald-500/90 border border-transparent`},i={sm:`h-8 px-3 text-xs gap-1.5`,md:`h-9 px-4 text-sm gap-2`};function a({children:e,variant:a=`default`,size:o=`md`,className:s,...c}){return(0,n.jsx)(`button`,{type:`button`,className:t(`inline-flex items-center justify-center rounded-lg font-medium transition-colors`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent`,`disabled:cursor-not-allowed disabled:opacity-50`,r[a],i[o],s),...c,children:e})}function o({children:e,className:i,variant:a=`ghost`,...o}){return(0,n.jsx)(`button`,{type:`button`,className:t(`inline-flex size-8 items-center justify-center rounded-lg transition-colors`,`focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent`,`disabled:cursor-not-allowed disabled:opacity-50`,r[a],i),...o,children:e})}export{o as n,a as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./react-vendor-CFL9l8LK.js";import{r as t}from"./StatusBadge-DereLzOj.js";var n=e();function r({children:e,className:r,padded:i=!0}){return(0,n.jsx)(`div`,{className:t(`rounded-xl border border-line bg-surface`,i&&`p-5`,r),children:e})}function i({title:e,action:t,icon:r,headingLevel:i=2}){return(0,n.jsxs)(`div`,{className:`mb-4 flex items-center justify-between gap-3`,children:[(0,n.jsxs)(`h${i}`,{className:`flex items-center gap-2 text-base font-semibold text-fg`,children:[r,e]}),t]})}export{i as n,r as t};
@@ -0,0 +1 @@
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{g as t,t as n}from"./react-vendor-CFL9l8LK.js";import{O as r,c as i}from"./icons-DH9SS1DA.js";import{t as a}from"./api-D9aT0ND7.js";import{n as o}from"./usePolledData-CEyyLRYa.js";import{n as s}from"./Button-_aSJvRoW.js";import{i as c,n as l,r as u,t as d}from"./feedback-CtGN_kqB.js";import{t as f}from"./PageHeader-CQzNsw8r.js";import{i as p,s as m}from"./format-Cg7VCIZW.js";import{t as h}from"./Pagination-CSkzhNW6.js";import{r as g,t as _}from"./useServerActionGuard-CUx8TOAC.js";var v=e(t(),1),y=n();function b(){let{data:e,error:t,loading:n,refetch:b}=o(()=>a.crons(),[]),x=(e?.crons??[]).slice(),[S,C]=(0,v.useState)(0),w=Math.max(1,Math.ceil(x.length/15)),T=Math.min(S,w-1),[E,D]=(0,v.useState)(null),[O,k]=(0,v.useState)(null),A=g(`classic-cron`);(0,v.useEffect)(()=>{D(null),k(null)},[A.scopeKey]);let j=async e=>{if(!window.confirm(`Delete cron "${e}"?`))return;let t=A.begin(`delete:${e}`);if(t){D(null),k(e);try{if(_(await a.deleteCron(e),`Delete cron`),!t.isCurrent())return;await b()}catch(e){t.isCurrent()&&D(`Delete failed: ${e.message}`)}finally{t.finish()&&k(null)}}};return(0,y.jsxs)(`div`,{children:[t&&e&&(0,y.jsx)(c,{message:`Cron refresh failed — showing the last successful schedule list.`,onRetry:b}),(0,y.jsx)(f,{title:`Cron Jobs`,description:e?`${x.length} scheduled`:`Schedule inventory unavailable`,live:!!e&&!t}),E&&(0,y.jsx)(`p`,{role:`alert`,className:`mb-4 text-sm text-danger`,children:E}),t&&!e?(0,y.jsx)(l,{error:t,onRetry:b}):n&&!e?(0,y.jsx)(u,{label:`Loading cron jobs…`}):x.length===0?(0,y.jsx)(d,{icon:(0,y.jsx)(i,{}),title:`No scheduled jobs`,hint:`Repeatable jobs created with upsertJobScheduler appear here.`}):(0,y.jsxs)(y.Fragment,{children:[(0,y.jsx)(`div`,{className:`overflow-x-auto rounded-xl border border-line bg-surface`,children:(0,y.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,y.jsx)(`thead`,{children:(0,y.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,y.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Name`}),(0,y.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Queue`}),(0,y.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Schedule`}),(0,y.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Next Run`}),(0,y.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Runs`}),(0,y.jsx)(`th`,{className:`w-12 px-5 py-3`})]})}),(0,y.jsx)(`tbody`,{children:x.slice(T*15,T*15+15).map(e=>(0,y.jsxs)(`tr`,{className:`border-b border-line last:border-0 hover:bg-surface-2/40`,children:[(0,y.jsx)(`td`,{className:`px-5 py-3 font-medium text-fg`,children:e.name}),(0,y.jsx)(`td`,{className:`px-5 py-3 font-mono text-xs text-muted`,children:e.queue??`—`}),(0,y.jsx)(`td`,{className:`px-5 py-3 font-mono text-xs text-muted`,children:e.schedule??(e.repeatEvery?`every ${e.repeatEvery}ms`:`—`)}),(0,y.jsx)(`td`,{className:`px-5 py-3 text-faint`,children:p(e.nextRun)}),(0,y.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-muted`,children:m(e.executions??0)}),(0,y.jsx)(`td`,{className:`px-5 py-3 text-right`,children:(0,y.jsx)(s,{"aria-label":`Delete cron`,disabled:O!==null,onClick:()=>j(e.name),children:(0,y.jsx)(r,{className:`size-3.5`})})})]},e.name))})]})}),(0,y.jsx)(h,{page:T,pageSize:15,total:x.length,onPageChange:C,label:`crons`})]})]})}export{b as Cron};
@@ -0,0 +1 @@
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{g as t,t as n}from"./react-vendor-CFL9l8LK.js";import{t as r}from"./upstreamPaths-DQeKSxGc.js";import{t as i}from"./bq-DR2BTISO.js";import{t as a}from"./toastStore-XmMX7A5W.js";import{O as o,c as s}from"./icons-DH9SS1DA.js";import{r as c}from"./StatusBadge-DereLzOj.js";import{n as l}from"./usePolledData-CEyyLRYa.js";import{n as u,t as d}from"./Button-_aSJvRoW.js";import{n as f,t as p}from"./Card-egIDLwVk.js";import{i as m,n as h,r as g,t as _}from"./feedback-CtGN_kqB.js";import{t as v}from"./PageHeader-CQzNsw8r.js";import{i as y,s as b}from"./format-Cg7VCIZW.js";import{i as x,n as S,o as C,t as w}from"./form-DG3X6cLL.js";import{t as ee}from"./Pagination-CSkzhNW6.js";import{r as te}from"./useServerActionGuard-CUx8TOAC.js";import{d as ne,h as re,m as T}from"./responses-BkR2JTH9.js";import"./AddJob-CiwWycYG.js";var E=e(t(),1),D=6e4;function O(e){return{year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),weekday:e.getDay(),hour:e.getHours(),minute:e.getMinutes()}}function k(e){e.minute>59&&(e.minute-=60,e.hour+=1),e.hour>23&&(e.hour-=24,e.day+=1);let t=new Date(Date.UTC(e.year,e.month-1,e.day,12));e.year=t.getUTCFullYear(),e.month=t.getUTCMonth()+1,e.day=t.getUTCDate(),e.weekday=t.getUTCDay()}function A(e,t,n){let r=e.dayOfMonth.values.has(t),i=e.dayOfWeek.values.has(n);return e.dayOfMonth.literalWildcard||e.dayOfWeek.literalWildcard?r&&i:r||i}function j(e,t){let n=new Date(t);return e.minute.values.has(n.getMinutes())&&e.hour.values.has(n.getHours())&&e.month.values.has(n.getMonth()+1)&&A(e,n.getDate(),n.getDay())}function M(e,t){return e.values.size===t}function N(e,t,n,r){let i=new Date(t.year,t.month-1,t.day,t.hour,t.minute,0,0).getTime();if(M(e.minute,60)||M(e.hour,24)){let a=Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute),o=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute);if(i<=n||i-n>o-a){let t=(Math.floor(n/D)+1)*D,r=n+121*D;for(i>n&&(r=Math.min(r,i));t<r;){if(j(e,t))return t;t+=D}}}return i>n?i:null}function P(e,t){if(!Number.isFinite(t))return null;let n=O(new Date(t)),r={...n,minute:n.minute+1},i=n.year+8;for(let a=0;a<1e5&&r.year<=i;a++){if(k(r),!e.month.values.has(r.month)){r.month+=1,r.day=1,r.hour=0,r.minute=0;continue}if(!A(e,r.day,r.weekday)){r.day+=1,r.hour=0,r.minute=0;continue}if(!e.hour.values.has(r.hour)){r.hour+=1,r.minute=0;continue}if(!e.minute.values.has(r.minute)){r.minute+=1;continue}let i=N(e,r,t,n);if(i!==null)return i;r.minute+=1}return null}function F(e,t,n){let r=P(e,Math.floor(n/D)*D-1);for(;r!==null;){for(let e of t){let t=r+e*1e3;if(t>n)return t}let i=P(e,r);if(i===null||i<=r)return null;r=i}return null}var I={jan:1,january:1,feb:2,february:2,mar:3,march:3,apr:4,april:4,may:5,jun:6,june:6,jul:7,july:7,aug:8,august:8,sep:9,september:9,oct:10,october:10,nov:11,november:11,dec:12,december:12},L={sun:0,sunday:0,mon:1,monday:1,tue:2,tuesday:2,wed:3,wednesday:3,thu:4,thursday:4,fri:5,friday:5,sat:6,saturday:6},ie={"@yearly":`0 0 1 1 *`,"@annually":`0 0 1 1 *`,"@monthly":`0 0 1 * *`,"@weekly":`0 0 * * 0`,"@daily":`0 0 * * *`,"@midnight":`0 0 * * *`,"@hourly":`0 * * * *`};function R(e,t,n,r){let i=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(!Number.isSafeInteger(s)||s<1||s>127)return null;let l,u;if(c===`*`)l=t,u=n;else if(c.includes(`-`)){let e=c.split(`-`);if(e.length!==2)return null;let[t,n]=e,i=z(t,r),a=z(n,r);if(i==null||a==null)return null;l=i,u=a}else{let e=z(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 z(e,t){let n=e.trim().toLowerCase();if(n===``)return null;if(t){let e=t[n];if(e!==void 0)return e}if(!/^\+?\d+$/.test(n))return null;let r=Number(n);return Number.isSafeInteger(r)?r:null}function B(e,t,n){let r=e.trim(),i=(ie[r.toLowerCase()]??r).split(/\s+/);if(i.length!==5&&i.length!==6)return{valid:!1,error:`Expected 5 fields (min hour day month weekday) or 6 with leading seconds, got ${i.length}.`,runs:[]};let a=i.length===6,o=+!!a,s=a?H(i[0]):V(0),c=R(i[o],0,59),l=R(i[o+1],0,23),u=R(i[o+2],1,31),d=R(i[o+3],1,12,I),f=R(i[o+4],0,7,L);if(!s||!c||!l||!u||!d||!f)return{valid:!1,error:`Invalid field syntax.`,runs:[]};let p=new Set;for(let e of f.values)p.add(e===7?0:e);let m={values:p,star:f.star},h={minute:{values:c.values,literalWildcard:c.star},hour:{values:l.values,literalWildcard:l.star},dayOfMonth:{values:u.values,literalWildcard:u.star},month:{values:d.values,literalWildcard:d.star},dayOfWeek:{values:m.values,literalWildcard:m.star}},g=[],_=Number.isSafeInteger(t)?Math.max(0,Math.min(t,100)):0,v=[...s.values].sort((e,t)=>e-t),y=n;for(;g.length<_;){let e=a?F(h,v,y):P(h,y);if(e===null||e<=y)break;g.push(e),y=e}return{valid:!0,runs:g}}function V(e){return{values:new Set([e]),star:!1}}function H(e){let t=new Set;for(let n of e.split(`,`)){if(!n)return null;let e=n.split(`/`);if(e.length>2||!e[0]||e[1]===``)return null;let r=e[0],i=e.length===2;if(i&&!/^\d+$/.test(e[1]))return null;let a=i?Number(e[1]):1;if(a<1||a>60)return null;let o,s;if(r===`*`)o=0,s=59;else if(r.includes(`-`)){let e=r.split(`-`);if(e.length!==2||!e[0]||!e[1]||!/^\d+$/.test(e[0])||!/^\d+$/.test(e[1]))return null;o=Number(e[0]),s=Number(e[1])}else{if(i||!/^\d+$/.test(r))return null;o=Number(r),s=o}if(o<0||s>59||o>s)return null;for(let e=o;e<=s;e+=a)t.add(e)}return t.size?{values:t,star:e===`*`||/^\*\/\d+$/.test(e)}:null}var U=365*24*60*60*1e3,W=1440*60*1e3;function G(e){if(typeof e!=`object`||!e||e.ok!==!0)throw Error(`Delete cron returned a malformed success response`)}function K(e,t){let n=e?.cron;if(typeof e!=`object`||!e||e.ok!==!0||typeof n!=`object`||!n||n.name!==t.name||n.queue!==t.queue)throw Error(`Create cron returned a malformed success response`)}var q=e=>`Cron "${e}" already exists. Bunqueue v2.9.3 does not return complete cron definitions, so editing could reset hidden options. Delete it explicitly, wait for the list to refresh, then create the replacement as a separate action.`;function J(e,t){let n=e.trim();return n&&t.has(n)?q(n):null}function ae(e,t){let n=e;if(typeof n!=`object`||!n||n.ok!==!0||!Array.isArray(n.crons)||n.crons.some(e=>typeof e!=`object`||!e||typeof e.name!=`string`))throw Error(`Cannot verify that the cron name is unused; creation was not attempted`);if(n.crons.some(e=>e.name===t.trim()))throw Error(q(t.trim()))}function oe(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 Y(e,t,n,r){if(!e.trim())return{ok:!0};let i=Number(e);return!Number.isSafeInteger(i)||i<n||i>r?{ok:!1,msg:`${t} must be a whole number from ${n} to ${r}`}:{ok:!0,value:i}}function se(e,t=Date.now()){let n=e.name.trim(),i=e.queue.trim();if(!n)return{ok:!1,msg:`Name is required`};if(n.length>256)return{ok:!1,msg:`Name must be 256 characters or fewer`};let a=r(n,`Name`,256);if(a)return{ok:!1,msg:a};let o=ne(i);if(o)return{ok:!1,msg:o};let s=e.jobName?.trim()||`default`;if(s.length>256)return{ok:!1,msg:`Spawned job name must be 256 characters or fewer`};let c={};if(e.dataText.trim()){let t=re(e.dataText);if(!t.ok)return{ok:!1,msg:t.kind===`json`?`Data is not valid JSON`:t.msg};c=t.data}let l={name:n,jobName:s,queue:i,data:c,preventOverlap:e.preventOverlap,skipIfNoWorker:e.skipIfNoWorker,immediately:e.immediately,skipMissedOnRestart:e.skipMissedOnRestart};if(e.mode===`cron`){let n=e.schedule.trim();if(!n)return{ok:!1,msg:`Cron expression required`};let r=B(n,1,t);if(!r.valid)return{ok:!1,msg:`Cron expression is not supported by Bunqueue 2.9: ${r.error??`invalid syntax`}`};l.schedule=n}else{let t=Y(e.every,`Interval`,1,U);if(!t.ok||t.value===void 0)return{ok:!1,msg:t.ok?`Interval is required`:t.msg};l.repeatEvery=t.value}let u=e.timezone.trim();if(u){if(e.mode!==`cron`)return{ok:!1,msg:`Timezone applies only to cron expressions, not intervals`};try{new Intl.DateTimeFormat(`en`,{timeZone:u}).format(t)}catch{return{ok:!1,msg:`Timezone must be a valid IANA timezone`}}l.timezone=u}let d=Y(e.priority,`Priority`,-1e6,1e6);if(!d.ok)return d;d.value!==void 0&&(l.priority=d.value);let f=Y(e.maxLimit,`Max executions`,1,2**53-1);if(!f.ok)return f;f.value!==void 0&&(l.maxLimit=f.value);let p=e.uniqueKey.trim();if(p.length>1024)return{ok:!1,msg:`Unique key must be 1024 characters or fewer`};p&&(l.uniqueKey=p);let m=Y(e.dedupTtl,`Dedup TTL`,1,U);if(!m.ok)return m;let h=m.value!==void 0||e.dedupExtend||e.dedupReplace;if(e.dedupExtend&&e.dedupReplace)return{ok:!1,msg:`Dedup extend and replace are mutually exclusive`};if(e.dedupExtend&&m.value===void 0)return{ok:!1,msg:`Dedup extend requires a TTL`};if(h&&!p&&!e.preventOverlap)return{ok:!1,msg:`Dedup options require a unique key or Prevent overlap`};h&&(l.dedup={...m.value===void 0?{}:{ttl:m.value},...e.dedupExtend?{extend:!0}:{},...e.dedupReplace?{replace:!0}:{}});let g=[{raw:e.jobMaxAttempts,label:`Spawned-job max attempts`,min:1,max:1e3,key:`maxAttempts`},{raw:e.jobBackoff,label:`Spawned-job backoff`,min:0,max:W,key:`backoff`},{raw:e.jobTimeout,label:`Spawned-job timeout`,min:0,max:W,key:`timeout`},{raw:e.jobDelay,label:`Spawned-job delay`,min:0,max:U,key:`delay`},{raw:e.jobStallTimeout,label:`Spawned-job stall timeout`,min:0,max:W,key:`stallTimeout`}],_={};for(let e of g){let t=Y(e.raw,e.label,e.min,e.max);if(!t.ok)return t;t.value!==void 0&&(_[e.key]=t.value)}return e.jobRemoveOnComplete&&(_.removeOnComplete=!0),e.jobRemoveOnFail&&(_.removeOnFail=!0),Object.keys(_).length&&(l.jobOptions=_),{ok:!0,body:l}}var X=n();function ce({values:e,setValue:t}){return(0,X.jsxs)(`div`,{id:`cron-advanced-options`,className:`mt-3 grid grid-cols-2 gap-3`,children:[(0,X.jsx)(w,{label:`Timezone (IANA)`,hint:`e.g. Europe/Rome. Default: server timezone.`,children:(0,X.jsx)(S,{name:`cron-timezone`,autoComplete:`off`,value:e.timezone,onChange:e=>t(`timezone`,e.target.value),placeholder:`Europe/Rome`})}),(0,X.jsx)(w,{label:`Priority`,children:(0,X.jsx)(S,{type:`number`,min:-1e6,max:1e6,step:1,name:`cron-priority`,value:e.priority,onChange:e=>t(`priority`,e.target.value),placeholder:`0`})}),(0,X.jsx)(w,{label:`Max executions`,hint:`blank = unlimited`,children:(0,X.jsx)(S,{type:`number`,min:1,max:2**53-1,step:1,name:`cron-max-executions`,value:e.maxLimit,onChange:e=>t(`maxLimit`,e.target.value),placeholder:`∞`})}),(0,X.jsx)(w,{label:`Unique key`,hint:`optional deduplication key`,children:(0,X.jsx)(S,{name:`cron-unique-key`,autoComplete:`off`,maxLength:1024,value:e.uniqueKey,onChange:e=>t(`uniqueKey`,e.target.value),placeholder:`daily-report`})}),(0,X.jsxs)(`div`,{className:`col-span-2 flex flex-wrap gap-6`,children:[(0,X.jsx)(Q,{label:`prevent overlap`,checked:e.preventOverlap,onChange:e=>t(`preventOverlap`,e)}),(0,X.jsx)(Q,{label:`skip if no worker`,checked:e.skipIfNoWorker,onChange:e=>t(`skipIfNoWorker`,e)}),(0,X.jsx)(Q,{label:`run immediately`,checked:e.immediately,onChange:e=>t(`immediately`,e)}),(0,X.jsx)(Q,{label:`skip missed on restart`,checked:e.skipMissedOnRestart,onChange:e=>t(`skipMissedOnRestart`,e)})]}),(0,X.jsxs)(`div`,{className:`col-span-2`,children:[(0,X.jsx)(`div`,{className:`mb-2 text-[11px] uppercase tracking-wider text-faint`,children:`Cron deduplication`}),(0,X.jsxs)(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-3`,children:[(0,X.jsx)(w,{label:`Dedup TTL (ms)`,hint:`blank = no TTL`,children:(0,X.jsx)(S,{type:`number`,min:1,max:U,step:1,name:`cron-dedup-ttl`,value:e.dedupTtl,onChange:e=>t(`dedupTtl`,e.target.value),placeholder:`60000`})}),(0,X.jsx)(Q,{className:`items-end pb-2`,label:`extend TTL`,controlLabel:`extend dedup TTL`,checked:e.dedupExtend,onChange:e=>t(`dedupExtend`,e)}),(0,X.jsx)(Q,{className:`items-end pb-2`,label:`replace duplicate`,checked:e.dedupReplace,onChange:e=>t(`dedupReplace`,e)})]})]}),(0,X.jsxs)(`div`,{className:`col-span-2`,children:[(0,X.jsx)(`div`,{className:`mb-2 text-[11px] uppercase tracking-wider text-faint`,children:`Spawned-job options`}),(0,X.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 lg:grid-cols-5`,children:[(0,X.jsx)(Z,{label:`Max attempts`,name:`cron-job-max-attempts`,value:e.jobMaxAttempts,min:1,max:1e3,placeholder:`3`,onChange:e=>t(`jobMaxAttempts`,e)}),(0,X.jsx)(Z,{label:`Backoff (ms)`,name:`cron-job-backoff`,value:e.jobBackoff,min:0,max:W,placeholder:`1000`,onChange:e=>t(`jobBackoff`,e)}),(0,X.jsx)(Z,{label:`Timeout (ms)`,name:`cron-job-timeout`,value:e.jobTimeout,min:0,max:W,placeholder:`—`,onChange:e=>t(`jobTimeout`,e)}),(0,X.jsx)(Z,{label:`Delay (ms)`,name:`cron-job-delay`,value:e.jobDelay,min:0,max:U,placeholder:`0`,onChange:e=>t(`jobDelay`,e)}),(0,X.jsx)(Z,{label:`Stall timeout (ms)`,name:`cron-job-stall-timeout`,value:e.jobStallTimeout,min:0,max:W,placeholder:`server default`,onChange:e=>t(`jobStallTimeout`,e)})]}),(0,X.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-6`,children:[(0,X.jsx)(Q,{label:`remove on complete`,controlLabel:`remove spawned jobs on complete`,checked:e.jobRemoveOnComplete,onChange:e=>t(`jobRemoveOnComplete`,e)}),(0,X.jsx)(Q,{label:`remove on fail`,controlLabel:`remove spawned jobs on fail`,checked:e.jobRemoveOnFail,onChange:e=>t(`jobRemoveOnFail`,e)})]})]})]})}function Z({label:e,name:t,value:n,min:r,max:i,placeholder:a,onChange:o}){return(0,X.jsx)(w,{label:e,children:(0,X.jsx)(S,{type:`number`,min:r,max:i,step:1,name:t,value:n,onChange:e=>o(e.target.value),placeholder:a})})}function Q({label:e,controlLabel:t=e,checked:n,onChange:r,className:i=`items-center`}){return(0,X.jsxs)(`div`,{className:`flex gap-2 ${i}`,children:[(0,X.jsx)(C,{checked:n,onChange:r,label:t}),(0,X.jsx)(`span`,{className:`text-sm text-muted`,children:e})]})}function le({values:e,setValue:t}){let n=e.mode===`cron`&&e.schedule.trim()?B(e.schedule.trim(),3,Date.now()):null,r=oe(e.every);return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,X.jsx)(w,{label:`Name`,children:(0,X.jsx)(S,{name:`cron-name`,autoComplete:`off`,maxLength:256,value:e.name,onChange:e=>t(`name`,e.target.value),placeholder:`daily-report`})}),(0,X.jsx)(w,{label:`Queue`,children:(0,X.jsx)(S,{name:`cron-queue`,autoComplete:`off`,maxLength:256,value:e.queue,onChange:e=>t(`queue`,e.target.value),placeholder:`reports`})}),(0,X.jsx)(w,{label:`Spawned job name`,hint:`First-class worker routing name; separate from schedule data.`,children:(0,X.jsx)(S,{name:`cron-job-name`,autoComplete:`off`,maxLength:256,value:e.jobName,onChange:e=>t(`jobName`,e.target.value),placeholder:`default`})})]}),(0,X.jsxs)(`div`,{className:`flex flex-wrap items-end gap-3`,children:[(0,X.jsxs)(`fieldset`,{children:[(0,X.jsx)(`legend`,{className:`sr-only`,children:`Schedule type`}),(0,X.jsx)(x,{options:[`cron`,`every`],value:e.mode,onChange:e=>t(`mode`,e)})]}),e.mode===`cron`?(0,X.jsx)(`div`,{className:`min-w-56 flex-1`,children:(0,X.jsx)(w,{label:`Cron expression`,hint:`Standard 5-field syntax, 6 fields with leading seconds, or an official @hourly/@daily-style shortcut. Croner extensions L/W/#/? are rejected by Bunqueue 2.9.`,children:(0,X.jsx)(S,{name:`cron-expression`,value:e.schedule,onChange:e=>t(`schedule`,e.target.value),placeholder:`0 9 * * *`})})}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{className:`w-40`,children:(0,X.jsx)(w,{label:`Every (ms)`,children:(0,X.jsx)(S,{type:`number`,min:1,max:U,step:1,name:`cron-interval`,value:e.every,onChange:e=>t(`every`,e.target.value),placeholder:`30000`})})}),e.every.trim()!==``&&(0,X.jsx)(`span`,{className:c(`pb-2 text-xs`,r?`text-muted`:`text-danger`),children:r??`not a valid interval`})]})]}),e.mode===`cron`&&e.schedule.trim()&&n&&(0,X.jsx)(`div`,{className:`rounded-lg border border-line bg-surface-2 px-3 py-2 text-xs`,children:n.valid?n.runs.length?(0,X.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,X.jsx)(`span`,{className:`text-faint`,children:`Next runs (browser-local time):`}),n.runs.map(e=>(0,X.jsx)(`span`,{className:`font-mono text-muted`,children:y(e)},e)),(0,X.jsx)(`span`,{className:`text-faint`,children:e.timezone.trim()?`— server evaluates in ${e.timezone.trim()}`:`— no timezone set: the server evaluates in its own timezone, which may differ`})]}):(0,X.jsx)(`span`,{className:`text-warning`,children:`Valid, but no runs in the next few years.`}):(0,X.jsxs)(`span`,{className:`text-warning`,children:[`Unsupported expression: `,n.error,` Fix it before creating the schedule.`]})}),(0,X.jsx)(w,{label:`Data (JSON)`,children:(0,X.jsx)(`textarea`,{name:`cron-data`,value:e.dataText,onChange:e=>t(`dataText`,e.target.value),maxLength:T,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`})})]})}function $(e){let[t,n]=(0,E.useState)(0);return(0,E.useEffect)(()=>{t>e-1&&n(e-1)},[t,e]),[Math.min(t,e-1),n]}function ue(e){let[t,n]=(0,E.useState)(!1),r=(0,E.useRef)(null),i=()=>{r.current&&clearTimeout(r.current),r.current=null};return(0,E.useEffect)(()=>()=>{r.current&&clearTimeout(r.current)},[]),{on:t,fire:()=>{i(),n(!0),r.current=setTimeout(()=>n(!1),e)},reset:()=>{i(),n(!1)}}}var de={name:``,jobName:`default`,queue:``,mode:`cron`,schedule:``,every:``,dataText:`{}`,timezone:``,priority:``,preventOverlap:!0,skipIfNoWorker:!1,maxLimit:``,immediately:!1,skipMissedOnRestart:!0,uniqueKey:``,dedupTtl:``,dedupExtend:!1,dedupReplace:!1,jobMaxAttempts:``,jobBackoff:``,jobTimeout:``,jobDelay:``,jobStallTimeout:``,jobRemoveOnComplete:!1,jobRemoveOnFail:!1};function fe({onCreate:e,onAccepted:t,beginCreate:n,scopeKey:r,existingNames:i}){let[o,s]=(0,E.useState)(de),[c,l]=(0,E.useState)(!1),[u,f]=(0,E.useState)(null),[p,m]=(0,E.useState)(!1),{on:h,fire:g,reset:_}=ue(3e3),v=(e,t)=>s(n=>({...n,[e]:t}));(0,E.useEffect)(()=>{m(!1),f(null),_()},[r]);let y=J(o.name,i),b=async()=>{f(null),_();let r=se(o);if(!r.ok){f(r.msg);return}let c=J(r.body.name,i);if(c){f(c);return}if(!window.confirm(`Submit an upsert for cron "${r.body.name}"? Bunqueue v2.9.3 has no atomic create-only condition. The dashboard will recheck immediately before writing, but another client using the same name at the same time could still be replaced. Continue only if you authorize last-writer-wins behavior for this globally unique name.`))return;let l=n(r.body.name);if(l){m(!0);try{if(K(await e(r.body,l.isCurrent),r.body),!l.isCurrent())return;s(e=>({...e,name:``,schedule:``,every:``})),g(),a.success(`Cron upsert acknowledged`,r.body.name),t()}catch(e){l.isCurrent()&&f(e.message)}finally{l.finish()&&m(!1)}}};return(0,X.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),b()},children:[(0,X.jsx)(le,{values:o,setValue:v}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`button`,{type:`button`,onClick:()=>l(e=>!e),"aria-expanded":c,"aria-controls":`cron-advanced-options`,className:`text-xs font-medium text-muted hover:text-fg`,children:c?`− Hide advanced`:`+ Advanced options`}),c&&(0,X.jsx)(ce,{values:o,setValue:v})]}),(0,X.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,X.jsx)(d,{type:`submit`,variant:`accent`,size:`sm`,disabled:p||!!y,children:p?`Saving…`:y?`Name already exists`:`Submit upsert`}),y&&!u&&(0,X.jsx)(`span`,{role:`alert`,className:`max-w-2xl text-xs text-warning`,children:y}),u&&(0,X.jsx)(`span`,{role:`alert`,className:`text-xs text-danger`,children:u}),h&&(0,X.jsx)(`span`,{role:`status`,className:`text-xs text-success`,children:`Cron upsert acknowledged ✓`})]}),(0,X.jsx)(`p`,{className:`text-xs text-warning`,children:`Creation is an upstream upsert, not an atomic create-only operation. Use a globally unique name; the fail-closed preflight cannot eliminate a simultaneous write from another client.`})]})}function pe({crons:e,page:t,removing:n,onPageChange:r,onRemove:i}){let a=e.slice(t*15,t*15+15);return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{className:`overflow-x-auto rounded-xl border border-line bg-surface`,children:(0,X.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,X.jsx)(`thead`,{children:(0,X.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,X.jsx)(`th`,{scope:`col`,className:`px-5 py-3 font-medium`,children:`Name`}),(0,X.jsx)(`th`,{scope:`col`,className:`px-5 py-3 font-medium`,children:`Queue`}),(0,X.jsx)(`th`,{scope:`col`,className:`px-5 py-3 font-medium`,children:`Job name`}),(0,X.jsx)(`th`,{scope:`col`,className:`px-5 py-3 font-medium`,children:`Schedule`}),(0,X.jsx)(`th`,{scope:`col`,className:`px-5 py-3 font-medium`,children:`Next Run`}),(0,X.jsx)(`th`,{scope:`col`,className:`px-5 py-3 text-right font-medium`,children:`Runs`}),(0,X.jsx)(`th`,{scope:`col`,className:`w-12 px-5 py-3`})]})}),(0,X.jsx)(`tbody`,{children:a.map(e=>(0,X.jsxs)(`tr`,{className:`border-b border-line last:border-0 hover:bg-surface-2/40`,children:[(0,X.jsx)(`td`,{className:`px-5 py-3 font-medium text-fg`,children:e.name}),(0,X.jsx)(`td`,{className:`px-5 py-3 font-mono text-xs text-muted`,children:e.queue}),(0,X.jsx)(`td`,{className:`px-5 py-3 font-mono text-xs text-muted`,children:e.jobName??`default`}),(0,X.jsx)(`td`,{className:`px-5 py-3 font-mono text-xs text-muted`,children:e.schedule??(e.repeatEvery?`every ${e.repeatEvery}ms`:`—`)}),(0,X.jsx)(`td`,{className:`px-5 py-3 text-faint`,children:y(e.nextRun)}),(0,X.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-muted`,children:b(e.executions)}),(0,X.jsx)(`td`,{className:`px-5 py-3 text-right`,children:(0,X.jsx)(u,{"aria-label":`Delete cron ${e.name}`,disabled:n.has(e.name),onClick:()=>i(e.name),children:(0,X.jsx)(o,{className:`size-3.5`})})})]},e.name))})]})}),(0,X.jsx)(ee,{page:t,pageSize:15,total:e.length,onPageChange:r,label:`crons`})]})}var me=[];function he(){let{data:e,error:t,loading:n,refetch:r}=l(()=>i.crons(),[]),o=e?.crons??me,c=(0,E.useMemo)(()=>new Set(o.map(e=>e.name)),[o]),[u,d]=$(Math.max(1,Math.ceil(o.length/15))),[y,b]=(0,E.useState)(null),[x,S]=(0,E.useState)(new Set),C=te(`cron-manager`);(0,E.useEffect)(()=>{b(null),S(new Set)},[C.scopeKey]);let w=async e=>{if(!window.confirm(`Delete cron "${e}"? It will not be recreated automatically; creating a replacement is a separate action.`))return;let t=C.begin(`cron:${e}`);if(t){b(null),S(t=>new Set(t).add(e));try{if(G(await i.deleteCron(e)),!t.isCurrent())return;a.success(`Cron deleted`,e),r()}catch(e){if(!t.isCurrent())return;b(e.message),a.error(`Delete cron failed`,e.message)}finally{t.finish()&&S(t=>{let n=new Set(t);return n.delete(e),n})}}};return(0,X.jsxs)(`div`,{children:[t&&e&&(0,X.jsx)(m,{message:`Cron refresh failed — showing the last successful schedule list.`,onRetry:r}),(0,X.jsx)(v,{title:`Cron Manager`,description:`Submit explicitly acknowledged schedule upserts and manage repeatable jobs.`,live:!!e&&!t}),y&&(0,X.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:y}),(0,X.jsxs)(p,{className:`mb-6`,children:[(0,X.jsx)(f,{title:`Create schedule via upstream upsert`}),(0,X.jsx)(fe,{existingNames:c,onCreate:async(e,t)=>{let n=await i.crons();if(!t())throw Error(`Cron creation target changed during preflight`);return ae(n,e.name),i.createCron(e)},onAccepted:r,beginCreate:e=>C.begin(`cron:${e}`),scopeKey:C.scopeKey})]}),t&&!e?(0,X.jsx)(h,{error:t,onRetry:r}):n&&!e?(0,X.jsx)(g,{label:`Loading crons…`}):o.length===0?(0,X.jsx)(_,{icon:(0,X.jsx)(s,{}),title:`No scheduled jobs`,hint:`Submit one above.`}):(0,X.jsx)(pe,{crons:o,page:u,removing:x,onPageChange:d,onRemove:e=>void w(e)})]})}export{he as CronManager};
@@ -1,3 +1,3 @@
1
- import{i as e,t}from"./cn-zFEt5SO8.js";import{g as n,h as r,t as i}from"./react-vendor-CvwrP0tU.js";import{o as a}from"./connectionStore-BJLihGaC.js";import{a as o,i as s,t as c}from"./bq-F5BbTG1T.js";import{t as l}from"./toastStore-IZn6OPLZ.js";import{T as u,o as d}from"./icons-BVzwsfbG.js";import{n as f}from"./usePolledData-0CVelkl2.js";import{t as p}from"./Button-Ch1W94fJ.js";import{n as m,t as h}from"./Card-CWxrC8OY.js";import{i as g,n as _,r as v,t as y}from"./feedback-QDN1AsYt.js";import{t as b}from"./PageHeader-CvIyaFOO.js";import{n as x,s as S}from"./format-Cg7VCIZW.js";import{a as C,c as w,n as T,s as E}from"./index-8Ii-_Rml.js";import{a as D}from"./form-C4oby9pI.js";import{t as ee}from"./Pagination-x-Cwgrul.js";var O=e(r(),1),k=e(n(),1),A=i();function j({columns:e,filter:t,onChange:n}){let[r,i]=(0,k.useState)(t?.column??``),[a,o]=(0,k.useState)(t?.op??`contains`),[s,c]=(0,k.useState)(t?.value??``),l=r||e[0]||``,d=()=>n(s.trim()?{column:l,op:a,value:s.trim()}:null);return e.length===0?null:(0,A.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-center gap-2`,children:[(0,A.jsx)(`div`,{className:`w-40`,children:(0,A.jsx)(D,{value:l,"aria-label":`Filter column`,name:`database-filter-column`,autoComplete:`off`,onChange:e=>i(e.target.value),children:e.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})}),(0,A.jsx)(`div`,{className:`w-32`,children:(0,A.jsxs)(D,{value:a,"aria-label":`Filter operator`,name:`database-filter-operator`,autoComplete:`off`,onChange:e=>o(e.target.value),children:[(0,A.jsx)(`option`,{value:`contains`,children:`contains`}),(0,A.jsx)(`option`,{value:`eq`,children:`=`}),(0,A.jsx)(`option`,{value:`ne`,children:`≠`})]})}),(0,A.jsxs)(`div`,{className:`relative min-w-40 flex-1`,children:[(0,A.jsx)(u,{className:`pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-faint`}),(0,A.jsx)(`input`,{value:s,onChange:e=>c(e.target.value),onKeyDown:e=>e.key===`Enter`&&d(),"aria-label":`Filter value`,name:`database-filter-value`,autoComplete:`off`,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,A.jsx)(p,{size:`sm`,onClick:d,disabled:!s.trim(),children:`Filter`}),t&&(0,A.jsx)(p,{size:`sm`,variant:`ghost`,onClick:()=>{c(``),n(null)},children:`Clear`}),(0,A.jsx)(`span`,{className:`text-[11px] text-faint`,children:`filters the whole table, server-side`})]})}var M=`bq-dash-db-history`,N=10,P=2e4,F=100;function I(e){let t=e==null?``:String(e),n=typeof e==`string`&&/^[=+\-@\t\r]/.test(e)?`'${e}`:t;return/[",\r\n]/.test(n)?`"${n.replaceAll(`"`,`""`)}"`:n}function L(e,t){return[e.map(I).join(`,`),...t.map(e=>e.map(I).join(`,`))].join(`
2
- `)}function R(e,t,n){let r=URL.createObjectURL(new Blob([n],{type:t})),i=document.createElement(`a`);i.href=r,i.download=e,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(r),0)}function z(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e.slice(0,F))if(!(typeof r!=`string`||r.length===0||r.length>P||n.has(r))&&(n.add(r),t.push(r),t.length===N))break;return t}function B(){try{return z(JSON.parse(localStorage.getItem(M)??`[]`))}catch{return[]}}function V(e){let t=z(e);try{localStorage.setItem(M,JSON.stringify(t))}catch{}return t}function H(e){return V([e,...B().filter(t=>t!==e)].slice(0,N))}function U(e){if(e==null)return`NULL`;let t=typeof e==`string`?e:String(e),n=t.trimStart();if(n.startsWith(`{`)||n.startsWith(`[`))try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}return t}async function W(e,t=c.captureAgentRequestTarget(),n){let r=Object.freeze({table:e.table,orderBy:e.orderBy,dir:e.dir,filter:e.filter?Object.freeze({...e.filter}):void 0});return c.getDbExportAtTarget(t,r,n)}var G=e=>JSON.stringify([e.activeProfileId,e.baseUrl,e.agentBaseUrl,e.token,e.agentToken]);function te({value:e,align:n}){if(e==null)return(0,A.jsx)(`span`,{className:`italic text-faint`,children:`NULL`});let r=typeof e==`string`?e:String(e);return(0,A.jsx)(`span`,{className:t(`block max-w-[24rem] truncate`,n===`right`&&`text-right tabular-nums`),title:r,children:r})}function ne({columns:e,rows:n,truncatedCells:r,colMeta:i,sort:a,onSort:o,onRowClick:s,dimmed:c}){let l=(0,k.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,A.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,A.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,A.jsx)(`thead`,{children:(0,A.jsxs)(`tr`,{className:`text-left text-[11px] uppercase tracking-wider text-faint`,children:[s&&(0,A.jsx)(`th`,{className:`sticky top-0 z-10 whitespace-nowrap border-b border-line bg-surface px-4 py-3 font-medium`,children:(0,A.jsx)(`span`,{className:`sr-only`,children:`Row actions`})}),e.map((e,n)=>{let r=i?.[e];return(0,A.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,A.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,A.jsx)(`span`,{className:`rounded bg-accent/15 px-1 py-0.5 text-[9px] font-semibold text-accent`,children:`PK`}),r?.type&&(0,A.jsx)(`span`,{className:`text-faint/70`,children:r.type.toLowerCase()}),(0,A.jsx)(`span`,{"aria-hidden":`true`,className:a?.col===e?`text-accent`:`text-faint/60`,children:a?.col===e?a.dir===`asc`?`▲`:`▼`:`↕`})]}):e},e)})]})}),(0,A.jsx)(`tbody`,{children:n.map((e,t)=>(0,A.jsxs)(`tr`,{className:`border-b border-line font-mono text-xs last:border-0 hover:bg-surface-2/40`,children:[s&&(0,A.jsx)(`td`,{className:`whitespace-nowrap px-4 py-2`,children:(0,A.jsx)(`button`,{type:`button`,"aria-label":`View row ${t+1} details`,onClick:()=>s(t),className:`rounded-md border border-line px-2 py-1 font-sans text-[11px] font-medium text-muted transition-colors hover:border-line-strong hover:text-fg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent`,children:`View`})}),e.map((e,n)=>(0,A.jsx)(`td`,{className:`whitespace-nowrap px-4 py-2 text-muted`,children:(0,A.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,A.jsx)(te,{value:e,align:l[n]?`right`:`left`}),r?.[t]?.[n]&&(0,A.jsx)(`span`,{title:`Value truncated — use the row's View action to read it in full`,className:`shrink-0 rounded bg-warning/15 px-1 text-[9px] font-semibold text-warning`,children:`…`})]})},n))]},t))})]})})}function K(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Malformed database query response.`);let t=e;if(t.ok!==!0||!Array.isArray(t.columns)||t.columns.some(e=>typeof e!=`string`)||!Array.isArray(t.rows)||t.rows.length>500||t.rows.some(e=>!Array.isArray(e)||e.length!==t.columns.length)||!Number.isSafeInteger(t.rowCount)||t.rowCount!==t.rows.length||typeof t.truncated!=`boolean`||typeof t.ms!=`number`||!Number.isFinite(t.ms)||t.ms<0)throw Error(`Malformed database query response.`);return{columns:[...t.columns],rows:t.rows.map(e=>[...e]),rowCount:t.rowCount,truncated:t.truncated,ms:t.ms}}function re({sql:e,setSql:t,editorRef:n}){let r=a(G),[i,o]=(0,k.useState)(null),[s,l]=(0,k.useState)(null),[u,d]=(0,k.useState)(B),[f,g]=(0,k.useState)(null),_=(0,k.useRef)(0),v=(0,k.useRef)(null),y=(0,k.useRef)(r);y.current!==r&&(y.current=r,_.current++,v.current=null),(0,k.useEffect)(()=>(_.current++,v.current=null,o(null),l(null),g(null),()=>{_.current++,v.current=null}),[r]);let b=i===r,x=s?.target===r?s.message:null,C=f?.target===r?f:null,w=async(t=e,n=!0)=>{let i=t.trim();if(!i||v.current?.target===r)return;let s=++_.current,u=r;v.current={generation:s,target:u},o(u),l(null);try{let e=K(await c.db.query(t));if(s!==_.current||G(a.getState())!==u)return;g({...e,target:u}),n&&d(H(i))}catch(e){if(s!==_.current||G(a.getState())!==u)return;g(null),l({target:u,message:e.message})}finally{v.current?.generation===s&&(v.current=null),s===_.current&&o(null)}};return(0,A.jsxs)(h,{className:`mt-6`,children:[(0,A.jsx)(m,{title:`Query`,action:(0,A.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,A.jsx)(p,{size:`sm`,disabled:b||!e.trim(),onClick:()=>{let t=e.trim();t&&w(`EXPLAIN QUERY PLAN ${t}`,!1)},children:`Explain`}),(0,A.jsx)(p,{size:`sm`,variant:`accent`,disabled:b||!e.trim(),onClick:()=>w(),children:b?`Running…`:`Run`})]})}),(0,A.jsx)(`textarea`,{name:`database-sql-query`,autoComplete:`off`,ref:n,value:e,onChange:e=>t(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&w()},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,A.jsx)(`p`,{className:`mt-1 text-[11px] text-faint`,children:`⌘/Ctrl+Enter runs. Connection is read-only.`}),u.length>0&&(0,A.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-1.5`,children:[(0,A.jsx)(`span`,{className:`text-[11px] uppercase tracking-wider text-faint`,children:`History`}),u.map(e=>(0,A.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,A.jsx)(`button`,{type:`button`,onClick:()=>{V([]),d([])},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,A.jsxs)(`div`,{"aria-live":`polite`,children:[x&&(0,A.jsx)(`p`,{role:`alert`,className:`mt-3 text-xs text-danger`,children:x}),C&&!x&&(0,A.jsxs)(`div`,{className:`mt-4`,children:[(0,A.jsxs)(`div`,{className:`mb-2 flex flex-wrap items-center gap-3`,children:[(0,A.jsxs)(`p`,{className:`text-xs text-faint`,children:[C.truncated?`≥ `:``,S(C.rowCount),` row`,C.rowCount===1?``:`s`,` · `,S(C.ms),` ms`,C.truncated&&(0,A.jsxs)(`span`,{className:`text-warning`,children:[` — showing first `,C.rows.length]})]}),C.rows.length>0&&(0,A.jsxs)(`div`,{className:`ml-auto flex gap-2`,children:[(0,A.jsx)(p,{size:`sm`,onClick:()=>R(`query-results.csv`,`text/csv`,L(C.columns,C.rows)),children:`CSV`}),(0,A.jsx)(p,{size:`sm`,onClick:()=>R(`query-results.json`,`application/json`,JSON.stringify(C.rows.map(e=>Object.fromEntries(C.columns.map((t,n)=>[t,e[n]]))),null,2)),children:`JSON`})]})]}),C.rows.length>0?(0,A.jsx)(ne,{columns:C.columns,rows:C.rows}):(0,A.jsx)(`p`,{className:`text-xs text-faint`,children:`Query returned no rows.`})]})]})]})}var q=(e,t)=>t?e?.column===t.column&&e.op===t.op&&e.value===t.value:e===null;function J(e,t){return e.table===t.table&&e.limit===t.limit&&e.offset===t.offset&&e.orderBy===(t.orderBy??null)&&e.dir===t.dir&&q(e.filter,t.filter)}var Y=-(1n<<63n),X=(1n<<63n)-1n;function Z(e){if(e===null)return!0;if(typeof e==`number`)return Number.isSafeInteger(e);if(typeof e!=`string`||!/^-?(?:0|[1-9]\d*)$/.test(e)||e.length>20)return!1;try{let t=BigInt(e);return t>=Y&&t<=X}catch{return!1}}var ie=e=>e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e);function ae(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Malformed database rows response.`);let n=e,r=n.columns,i=n.rows,a=n.rowids,o=n.truncatedCells,s=n.filter,c=s===null||typeof s==`object`&&!!s&&!Array.isArray(s)&&typeof s.column==`string`&&(s.op===`contains`||s.op===`eq`||s.op===`ne`)&&typeof s.value==`string`;if(n.ok!==!0||typeof n.table!=`string`||!Array.isArray(r)||r.length===0||r.length>2e3||r.some(e=>typeof e!=`string`||!e)||new Set(r).size!==r.length||!Array.isArray(i)||i.length>t.limit||i.some(e=>!Array.isArray(e)||e.length!==r.length||e.some(e=>!ie(e)))||!Array.isArray(a)||a.length!==i.length||a.some(e=>!Z(e))||!Array.isArray(o)||o.length!==i.length||o.some(e=>!Array.isArray(e)||e.length!==r.length||e.some(e=>typeof e!=`boolean`))||!Number.isSafeInteger(n.total)||n.total<0||!Number.isSafeInteger(n.limit)||!Number.isSafeInteger(n.offset)||n.offset<0||n.orderBy!==null&&typeof n.orderBy!=`string`||n.dir!==`asc`&&n.dir!==`desc`||!c)throw Error(`Malformed database rows response.`);let l={ok:!0,table:n.table,columns:[...r],rows:i.map(e=>[...e]),rowids:[...a],truncatedCells:o.map(e=>[...e]),total:n.total,limit:n.limit,offset:n.offset,orderBy:n.orderBy,dir:n.dir,filter:s===null?null:{...s}};if(!J(l,t))throw Error(`Database rows identity mismatch: requested table "${t.table}" at offset ${t.offset}.`);let u=Math.min(l.limit,Math.max(0,l.total-l.offset));if(l.rows.length!==u)throw Error(`Malformed database rows response: row count does not match pagination metadata.`);return l}function Q(e,t){let n=e.rows[t],r=e.truncatedCells[t],i=e.rowids[t];return!n||!r||i===void 0||t<0?null:{index:t,table:e.table,columns:[...e.columns],row:[...n],rowid:i,truncated:[...r]}}var oe=(e,t)=>e.length===t.length&&e.every((e,n)=>Object.is(e,t[n]));function se(e,t){let n=Q(t,e.index);return n!==null&&n.table===e.table&&n.rowid===e.rowid&&oe(n.columns,e.columns)&&oe(n.row,e.row)&&oe(n.truncated,e.truncated)}function ce({schema:e}){return(0,A.jsxs)(`div`,{className:`flex flex-col gap-6`,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`,{className:`px-4 py-3 font-medium`,children:`Column`}),(0,A.jsx)(`th`,{className:`px-4 py-3 font-medium`,children:`Type`}),(0,A.jsx)(`th`,{className:`px-4 py-3 font-medium`,children:`Constraints`}),(0,A.jsx)(`th`,{className:`px-4 py-3 font-medium`,children:`Default`})]})}),(0,A.jsx)(`tbody`,{children:e.columns.map(e=>(0,A.jsxs)(`tr`,{className:`border-b border-line last:border-0`,children:[(0,A.jsx)(`td`,{className:`px-4 py-2 font-mono text-xs text-fg`,children:e.name}),(0,A.jsx)(`td`,{className:`px-4 py-2 font-mono text-xs text-muted`,children:e.type}),(0,A.jsxs)(`td`,{className:`px-4 py-2 text-xs`,children:[e.primaryKey&&(0,A.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,A.jsx)(`span`,{className:`rounded-md bg-surface-2 px-1.5 py-0.5 text-[10px] font-semibold text-muted`,children:`NOT NULL`})]}),(0,A.jsx)(`td`,{className:`px-4 py-2 font-mono text-xs text-faint`,children:e.defaultValue??`—`})]},e.name))})]})}),(0,A.jsxs)(h,{children:[(0,A.jsx)(m,{title:`Indexes (${e.indexes.length})`}),e.indexes.length===0?(0,A.jsx)(`p`,{className:`text-xs text-faint`,children:`No indexes on this table.`}):(0,A.jsx)(`ul`,{className:`flex flex-col gap-1.5`,children:e.indexes.map(e=>(0,A.jsxs)(`li`,{className:`flex flex-wrap items-center gap-2 font-mono text-xs`,children:[(0,A.jsx)(`span`,{className:`text-fg`,children:e.name}),e.unique&&(0,A.jsx)(`span`,{className:`rounded-md bg-accent/15 px-1.5 py-0.5 text-[10px] font-semibold text-accent`,children:`UNIQUE`}),(0,A.jsxs)(`span`,{className:`text-faint`,children:[`(`,e.columns.join(`, `),`)`]})]},e.name))})]}),e.sql&&(0,A.jsxs)(h,{children:[(0,A.jsx)(m,{title:`DDL`,action:(0,A.jsx)(C,{value:e.sql})}),(0,A.jsx)(`pre`,{className:`overflow-x-auto rounded-lg bg-surface-2 p-3 font-mono text-xs text-muted`,children:e.sql})]})]})}function le({db:e}){let{anyTruncated:n,colMeta:r,cycleSort:i,data:a,dbMissing:o,detail:s,editorRef:c,exportBusy:l,exportPage:u,exportTable:d,filter:f,info:m,infoError:C,msg:w,page:E,pageSize:D,queryThisTable:O,refetchInfo:k,refetchRows:M,refetchSchema:N,refetchTables:P,requestModal:F,rowsLoading:I,schema:L,schemaError:R,selectTable:z,selected:B,setDetailSelection:V,setFilter:H,setPage:U,setSql:W,setTab:G,sort:te,sql:K,tab:q,tables:J,tablesError:Y,tablesLoading:X,visibleRowsError:Z}=e;return(0,A.jsxs)(`div`,{"data-database-background":``,inert:s?!0:void 0,"aria-hidden":s?!0:void 0,children:[(0,A.jsx)(b,{title:`Database`,description:`SQLite inspector — schema, data and queries over a read-only connection.`,actions:(0,A.jsx)(`span`,{className:`rounded-full bg-emerald-500/10 px-2.5 py-1 text-[11px] font-medium text-success`,children:`read-only`})}),Y&&!o&&(0,A.jsx)(g,{message:`Could not read the database — ${Y.message}`,onRetry:P}),C&&!o&&(0,A.jsx)(g,{message:`Could not read database metadata — ${C.message}`,onRetry:k}),m&&(0,A.jsxs)(`div`,{className:`mb-6 grid grid-cols-2 gap-4 md:grid-cols-3 xl:grid-cols-5`,children:[(0,A.jsx)(T,{label:`SQLite`,value:m.sqliteVersion,compact:!0}),(0,A.jsx)(T,{label:`On disk`,value:x(m.fileSize+m.walSize),compact:!0}),(0,A.jsx)(T,{label:`Journal`,value:m.journalMode.toUpperCase(),compact:!0}),(0,A.jsx)(T,{label:`Tables`,value:S(m.tables),compact:!0}),(0,A.jsx)(T,{label:`Indexes`,value:S(m.indexes),compact:!0})]}),o?(0,A.jsx)(y,{title:`No database yet`,hint:Y.message}):X&&J.length===0?(0,A.jsx)(v,{label:`Reading database…`}):(0,A.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-4`,children:[(0,A.jsxs)(h,{padded:!1,className:`self-start overflow-hidden`,children:[(0,A.jsxs)(`div`,{className:`border-b border-line px-4 py-3 text-[11px] font-medium uppercase tracking-wider text-faint`,children:[`Tables (`,J.length,`)`]}),(0,A.jsxs)(`ul`,{className:`max-h-[28rem] overflow-y-auto`,children:[J.map(e=>(0,A.jsx)(`li`,{children:(0,A.jsxs)(`button`,{type:`button`,onClick:()=>z(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`,B===e.name?`bg-surface-2 text-fg`:`text-muted hover:bg-surface-2/60 hover:text-fg`),children:[(0,A.jsx)(`span`,{className:`min-w-0 truncate font-mono text-xs`,children:e.name}),(0,A.jsx)(`span`,{className:`shrink-0 text-[11px] text-faint tabular-nums`,children:S(e.rows)})]})},e.name)),J.length===0&&(0,A.jsx)(`li`,{className:`px-4 py-6 text-center text-xs text-faint`,children:`No tables.`})]})]}),(0,A.jsx)(`div`,{className:`min-w-0 lg:col-span-3`,children:J.length===0?(0,A.jsx)(y,{title:`No tables`,hint:`This database has no user tables yet.`}):(0,A.jsxs)(A.Fragment,{children:[B&&(0,A.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center gap-2`,children:[(0,A.jsx)(`span`,{className:`mr-auto min-w-0 truncate font-mono text-sm text-fg`,title:B,children:B}),(0,A.jsx)(p,{size:`sm`,variant:`ghost`,onClick:O,children:`Query`}),(0,A.jsx)(`div`,{className:`inline-flex items-center gap-1 rounded-lg border border-line bg-surface p-1`,children:[`data`,`schema`].map(e=>(0,A.jsx)(`button`,{type:`button`,onClick:()=>G(e),"aria-pressed":q===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`,q===e?`bg-surface-2 text-fg`:`text-muted hover:text-fg`),children:e},e))}),q===`data`&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(p,{size:`sm`,disabled:!a||a.rows.length===0,title:a?`Exports the ${a.rows.length} rows on this page only`:void 0,onClick:u,children:[`Export page`,a?` (${a.rows.length})`:``]}),(0,A.jsx)(p,{size:`sm`,variant:`accent`,disabled:l||!a||a.total===0,onClick:d,children:l?`Exporting…`:`Export table${a?` (${S(a.total)})`:``}`})]})]}),q===`data`&&B&&(0,A.jsx)(j,{columns:a?.columns??L?.columns.map(e=>e.name)??[],filter:f,onChange:e=>{H(e),U(0),V(null)}},B),w&&(0,A.jsx)(`p`,{className:`mb-3 text-xs text-muted`,children:w}),q===`schema`?R?(0,A.jsx)(y,{title:`Could not read schema`,hint:R.message,action:(0,A.jsx)(p,{size:`sm`,onClick:N,children:`Retry`})}):L?.table===B?(0,A.jsx)(ce,{schema:L}):(0,A.jsx)(v,{label:`Reading schema of ${B}…`}):Z?(0,A.jsx)(_,{error:Z,onRetry:M}):I&&!a?(0,A.jsx)(v,{label:`Reading ${B}…`}):a?a.total===0?(0,A.jsx)(y,{title:f?`No matching rows`:`Empty table`,hint:f?`No rows match the current filter.`:`"${a.table}" has no rows.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(ne,{columns:a.columns,rows:a.rows,truncatedCells:a.truncatedCells,colMeta:r,sort:te,onSort:i,onRowClick:e=>{let t=Q(a,e);t&&F(`database-row`)&&V(t)},dimmed:I&&!a}),n&&(0,A.jsx)(`p`,{className:`mt-2 text-[11px] text-faint`,children:`Cells over 2000 chars and BLOBs are abbreviated in the grid and CSV — use the row's View action to read the full value.`}),(0,A.jsx)(ee,{page:E,pageSize:D,total:a.total,onPageChange:e=>{U(e),V(null)},label:`rows`})]}):(0,A.jsx)(y,{title:`Select a table`,hint:`Pick a table on the left to browse its rows.`}),(0,A.jsx)(re,{sql:K,setSql:W,editorRef:c})]})})]})]})}var ue=[`a[href]`,`button:not([disabled])`,`input:not([disabled])`,`select:not([disabled])`,`textarea:not([disabled])`,`[tabindex]:not([tabindex="-1"])`].join(`,`);function de({table:e,columns:t,row:n,rowid:r,truncated:i,onClose:a}){let[o,s]=(0,k.useState)({}),[l,u]=(0,k.useState)({}),f=(0,k.useRef)(null),p=(0,k.useRef)(null),m=(0,k.useRef)(a);m.current=a,(0,k.useEffect)(()=>{let e=document.activeElement,t=f.current,n=()=>t?Array.from(t.querySelectorAll(ue)).filter(e=>e.getAttribute(`aria-hidden`)!==`true`):[],r=(e=!1)=>{let r=n();(e?r.at(-1):r[0])?.focus(),r.length===0&&t?.focus()},i=e=>{if(e.key===`Escape`){e.preventDefault(),m.current();return}if(e.key!==`Tab`)return;let r=n();if(r.length===0){e.preventDefault(),t?.focus();return}let i=document.activeElement,a=r[0],o=r[r.length-1];e.shiftKey&&(i===a||!i||!t?.contains(i))?(e.preventDefault(),o.focus()):!e.shiftKey&&(i===o||!i||!t?.contains(i))&&(e.preventDefault(),a.focus())},a=e=>{t&&!t.contains(e.target)&&r()};return p.current?.focus(),document.activeElement!==p.current&&t?.focus(),document.addEventListener(`keydown`,i,!0),document.addEventListener(`focusin`,a),()=>{document.removeEventListener(`keydown`,i,!0),document.removeEventListener(`focusin`,a),E(`database-row`)&&e?.isConnected&&e.focus()}},[]);let h=JSON.stringify(t.filter((e,t)=>i[t]));return(0,k.useEffect)(()=>{s({}),u({});let t=JSON.parse(h);if(r==null||t.length===0)return;let n=!1;return Promise.all(t.map(async t=>{try{let i=await c.db.cell(e,r,t);if(!i||typeof i!=`object`||!Object.hasOwn(i,`value`))throw Error(`Malformed full-cell response.`);n||s(e=>({...e,[t]:i.value}))}catch(e){if(!n){let n=e instanceof Error?e.message:String(e);u(e=>({...e,[t]:n.slice(0,300)}))}}})),()=>{n=!0}},[e,r,h]),(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`button`,{type:`button`,"aria-label":`Close row detail`,onClick:a,className:`fixed inset-0 z-40 bg-black/50`}),(0,A.jsxs)(`aside`,{ref:f,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-2 focus-visible:outline-offset-[-2px] focus-visible:outline-accent`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between border-b border-line px-5 py-4`,children:[(0,A.jsxs)(`h2`,{className:`font-mono text-sm text-fg`,children:[e,` · row detail`]}),(0,A.jsx)(`button`,{ref:p,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,A.jsx)(d,{className:`size-4`})})]}),(0,A.jsx)(`div`,{className:`flex-1 overscroll-contain overflow-y-auto p-5`,children:(0,A.jsx)(`dl`,{className:`flex flex-col gap-4`,children:t.map((e,t)=>{let r=Object.hasOwn(o,e),a=r?o[e]:n[t],s=U(a),c=s.includes(`
3
- `)||s.length>80;return(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`dt`,{className:`mb-1 flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-faint`,children:[e,a!=null&&(0,A.jsx)(C,{value:String(a)}),i[t]&&!r&&(Object.hasOwn(l,e)?(0,A.jsxs)(`span`,{role:`alert`,className:`normal-case text-danger`,children:[`(full value unavailable — `,l[e],`)`]}):(0,A.jsx)(`span`,{className:`text-warning`,children:`(loading full value…)`}))]}),(0,A.jsx)(`dd`,{children:a==null?(0,A.jsx)(`span`,{className:`italic text-faint`,children:`NULL`}):c?(0,A.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:s}):(0,A.jsx)(`span`,{className:`break-words font-mono text-sm text-fg`,children:s})})]},e)})})})]})]})}function fe({data:e,filter:t,page:n,selected:r,sort:i}){let o=a(G),[u,d]=(0,k.useState)(!1),[f,p]=(0,k.useState)(null),m=(0,k.useRef)(!1),h=(0,k.useRef)(null);return(0,k.useEffect)(()=>(h.current?.abort(),h.current=null,m.current=!1,d(!1),p(null),()=>{h.current?.abort(),h.current=null,m.current=!1}),[o]),{exportBusy:u,exportPage:()=>{e&&R(`${e.table}-page${n+1}.csv`,`text/csv`,L(e.columns,e.rows))},exportTable:async()=>{if(!r||m.current)return;m.current=!0;let e=G(a.getState()),n={table:r,orderBy:i?.col,dir:i?.dir??`asc`,filter:t?{...t}:void 0},o=c.captureAgentRequestTarget(),u=new AbortController;h.current=u,d(!0),p(null);try{let t=await W(n,o,u.signal);if(u.signal.aborted||G(a.getState())!==e)return;R(`${n.table}.csv`,`text/csv;charset=utf-8`,t.content);let r=t.cap===`rows`?`Exported the first ${S(t.rowCount)} rows (row cap reached)`:t.cap===`bytes`?`Exported ${S(t.rowCount)} rows (${x(s)} byte cap reached)`:`Exported ${S(t.rowCount)} rows`;p(r),l.success(`Export of ${n.table} complete`,r)}catch(t){if(u.signal.aborted||G(a.getState())!==e)return;p(`Export failed: ${t.message}`),l.error(`Export of ${n.table} failed`,t.message)}finally{h.current===u&&(h.current=null,m.current=!1,u.signal.aborted||d(!1))}},msg:f}}var $=50;function pe(){let[e,t]=(0,k.useState)(``),[n,r]=(0,k.useState)(0),[i,a]=(0,k.useState)(null),[s,l]=(0,k.useState)(`data`),[u,d]=(0,k.useState)(null),[p,m]=(0,k.useState)(null),h=w(e=>e.active),g=w(e=>e.request),_=w(e=>e.release),[v,y]=(0,k.useState)(`SELECT name FROM sqlite_master WHERE type = 'table'`),b=(0,k.useRef)(null);(0,k.useEffect)(()=>{p===null?_(`database-row`):h!==`database-row`&&m(null)},[p,h,_]),(0,k.useEffect)(()=>()=>{w.getState().release(`database-row`)},[]);let{data:x,error:S,loading:C,refetch:T}=f(()=>c.db.tables(),[],{intervalMs:1e4}),E=(0,k.useMemo)(()=>x?.tables??[],[x]),D=S instanceof o&&S.status===404,{data:ee,error:O,refetch:A}=f(()=>D?Promise.resolve(null):c.db.info(),[D],{intervalMs:15e3}),j=e||E[0]?.name||``;(0,k.useEffect)(()=>{!e&&E[0]&&t(E[0].name)},[e,E]);let{data:M,error:N,refetch:P}=f(()=>j?c.db.schema(j):Promise.resolve(null),[j],{intervalMs:3e4}),F=(0,k.useMemo)(()=>{let e={};if(M?.table===j)for(let t of M.columns)e[t.name]={type:t.type,primaryKey:t.primaryKey};return e},[M,j]),I=u?JSON.stringify([u.column,u.op,u.value]):``,{data:L,error:R,loading:z,refetch:B}=f((0,k.useCallback)(async()=>{if(!j)return null;let e={table:j,limit:$,offset:n*$,orderBy:i?.col,dir:i?.dir??`asc`,filter:u??void 0};return ae(await c.db.rows(j,$,e.offset,i?.col,i?.dir,u??void 0),e)},[j,n,i,u]),[j,n,i,I],{intervalMs:6e3}),V={table:j,limit:$,offset:n*$,orderBy:i?.col,dir:i?.dir??`asc`,filter:u??void 0},H=!!L&&J(L,V),U=R??(L&&!H?Error(`Database rows identity no longer matches the selected table and page.`):null),W=!U&&H?L:null,G=p!==null&&W!==null&&se(p,W),te=G?p:null;(0,k.useEffect)(()=>{p&&!G&&m(null)},[p,G]),(0,k.useEffect)(()=>{W&&W.total>0&&W.rows.length===0&&n>0&&r(Math.max(0,Math.ceil(W.total/$)-1))},[W,n]);let ne=()=>{r(0),a(null),d(null),m(null)},K=e=>{t(e),l(`data`),ne()},re=e=>{r(0),m(null),a(t=>t?.col===e?t.dir===`asc`?{col:e,dir:`desc`}:null:{col:e,dir:`asc`})},q=()=>{let e=`SELECT * FROM "${j.replaceAll(`"`,`""`)}" LIMIT 100`;y(e),requestAnimationFrame(()=>{b.current?.focus(),b.current?.scrollIntoView({behavior:`smooth`,block:`center`})})},Y=!!W?.truncatedCells.some(e=>e.some(Boolean)),{exportBusy:X,exportPage:Z,exportTable:ie,msg:Q}=fe({data:W,filter:u,page:n,selected:j,sort:i});return{activeModal:h,anyTruncated:Y,colMeta:F,cycleSort:re,data:W,dbMissing:D,detail:te,editorRef:b,exportBusy:X,exportPage:Z,exportTable:ie,filter:u,info:ee,infoError:O,msg:Q,page:n,pageSize:$,queryThisTable:q,refetchInfo:A,refetchRows:B,refetchSchema:P,refetchTables:T,requestModal:g,rowsLoading:z,schema:M,schemaError:N,selectTable:K,selected:j,setDetailSelection:m,setFilter:d,setPage:r,setSql:y,setTab:l,sort:i,sql:v,tab:s,tables:E,tablesError:S,tablesLoading:C,visibleRowsError:U}}function me(){let e=pe(),{activeModal:t,detail:n,setDetailSelection:r}=e;return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(le,{db:e}),n&&t===`database-row`&&(0,O.createPortal)((0,A.jsx)(de,{table:n.table,columns:n.columns,row:n.row,rowid:n.rowid,truncated:n.truncated,onClose:()=>r(null)}),document.body)]})}export{me as Database};
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{g as t,h as n,t as r}from"./react-vendor-CFL9l8LK.js";import{o as i}from"./connectionStore-CVjQyIZv.js";import{a,i as o,t as s}from"./bq-DR2BTISO.js";import{t as c}from"./toastStore-XmMX7A5W.js";import{T as l,o as u}from"./icons-DH9SS1DA.js";import{r as d}from"./StatusBadge-DereLzOj.js";import{n as f}from"./usePolledData-CEyyLRYa.js";import{t as p}from"./Button-_aSJvRoW.js";import{n as m,t as h}from"./Card-egIDLwVk.js";import{i as g,n as _,r as v,t as y}from"./feedback-CtGN_kqB.js";import{t as b}from"./PageHeader-CQzNsw8r.js";import{n as x,s as S}from"./format-Cg7VCIZW.js";import{a as C,c as w,r as T,s as E}from"./index-Bat1DN5U.js";import{a as D}from"./form-DG3X6cLL.js";import{t as ee}from"./Pagination-CSkzhNW6.js";var O=e(n(),1),k=e(t(),1),A=r();function j({columns:e,filter:t,onChange:n}){let[r,i]=(0,k.useState)(t?.column??``),[a,o]=(0,k.useState)(t?.op??`contains`),[s,c]=(0,k.useState)(t?.value??``),u=r||e[0]||``,d=()=>n(s.trim()?{column:u,op:a,value:s.trim()}:null);return e.length===0?null:(0,A.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-center gap-2`,children:[(0,A.jsx)(`div`,{className:`w-40`,children:(0,A.jsx)(D,{value:u,"aria-label":`Filter column`,name:`database-filter-column`,autoComplete:`off`,onChange:e=>i(e.target.value),children:e.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})}),(0,A.jsx)(`div`,{className:`w-32`,children:(0,A.jsxs)(D,{value:a,"aria-label":`Filter operator`,name:`database-filter-operator`,autoComplete:`off`,onChange:e=>o(e.target.value),children:[(0,A.jsx)(`option`,{value:`contains`,children:`contains`}),(0,A.jsx)(`option`,{value:`eq`,children:`=`}),(0,A.jsx)(`option`,{value:`ne`,children:`≠`})]})}),(0,A.jsxs)(`div`,{className:`relative min-w-40 flex-1`,children:[(0,A.jsx)(l,{className:`pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-faint`}),(0,A.jsx)(`input`,{value:s,onChange:e=>c(e.target.value),onKeyDown:e=>e.key===`Enter`&&d(),"aria-label":`Filter value`,name:`database-filter-value`,autoComplete:`off`,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,A.jsx)(p,{size:`sm`,onClick:d,disabled:!s.trim(),children:`Filter`}),t&&(0,A.jsx)(p,{size:`sm`,variant:`ghost`,onClick:()=>{c(``),n(null)},children:`Clear`}),(0,A.jsx)(`span`,{className:`text-[11px] text-faint`,children:`filters the whole table, server-side`})]})}var M=`bq-dash-db-history`,N=10,P=2e4,F=100;function I(e){let t=e==null?``:String(e),n=typeof e==`string`&&/^[=+\-@\t\r]/.test(e)?`'${e}`:t;return/[",\r\n]/.test(n)?`"${n.replaceAll(`"`,`""`)}"`:n}function L(e,t){return[e.map(I).join(`,`),...t.map(e=>e.map(I).join(`,`))].join(`
2
+ `)}function R(e,t,n){let r=URL.createObjectURL(new Blob([n],{type:t})),i=document.createElement(`a`);i.href=r,i.download=e,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(r),0)}function z(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e.slice(0,F))if(!(typeof r!=`string`||r.length===0||r.length>P||n.has(r))&&(n.add(r),t.push(r),t.length===N))break;return t}function B(){try{return z(JSON.parse(localStorage.getItem(M)??`[]`))}catch{return[]}}function V(e){let t=z(e);try{localStorage.setItem(M,JSON.stringify(t))}catch{}return t}function H(e){return V([e,...B().filter(t=>t!==e)].slice(0,N))}function U(e){if(e==null)return`NULL`;let t=typeof e==`string`?e:String(e),n=t.trimStart();if(n.startsWith(`{`)||n.startsWith(`[`))try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}return t}async function W(e,t=s.captureAgentRequestTarget(),n){let r=Object.freeze({table:e.table,orderBy:e.orderBy,dir:e.dir,filter:e.filter?Object.freeze({...e.filter}):void 0});return s.getDbExportAtTarget(t,r,n)}var G=e=>JSON.stringify([e.activeProfileId,e.baseUrl,e.agentBaseUrl,e.token,e.agentToken]);function te({value:e,align:t}){if(e==null)return(0,A.jsx)(`span`,{className:`italic text-faint`,children:`NULL`});let n=typeof e==`string`?e:String(e);return(0,A.jsx)(`span`,{className:d(`block max-w-[24rem] truncate`,t===`right`&&`text-right tabular-nums`),title:n,children:n})}function ne({columns:e,rows:t,truncatedCells:n,colMeta:r,sort:i,onSort:a,onRowClick:o,dimmed:s}){let c=(0,k.useMemo)(()=>e.map((e,n)=>{let i=r?.[e]?.type?.toUpperCase()??``;if(/INT|REAL|NUM|DEC|DOUB|FLOA/.test(i))return!0;let a=!1;for(let e of t){let t=e[n];if(t!=null&&(a=!0,typeof t!=`number`))return!1}return a}),[e,t,r]);return(0,A.jsx)(`div`,{className:d(`max-h-[70vh] overflow-auto rounded-xl border border-line bg-surface transition-opacity`,s&&`pointer-events-none opacity-50`),children:(0,A.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,A.jsx)(`thead`,{children:(0,A.jsxs)(`tr`,{className:`text-left text-[11px] uppercase tracking-wider text-faint`,children:[o&&(0,A.jsx)(`th`,{className:`sticky top-0 z-10 whitespace-nowrap border-b border-line bg-surface px-4 py-3 font-medium`,children:(0,A.jsx)(`span`,{className:`sr-only`,children:`Row actions`})}),e.map((e,t)=>{let n=r?.[e];return(0,A.jsx)(`th`,{className:d(`sticky top-0 z-10 whitespace-nowrap border-b border-line bg-surface px-4 py-3 font-medium`,c[t]&&`text-right`),"aria-sort":i?.col===e?i.dir===`asc`?`ascending`:`descending`:a?`none`:void 0,children:a?(0,A.jsxs)(`button`,{type:`button`,onClick:()=>a(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,n?.primaryKey&&(0,A.jsx)(`span`,{className:`rounded bg-accent/15 px-1 py-0.5 text-[9px] font-semibold text-accent`,children:`PK`}),n?.type&&(0,A.jsx)(`span`,{className:`text-faint/70`,children:n.type.toLowerCase()}),(0,A.jsx)(`span`,{"aria-hidden":`true`,className:i?.col===e?`text-accent`:`text-faint/60`,children:i?.col===e?i.dir===`asc`?`▲`:`▼`:`↕`})]}):e},e)})]})}),(0,A.jsx)(`tbody`,{children:t.map((e,t)=>(0,A.jsxs)(`tr`,{className:`border-b border-line font-mono text-xs last:border-0 hover:bg-surface-2/40`,children:[o&&(0,A.jsx)(`td`,{className:`whitespace-nowrap px-4 py-2`,children:(0,A.jsx)(`button`,{type:`button`,"aria-label":`View row ${t+1} details`,onClick:()=>o(t),className:`rounded-md border border-line px-2 py-1 font-sans text-[11px] font-medium text-muted transition-colors hover:border-line-strong hover:text-fg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent`,children:`View`})}),e.map((e,r)=>(0,A.jsx)(`td`,{className:`whitespace-nowrap px-4 py-2 text-muted`,children:(0,A.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,A.jsx)(te,{value:e,align:c[r]?`right`:`left`}),n?.[t]?.[r]&&(0,A.jsx)(`span`,{title:`Value truncated — use the row's View action to read it in full`,className:`shrink-0 rounded bg-warning/15 px-1 text-[9px] font-semibold text-warning`,children:`…`})]})},r))]},t))})]})})}function K(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Malformed database query response.`);let t=e;if(t.ok!==!0||!Array.isArray(t.columns)||t.columns.some(e=>typeof e!=`string`)||!Array.isArray(t.rows)||t.rows.length>500||t.rows.some(e=>!Array.isArray(e)||e.length!==t.columns.length)||!Number.isSafeInteger(t.rowCount)||t.rowCount!==t.rows.length||typeof t.truncated!=`boolean`||typeof t.ms!=`number`||!Number.isFinite(t.ms)||t.ms<0)throw Error(`Malformed database query response.`);return{columns:[...t.columns],rows:t.rows.map(e=>[...e]),rowCount:t.rowCount,truncated:t.truncated,ms:t.ms}}function re({sql:e,setSql:t,editorRef:n}){let r=i(G),[a,o]=(0,k.useState)(null),[c,l]=(0,k.useState)(null),[u,d]=(0,k.useState)(B),[f,g]=(0,k.useState)(null),_=(0,k.useRef)(0),v=(0,k.useRef)(null),y=(0,k.useRef)(r);y.current!==r&&(y.current=r,_.current++,v.current=null),(0,k.useEffect)(()=>(_.current++,v.current=null,o(null),l(null),g(null),()=>{_.current++,v.current=null}),[r]);let b=a===r,x=c?.target===r?c.message:null,C=f?.target===r?f:null,w=async(t=e,n=!0)=>{let a=t.trim();if(!a||v.current?.target===r)return;let c=++_.current,u=r;v.current={generation:c,target:u},o(u),l(null);try{let e=K(await s.db.query(t));if(c!==_.current||G(i.getState())!==u)return;g({...e,target:u}),n&&d(H(a))}catch(e){if(c!==_.current||G(i.getState())!==u)return;g(null),l({target:u,message:e.message})}finally{v.current?.generation===c&&(v.current=null),c===_.current&&o(null)}};return(0,A.jsxs)(h,{className:`mt-6`,children:[(0,A.jsx)(m,{title:`Query`,action:(0,A.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,A.jsx)(p,{size:`sm`,disabled:b||!e.trim(),onClick:()=>{let t=e.trim();t&&w(`EXPLAIN QUERY PLAN ${t}`,!1)},children:`Explain`}),(0,A.jsx)(p,{size:`sm`,variant:`accent`,disabled:b||!e.trim(),onClick:()=>w(),children:b?`Running…`:`Run`})]})}),(0,A.jsx)(`textarea`,{name:`database-sql-query`,autoComplete:`off`,ref:n,value:e,onChange:e=>t(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&w()},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,A.jsx)(`p`,{className:`mt-1 text-[11px] text-faint`,children:`⌘/Ctrl+Enter runs. Connection is read-only.`}),u.length>0&&(0,A.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-1.5`,children:[(0,A.jsx)(`span`,{className:`text-[11px] uppercase tracking-wider text-faint`,children:`History`}),u.map(e=>(0,A.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,A.jsx)(`button`,{type:`button`,onClick:()=>{V([]),d([])},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,A.jsxs)(`div`,{"aria-live":`polite`,children:[x&&(0,A.jsx)(`p`,{role:`alert`,className:`mt-3 text-xs text-danger`,children:x}),C&&!x&&(0,A.jsxs)(`div`,{className:`mt-4`,children:[(0,A.jsxs)(`div`,{className:`mb-2 flex flex-wrap items-center gap-3`,children:[(0,A.jsxs)(`p`,{className:`text-xs text-faint`,children:[C.truncated?`≥ `:``,S(C.rowCount),` row`,C.rowCount===1?``:`s`,` · `,S(C.ms),` ms`,C.truncated&&(0,A.jsxs)(`span`,{className:`text-warning`,children:[` — showing first `,C.rows.length]})]}),C.rows.length>0&&(0,A.jsxs)(`div`,{className:`ml-auto flex gap-2`,children:[(0,A.jsx)(p,{size:`sm`,onClick:()=>R(`query-results.csv`,`text/csv`,L(C.columns,C.rows)),children:`CSV`}),(0,A.jsx)(p,{size:`sm`,onClick:()=>R(`query-results.json`,`application/json`,JSON.stringify(C.rows.map(e=>Object.fromEntries(C.columns.map((t,n)=>[t,e[n]]))),null,2)),children:`JSON`})]})]}),C.rows.length>0?(0,A.jsx)(ne,{columns:C.columns,rows:C.rows}):(0,A.jsx)(`p`,{className:`text-xs text-faint`,children:`Query returned no rows.`})]})]})]})}var q=(e,t)=>t?e?.column===t.column&&e.op===t.op&&e.value===t.value:e===null;function J(e,t){return e.table===t.table&&e.limit===t.limit&&e.offset===t.offset&&e.orderBy===(t.orderBy??null)&&e.dir===t.dir&&q(e.filter,t.filter)}var Y=-(1n<<63n),X=(1n<<63n)-1n;function Z(e){if(e===null)return!0;if(typeof e==`number`)return Number.isSafeInteger(e);if(typeof e!=`string`||!/^-?(?:0|[1-9]\d*)$/.test(e)||e.length>20)return!1;try{let t=BigInt(e);return t>=Y&&t<=X}catch{return!1}}var ie=e=>e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e);function ae(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Malformed database rows response.`);let n=e,r=n.columns,i=n.rows,a=n.rowids,o=n.truncatedCells,s=n.filter,c=s===null||typeof s==`object`&&!!s&&!Array.isArray(s)&&typeof s.column==`string`&&(s.op===`contains`||s.op===`eq`||s.op===`ne`)&&typeof s.value==`string`;if(n.ok!==!0||typeof n.table!=`string`||!Array.isArray(r)||r.length===0||r.length>2e3||r.some(e=>typeof e!=`string`||!e)||new Set(r).size!==r.length||!Array.isArray(i)||i.length>t.limit||i.some(e=>!Array.isArray(e)||e.length!==r.length||e.some(e=>!ie(e)))||!Array.isArray(a)||a.length!==i.length||a.some(e=>!Z(e))||!Array.isArray(o)||o.length!==i.length||o.some(e=>!Array.isArray(e)||e.length!==r.length||e.some(e=>typeof e!=`boolean`))||!Number.isSafeInteger(n.total)||n.total<0||!Number.isSafeInteger(n.limit)||!Number.isSafeInteger(n.offset)||n.offset<0||n.orderBy!==null&&typeof n.orderBy!=`string`||n.dir!==`asc`&&n.dir!==`desc`||!c)throw Error(`Malformed database rows response.`);let l={ok:!0,table:n.table,columns:[...r],rows:i.map(e=>[...e]),rowids:[...a],truncatedCells:o.map(e=>[...e]),total:n.total,limit:n.limit,offset:n.offset,orderBy:n.orderBy,dir:n.dir,filter:s===null?null:{...s}};if(!J(l,t))throw Error(`Database rows identity mismatch: requested table "${t.table}" at offset ${t.offset}.`);let u=Math.min(l.limit,Math.max(0,l.total-l.offset));if(l.rows.length!==u)throw Error(`Malformed database rows response: row count does not match pagination metadata.`);return l}function Q(e,t){let n=e.rows[t],r=e.truncatedCells[t],i=e.rowids[t];return!n||!r||i===void 0||t<0?null:{index:t,table:e.table,columns:[...e.columns],row:[...n],rowid:i,truncated:[...r]}}var oe=(e,t)=>e.length===t.length&&e.every((e,n)=>Object.is(e,t[n]));function se(e,t){let n=Q(t,e.index);return n!==null&&n.table===e.table&&n.rowid===e.rowid&&oe(n.columns,e.columns)&&oe(n.row,e.row)&&oe(n.truncated,e.truncated)}function ce({schema:e}){return(0,A.jsxs)(`div`,{className:`flex flex-col gap-6`,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`,{className:`px-4 py-3 font-medium`,children:`Column`}),(0,A.jsx)(`th`,{className:`px-4 py-3 font-medium`,children:`Type`}),(0,A.jsx)(`th`,{className:`px-4 py-3 font-medium`,children:`Constraints`}),(0,A.jsx)(`th`,{className:`px-4 py-3 font-medium`,children:`Default`})]})}),(0,A.jsx)(`tbody`,{children:e.columns.map(e=>(0,A.jsxs)(`tr`,{className:`border-b border-line last:border-0`,children:[(0,A.jsx)(`td`,{className:`px-4 py-2 font-mono text-xs text-fg`,children:e.name}),(0,A.jsx)(`td`,{className:`px-4 py-2 font-mono text-xs text-muted`,children:e.type}),(0,A.jsxs)(`td`,{className:`px-4 py-2 text-xs`,children:[e.primaryKey&&(0,A.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,A.jsx)(`span`,{className:`rounded-md bg-surface-2 px-1.5 py-0.5 text-[10px] font-semibold text-muted`,children:`NOT NULL`})]}),(0,A.jsx)(`td`,{className:`px-4 py-2 font-mono text-xs text-faint`,children:e.defaultValue??`—`})]},e.name))})]})}),(0,A.jsxs)(h,{children:[(0,A.jsx)(m,{title:`Indexes (${e.indexes.length})`}),e.indexes.length===0?(0,A.jsx)(`p`,{className:`text-xs text-faint`,children:`No indexes on this table.`}):(0,A.jsx)(`ul`,{className:`flex flex-col gap-1.5`,children:e.indexes.map(e=>(0,A.jsxs)(`li`,{className:`flex flex-wrap items-center gap-2 font-mono text-xs`,children:[(0,A.jsx)(`span`,{className:`text-fg`,children:e.name}),e.unique&&(0,A.jsx)(`span`,{className:`rounded-md bg-accent/15 px-1.5 py-0.5 text-[10px] font-semibold text-accent`,children:`UNIQUE`}),(0,A.jsxs)(`span`,{className:`text-faint`,children:[`(`,e.columns.join(`, `),`)`]})]},e.name))})]}),e.sql&&(0,A.jsxs)(h,{children:[(0,A.jsx)(m,{title:`DDL`,action:(0,A.jsx)(C,{value:e.sql})}),(0,A.jsx)(`pre`,{className:`overflow-x-auto rounded-lg bg-surface-2 p-3 font-mono text-xs text-muted`,children:e.sql})]})]})}function le({db:e}){let{anyTruncated:t,colMeta:n,cycleSort:r,data:i,dbMissing:a,detail:o,editorRef:s,exportBusy:c,exportPage:l,exportTable:u,filter:f,info:m,infoError:C,msg:w,page:E,pageSize:D,queryThisTable:O,refetchInfo:k,refetchRows:M,refetchSchema:N,refetchTables:P,requestModal:F,rowsLoading:I,schema:L,schemaError:R,selectTable:z,selected:B,setDetailSelection:V,setFilter:H,setPage:U,setSql:W,setTab:G,sort:te,sql:K,tab:q,tables:J,tablesError:Y,tablesLoading:X,visibleRowsError:Z}=e;return(0,A.jsxs)(`div`,{"data-database-background":``,inert:o?!0:void 0,"aria-hidden":o?!0:void 0,children:[(0,A.jsx)(b,{title:`Database`,description:`SQLite inspector — schema, data and queries over a read-only connection.`,actions:(0,A.jsx)(`span`,{className:`rounded-full bg-emerald-500/10 px-2.5 py-1 text-[11px] font-medium text-success`,children:`read-only`})}),Y&&!a&&(0,A.jsx)(g,{message:`Could not read the database — ${Y.message}`,onRetry:P}),C&&!a&&(0,A.jsx)(g,{message:`Could not read database metadata — ${C.message}`,onRetry:k}),m&&(0,A.jsxs)(`div`,{className:`mb-6 grid grid-cols-2 gap-4 md:grid-cols-3 xl:grid-cols-5`,children:[(0,A.jsx)(T,{label:`SQLite`,value:m.sqliteVersion,compact:!0}),(0,A.jsx)(T,{label:`On disk`,value:x(m.fileSize+m.walSize),compact:!0}),(0,A.jsx)(T,{label:`Journal`,value:m.journalMode.toUpperCase(),compact:!0}),(0,A.jsx)(T,{label:`Tables`,value:S(m.tables),compact:!0}),(0,A.jsx)(T,{label:`Indexes`,value:S(m.indexes),compact:!0})]}),a?(0,A.jsx)(y,{title:`No database yet`,hint:Y.message}):X&&J.length===0?(0,A.jsx)(v,{label:`Reading database…`}):(0,A.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-4`,children:[(0,A.jsxs)(h,{padded:!1,className:`self-start overflow-hidden`,children:[(0,A.jsxs)(`div`,{className:`border-b border-line px-4 py-3 text-[11px] font-medium uppercase tracking-wider text-faint`,children:[`Tables (`,J.length,`)`]}),(0,A.jsxs)(`ul`,{className:`max-h-[28rem] overflow-y-auto`,children:[J.map(e=>(0,A.jsx)(`li`,{children:(0,A.jsxs)(`button`,{type:`button`,onClick:()=>z(e.name),className:d(`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`,B===e.name?`bg-surface-2 text-fg`:`text-muted hover:bg-surface-2/60 hover:text-fg`),children:[(0,A.jsx)(`span`,{className:`min-w-0 truncate font-mono text-xs`,children:e.name}),(0,A.jsx)(`span`,{className:`shrink-0 text-[11px] text-faint tabular-nums`,children:S(e.rows)})]})},e.name)),J.length===0&&(0,A.jsx)(`li`,{className:`px-4 py-6 text-center text-xs text-faint`,children:`No tables.`})]})]}),(0,A.jsx)(`div`,{className:`min-w-0 lg:col-span-3`,children:J.length===0?(0,A.jsx)(y,{title:`No tables`,hint:`This database has no user tables yet.`}):(0,A.jsxs)(A.Fragment,{children:[B&&(0,A.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center gap-2`,children:[(0,A.jsx)(`span`,{className:`mr-auto min-w-0 truncate font-mono text-sm text-fg`,title:B,children:B}),(0,A.jsx)(p,{size:`sm`,variant:`ghost`,onClick:O,children:`Query`}),(0,A.jsx)(`div`,{className:`inline-flex items-center gap-1 rounded-lg border border-line bg-surface p-1`,children:[`data`,`schema`].map(e=>(0,A.jsx)(`button`,{type:`button`,onClick:()=>G(e),"aria-pressed":q===e,className:d(`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`,q===e?`bg-surface-2 text-fg`:`text-muted hover:text-fg`),children:e},e))}),q===`data`&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(p,{size:`sm`,disabled:!i||i.rows.length===0,title:i?`Exports the ${i.rows.length} rows on this page only`:void 0,onClick:l,children:[`Export page`,i?` (${i.rows.length})`:``]}),(0,A.jsx)(p,{size:`sm`,variant:`accent`,disabled:c||!i||i.total===0,onClick:u,children:c?`Exporting…`:`Export table${i?` (${S(i.total)})`:``}`})]})]}),q===`data`&&B&&(0,A.jsx)(j,{columns:i?.columns??L?.columns.map(e=>e.name)??[],filter:f,onChange:e=>{H(e),U(0),V(null)}},B),w&&(0,A.jsx)(`p`,{className:`mb-3 text-xs text-muted`,children:w}),q===`schema`?R?(0,A.jsx)(y,{title:`Could not read schema`,hint:R.message,action:(0,A.jsx)(p,{size:`sm`,onClick:N,children:`Retry`})}):L?.table===B?(0,A.jsx)(ce,{schema:L}):(0,A.jsx)(v,{label:`Reading schema of ${B}…`}):Z?(0,A.jsx)(_,{error:Z,onRetry:M}):I&&!i?(0,A.jsx)(v,{label:`Reading ${B}…`}):i?i.total===0?(0,A.jsx)(y,{title:f?`No matching rows`:`Empty table`,hint:f?`No rows match the current filter.`:`"${i.table}" has no rows.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(ne,{columns:i.columns,rows:i.rows,truncatedCells:i.truncatedCells,colMeta:n,sort:te,onSort:r,onRowClick:e=>{let t=Q(i,e);t&&F(`database-row`)&&V(t)},dimmed:I&&!i}),t&&(0,A.jsx)(`p`,{className:`mt-2 text-[11px] text-faint`,children:`Cells over 2000 chars and BLOBs are abbreviated in the grid and CSV — use the row's View action to read the full value.`}),(0,A.jsx)(ee,{page:E,pageSize:D,total:i.total,onPageChange:e=>{U(e),V(null)},label:`rows`})]}):(0,A.jsx)(y,{title:`Select a table`,hint:`Pick a table on the left to browse its rows.`}),(0,A.jsx)(re,{sql:K,setSql:W,editorRef:s})]})})]})]})}var ue=[`a[href]`,`button:not([disabled])`,`input:not([disabled])`,`select:not([disabled])`,`textarea:not([disabled])`,`[tabindex]:not([tabindex="-1"])`].join(`,`);function de({table:e,columns:t,row:n,rowid:r,truncated:i,onClose:a}){let[o,c]=(0,k.useState)({}),[l,d]=(0,k.useState)({}),f=(0,k.useRef)(null),p=(0,k.useRef)(null),m=(0,k.useRef)(a);m.current=a,(0,k.useEffect)(()=>{let e=document.activeElement,t=f.current,n=()=>t?Array.from(t.querySelectorAll(ue)).filter(e=>e.getAttribute(`aria-hidden`)!==`true`):[],r=(e=!1)=>{let r=n();(e?r.at(-1):r[0])?.focus(),r.length===0&&t?.focus()},i=e=>{if(e.key===`Escape`){e.preventDefault(),m.current();return}if(e.key!==`Tab`)return;let r=n();if(r.length===0){e.preventDefault(),t?.focus();return}let i=document.activeElement,a=r[0],o=r[r.length-1];e.shiftKey&&(i===a||!i||!t?.contains(i))?(e.preventDefault(),o.focus()):!e.shiftKey&&(i===o||!i||!t?.contains(i))&&(e.preventDefault(),a.focus())},a=e=>{t&&!t.contains(e.target)&&r()};return p.current?.focus(),document.activeElement!==p.current&&t?.focus(),document.addEventListener(`keydown`,i,!0),document.addEventListener(`focusin`,a),()=>{document.removeEventListener(`keydown`,i,!0),document.removeEventListener(`focusin`,a),E(`database-row`)&&e?.isConnected&&e.focus()}},[]);let h=JSON.stringify(t.filter((e,t)=>i[t]));return(0,k.useEffect)(()=>{c({}),d({});let t=JSON.parse(h);if(r==null||t.length===0)return;let n=!1;return Promise.all(t.map(async t=>{try{let i=await s.db.cell(e,r,t);if(!i||typeof i!=`object`||!Object.hasOwn(i,`value`))throw Error(`Malformed full-cell response.`);n||c(e=>({...e,[t]:i.value}))}catch(e){if(!n){let n=e instanceof Error?e.message:String(e);d(e=>({...e,[t]:n.slice(0,300)}))}}})),()=>{n=!0}},[e,r,h]),(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`button`,{type:`button`,"aria-label":`Close row detail`,onClick:a,className:`fixed inset-0 z-40 bg-black/50`}),(0,A.jsxs)(`aside`,{ref:f,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-2 focus-visible:outline-offset-[-2px] focus-visible:outline-accent`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between border-b border-line px-5 py-4`,children:[(0,A.jsxs)(`h2`,{className:`font-mono text-sm text-fg`,children:[e,` · row detail`]}),(0,A.jsx)(`button`,{ref:p,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,A.jsx)(u,{className:`size-4`})})]}),(0,A.jsx)(`div`,{className:`flex-1 overscroll-contain overflow-y-auto p-5`,children:(0,A.jsx)(`dl`,{className:`flex flex-col gap-4`,children:t.map((e,t)=>{let a=Object.hasOwn(o,e),s=a?o[e]:n[t],c=U(s),u=c.includes(`
3
+ `)||c.length>80;return(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`dt`,{className:`mb-1 flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-faint`,children:[e,s!=null&&(0,A.jsx)(C,{value:String(s)}),i[t]&&!a&&(r==null?(0,A.jsx)(`span`,{className:`normal-case text-warning`,children:`(truncated — full value unavailable: this table has no rowid to fetch it by)`}):Object.hasOwn(l,e)?(0,A.jsxs)(`span`,{role:`alert`,className:`normal-case text-danger`,children:[`(full value unavailable — `,l[e],`)`]}):(0,A.jsx)(`span`,{className:`text-warning`,children:`(loading full value…)`}))]}),(0,A.jsx)(`dd`,{children:s==null?(0,A.jsx)(`span`,{className:`italic text-faint`,children:`NULL`}):u?(0,A.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:c}):(0,A.jsx)(`span`,{className:`break-words font-mono text-sm text-fg`,children:c})})]},e)})})})]})]})}function fe({data:e,filter:t,page:n,selected:r,sort:a}){let l=i(G),[u,d]=(0,k.useState)(!1),[f,p]=(0,k.useState)(null),m=(0,k.useRef)(!1),h=(0,k.useRef)(null);return(0,k.useEffect)(()=>(h.current?.abort(),h.current=null,m.current=!1,d(!1),p(null),()=>{h.current?.abort(),h.current=null,m.current=!1}),[l]),{exportBusy:u,exportPage:()=>{e&&R(`${e.table}-page${n+1}.csv`,`text/csv`,L(e.columns,e.rows))},exportTable:async()=>{if(!r||m.current)return;m.current=!0;let e=G(i.getState()),n={table:r,orderBy:a?.col,dir:a?.dir??`asc`,filter:t?{...t}:void 0},l=s.captureAgentRequestTarget(),u=new AbortController;h.current=u,d(!0),p(null);try{let t=await W(n,l,u.signal);if(u.signal.aborted||G(i.getState())!==e)return;R(`${n.table}.csv`,`text/csv;charset=utf-8`,t.content);let r=t.cap===`rows`?`Exported the first ${S(t.rowCount)} rows (row cap reached)`:t.cap===`bytes`?`Exported ${S(t.rowCount)} rows (${x(o)} byte cap reached)`:`Exported ${S(t.rowCount)} rows`;p(r),c.success(`Export of ${n.table} complete`,r)}catch(t){if(u.signal.aborted||G(i.getState())!==e)return;p(`Export failed: ${t.message}`),c.error(`Export of ${n.table} failed`,t.message)}finally{h.current===u&&(h.current=null,m.current=!1,u.signal.aborted||d(!1))}},msg:f}}var $=50;function pe(){let[e,t]=(0,k.useState)(``),[n,r]=(0,k.useState)(0),[i,o]=(0,k.useState)(null),[c,l]=(0,k.useState)(`data`),[u,d]=(0,k.useState)(null),[p,m]=(0,k.useState)(null),h=w(e=>e.active),g=w(e=>e.request),_=w(e=>e.release),[v,y]=(0,k.useState)(`SELECT name FROM sqlite_master WHERE type = 'table'`),b=(0,k.useRef)(null);(0,k.useEffect)(()=>{p===null?_(`database-row`):h!==`database-row`&&m(null)},[p,h,_]),(0,k.useEffect)(()=>()=>{w.getState().release(`database-row`)},[]);let{data:x,error:S,loading:C,refetch:T}=f(()=>s.db.tables(),[],{intervalMs:1e4}),E=(0,k.useMemo)(()=>x?.tables??[],[x]),D=S instanceof a&&S.status===404,{data:ee,error:O,refetch:A}=f(()=>D?Promise.resolve(null):s.db.info(),[D],{intervalMs:15e3}),j=e||E[0]?.name||``;(0,k.useEffect)(()=>{!e&&E[0]&&t(E[0].name)},[e,E]);let{data:M,error:N,refetch:P}=f(()=>j?s.db.schema(j):Promise.resolve(null),[j],{intervalMs:3e4}),F=(0,k.useMemo)(()=>{let e={};if(M?.table===j)for(let t of M.columns)e[t.name]={type:t.type,primaryKey:t.primaryKey};return e},[M,j]),I=u?JSON.stringify([u.column,u.op,u.value]):``,{data:L,error:R,loading:z,refetch:B}=f((0,k.useCallback)(async()=>{if(!j)return null;let e={table:j,limit:$,offset:n*$,orderBy:i?.col,dir:i?.dir??`asc`,filter:u??void 0};return ae(await s.db.rows(j,$,e.offset,i?.col,i?.dir,u??void 0),e)},[j,n,i,u]),[j,n,i,I],{intervalMs:6e3}),V={table:j,limit:$,offset:n*$,orderBy:i?.col,dir:i?.dir??`asc`,filter:u??void 0},H=!!L&&J(L,V),U=R??(L&&!H?Error(`Database rows identity no longer matches the selected table and page.`):null),W=!U&&H?L:null,G=p!==null&&W!==null&&se(p,W),te=G?p:null;(0,k.useEffect)(()=>{p&&!G&&m(null)},[p,G]),(0,k.useEffect)(()=>{W&&W.total>0&&W.rows.length===0&&n>0&&r(Math.max(0,Math.ceil(W.total/$)-1))},[W,n]);let ne=()=>{r(0),o(null),d(null),m(null)},K=e=>{t(e),l(`data`),ne()},re=e=>{r(0),m(null),o(t=>t?.col===e?t.dir===`asc`?{col:e,dir:`desc`}:null:{col:e,dir:`asc`})},q=()=>{let e=`SELECT * FROM "${j.replaceAll(`"`,`""`)}" LIMIT 100`;y(e),requestAnimationFrame(()=>{b.current?.focus(),b.current?.scrollIntoView({behavior:`smooth`,block:`center`})})},Y=!!W?.truncatedCells.some(e=>e.some(Boolean)),{exportBusy:X,exportPage:Z,exportTable:ie,msg:Q}=fe({data:W,filter:u,page:n,selected:j,sort:i});return{activeModal:h,anyTruncated:Y,colMeta:F,cycleSort:re,data:W,dbMissing:D,detail:te,editorRef:b,exportBusy:X,exportPage:Z,exportTable:ie,filter:u,info:ee,infoError:O,msg:Q,page:n,pageSize:$,queryThisTable:q,refetchInfo:A,refetchRows:B,refetchSchema:P,refetchTables:T,requestModal:g,rowsLoading:z,schema:M,schemaError:N,selectTable:K,selected:j,setDetailSelection:m,setFilter:d,setPage:r,setSql:y,setTab:l,sort:i,sql:v,tab:c,tables:E,tablesError:S,tablesLoading:C,visibleRowsError:U}}function me(){let e=pe(),{activeModal:t,detail:n,setDetailSelection:r}=e;return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(le,{db:e}),n&&t===`database-row`&&(0,O.createPortal)((0,A.jsx)(de,{table:n.table,columns:n.columns,row:n.row,rowid:n.rowid,truncated:n.truncated,onClose:()=>r(null)}),document.body)]})}export{me as Database};
@@ -0,0 +1 @@
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{g as t,t as n}from"./react-vendor-CFL9l8LK.js";import{t as r}from"./bq-DR2BTISO.js";import{t as i}from"./toastStore-XmMX7A5W.js";import{n as a}from"./StatusBadge-DereLzOj.js";import{t as o}from"./api-D9aT0ND7.js";import{n as s}from"./usePolledData-CEyyLRYa.js";import{t as c}from"./Button-_aSJvRoW.js";import{n as l,t as u}from"./Card-egIDLwVk.js";import{i as d,r as f}from"./feedback-CtGN_kqB.js";import{t as p}from"./PageHeader-CQzNsw8r.js";import{n as m,s as h,u as g}from"./format-Cg7VCIZW.js";import{a as _,r as v}from"./index-Bat1DN5U.js";import{t as y}from"./useControlActionGuard-1i7aFA7E.js";var b=n();function x(e,t){return t?{label:`Unavailable`,tone:`red`,detail:t}:e===null?{label:`Unknown`,tone:`zinc`,detail:`No response yet`}:e.trim()===`OK`?{label:`Live`,tone:`green`,detail:`HTTP 200 · OK`}:{label:`Unexpected`,tone:`amber`,detail:`HTTP 200 · ${e.trim().slice(0,80)||`empty body`}`}}function S(e,t){return t?{label:`Unavailable`,tone:`red`,detail:t}:e?e.ok===!0&&e.ready===!0?{label:`Ready`,tone:`green`,detail:`Persistence accepts traffic`}:e.ok===!1&&e.ready===!1?{label:`Not ready`,tone:`red`,detail:e.storage.error??`Persistence is degraded`}:{label:`Unexpected`,tone:`amber`,detail:`Incoherent readiness payload`}:{label:`Unknown`,tone:`zinc`,detail:`No response yet`}}function C({path:e,state:t}){return(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-1 border-b border-line py-2.5 last:border-0`,children:[(0,b.jsx)(`code`,{className:`w-20 shrink-0 font-mono text-xs text-fg`,children:e}),(0,b.jsx)(a,{label:t.label,tone:t.tone}),(0,b.jsx)(`span`,{className:`min-w-0 flex-1 text-right text-xs text-faint`,children:t.detail})]})}function w({snapshot:e}){let t=e.metrics?.metrics;return(0,b.jsxs)(`div`,{className:`mt-6 grid grid-cols-1 gap-6 lg:grid-cols-2`,children:[(0,b.jsxs)(u,{children:[(0,b.jsx)(l,{title:`Orchestrator probes`}),(0,b.jsx)(`p`,{className:`mb-2 text-xs text-muted`,children:`Native Bunqueue liveness and persistence-readiness endpoints.`}),(0,b.jsxs)(`div`,{children:[(0,b.jsx)(C,{path:`/healthz`,state:x(e.healthz,e.healthzError)}),(0,b.jsx)(C,{path:`/live`,state:x(e.live,e.liveError)}),(0,b.jsx)(C,{path:`/ready`,state:S(e.ready,e.readyError)})]})]}),(0,b.jsxs)(u,{children:[(0,b.jsx)(l,{title:`JSON metrics`}),e.metricsError?(0,b.jsxs)(`p`,{className:`text-sm text-danger`,children:[`Unavailable — `,e.metricsError]}):t?(0,b.jsxs)(`div`,{className:`grid grid-cols-2 gap-4`,children:[(0,b.jsx)(O,{k:`Pushed`,v:h(t.totalPushed)}),(0,b.jsx)(O,{k:`Pulled`,v:h(t.totalPulled)}),(0,b.jsx)(O,{k:`Completed`,v:h(t.totalCompleted)}),(0,b.jsx)(O,{k:`Failed`,v:h(t.totalFailed)})]}):(0,b.jsx)(`p`,{className:`text-sm text-muted`,children:`No metrics response yet.`}),(0,b.jsx)(`p`,{className:`mt-3 font-mono text-xs text-faint`,children:`GET /metrics · application/json`})]})]})}function T({heap:e,busy:t,onLoad:n}){return(0,b.jsxs)(u,{className:`mt-6`,children:[(0,b.jsx)(l,{title:`Heap statistics`,action:(0,b.jsx)(c,{size:`sm`,disabled:t,onClick:n,children:t?`Loading…`:e?`Refresh`:`Load`})}),e?(0,b.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-2`,children:[(0,b.jsxs)(`div`,{className:`grid grid-cols-3 gap-4`,children:[(0,b.jsx)(O,{k:`Objects`,v:h(e.heap?.objectCount??0)}),(0,b.jsx)(O,{k:`Protected`,v:h(e.heap?.protectedCount??0)}),(0,b.jsx)(O,{k:`Global`,v:h(e.heap?.globalCount??0)})]}),(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`div`,{className:`mb-2 text-[11px] uppercase tracking-wider text-faint`,children:`Top object types`}),(0,b.jsx)(`div`,{className:`max-h-52 overflow-y-auto rounded-lg border border-line`,children:(0,b.jsx)(`table`,{className:`w-full text-xs`,children:(0,b.jsx)(`tbody`,{children:(e.topObjectTypes??[]).map(e=>(0,b.jsxs)(`tr`,{className:`border-b border-line last:border-0`,children:[(0,b.jsx)(`td`,{className:`px-3 py-1.5 font-mono text-muted`,children:e.type}),(0,b.jsx)(`td`,{className:`px-3 py-1.5 text-right tnum text-fg`,children:h(e.count)})]},e.type))})})})]})]}):(0,b.jsxs)(`p`,{className:`text-sm text-muted`,children:[`On-demand `,(0,b.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.`]})]})}function E(){let e=r.prometheusUrl();return(0,b.jsxs)(u,{className:`mt-6`,children:[(0,b.jsx)(l,{title:`Prometheus`}),(0,b.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,b.jsx)(`code`,{className:`font-mono text-xs`,children:`requireAuthForMetrics`}),`.`]}),(0,b.jsxs)(`div`,{className:`flex items-center gap-2 rounded-lg border border-line bg-surface-2 px-3 py-2`,children:[(0,b.jsx)(`code`,{className:`min-w-0 flex-1 truncate font-mono text-xs text-fg`,children:e}),(0,b.jsx)(_,{value:e})]})]})}function D({stats:e}){return e?(0,b.jsxs)(u,{className:`mt-6`,children:[(0,b.jsx)(l,{title:`Totals since restart`}),(0,b.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 md:grid-cols-4`,children:[(0,b.jsx)(O,{k:`Pushed`,v:h(e.totalPushed)}),(0,b.jsx)(O,{k:`Pulled`,v:h(e.totalPulled)}),(0,b.jsx)(O,{k:`Completed`,v:h(e.totalCompleted)}),(0,b.jsx)(O,{k:`Failed`,v:h(e.totalFailed)})]})]}):null}function O({k:e,v:t}){return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`div`,{className:`text-[11px] uppercase tracking-wider text-faint`,children:e}),(0,b.jsx)(`div`,{className:`mt-1 text-lg font-semibold tnum text-fg`,children:t})]})}var k=e(t(),1);function A(e){let t=y(`diagnostics`),[n,a]=(0,k.useState)(null),o=n?.scope===t.scopeKey?n.value:null,s=(0,k.useRef)(0),c=async()=>{let e=++s.current,n=t.begin(`ping:${e}`);if(!n)return;a({scope:t.scopeKey,value:`…`});let i=performance.now();try{await r.ping(),n.isCurrent()&&s.current===e&&a({scope:t.scopeKey,value:`${Math.round(performance.now()-i)} ms`})}catch{n.isCurrent()&&s.current===e&&a({scope:t.scopeKey,value:`unreachable`})}finally{n.finish()}},[l,u]=(0,k.useState)(null),d=l?.scope===t.scopeKey&&l.busy,f=l?.scope===t.scopeKey?l.message:null,p=async()=>{let n=t.begin(`gc`);if(n){u({busy:!0,message:null,scope:t.scopeKey});try{let a=await r.gc();if(!n.isCurrent())return;let o=a.before.rss-a.after.rss,s=o>0?`Freed ${o} MB (RSS ${a.before.rss}→${a.after.rss})`:`No memory reclaimed`;u({busy:!0,message:s,scope:t.scopeKey}),i.success(`Memory compacted`,s),e()}catch(e){if(!n.isCurrent())return;let r=e.message;i.error(`GC failed`,r),u({busy:!0,message:r,scope:t.scopeKey})}finally{n.finish()&&u(e=>e?.scope===t.scopeKey?{...e,busy:!1}:e)}}},[m,h]=(0,k.useState)(null);return{doGc:p,doPing:c,gcBusy:d,gcMsg:f,heap:m?.scope===t.scopeKey?m.value:null,heapBusy:m?.scope===t.scopeKey&&m.busy,loadHeap:async()=>{let e=t.begin(`heap`);if(e){h({busy:!0,scope:t.scopeKey,value:null});try{let n=await r.heapStats();e.isCurrent()&&h({busy:!0,scope:t.scopeKey,value:n})}catch(t){e.isCurrent()&&i.error(`Heap stats failed`,t.message)}finally{e.finish()&&h(e=>e?.scope===t.scopeKey?{...e,busy:!1}:e)}}},ping:o}}async function j(e){try{return{value:await e,error:null}}catch(e){return{value:null,error:e instanceof Error?e.message:String(e)}}}function M(){let{data:e,error:t,loading:n,refetch:i}=s(async()=>{let[e,t,n,i,a,s,c]=await Promise.all([j(r.health()),j(r.storage()),j(r.stats()),j(o.healthz()),j(o.live()),j(o.ready()),j(o.metrics())]);return{health:e.value,storage:t.value,stats:n.value,healthError:e.error,storageError:t.error,statsError:n.error,healthz:i.value,live:a.value,ready:s.value,metrics:c.value,healthzError:i.error,liveError:a.error,readyError:s.error,metricsError:c.error}},[]),{doGc:a,doPing:h,gcBusy:_,gcMsg:y,heap:x,heapBusy:S,loadHeap:C,ping:k}=A(i);if(n&&!e&&!t)return(0,b.jsx)(f,{label:`Loading diagnostics…`});let M=e??{health:null,storage:null,stats:null,healthError:null,storageError:null,statsError:null,healthz:null,live:null,ready:null,metrics:null,healthzError:null,liveError:null,readyError:null,metricsError:null},P=M.health,F=M.storage?.data,I=M.stats?.stats,L=P!=null,R=F!=null,z=L&&P.ok===!0,B=!!t||!!M.healthError||!!M.storageError||!!M.statsError||!!M.healthzError||!!M.liveError||!!M.readyError||!!M.metricsError;return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(p,{title:`Diagnostics`,description:`Server health, storage, memory and connections.`,live:!!e&&!B}),t&&(0,b.jsx)(d,{message:`Diagnostics refresh failed — ${t.message}`,onRetry:i}),M.healthError&&(0,b.jsx)(d,{message:`Health unavailable — ${M.healthError}`,onRetry:i}),M.storageError&&(0,b.jsx)(d,{message:`Storage diagnostics unavailable — ${M.storageError}`,onRetry:i}),M.statsError&&(0,b.jsx)(d,{message:`Server totals unavailable — ${M.statsError}`,onRetry:i}),(0,b.jsxs)(`div`,{className:`mb-6 grid grid-cols-2 gap-4 md:grid-cols-4`,children:[(0,b.jsx)(v,{label:`Status`,value:L?P.status??(P.ok?`healthy`:`degraded`):`Unavailable`,tone:z?`green`:`red`,compact:!0}),(0,b.jsx)(v,{label:`Version`,value:P?.version?`v${P.version}`:`—`,compact:!0}),(0,b.jsx)(v,{label:`Uptime`,value:g(P?.uptime),compact:!0}),(0,b.jsx)(v,{label:`Disk`,value:R?F.diskFull?`Full`:`Healthy`:`Unavailable`,tone:!R||F.diskFull?`red`:`green`,compact:!0})]}),(0,b.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-2`,children:[(0,b.jsxs)(u,{children:[(0,b.jsx)(l,{title:`Connectivity`,action:(0,b.jsxs)(c,{size:`sm`,onClick:h,children:[`Ping`,k?` · ${k}`:``]})}),(0,b.jsxs)(`dl`,{className:`divide-y divide-line text-sm`,children:[(0,b.jsx)(N,{k:`WebSocket clients`,v:P?.connections?.ws==null?`—`:String(P.connections.ws)}),(0,b.jsx)(N,{k:`SSE clients`,v:P?.connections?.sse==null?`—`:String(P.connections.sse)}),(0,b.jsx)(N,{k:`Storage error`,v:M.storageError?`unavailable — ${M.storageError}`:F?.error?String(F.error):R?`none`:`—`})]})]}),(0,b.jsxs)(u,{children:[(0,b.jsx)(l,{title:`Memory`,action:(0,b.jsx)(c,{size:`sm`,disabled:_,onClick:a,children:_?`Compacting…`:`Compact (GC)`})}),(0,b.jsxs)(`div`,{className:`grid grid-cols-3 gap-4`,children:[(0,b.jsx)(O,{k:`Heap used`,v:P?.memory?m(P.memory.heapUsed*1024*1024):`—`}),(0,b.jsx)(O,{k:`Heap total`,v:P?.memory?m(P.memory.heapTotal*1024*1024):`—`}),(0,b.jsx)(O,{k:`RSS`,v:P?.memory?m(P.memory.rss*1024*1024):`—`})]}),y&&(0,b.jsx)(`p`,{className:`mt-3 text-xs text-muted`,children:y})]})]}),(0,b.jsx)(w,{snapshot:M}),(0,b.jsx)(T,{heap:x,busy:S,onLoad:C}),(0,b.jsx)(E,{}),(0,b.jsx)(D,{stats:I})]})}function N({k:e,v:t}){return(0,b.jsxs)(`div`,{className:`flex items-center justify-between py-2.5`,children:[(0,b.jsx)(`dt`,{className:`text-muted`,children:e}),(0,b.jsx)(`dd`,{className:`font-medium text-fg`,children:t})]})}export{M as Diagnostics};
@@ -0,0 +1 @@
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{g as t,t as n}from"./react-vendor-CFL9l8LK.js";import{u as r}from"./icons-DH9SS1DA.js";import{t as i}from"./api-D9aT0ND7.js";import{n as a}from"./usePolledData-CEyyLRYa.js";import{t as o}from"./Button-_aSJvRoW.js";import{i as s,n as c,r as l,t as u}from"./feedback-CtGN_kqB.js";import{t as d}from"./PageHeader-CQzNsw8r.js";import{l as f,s as p}from"./format-Cg7VCIZW.js";import{r as m}from"./index-Bat1DN5U.js";import{a as h}from"./form-DG3X6cLL.js";import{t as g}from"./Pagination-CSkzhNW6.js";import{r as _,t as v}from"./flowMutationSafety-YKTHxqKv.js";import{i as y,r as b}from"./classicJobsData-Csj4iihY.js";import"./Jobs-IrlneOy6.js";var x=e(t(),1),S=n(),C=25;function w(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}async function T(){let e=await b();if(!Number.isFinite(e.timestamp)||e.queues.some(e=>!w(e.waiting)||!w(e.delayed)||!w(e.active)||!w(e.dlq)||typeof e.paused!=`boolean`))throw Error(`Queue discovery returned malformed queue summaries`);return e}function E(){let[e,t]=(0,x.useState)(``),[n,b]=(0,x.useState)(0),{data:w,error:E,loading:D,refetch:O}=a(T,[],{intervalMs:3e4});(0,x.useEffect)(()=>{if(e||!w?.queues?.length)return;let n=w.queues.find(e=>e.dlq>0)??w.queues[0];t(n.name)},[w,e]);let{data:k,error:A,loading:j,refetch:M}=a((0,x.useCallback)(async()=>{if(!e)return{entries:[],total:0};let t=await i.dlq(e,C,n*C);return{entries:t.entries??[],total:t.total??t.entries?.length??0}},[e,n]),[e,n]),N=k?.entries??[];return(0,S.jsxs)(`div`,{children:[A&&k&&(0,S.jsx)(s,{message:`DLQ refresh failed — showing the last successful page.`,onRetry:M}),E&&(0,S.jsx)(s,{onRetry:O,message:`Could not discover queues — ${E.message}. Retry before selecting a queue.`}),(0,S.jsx)(d,{title:`Dead Letter Queue`,description:`Jobs that exhausted their retries.`,live:!!e&&!!k&&!A&&!E,actions:(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(o,{size:`sm`,disabled:!0,title:v,children:`Retry all`}),(0,S.jsx)(o,{variant:`danger`,size:`sm`,disabled:!0,title:_,children:`Purge`})]})}),(0,S.jsxs)(`div`,{className:`mb-6 flex flex-wrap items-center gap-3`,children:[(0,S.jsx)(`div`,{className:`w-56`,children:(0,S.jsx)(h,{value:e,"aria-label":`Queue`,name:`classic-dlq-queue`,autoComplete:`off`,onChange:e=>{t(e.target.value),b(0)},children:(w?.queues??[]).map(e=>(0,S.jsxs)(`option`,{value:e.name,children:[e.name,` `,e.dlq?`(${e.dlq})`:``]},e.name))})}),(0,S.jsx)(`div`,{className:`w-40`,children:(0,S.jsx)(m,{label:`DLQ Entries`,value:e&&k?p(k.total):`—`,tone:e&&k?.total?`red`:`default`,compact:!0})})]}),A&&!k?(0,S.jsx)(c,{error:A,onRetry:M}):D&&!w&&!e&&!E?(0,S.jsx)(l,{label:`Discovering queues…`}):j&&!k&&!A?(0,S.jsx)(l,{label:`Loading DLQ…`}):E&&!e?(0,S.jsx)(u,{icon:(0,S.jsx)(r,{}),title:`Could not discover queues`,hint:`${E.message}. Retry the queue discovery request above.`}):e?N.length===0?(0,S.jsx)(u,{icon:(0,S.jsx)(r,{}),title:`Dead letter queue is empty`,hint:`Jobs land here after exhausting their retry attempts.`}):(0,S.jsx)(`div`,{className:`overflow-x-auto rounded-xl border border-line bg-surface`,children:(0,S.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,S.jsx)(`thead`,{children:(0,S.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,S.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Job ID`}),(0,S.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Name`}),(0,S.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Reason`}),(0,S.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Attempts`}),(0,S.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Failed`})]})}),(0,S.jsx)(`tbody`,{children:N.map((e,t)=>(0,S.jsxs)(`tr`,{className:`border-b border-line last:border-0 align-top hover:bg-surface-2/40`,children:[(0,S.jsx)(`td`,{className:`px-5 py-3 font-mono text-xs text-muted`,children:e.job.id}),(0,S.jsx)(`td`,{className:`px-5 py-3 text-fg`,children:e.job.name??y(e.job.data)??`default`}),(0,S.jsx)(`td`,{className:`max-w-md px-5 py-3 text-xs text-red-400/90`,children:String(e.reason||e.error||`—`)}),(0,S.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-muted`,children:e.attempts?.length??e.job.attempts??`—`}),(0,S.jsx)(`td`,{className:`px-5 py-3 text-right text-faint`,children:f(e.attempts?.at(-1)?.failedAt??e.enteredAt)})]},e.job.id||t))})]})}):(0,S.jsx)(u,{icon:(0,S.jsx)(r,{}),title:w?.queues.length===0?`No queues available`:`Select a queue`,hint:`A queue must be selected before its dead letter entries can be inspected.`}),k&&(0,S.jsx)(g,{page:n,pageSize:C,total:k.total,onPageChange:b,label:`entries`})]})}export{E as Dlq};
@@ -0,0 +1 @@
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{g as t,r as n,t as r}from"./react-vendor-CFL9l8LK.js";import{t as i}from"./bq-DR2BTISO.js";import{t as a}from"./toastStore-XmMX7A5W.js";import{C as o,T as s,a as c,d as l,f as u,u as d}from"./icons-DH9SS1DA.js";import{r as f}from"./StatusBadge-DereLzOj.js";import{n as p}from"./usePolledData-CEyyLRYa.js";import{n as m,t as h}from"./Button-_aSJvRoW.js";import{i as g,n as _,r as v,t as y}from"./feedback-CtGN_kqB.js";import{t as b}from"./PageHeader-CQzNsw8r.js";import{a as x,i as S,l as C,s as w}from"./format-Cg7VCIZW.js";import{a as T,r as E}from"./index-Bat1DN5U.js";import{a as D}from"./form-DG3X6cLL.js";import{t as O}from"./Pagination-CSkzhNW6.js";import{r as k,t as A}from"./flowMutationSafety-YKTHxqKv.js";import{t as j}from"./exportFile-C7xhE8Yh.js";import{t as M}from"./QueueControl-C01l6bBJ.js";var N=e(t(),1),P=r();function F({queue:e,data:t,reasons:n,topReason:r}){return(0,P.jsxs)(`div`,{className:`mb-6 grid grid-cols-2 gap-4 md:grid-cols-4`,children:[(0,P.jsx)(E,{label:`Entries`,value:e&&t?w(t.total):`—`,tone:!e||!t?`default`:t.total?`red`:`green`,hint:!e||!t?`waiting for queue data`:t.total?r?`top: ${r}`:void 0:`queue is clean`,compact:!0}),(0,P.jsx)(E,{label:`Failure types`,value:t?.stats?w(n.length):`—`,hint:`distinct reasons`,compact:!0}),(0,P.jsx)(E,{label:`Pending retry`,value:t?.stats?w(t.stats.pendingRetry??0):`—`,tone:t?.stats?.pendingRetry?`amber`:`default`,hint:`auto-retry queued`,compact:!0}),(0,P.jsx)(E,{label:`Oldest entry`,value:t?.stats?.oldestEntry?C(t.stats.oldestEntry):`—`,hint:`time in DLQ`,compact:!0})]})}function I({queue:e,queues:t,reason:n,reasons:r,byReason:i,search:a,pageScoped:o,onQueue:c,onReason:l,onSearch:u}){return(0,P.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-center gap-3`,children:[(0,P.jsx)(`div`,{className:`w-56`,children:(0,P.jsx)(D,{value:e,"aria-label":`Queue`,name:`dlq-control-queue`,autoComplete:`off`,onChange:e=>c(e.target.value),children:t.map(e=>(0,P.jsxs)(`option`,{value:e.name,children:[e.name,` `,e.dlq?`(${e.dlq})`:``]},e.name))})}),(0,P.jsx)(`div`,{className:`w-44`,children:(0,P.jsxs)(D,{value:n,"aria-label":`Filter by reason`,name:`dlq-control-reason`,autoComplete:`off`,onChange:e=>l(e.target.value),children:[(0,P.jsx)(`option`,{value:`all`,children:`All reasons`}),r.map(e=>(0,P.jsxs)(`option`,{value:e,children:[e,` (`,i[e],`)`]},e))]})}),(0,P.jsxs)(`div`,{className:`relative min-w-40 flex-1`,children:[(0,P.jsx)(s,{className:`pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-faint`}),(0,P.jsx)(`input`,{value:a,onChange:e=>u(e.target.value),placeholder:o?`Filter this page by job ID…`:`Filter by job ID…`,"aria-label":`Filter by job ID`,name:`dlq-control-job-filter`,autoComplete:`off`,className:`h-9 w-full rounded-lg border border-line bg-surface pl-9 pr-3 text-sm text-fg placeholder:text-faint focus:border-accent/60 focus:outline-none focus:ring-2 focus:ring-accent/30`})]})]})}function L({entry:e,isOpen:t,onToggle:r,attempts:i}){return(0,P.jsxs)(P.Fragment,{children:[(0,P.jsxs)(`tr`,{className:`border-b border-line align-top last:border-0 hover:bg-surface-2/40`,children:[(0,P.jsx)(`td`,{className:`py-3 pl-4`,children:(0,P.jsx)(m,{"aria-label":t?`Collapse details`:`Expand details`,"aria-expanded":t,onClick:r,children:(0,P.jsx)(c,{className:f(`size-3.5 transition-transform`,t&&`rotate-90`)})})}),(0,P.jsx)(`td`,{className:`px-3 py-3 font-mono text-xs text-muted`,children:e.job.name??`default`}),(0,P.jsx)(`td`,{className:`px-3 py-3`,children:(0,P.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,P.jsx)(n,{to:`/job?id=${encodeURIComponent(e.job.id)}`,className:`max-w-[14rem] truncate font-mono text-xs text-accent hover:underline`,title:e.job.id,children:e.job.id}),(0,P.jsx)(T,{value:e.job.id})]})}),(0,P.jsx)(`td`,{className:`px-3 py-3`,children:(0,P.jsx)(`span`,{className:`inline-block rounded-md bg-red-500/10 px-2 py-0.5 text-xs text-danger`,children:e.reason})}),(0,P.jsx)(`td`,{className:`px-3 py-3`,children:(0,P.jsx)(`span`,{className:`block max-w-md truncate text-xs text-danger/80`,title:e.error??``,children:e.error||`—`})}),(0,P.jsx)(`td`,{className:`px-3 py-3 text-right tnum text-muted`,children:e.job.attempts??i.length}),(0,P.jsx)(`td`,{className:`px-3 py-3 text-right text-faint`,title:S(e.enteredAt),children:C(e.enteredAt)}),(0,P.jsx)(`td`,{className:`px-4 py-3`,children:(0,P.jsxs)(`div`,{className:`flex items-center justify-end gap-1`,children:[(0,P.jsx)(n,{to:`/job?id=${encodeURIComponent(e.job.id)}`,"aria-label":`Inspect job ${e.job.id}`,className:`inline-flex size-8 items-center justify-center rounded-lg text-muted transition-colors hover:bg-surface-2 hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50`,children:(0,P.jsx)(u,{className:`size-3.5`})}),(0,P.jsx)(m,{"aria-label":`Retry job unavailable`,disabled:!0,title:A,children:(0,P.jsx)(o,{className:`size-3.5`})})]})})]}),t&&(0,P.jsxs)(`tr`,{className:`border-b border-line bg-surface-2/30 last:border-0`,children:[(0,P.jsx)(`td`,{}),(0,P.jsxs)(`td`,{colSpan:7,className:`px-3 pb-4 pt-1`,children:[e.error&&(0,P.jsxs)(`div`,{className:`mb-3`,children:[(0,P.jsx)(`div`,{className:`mb-1 text-[11px] font-medium uppercase tracking-wider text-faint`,children:`Error`}),(0,P.jsx)(`pre`,{className:`max-h-40 overflow-auto whitespace-pre-wrap rounded-lg bg-surface p-3 font-mono text-xs text-danger/90`,children:e.error})]}),(0,P.jsxs)(`div`,{className:`mb-1 flex items-center gap-2 text-[11px] font-medium uppercase tracking-wider text-faint`,children:[`Failure history`,typeof e.retryCount==`number`&&e.retryCount>0&&(0,P.jsxs)(`span`,{className:`rounded-full bg-surface px-2 py-0.5 text-[10px] normal-case text-muted`,children:[`retried `,e.retryCount,`×`]})]}),i.length===0?(0,P.jsx)(`p`,{className:`text-xs text-faint`,children:`No per-attempt history recorded.`}):(0,P.jsx)(`ol`,{className:`space-y-1.5`,children:i.map(e=>(0,P.jsxs)(`li`,{className:`flex flex-wrap items-baseline gap-x-3 gap-y-0.5 rounded-lg border border-line bg-surface px-3 py-2 text-xs`,children:[(0,P.jsxs)(`span`,{className:`font-medium text-fg`,children:[`Attempt `,e.attempt]}),(0,P.jsx)(`span`,{className:`text-faint`,title:S(e.failedAt),children:C(e.failedAt)}),e.duration!=null&&(0,P.jsx)(`span`,{className:`tnum text-muted`,children:x(e.duration)}),e.reason&&(0,P.jsx)(`span`,{className:`rounded bg-red-500/10 px-1.5 text-danger`,children:e.reason}),e.error&&(0,P.jsx)(`span`,{className:`w-full truncate text-danger/70`,children:e.error})]},`${e.attempt}-${e.failedAt}`))})]})]})]})}var R=25,z={},B=[],V=e=>`${e.job.id}-${e.enteredAt}`;function H(){let[e,t]=(0,N.useState)(``),[n,r]=(0,N.useState)(0),[s,c]=(0,N.useState)(`all`),[u,f]=(0,N.useState)(``),[m,x]=(0,N.useState)(new Set),{data:S,error:C,loading:w,refetch:T}=p(M,[],{intervalMs:3e4});(0,N.useEffect)(()=>{if(e&&S&&!S.queues.some(t=>t.name===e)){t(``),r(0),c(`all`),f(``);return}e||!S?.queues?.length||t((S.queues.find(e=>e.dlq>0)??S.queues[0]).name)},[S,e]);let{data:E,error:D,loading:H,refetch:U}=p((0,N.useCallback)(async()=>{if(!e)return{queue:e,page:n,entries:[],total:0,stats:null,statsError:null};let[t,r]=await Promise.all([i.dlq(e,R,n*R),i.dlqStats(e).then(e=>({stats:e.stats,error:null})).catch(e=>({stats:null,error:e.message||`Unknown error`}))]);return{queue:e,page:n,entries:t.entries??[],total:t.total??0,stats:r.stats,statsError:r.error}},[e,n]),[e,n]),W=E?.queue===e&&E.page===n?E:null;(0,N.useEffect)(()=>{if(!W)return;let e=Math.max(0,Math.ceil((W.total??0)/R)-1);n>e&&r(e)},[W,n]),(0,N.useEffect)(()=>{x(new Set)},[e,n]);let G=W?.stats?.byReason??z,K=(0,N.useMemo)(()=>Object.keys(G).filter(e=>G[e]>0),[G]),q=(0,N.useMemo)(()=>[...K].sort((e,t)=>(G[t]??0)-(G[e]??0))[0],[K,G]);(0,N.useEffect)(()=>{s!==`all`&&W&&!K.includes(s)&&c(`all`)},[W,s,K]);let J=W?.entries??B,Y=(0,N.useMemo)(()=>{let e=J;s!==`all`&&(e=e.filter(e=>e.reason===s));let t=u.trim().toLowerCase();return t&&(e=e.filter(e=>e.job.id.toLowerCase().includes(t))),[...e].sort((e,t)=>t.enteredAt-e.enteredAt)},[J,s,u]),X=s!==`all`||u.trim()!==``,Z=(W?.total??0)>R,Q=e=>x(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});return(0,P.jsxs)(`div`,{children:[(0,P.jsx)(b,{title:`DLQ Control`,description:`Inspect and triage one queue's dead-lettered jobs.`,live:!!e&&!!W&&!W.statsError&&!D&&!C,actions:(0,P.jsxs)(P.Fragment,{children:[(0,P.jsxs)(h,{size:`sm`,disabled:!e||!Y.length,onClick:()=>{if(Y.length===0){a.info(`Nothing to export`);return}j(`dlq-${e}`,Y.map(e=>({jobId:e.job.id,reason:e.reason,error:e.error??``,attempts:e.job.attempts??e.attempts?.length??``,enteredAt:new Date(e.enteredAt).toISOString()})),[`jobId`,`reason`,`error`,`attempts`,`enteredAt`])},children:[(0,P.jsx)(l,{className:`size-3.5`}),` Export`]}),(0,P.jsxs)(h,{size:`sm`,disabled:!0,title:A,children:[(0,P.jsx)(o,{className:`size-3.5`}),` Retry all`]}),(0,P.jsx)(h,{variant:`danger`,size:`sm`,disabled:!0,title:k,children:`Purge`})]})}),D&&W&&(0,P.jsx)(g,{message:`DLQ refresh failed — showing the last successful page.`,onRetry:U}),C&&(0,P.jsx)(g,{onRetry:T,message:`Could not discover queues — ${C.message}. Retry before selecting a queue.`}),W?.statsError&&(0,P.jsx)(g,{message:`DLQ statistics are unavailable — ${W.statsError}. The entry list may still be current.`,onRetry:U}),(0,P.jsx)(F,{queue:e,data:W,reasons:K,topReason:q}),(0,P.jsx)(I,{queue:e,queues:S?.queues??[],reason:s,reasons:K,byReason:G,search:u,pageScoped:Z,onQueue:e=>{t(e),r(0),c(`all`),f(``)},onReason:c,onSearch:f}),(0,P.jsx)(`p`,{className:`mb-4 text-xs text-warning`,children:A}),D&&!W?(0,P.jsx)(_,{error:D,onRetry:U}):w&&!S&&!e&&!C?(0,P.jsx)(v,{label:`Discovering queues…`}):H&&!W&&!D?(0,P.jsx)(v,{label:`Loading DLQ…`}):C&&!e?(0,P.jsx)(y,{icon:(0,P.jsx)(d,{}),title:`Could not discover queues`,hint:`${C.message}. Retry the queue discovery request above.`}):e?Y.length===0?(0,P.jsx)(y,{icon:(0,P.jsx)(d,{}),title:X?`No matches`:`Dead letter queue is empty`,hint:X?Z?`No entries on this page match your filter — filters are page-scoped. Try another page or clear them.`:`No entries match your filter. Clear it to see all entries.`:`Failed jobs that exhaust their retries land here.`}):(0,P.jsx)(`div`,{className:`overflow-x-auto rounded-xl border border-line bg-surface`,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:`w-8 py-3 pl-4`}),(0,P.jsx)(`th`,{className:`px-3 py-3 font-medium`,children:`Name`}),(0,P.jsx)(`th`,{className:`px-3 py-3 font-medium`,children:`Job ID`}),(0,P.jsx)(`th`,{className:`px-3 py-3 font-medium`,children:`Reason`}),(0,P.jsx)(`th`,{className:`px-3 py-3 font-medium`,children:`Error`}),(0,P.jsx)(`th`,{className:`px-3 py-3 text-right font-medium`,children:`Attempts`}),(0,P.jsx)(`th`,{className:`px-3 py-3 text-right font-medium`,children:`Entered`}),(0,P.jsx)(`th`,{className:`w-20 px-4 py-3`})]})}),(0,P.jsx)(`tbody`,{children:Y.map(e=>{let t=V(e);return(0,P.jsx)(L,{entry:e,isOpen:m.has(t),onToggle:()=>Q(t),attempts:e.attempts??[]},t)})})]})}):(0,P.jsx)(y,{icon:(0,P.jsx)(d,{}),title:S?.queues.length===0?`No queues available`:`Select a queue`,hint:`A queue must be selected before its dead letter entries can be inspected.`}),W&&(0,P.jsx)(O,{page:n,pageSize:R,total:W.total,onPageChange:r,label:`entries`})]})}export{H as DlqControl};
@@ -0,0 +1 @@
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{f as t,g as n,r,t as i}from"./react-vendor-CFL9l8LK.js";import{t as a}from"./bq-DR2BTISO.js";import{t as o}from"./toastStore-XmMX7A5W.js";import{C as s,d as c,u as l}from"./icons-DH9SS1DA.js";import{r as u}from"./StatusBadge-DereLzOj.js";import{n as d}from"./usePolledData-CEyyLRYa.js";import{n as f,t as p}from"./Button-_aSJvRoW.js";import{t as m}from"./Card-egIDLwVk.js";import{i as h,n as ee,r as g,t as _}from"./feedback-CtGN_kqB.js";import{t as v}from"./PageHeader-CQzNsw8r.js";import{l as y,s as b}from"./format-Cg7VCIZW.js";import{a as x}from"./form-DG3X6cLL.js";import{t as S}from"./Pagination-CSkzhNW6.js";import{r as C,t as w}from"./flowMutationSafety-YKTHxqKv.js";import{t as te}from"./exportFile-C7xhE8Yh.js";import{t as T}from"./QueueControl-C01l6bBJ.js";var E=e(n(),1),D=i();function O({total:e,discoveryError:t,healthy:n,statsError:r,queue:i,topReason:a,pendingRetry:o,reasonCount:s}){return(0,D.jsxs)(`div`,{className:`mb-6 grid grid-cols-2 gap-4 md:grid-cols-4`,children:[(0,D.jsxs)(m,{children:[(0,D.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,D.jsx)(`span`,{className:`text-[11px] font-medium uppercase tracking-wider text-faint`,children:`Total in DLQ`}),(0,D.jsx)(`span`,{className:u(`rounded-full px-2 py-0.5 text-[11px] font-medium`,t?`bg-amber-500/10 text-warning`:e==null?`bg-surface-2 text-muted`:n?`bg-emerald-500/10 text-success`:`bg-red-500/10 text-danger`),children:t?`Unavailable`:e==null?`Loading`:n?`Healthy`:`Attention`})]}),(0,D.jsx)(`div`,{className:u(`mt-2 text-3xl font-bold tnum`,e==null||t?`text-muted`:n?`text-success`:`text-danger`),children:e==null?`—`:b(e)})]}),(0,D.jsxs)(m,{children:[(0,D.jsx)(`div`,{className:`text-[11px] font-medium uppercase tracking-wider text-faint`,children:`Top Reason`}),(0,D.jsx)(`div`,{className:`mt-2 text-lg font-semibold text-fg`,children:t||r?`Unavailable`:i?a??`No failures`:`Select a queue`})]}),(0,D.jsxs)(m,{children:[(0,D.jsx)(`div`,{className:`text-[11px] font-medium uppercase tracking-wider text-faint`,children:`Pending Retry`}),(0,D.jsx)(`div`,{className:`mt-2 text-3xl font-bold tnum text-fg`,children:o==null?`—`:b(o)}),(0,D.jsx)(`div`,{className:`mt-1 text-xs text-faint`,children:i?`in this queue`:`awaiting retry`})]}),(0,D.jsxs)(m,{children:[(0,D.jsx)(`div`,{className:`text-[11px] font-medium uppercase tracking-wider text-faint`,children:`Failure Types`}),(0,D.jsx)(`div`,{className:`mt-2 text-3xl font-bold tnum text-fg`,children:s==null?`—`:b(s)}),(0,D.jsx)(`div`,{className:`mt-1 text-xs text-faint`,children:`distinct reasons`})]})]})}function k({queues:e,queue:t,onSelect:n}){return e.length===0?null:(0,D.jsxs)(m,{className:`mb-6`,children:[(0,D.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center justify-between gap-2`,children:[(0,D.jsx)(`span`,{className:`text-[11px] font-medium uppercase tracking-wider text-faint`,children:`DLQ by queue`}),(0,D.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,D.jsxs)(p,{size:`sm`,disabled:!0,title:w,children:[(0,D.jsx)(s,{className:`size-3.5`}),` Retry all (`,e.length,` queues)`]}),(0,D.jsxs)(p,{variant:`danger`,size:`sm`,disabled:!0,title:C,children:[`Purge all (`,e.length,` queues)`]})]})]}),(0,D.jsx)(`div`,{className:`grid grid-cols-2 gap-3 md:grid-cols-4 xl:grid-cols-5`,children:e.map(e=>(0,D.jsxs)(`button`,{type:`button`,onClick:()=>n(e.name),className:u(`rounded-lg border p-3 text-left transition-colors`,t===e.name?`border-accent/50 bg-surface-2`:`border-line hover:border-line-strong`),children:[(0,D.jsx)(`div`,{className:`truncate font-mono text-xs text-muted`,children:e.name}),(0,D.jsx)(`div`,{className:`mt-1 text-xl font-bold tnum text-danger`,children:e.dlq})]},e.name))})]})}function A({queue:e,queues:t,reason:n,reasons:r,sort:i,search:a,pageScoped:o,onQueue:l,onReason:u,onSort:d,onSearch:m,onExport:h}){return(0,D.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-center gap-3`,children:[(0,D.jsx)(`div`,{className:`w-48`,children:(0,D.jsxs)(x,{value:e,"aria-label":`Queue`,name:`dlq-queue`,autoComplete:`off`,onChange:e=>l(e.target.value),children:[(0,D.jsx)(`option`,{value:``,children:`Select a queue…`}),t.map(e=>(0,D.jsxs)(`option`,{value:e.name,children:[e.name,e.dlq?` (${e.dlq})`:``]},e.name))]})}),(0,D.jsx)(`div`,{className:`w-40`,children:(0,D.jsxs)(x,{value:n,onChange:e=>u(e.target.value),"aria-label":`Filter by reason`,name:`dlq-reason-filter`,autoComplete:`off`,children:[(0,D.jsx)(`option`,{value:`all`,children:`All Reasons`}),r.map(e=>(0,D.jsx)(`option`,{value:e,children:e},e))]})}),(0,D.jsx)(`div`,{className:`w-36`,children:(0,D.jsxs)(x,{value:i,onChange:e=>d(e.target.value),"aria-label":o?`Sort this page`:`Sort`,name:`dlq-sort`,autoComplete:`off`,children:[(0,D.jsxs)(`option`,{value:`newest`,children:[`Newest First`,o?` (this page)`:``]}),(0,D.jsxs)(`option`,{value:`oldest`,children:[`Oldest First`,o?` (this page)`:``]})]})}),(0,D.jsx)(`input`,{value:a,onChange:e=>m(e.target.value),placeholder:`Filter this page by job ID…`,"aria-label":`Filter this page by job ID`,name:`dlq-job-filter`,autoComplete:`off`,className:`h-9 min-w-40 flex-1 rounded-lg border border-line bg-surface px-3 text-sm text-fg placeholder:text-faint focus:border-accent/60 focus:outline-none focus:ring-2 focus:ring-accent/30`}),(0,D.jsxs)(p,{size:`sm`,disabled:!0,title:w,children:[(0,D.jsx)(s,{className:`size-3.5`}),` Retry All`]}),(0,D.jsx)(p,{variant:`danger`,size:`sm`,disabled:!0,title:C,children:`Purge All`}),(0,D.jsx)(f,{"aria-label":`Export this page to CSV`,title:`Export this page to CSV`,disabled:!e,onClick:h,children:(0,D.jsx)(c,{className:`size-3.5`})})]})}function j({entries:e,expanded:t,onToggle:n}){return(0,D.jsx)(`div`,{className:`overflow-x-auto rounded-xl border border-line bg-surface`,children:(0,D.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,D.jsx)(`thead`,{children:(0,D.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,D.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Job ID`}),(0,D.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Name`}),(0,D.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Reason`}),(0,D.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Error`}),(0,D.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Entered`}),(0,D.jsx)(`th`,{className:`w-16 px-5 py-3`})]})}),(0,D.jsx)(`tbody`,{children:e.map(e=>{let i=`${e.job.id}-${e.enteredAt}`;return(0,D.jsxs)(`tr`,{className:`border-b border-line last:border-0 align-top hover:bg-surface-2/40`,children:[(0,D.jsx)(`td`,{className:`px-5 py-3`,children:(0,D.jsx)(r,{to:`/job?id=${encodeURIComponent(e.job.id)}`,className:`font-mono text-xs text-accent hover:underline`,children:e.job.id})}),(0,D.jsx)(`td`,{className:`px-5 py-3 font-mono text-xs text-muted`,children:e.job.name??`default`}),(0,D.jsx)(`td`,{className:`px-5 py-3`,children:(0,D.jsx)(`span`,{className:`rounded-md bg-red-500/10 px-2 py-0.5 text-xs text-danger`,children:e.reason})}),(0,D.jsx)(`td`,{className:`max-w-md px-5 py-3 text-xs text-danger/80`,children:e.error?(0,D.jsx)(`button`,{type:`button`,title:e.error,"aria-expanded":t.has(i),onClick:()=>n(i),className:u(`block w-full break-words text-left`,!t.has(i)&&`line-clamp-2`),children:e.error}):`—`}),(0,D.jsx)(`td`,{className:`px-5 py-3 text-right text-faint`,children:y(e.enteredAt)}),(0,D.jsx)(`td`,{className:`px-5 py-3 text-right`,children:(0,D.jsx)(f,{"aria-label":`Retry unavailable`,disabled:!0,title:w,children:(0,D.jsx)(s,{className:`size-3.5`})})})]},i)})})]})})}var M=25,ne=[];function N(){let[e,n]=t(),[r,i]=(0,E.useState)(``),[s,c]=(0,E.useState)(`all`),[u,f]=(0,E.useState)(`newest`),[p,m]=(0,E.useState)(``),[y,b]=(0,E.useState)(0),[x,C]=(0,E.useState)(new Set),{data:N,error:P,loading:F,refetch:I}=d(T,[],{intervalMs:1e4}),L=N?.queues??ne,R=N?L.reduce((e,t)=>e+t.dlq,0):null,{data:z,error:B,loading:V,refetch:H}=d((0,E.useCallback)(async()=>{if(!r)return{queue:r,page:y,entries:[],entriesTotal:0,stats:null,statsError:null};let[e,t]=await Promise.all([a.dlq(r,M,y*M),a.dlqStats(r).then(e=>({stats:e.stats,error:null})).catch(e=>({stats:null,error:e.message||`Unknown error`}))]);return{queue:r,page:y,entries:e.entries??[],entriesTotal:e.total??0,stats:t.stats,statsError:t.error}},[r,y]),[r,y]),U=z?.queue===r&&z.page===y?z:null;(0,E.useEffect)(()=>{if(!U)return;let e=U.entriesTotal??0;y>0&&y*M>=e&&b(Math.max(0,Math.ceil(e/M)-1))},[U,y]);let W=()=>{let e=(U?.entries??[]).map(e=>({jobId:e.job.id,reason:e.reason,error:e.error??``,enteredAt:new Date(e.enteredAt).toISOString(),attempts:e.attempts?.length??0}));if(e.length===0){o.info(`Nothing to export on this page`);return}te(`dlq-${r}`,e,[`jobId`,`reason`,`error`,`enteredAt`,`attempts`])},G=e=>{X.current=!0,i(e),b(0),c(`all`),n(e?{queue:e}:{},{replace:!0})};(0,E.useEffect)(()=>{s===`all`||!U||(U.stats?.byReason?.[s]??0)>0||c(`all`)},[U,s]);let K=U?.stats?.byReason??{},q=Object.keys(K).filter(e=>K[e]>0),J=[...q].sort((e,t)=>(K[t]??0)-(K[e]??0))[0],Y=(0,E.useMemo)(()=>L.filter(e=>e.dlq>0).sort((e,t)=>t.dlq-e.dlq),[L]),X=(0,E.useRef)(!1),Z=e.get(`queue`);(0,E.useEffect)(()=>{if(!(X.current||r)){if(Z){if(L.some(e=>e.name===Z)){X.current=!0,i(Z),b(0),c(`all`);return}if(L.length===0)return}Y.length!==0&&(X.current=!0,i(Y[0].name),b(0),c(`all`))}},[r,L,Y,Z]);let Q=(0,E.useMemo)(()=>{let e=U?.entries??[];s!==`all`&&(e=e.filter(e=>e.reason===s));let t=p.trim().toLowerCase();return t&&(e=e.filter(e=>e.job.id.toLowerCase().includes(t))),[...e].sort((e,t)=>u===`newest`?t.enteredAt-e.enteredAt:e.enteredAt-t.enteredAt)},[U,s,p,u]),re=R===0&&!P,$=s!==`all`||p.trim()!==``,ie=(U?.entriesTotal??0)>M;return(0,D.jsxs)(`div`,{children:[(0,D.jsx)(v,{title:`Dead Letter Queue`,description:`Jobs that failed after exhausting all retries. Inspect and export entries without mutating flow topology.`,live:!!r&&!!U&&!U.statsError&&!B&&!P}),B&&U&&(0,D.jsx)(h,{message:`DLQ refresh failed — showing the last successful page.`,onRetry:H}),P&&(0,D.jsx)(h,{onRetry:I,message:`Could not discover queue DLQ totals — ${P.message}. Health status is unavailable.`}),U?.statsError&&(0,D.jsx)(h,{message:`DLQ statistics are unavailable — ${U.statsError}. The entry list may still be current.`,onRetry:H}),(0,D.jsx)(O,{total:R,discoveryError:!!P,healthy:re,statsError:!!U?.statsError,queue:r,topReason:J,pendingRetry:U?.stats?.pendingRetry,reasonCount:U?.stats?q.length:void 0}),(0,D.jsx)(k,{queues:Y,queue:r,onSelect:G}),(0,D.jsx)(A,{queue:r,queues:L,reason:s,reasons:q,sort:u,search:p,pageScoped:ie,onQueue:G,onReason:c,onSort:f,onSearch:m,onExport:W}),(0,D.jsx)(`p`,{className:`mb-4 text-xs text-warning`,children:w}),B&&!U?(0,D.jsx)(ee,{error:B,onRetry:H}):F&&!N&&!r&&!P?(0,D.jsx)(g,{label:`Discovering queues…`}):V&&!U&&!B?(0,D.jsx)(g,{label:`Loading DLQ…`}):P&&!r?(0,D.jsx)(_,{icon:(0,D.jsx)(l,{}),title:`Could not discover queues`,hint:`${P.message}. Retry the queue discovery request above.`}):r?Q.length===0?(0,D.jsx)(_,{icon:(0,D.jsx)(l,{}),title:$?`No matches on this page`:`No dead letter entries`,hint:$?`No entries on this page match your filter — the filter is page-scoped. Use the pager below to check other pages.`:`This queue has no dead letter entries.`}):(0,D.jsx)(j,{entries:Q,expanded:x,onToggle:e=>C(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}):(0,D.jsx)(_,{icon:(0,D.jsx)(l,{}),title:`Select a queue`,hint:`Choose a queue from the dropdown to view its dead letter queue entries.`}),r&&U&&(0,D.jsx)(S,{page:y,pageSize:M,total:U.entriesTotal,onPageChange:b,label:`entries`})]})}export{N as DlqPro};
@@ -0,0 +1 @@
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{g as t,t as n}from"./react-vendor-CFL9l8LK.js";import{o as r,t as i}from"./connectionStore-CVjQyIZv.js";import{n as a}from"./usePolledData-CEyyLRYa.js";import{t as o}from"./Button-_aSJvRoW.js";import{n as s,t as c}from"./Card-egIDLwVk.js";import{t as l}from"./PageHeader-CQzNsw8r.js";import{n as u}from"./controlConnectionEpoch-ChAeMMLk.js";var d=e(t(),1),f=7500;function p(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Malformed ${t} response`);return e}async function m(e){try{let t=p(await e.json(),`error`);if(typeof t.error==`string`&&t.error)return Error(t.error)}catch{}return Error(`HTTP ${e.status}`)}async function h(e,t,n,r,i,a=[]){let o=AbortSignal.timeout(f),s=r?AbortSignal.any([r,o]):o,c=new Headers(i?.headers);n&&c.set(`Authorization`,`Bearer ${n}`);let l=await fetch(`${e}${t}`,{...i,headers:c,signal:s});if(!l.ok&&!a.includes(l.status))throw await m(l);return{response:l,body:p(await l.json(),t)}}async function g(e,t){try{let{response:n,body:r}=await h(e.baseUrl,`/health`,e.token,t,void 0,[503]);if(typeof r.ok!=`boolean`)throw Error(`Malformed Bunqueue health response`);return{reachable:!0,healthy:r.ok,statusCode:n.status,version:typeof r.version==`string`?r.version:void 0}}catch(e){return{reachable:!1,healthy:!1,error:e.message}}}function _(e){return[`running`,`stopped`,`starting`,`stopping`].includes(String(e.status))&&e.config!==null&&typeof e.config==`object`&&!Array.isArray(e.config)}async function v(e,t){try{let{response:n,body:r}=await h(e.agentBaseUrl,`/control/status`,e.agentToken,t);if(!_(r))throw Error(`Malformed control agent response`);return{reachable:!0,healthy:r.healthy===!0,statusCode:n.status,version:typeof r.version==`string`?r.version:void 0,status:r}}catch(e){return{reachable:!1,healthy:!1,error:e.message}}}async function y(e,t){let n=i(e);if(!n)throw Error(`Unknown Bunqueue connection profile: ${e}`);let[r,a]=await Promise.all([g(n,t),v(n,t)]);return{target:n,server:r,agent:a}}function b(e,t){return Promise.all(e.map(e=>y(e,t)))}async function x(e,t,n){let r=i(e);if(!r)throw Error(`Unknown Bunqueue connection profile: ${e}`);let{body:a}=await h(r.agentBaseUrl,`/control/${t}`,r.agentToken,n,{method:`POST`});if(!_(a))throw Error(`Malformed control agent response`);return a}function S(e){let t=e.agent.status;return t?.storageMode!==`postgres`||!t.postgresTarget?null:`${t.postgresTarget}\u0000${t.postgresNamespace??`default`}`}var C=n();function w({ok:e,reachable:t}){return(0,C.jsx)(`span`,{className:`inline-block size-2 rounded-full ${t?e?`bg-emerald-400`:`bg-amber-400`:`bg-red-400`}`})}function T({snapshot:e,active:t,busy:n,actionError:r,onActivate:i,onAction:a}){let{target:l,server:u,agent:d}=e,f=d.status,p=f?.managementMode===`external`,m=p?f?.reachable===!0:f?.status===`running`,h=n!==void 0||f?.status===`starting`||f?.status===`stopping`,g=f?.storageMode===`postgres`?`PostgreSQL · ${f.postgresNamespace??`default`}`:f?.storageMode??`unknown`;return(0,C.jsxs)(c,{className:t?`border-accent/60`:void 0,children:[(0,C.jsx)(s,{title:l.name,action:t?(0,C.jsx)(`span`,{className:`rounded-full bg-accent/15 px-2 py-1 text-[10px] font-semibold uppercase text-accent`,children:`active`}):(0,C.jsx)(o,{size:`sm`,onClick:i,children:`Use node`})}),(0,C.jsxs)(`dl`,{className:`grid grid-cols-[auto_1fr] gap-x-3 gap-y-2 text-xs`,children:[(0,C.jsx)(`dt`,{className:`text-faint`,children:`Server`}),(0,C.jsxs)(`dd`,{className:`flex min-w-0 items-center gap-2 text-muted`,children:[(0,C.jsx)(w,{ok:u.healthy,reachable:u.reachable}),(0,C.jsx)(`span`,{className:`truncate`,title:l.baseUrl,children:u.reachable?`${u.healthy?`healthy`:`degraded`}${u.version?` · v${u.version}`:``}`:`offline · ${u.error??`unreachable`}`})]}),(0,C.jsx)(`dt`,{className:`text-faint`,children:`Agent`}),(0,C.jsxs)(`dd`,{className:`flex min-w-0 items-center gap-2 text-muted`,children:[(0,C.jsx)(w,{ok:d.healthy,reachable:d.reachable}),(0,C.jsx)(`span`,{className:`truncate`,title:l.agentBaseUrl,children:d.reachable?`${f?.status??`connected`}${p?` · external`:``}`:`offline · ${d.error??`unreachable`}`})]}),(0,C.jsx)(`dt`,{className:`text-faint`,children:`Storage`}),(0,C.jsx)(`dd`,{className:`truncate font-mono text-muted`,title:f?.postgresTarget,children:g}),f?.storageMode===`postgres`&&(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(`dt`,{className:`text-faint`,children:`Cluster`}),(0,C.jsx)(`dd`,{className:`truncate font-mono text-muted`,children:f.postgresTarget??`configured PostgreSQL`})]})]}),r&&(0,C.jsx)(`p`,{role:`status`,className:`mt-3 text-xs text-danger`,children:r}),!p&&(0,C.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-2 border-t border-line pt-4`,children:[(0,C.jsx)(o,{size:`sm`,variant:`success`,disabled:!d.reachable||m||h,onClick:()=>a(`start`),children:`Start`}),(0,C.jsx)(o,{size:`sm`,variant:`warning`,disabled:!d.reachable||!m||h,onClick:()=>a(`stop`),children:`Stop`}),(0,C.jsx)(o,{size:`sm`,disabled:!d.reachable||h,onClick:()=>a(`restart`),children:n===`restart`?`Restarting…`:`Restart`})]})]})}function E(e){let t=new Map;for(let n of e){let e=S(n);e&&t.set(e,[...t.get(e)??[],n])}return[...t.entries()].map(([e,t])=>{let n=t[0]?.agent.status;return{key:e,target:n?.postgresTarget??`configured PostgreSQL`,namespace:n?.postgresNamespace??`default`,members:t}})}function D(){let e=r(e=>e.profiles),t=r(e=>e.activeProfileId),n=r(e=>e.activateProfile),i=u(),f=e.map(e=>e.id),p=`${i}:${JSON.stringify(e)}`,{data:m,error:h,loading:g,refetch:_}=a(e=>b(f,e),[p],{intervalMs:1e4}),[v,y]=(0,d.useState)({}),[S,w]=(0,d.useState)({}),D=(0,d.useRef)(0),O=(0,d.useMemo)(()=>E(m??[]),[m]);(0,d.useEffect)(()=>{D.current+=1,y({}),w({})},[p]);let k=async(e,t)=>{let n=e.target.id;if(v[n]||t!==`start`&&!window.confirm(`${t===`stop`?`Stop`:`Restart`} ${e.target.name}? In-flight jobs on this broker may be interrupted.`))return;let r=D.current;y(e=>({...e,[n]:t})),w(e=>({...e,[n]:``}));try{await x(n,t),r===D.current&&await _()}catch(e){r===D.current&&w(t=>({...t,[n]:e.message}))}finally{r===D.current&&y(e=>{let t={...e};return delete t[n],t})}};return(0,C.jsxs)(`div`,{children:[(0,C.jsx)(l,{title:`Fleet`,description:`Operate every Bunqueue broker and verify shared PostgreSQL topology.`,actions:(0,C.jsx)(o,{onClick:()=>void _(),children:`Refresh all`})}),(0,C.jsxs)(`div`,{className:`mb-6 grid grid-cols-1 gap-4 md:grid-cols-3`,children:[(0,C.jsxs)(c,{children:[(0,C.jsx)(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-faint`,children:`Configured nodes`}),(0,C.jsx)(`div`,{className:`mt-1 text-2xl font-bold text-fg`,children:e.length})]}),(0,C.jsxs)(c,{children:[(0,C.jsx)(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-faint`,children:`Healthy APIs`}),(0,C.jsxs)(`div`,{className:`mt-1 text-2xl font-bold text-fg`,children:[(m??[]).filter(e=>e.server.healthy).length,`/`,e.length]})]}),(0,C.jsxs)(c,{children:[(0,C.jsx)(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-faint`,children:`PostgreSQL clusters`}),(0,C.jsx)(`div`,{className:`mt-1 text-2xl font-bold text-fg`,children:O.length})]})]}),h&&(0,C.jsxs)(`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:[`Fleet refresh failed: `,h.message]}),O.length>0&&(0,C.jsxs)(c,{className:`mb-6`,children:[(0,C.jsx)(s,{title:`Shared PostgreSQL topology`}),(0,C.jsx)(`div`,{className:`flex flex-col gap-3`,children:O.map(e=>(0,C.jsxs)(`div`,{className:`rounded-lg border border-line bg-surface-2/40 px-4 py-3`,children:[(0,C.jsx)(`div`,{className:`font-mono text-sm text-fg`,children:e.target}),(0,C.jsxs)(`div`,{className:`mt-1 text-xs text-muted`,children:[`namespace `,(0,C.jsx)(`span`,{className:`font-mono text-fg`,children:e.namespace}),` ·`,` `,e.members.length,` broker`,e.members.length===1?``:`s`,`:`,` `,e.members.map(e=>e.target.name).join(`, `)]})]},e.key))})]}),g&&!m?(0,C.jsx)(c,{children:`Checking every Bunqueue node…`}):(0,C.jsx)(`div`,{className:`grid grid-cols-1 gap-4 xl:grid-cols-2`,children:(m??[]).map(e=>(0,C.jsx)(T,{snapshot:e,active:e.target.id===t,busy:v[e.target.id],actionError:S[e.target.id],onActivate:()=>n(e.target.id),onAction:t=>void k(e,t)},e.target.id))}),(0,C.jsx)(`p`,{className:`mt-5 text-xs leading-relaxed text-faint`,children:`PostgreSQL-backed queues, jobs, flows, crons, workers, limits, durable metrics and events are visible through every healthy broker in the same target and namespace. Lifecycle, process logs/configuration and in-memory webhooks are node-local; Workflow Engine storage uses each profile's agent data path.`})]})}export{D as Fleet};