@stacksjs/debugbar 0.75.735 → 0.75.755

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.
@@ -1,10 +1,10 @@
1
- (()=>{function u(e){return(...t)=>{try{let n=e(...t);if(n instanceof Promise)n.catch(()=>{})}catch{}}}function N(e,t){if(t===null||t===void 0||t===!1)return;if(Array.isArray(t)){for(let n of t)N(e,n);return}e.appendChild(t instanceof Node?t:document.createTextNode(String(t)))}function r(e,t,...n){let s=document.createElement(e);if(t)for(let[a,i]of Object.entries(t)){if(i===null||i===void 0||i===!1)continue;if(a==="class")s.className=String(i);else if(a.startsWith("on")&&typeof i==="function")s.addEventListener(a.slice(2).toLowerCase(),u(i));else if(a==="value"&&"value"in s)s.value=String(i);else if(i===!0)s.setAttribute(a,"");else s.setAttribute(a,String(i))}for(let a of n)N(s,a);return s}function E(e){while(e.firstChild)e.removeChild(e.firstChild)}function x(e){if(e===void 0||!Number.isFinite(e))return"-";if(e>=1000)return`${(e/1000).toFixed(2)}s`;if(e>=100)return`${Math.round(e)}ms`;if(e>=10)return`${e.toFixed(1)}ms`;return`${e.toFixed(2)}ms`}function R(e){if(e===void 0||!Number.isFinite(e))return"-";if(e>=1048576)return`${(e/1048576).toFixed(1)}MB`;if(e>=1024)return`${(e/1024).toFixed(1)}KB`;return`${e}B`}function P(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function S(e,t=0){if(e===null||e===void 0)return r("span",{class:"j-null"},"null");if(typeof e==="string")return r("span",{class:e==="[redacted]"?"j-redacted":"j-string"},e==="[redacted]"?e:JSON.stringify(e));if(typeof e==="number"||typeof e==="boolean")return r("span",{class:"j-number"},String(e));if(typeof e!=="object")return r("span",null,String(e));let n=Array.isArray(e)?e.map((i,o)=>[String(o),i]):Object.entries(e);if(n.length===0)return r("span",{class:"j-null"},Array.isArray(e)?"[]":"{}");let s=Array.isArray(e)?`Array(${n.length})`:`{${n.length}}`;return r("details",{class:"j-node",open:t<1},r("summary",null,s),r("div",{class:"j-children"},n.map(([i,o])=>r("div",{class:"j-row"},r("span",{class:"j-key"},`${i}: `),S(o,t+1)))))}function T(e){return r("table",{class:"kv"},r("tbody",null,e.filter(([,t])=>t!==void 0).map(([t,n])=>r("tr",null,r("th",{scope:"row"},t),r("td",null,n instanceof Node?n:typeof n==="object"&&n!==null?S(n):String(n??"-"))))))}function w(e){return r("p",{class:"empty"},e)}async function ue(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function C(e,t="Copy"){let n=r("button",{class:"btn",type:"button"},t);return n.addEventListener("click",u(async(s)=>{s.stopPropagation();let a=await ue(e());n.textContent=a?"Copied":"Copy failed",setTimeout(()=>{n.textContent=t},1200)})),n}var pe=new Set("select from where and or not in is null like ilike between exists insert into values update set delete join inner left right full outer cross on as distinct group by order having limit offset union all case when then else end create table alter drop index primary key foreign references default returning with recursive asc desc count sum avg min max begin commit rollback transaction savepoint release pragma explain analyze true false conflict do nothing replace using".split(" ")),ge=new Set(["from","where","group","order","having","limit","offset","values","set","returning","union"]),O=new Set(["and","or","join","inner","left","right","full","cross"]),B=/(--[^\n]*|\/\*[\s\S]*?\*\/)|('(?:[^']|'')*')|("(?:[^"]|"")*"|`[^`]*`)|(\$\d+|\?)|(\b\d+(?:\.\d+)?\b)|([A-Za-z_][\w$]*)|(\s+)|([\s\S])/g;function H(e){let t=[];B.lastIndex=0;let n;while((n=B.exec(e))!==null){let s=n[1]!==void 0?"comment":n[2]!==void 0?"string":n[3]!==void 0?"ident":n[4]!==void 0?"param":n[5]!==void 0?"number":n[6]!==void 0?"word":n[7]!==void 0?"space":"other";if(t.push({type:s,text:n[0]}),t.length>20000)break}return t}function he(e){if(e===null||e===void 0)return"NULL";if(typeof e==="number")return String(e);if(typeof e==="boolean")return e?"TRUE":"FALSE";return`'${(typeof e==="string"?e:JSON.stringify(e)).replace(/'/g,"''")}'`}function A(e,t){if(!t||t.length===0)return e;let n=0;return H(e).map((s)=>{if(s.type!=="param")return s.text;let a=s.text==="?"?n++:Number(s.text.slice(1))-1;return a>=0&&a<t.length?he(t[a]):s.text}).join("")}function F(e){let t=H(e.replace(/\s+/g," ").trim()),n=0,s="",a="";for(let i of t){if(i.type==="other"){if(i.text==="(")n++;else if(i.text===")")n=Math.max(0,n-1)}if(i.type==="word"&&n===0){let o=i.text.toLowerCase(),d=O.has(a)&&(o==="join"||o==="outer");if(ge.has(o)&&s.trim()!==""&&!(o==="set"&&a==="conflict"))s=`${s.trimEnd()}
2
- `;else if(O.has(o)&&s.trim()!==""&&!d&&a!=="between")s=`${s.trimEnd()}
3
- `;a=o}s+=i.text}return s}var fe={comment:"q-c",string:"q-s",ident:"q-i",param:"q-p",number:"q-n"};function D(e){let t=r("code",{class:"sql"});for(let n of H(e)){let s=n.type==="word"&&pe.has(n.text.toLowerCase())?"q-k":fe[n.type];if(s)t.appendChild(r("span",{class:s},n.text));else t.appendChild(document.createTextNode(n.text))}return t}function k(e,t){return e.collectors[t]}function q(e){return r("span",{class:"num dim",title:"Time since the request began"},`+${x(e)}`)}function K(e){if(e==="error"||e==="fatal"||e==="critical")return"tag bad";if(e==="warning"||e==="warn")return"tag warn";return"tag"}function z(e,t,n,s,a){let i=r("ul",{class:"rows"}),o=r("input",{class:"input",type:"search",placeholder:s,"aria-label":s}),d=r("span",{class:"stat"}),l=r("div",{class:"toolbar"},o),g,m=()=>{let b=o.value.trim().toLowerCase();E(i);let c=0;if(e.forEach((p,h)=>{if(b&&!t(p).toLowerCase().includes(b))return;if(g&&!g(p))return;c++,i.appendChild(n(p,h))}),d.textContent=c===e.length?P(e.length,"entry","entries"):`${c} of ${e.length}`,c===0)i.appendChild(r("li",{class:"empty"},"Nothing matches."))};return g=a?.(l,m),l.append(r("span",{class:"grow"}),d),o.addEventListener("input",u(m)),m(),r("div",null,l,i)}function _(e){let t=k(e,"messages")??[];if(t.length===0)return w("No messages. Call debugbar.info(), .warn(), .error() or .addMessage() during a request.");return z(t,(n)=>`${n.level} ${n.label??""} ${n.message}`,(n)=>r("li",{class:"row"},r("div",{class:"main"},r("div",{class:"mono"},n.message),n.context!==void 0&&r("div",{class:"meta"},S(n.context))),r("div",{class:"side"},n.label&&r("span",{class:"tag accent"},n.label),r("span",{class:K(n.level)},n.level),q(n.at))),"Filter messages")}function Q(e){let t=k(e,"logs")??[];if(t.length===0)return w("Nothing was logged during this request.");return z(t,(n)=>`${n.level} ${n.message}`,(n)=>r("li",{class:"row"},r("div",{class:"main"},r("div",{class:"mono"},n.message),n.context!==void 0&&r("div",{class:"meta"},S(n.context))),r("div",{class:"side"},r("span",{class:K(n.level)},n.level),q(n.at))),"Filter logs")}function me(e,t,n,s){let a=()=>s.prefs.interpolate?A(e.sql,e.params):e.sql,i=r("li",{class:"row q","data-slow":e.slow,"data-failed":Boolean(e.error)}),o=r("div",{role:"button",tabindex:"0","aria-expanded":"false",title:"Show the whole statement"}),d=r("div",{class:"bindings",hidden:!0}),l=()=>{let b=i.hasAttribute("data-open");E(o),o.appendChild(D(b?F(a()):a())),o.setAttribute("aria-expanded",String(b)),d.hidden=!b||e.params.length===0},g=()=>{i.toggleAttribute("data-open"),l()};if(o.addEventListener("click",u(g)),o.addEventListener("keydown",u((b)=>{if(b.key==="Enter"||b.key===" ")b.preventDefault(),g()})),e.params.length>0)d.append(r("span",{class:"dim"},"Bindings "),S(e.params,1));l();let m=n>0?Math.max(2,Math.round(e.duration/n*100)):0;return i.append(r("div",{class:"main"},r("div",{class:"line"},r("span",{class:"idx"},String(t+1)),o),d,r("div",{class:"meta"},e.source&&r("span",{class:"mono"},e.source),e.rows!==void 0&&r("span",null,P(e.rows,"row")),e.duplicates&&r("span",{class:"tag warn",title:"Identical statement and bindings ran this many times"},`duplicate x${e.duplicates}`),!e.duplicates&&e.similar&&e.similar>1&&r("span",{class:"tag",title:"Statements with this shape in the request"},`similar x${e.similar}`),e.slow&&r("span",{class:"tag warn"},"slow"),e.error&&r("span",{class:"tag bad"},e.error))),r("div",{class:"side"},r("span",{class:`meter${e.slow?" warn":""}`,title:"Share of the slowest statement"},r("i",{style:`width:${m}%`})),r("span",{class:"num"},x(e.duration)),C(()=>A(e.sql,e.params)))),i}function U(e,t){let n=k(e,"queries");if(!n||n.statements.length===0)return w("No queries ran during this request.");let s=Math.max(...n.statements.map((c)=>c.duration)),a=r("ul",{class:"rows"}),i=r("input",{class:"input",type:"search",placeholder:"Filter statements","aria-label":"Filter statements"}),o={slow:!1,duplicates:!1,sortByTime:!1},d=(c,p,h)=>{let f=r("button",{class:"btn",type:"button","aria-pressed":"false"},h===void 0?c:`${c} ${h}`);return f.addEventListener("click",u(()=>{o[p]=!o[p],f.setAttribute("aria-pressed",String(o[p])),m()})),f},l=r("button",{class:"btn",type:"button","aria-pressed":String(t.prefs.interpolate),title:"Write bound values into each statement"},"Bindings inline");l.addEventListener("click",u(()=>{t.prefs.interpolate=!t.prefs.interpolate,t.savePrefs(),l.setAttribute("aria-pressed",String(t.prefs.interpolate)),m()}));let g=r("span",{class:"stat"});function m(){let c=i.value.trim().toLowerCase(),p=n.statements.map((h,f)=>({query:h,index:f}));if(c)p=p.filter(({query:h})=>h.sql.toLowerCase().includes(c)||(h.source??"").toLowerCase().includes(c));if(o.slow)p=p.filter(({query:h})=>h.slow);if(o.duplicates)p=p.filter(({query:h})=>h.duplicates||(h.similar??0)>1);if(o.sortByTime)p=[...p].sort((h,f)=>f.query.duration-h.query.duration);E(a);for(let{query:h,index:f}of p)a.appendChild(me(h,f,s,t));if(p.length===0)a.appendChild(r("li",{class:"empty"},"Nothing matches."));g.textContent=p.length===n.statements.length?"":`${p.length} shown`}i.addEventListener("input",u(m)),m();let b=n.nPlusOne.map((c)=>r("div",{class:"callout"},r("p",null,r("b",null,`Possible N+1: ${c.count} statements with one shape`),c.source?` from ${c.source}`:""),D(c.sample)));if(n.dropped>0)b.push(r("div",{class:"callout"},r("p",null,`${n.dropped} more statements ran and were not kept. Raise debugbar.queries.maxQueries to see them.`)));return r("div",null,r("div",{class:"toolbar"},i,d("Slow","slow",n.slow),d("Repeated","duplicates",n.duplicates),d("Slowest first","sortByTime"),l,r("span",{class:"grow"}),g,r("span",{class:"stat"},r("b",null,String(n.count))," statements in ",r("b",null,x(n.duration))),n.failed>0&&r("span",{class:"tag bad"},`${n.failed} failed`),C(()=>n.statements.map((c)=>`${A(c.sql,c.params)};`).join(`
4
- `),"Copy all")),b,a)}function W(e){let t=k(e,"timeline"),n=k(e,"queries"),s=Math.max(t?.duration??e.summary.duration,0.01),a=[{label:`${e.summary.method} ${e.summary.path}`,start:0,duration:s,group:"request"},...t?.measures??[],...(n?.statements??[]).map((o,d)=>({label:`query ${d+1}: ${o.sql.replace(/\s+/g," ").slice(0,60)}`,start:o.start,duration:o.duration,group:"query",slow:o.slow}))];a.sort((o,d)=>o.start-d.start||d.duration-o.duration);let i=(o)=>`${Math.min(100,Math.max(0,o/s*100)).toFixed(3)}%`;return r("div",{class:"tl"},r("div",{class:"toolbar",style:"position:static;padding:0 0 8px;border:0"},r("span",{class:"stat"},"Total ",r("b",null,x(s))),n&&n.count>0&&r("span",{class:"stat"},"Queries ",r("b",null,x(n.duration))),t?.memory&&r("span",{class:"stat"},"Memory ",r("b",null,R(t.memory.rss))," resident, ",r("b",null,R(t.memory.heapUsed))," heap")),r("div",{class:"tl-axis"},r("div",null,"Span"),r("div",null,r("span",null,"0"),r("span",null,x(s/2)),r("span",null,x(s))),r("div",{class:"num"},"Time")),a.map((o)=>r("div",{class:"tl-row",title:`${o.label}
5
- Starts at ${x(o.start)}, takes ${x(o.duration)}`},r("div",{class:"tl-label"},o.group==="middleware"?`middleware: ${o.label}`:o.label),r("div",{class:"tl-track"},r("span",{class:`tl-bar g-${o.group}${o.slow?" slow":""}`,style:`left:${i(o.start)};width:${i(o.duration)}`})),r("div",{class:"num"},x(o.duration)))))}function X(e){let t=k(e,"exceptions")??[];if(t.length===0)return w("No exceptions were reported during this request.");return r("div",null,t.map((n)=>{let s=()=>`${n.name}: ${n.message}
1
+ (()=>{function u(e){return(...t)=>{try{let n=e(...t);if(n instanceof Promise)n.catch(()=>{})}catch{}}}function N(e,t){if(t===null||t===void 0||t===!1)return;if(Array.isArray(t)){for(let n of t)N(e,n);return}e.appendChild(t instanceof Node?t:document.createTextNode(String(t)))}function s(e,t,...n){let r=document.createElement(e);if(t)for(let[a,i]of Object.entries(t)){if(i===null||i===void 0||i===!1)continue;if(a==="class")r.className=String(i);else if(a.startsWith("on")&&typeof i==="function")r.addEventListener(a.slice(2).toLowerCase(),u(i));else if(a==="value"&&"value"in r)r.value=String(i);else if(i===!0)r.setAttribute(a,"");else r.setAttribute(a,String(i))}for(let a of n)N(r,a);return r}function E(e){while(e.firstChild)e.removeChild(e.firstChild)}function x(e){if(e===void 0||!Number.isFinite(e))return"-";if(e>=1000)return`${(e/1000).toFixed(2)}s`;if(e>=100)return`${Math.round(e)}ms`;if(e>=10)return`${e.toFixed(1)}ms`;return`${e.toFixed(2)}ms`}function M(e){if(e===void 0||!Number.isFinite(e))return"-";if(e>=1048576)return`${(e/1048576).toFixed(1)}MB`;if(e>=1024)return`${(e/1024).toFixed(1)}KB`;return`${e}B`}function R(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function S(e,t=0){if(e===null||e===void 0)return s("span",{class:"j-null"},"null");if(typeof e==="string")return s("span",{class:e==="[redacted]"?"j-redacted":"j-string"},e==="[redacted]"?e:JSON.stringify(e));if(typeof e==="number"||typeof e==="boolean")return s("span",{class:"j-number"},String(e));if(typeof e!=="object")return s("span",null,String(e));let n=Array.isArray(e)?e.map((i,o)=>[String(o),i]):Object.entries(e);if(n.length===0)return s("span",{class:"j-null"},Array.isArray(e)?"[]":"{}");let r=Array.isArray(e)?`Array(${n.length})`:`{${n.length}}`;return s("details",{class:"j-node",open:t<1},s("summary",null,r),s("div",{class:"j-children"},n.map(([i,o])=>s("div",{class:"j-row"},s("span",{class:"j-key"},`${i}: `),S(o,t+1)))))}function T(e){return s("table",{class:"kv"},s("tbody",null,e.filter(([,t])=>t!==void 0).map(([t,n])=>s("tr",null,s("th",{scope:"row"},t),s("td",null,n instanceof Node?n:typeof n==="object"&&n!==null?S(n):String(n??"-"))))))}function y(e){return s("p",{class:"empty"},e)}async function pe(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function A(e,t="Copy"){let n=s("button",{class:"btn",type:"button"},t);return n.addEventListener("click",u(async(r)=>{r.stopPropagation();let a=await pe(e());n.textContent=a?"Copied":"Copy failed",setTimeout(()=>{n.textContent=t},1200)})),n}var ge=new Set("select from where and or not in is null like ilike between exists insert into values update set delete join inner left right full outer cross on as distinct group by order having limit offset union all case when then else end create table alter drop index primary key foreign references default returning with recursive asc desc count sum avg min max begin commit rollback transaction savepoint release pragma explain analyze true false conflict do nothing replace using".split(" ")),he=new Set(["from","where","group","order","having","limit","offset","values","set","returning","union"]),O=new Set(["and","or","join","inner","left","right","full","cross"]),B=/(--[^\n]*|\/\*[\s\S]*?\*\/)|('(?:[^']|'')*')|("(?:[^"]|"")*"|`[^`]*`)|(\$\d+|\?)|(\b\d+(?:\.\d+)?\b)|([A-Za-z_][\w$]*)|(\s+)|([\s\S])/g;function H(e){let t=[];B.lastIndex=0;let n;while((n=B.exec(e))!==null){let r=n[1]!==void 0?"comment":n[2]!==void 0?"string":n[3]!==void 0?"ident":n[4]!==void 0?"param":n[5]!==void 0?"number":n[6]!==void 0?"word":n[7]!==void 0?"space":"other";if(t.push({type:r,text:n[0]}),t.length>20000)break}return t}function me(e){if(e===null||e===void 0)return"NULL";if(typeof e==="number")return String(e);if(typeof e==="boolean")return e?"TRUE":"FALSE";return`'${(typeof e==="string"?e:JSON.stringify(e)).replace(/'/g,"''")}'`}function z(e,t){if(!t||t.length===0)return e;let n=0;return H(e).map((r)=>{if(r.type!=="param")return r.text;let a=r.text==="?"?n++:Number(r.text.slice(1))-1;return a>=0&&a<t.length?me(t[a]):r.text}).join("")}function F(e){let t=H(e.replace(/\s+/g," ").trim()),n=0,r="",a="";for(let i of t){if(i.type==="other"){if(i.text==="(")n++;else if(i.text===")")n=Math.max(0,n-1)}if(i.type==="word"&&n===0){let o=i.text.toLowerCase(),d=O.has(a)&&(o==="join"||o==="outer");if(he.has(o)&&r.trim()!==""&&!(o==="set"&&a==="conflict"))r=`${r.trimEnd()}
2
+ `;else if(O.has(o)&&r.trim()!==""&&!d&&a!=="between")r=`${r.trimEnd()}
3
+ `;a=o}r+=i.text}return r}var fe={comment:"q-c",string:"q-s",ident:"q-i",param:"q-p",number:"q-n"};function D(e){let t=s("code",{class:"sql"});for(let n of H(e)){let r=n.type==="word"&&ge.has(n.text.toLowerCase())?"q-k":fe[n.type];if(r)t.appendChild(s("span",{class:r},n.text));else t.appendChild(document.createTextNode(n.text))}return t}function k(e,t){return e.collectors[t]}function q(e){return s("span",{class:"num dim",title:"Time since the request began"},`+${x(e)}`)}function K(e){if(e==="error"||e==="fatal"||e==="critical")return"tag bad";if(e==="warning"||e==="warn")return"tag warn";return"tag"}function P(e,t,n,r,a){let i=s("ul",{class:"rows"}),o=s("input",{class:"input",type:"search",placeholder:r,"aria-label":r}),d=s("span",{class:"stat"}),l=s("div",{class:"toolbar"},o),g,f=()=>{let b=o.value.trim().toLowerCase();E(i);let c=0;if(e.forEach((p,h)=>{if(b&&!t(p).toLowerCase().includes(b))return;if(g&&!g(p))return;c++,i.appendChild(n(p,h))}),d.textContent=c===e.length?R(e.length,"entry","entries"):`${c} of ${e.length}`,c===0)i.appendChild(s("li",{class:"empty"},"Nothing matches."))};return g=a?.(l,f),l.append(s("span",{class:"grow"}),d),o.addEventListener("input",u(f)),f(),s("div",null,l,i)}function _(e){let t=k(e,"messages")??[];if(t.length===0)return y("No messages. Call debugbar.info(), .warn(), .error() or .addMessage() during a request.");return P(t,(n)=>`${n.level} ${n.label??""} ${n.message}`,(n)=>s("li",{class:"row"},s("div",{class:"main"},s("div",{class:"mono"},n.message),n.context!==void 0&&s("div",{class:"meta"},S(n.context))),s("div",{class:"side"},n.label&&s("span",{class:"tag accent"},n.label),s("span",{class:K(n.level)},n.level),q(n.at))),"Filter messages")}function Q(e){let t=k(e,"logs")??[];if(t.length===0)return y("Nothing was logged during this request.");return P(t,(n)=>`${n.level} ${n.message}`,(n)=>s("li",{class:"row"},s("div",{class:"main"},s("div",{class:"mono"},n.message),n.context!==void 0&&s("div",{class:"meta"},S(n.context))),s("div",{class:"side"},s("span",{class:K(n.level)},n.level),q(n.at))),"Filter logs")}function be(e,t,n,r){let a=()=>r.prefs.interpolate?z(e.sql,e.params):e.sql,i=s("li",{class:"row q","data-slow":e.slow,"data-failed":Boolean(e.error)}),o=s("div",{role:"button",tabindex:"0","aria-expanded":"false",title:"Show the whole statement"}),d=s("div",{class:"bindings",hidden:!0}),l=()=>{let b=i.hasAttribute("data-open");E(o),o.appendChild(D(b?F(a()):a())),o.setAttribute("aria-expanded",String(b)),d.hidden=!b||e.params.length===0},g=()=>{i.toggleAttribute("data-open"),l()};if(o.addEventListener("click",u(g)),o.addEventListener("keydown",u((b)=>{if(b.key==="Enter"||b.key===" ")b.preventDefault(),g()})),e.params.length>0)d.append(s("span",{class:"dim"},"Bindings "),S(e.params,1));l();let f=n>0?Math.max(2,Math.round(e.duration/n*100)):0;return i.append(s("div",{class:"main"},s("div",{class:"line"},s("span",{class:"idx"},String(t+1)),o),d,s("div",{class:"meta"},e.source&&s("span",{class:"mono"},e.source),e.rows!==void 0&&s("span",null,R(e.rows,"row")),e.duplicates&&s("span",{class:"tag warn",title:"Identical statement and bindings ran this many times"},`duplicate x${e.duplicates}`),!e.duplicates&&e.similar&&e.similar>1&&s("span",{class:"tag",title:"Statements with this shape in the request"},`similar x${e.similar}`),e.slow&&s("span",{class:"tag warn"},"slow"),e.error&&s("span",{class:"tag bad"},e.error))),s("div",{class:"side"},s("span",{class:`meter${e.slow?" warn":""}`,title:"Share of the slowest statement"},s("i",{style:`width:${f}%`})),s("span",{class:"num"},x(e.duration)),A(()=>z(e.sql,e.params)))),i}function U(e,t){let n=k(e,"queries");if(!n||n.statements.length===0)return y("No queries ran during this request.");let r=Math.max(...n.statements.map((c)=>c.duration)),a=s("ul",{class:"rows"}),i=s("input",{class:"input",type:"search",placeholder:"Filter statements","aria-label":"Filter statements"}),o={slow:!1,duplicates:!1,sortByTime:!1},d=(c,p,h)=>{let m=s("button",{class:"btn",type:"button","aria-pressed":"false"},h===void 0?c:`${c} ${h}`);return m.addEventListener("click",u(()=>{o[p]=!o[p],m.setAttribute("aria-pressed",String(o[p])),f()})),m},l=s("button",{class:"btn",type:"button","aria-pressed":String(t.prefs.interpolate),title:"Write bound values into each statement"},"Bindings inline");l.addEventListener("click",u(()=>{t.prefs.interpolate=!t.prefs.interpolate,t.savePrefs(),l.setAttribute("aria-pressed",String(t.prefs.interpolate)),f()}));let g=s("span",{class:"stat"});function f(){let c=i.value.trim().toLowerCase(),p=n.statements.map((h,m)=>({query:h,index:m}));if(c)p=p.filter(({query:h})=>h.sql.toLowerCase().includes(c)||(h.source??"").toLowerCase().includes(c));if(o.slow)p=p.filter(({query:h})=>h.slow);if(o.duplicates)p=p.filter(({query:h})=>h.duplicates||(h.similar??0)>1);if(o.sortByTime)p=[...p].sort((h,m)=>m.query.duration-h.query.duration);E(a);for(let{query:h,index:m}of p)a.appendChild(be(h,m,r,t));if(p.length===0)a.appendChild(s("li",{class:"empty"},"Nothing matches."));g.textContent=p.length===n.statements.length?"":`${p.length} shown`}i.addEventListener("input",u(f)),f();let b=n.nPlusOne.map((c)=>s("div",{class:"callout"},s("p",null,s("b",null,`Possible N+1: ${c.count} statements with one shape`),c.source?` from ${c.source}`:""),D(c.sample)));if(n.dropped>0)b.push(s("div",{class:"callout"},s("p",null,`${n.dropped} more statements ran and were not kept. Raise debugbar.queries.maxQueries to see them.`)));return s("div",null,s("div",{class:"toolbar"},i,d("Slow","slow",n.slow),d("Repeated","duplicates",n.duplicates),d("Slowest first","sortByTime"),l,s("span",{class:"grow"}),g,s("span",{class:"stat"},s("b",null,String(n.count))," statements in ",s("b",null,x(n.duration))),n.failed>0&&s("span",{class:"tag bad"},`${n.failed} failed`),A(()=>n.statements.map((c)=>`${z(c.sql,c.params)};`).join(`
4
+ `),"Copy all")),b,a)}function W(e){let t=k(e,"models");if(!t||t.models.length===0)return y("No models were hydrated during this request.");let n=Math.max(...t.models.map((r)=>r.count));return P(t.models,(r)=>`${r.model} ${r.table??""}`,(r)=>{let a=n>0?Math.max(4,Math.round(r.count/n*100)):0;return s("li",{class:"row"},s("div",{class:"main"},s("div",{class:"mono"},r.model),r.table&&s("div",{class:"meta"},s("span",{class:"dim"},r.table))),s("div",{class:"side"},s("span",{class:"bar"},s("span",{style:`width:${a}%`})),s("span",{class:"num"},String(r.count))))},"Filter models",(r)=>{r.append(s("span",{class:"stat"},s("b",null,String(t.total))," hydrated across ",s("b",null,R(t.models.length,"model"))))})}function X(e){let t=k(e,"timeline"),n=k(e,"queries"),r=Math.max(t?.duration??e.summary.duration,0.01),a=[{label:`${e.summary.method} ${e.summary.path}`,start:0,duration:r,group:"request"},...t?.measures??[],...(n?.statements??[]).map((o,d)=>({label:`query ${d+1}: ${o.sql.replace(/\s+/g," ").slice(0,60)}`,start:o.start,duration:o.duration,group:"query",slow:o.slow}))];a.sort((o,d)=>o.start-d.start||d.duration-o.duration);let i=(o)=>`${Math.min(100,Math.max(0,o/r*100)).toFixed(3)}%`;return s("div",{class:"tl"},s("div",{class:"toolbar",style:"position:static;padding:0 0 8px;border:0"},s("span",{class:"stat"},"Total ",s("b",null,x(r))),n&&n.count>0&&s("span",{class:"stat"},"Queries ",s("b",null,x(n.duration))),t?.memory&&s("span",{class:"stat"},"Memory ",s("b",null,M(t.memory.rss))," resident, ",s("b",null,M(t.memory.heapUsed))," heap")),s("div",{class:"tl-axis"},s("div",null,"Span"),s("div",null,s("span",null,"0"),s("span",null,x(r/2)),s("span",null,x(r))),s("div",{class:"num"},"Time")),a.map((o)=>s("div",{class:"tl-row",title:`${o.label}
5
+ Starts at ${x(o.start)}, takes ${x(o.duration)}`},s("div",{class:"tl-label"},o.group==="middleware"?`middleware: ${o.label}`:o.label),s("div",{class:"tl-track"},s("span",{class:`tl-bar g-${o.group}${o.slow?" slow":""}`,style:`left:${i(o.start)};width:${i(o.duration)}`})),s("div",{class:"num"},x(o.duration)))))}function J(e){let t=k(e,"exceptions")??[];if(t.length===0)return y("No exceptions were reported during this request.");return s("div",null,t.map((n)=>{let r=()=>`${n.name}: ${n.message}
6
6
  ${n.frames.map((a)=>` at ${a.function??"<anonymous>"} (${a.file}:${a.line??0})`).join(`
7
- `)}`;return r("div",{class:"ex"},r("div",{class:"toolbar",style:"position:static;padding:0 0 4px;border:0"},r("p",{class:"ex-title"},`${n.name}: ${n.message}`),r("span",{class:"grow"}),q(n.at),C(s)),n.excerpt&&r("div",null,r("div",{class:"mono dim"},`${n.excerpt.file}:${n.excerpt.line}`),r("div",{class:"excerpt"},n.excerpt.lines.map((a,i)=>{let o=n.excerpt.start+i;return r("div",{"data-hit":o===n.excerpt.line},r("span",null,String(o)),r("span",null,a||" "))}))),n.context!==void 0&&r("div",null,r("span",{class:"dim"},"Context "),S(n.context)),r("ol",{class:"frames"},n.frames.map((a)=>r("li",{"data-app":a.app},`${a.function??"<anonymous>"} `,r("span",{class:"dim"},`${a.file}${a.line?`:${a.line}`:""}`)))))}))}function J(e){let t=k(e,"events")??[];if(t.length===0)return w("No events were dispatched during this request.");return z(t,(n)=>n.name,(n)=>r("li",{class:"row"},r("div",{class:"main"},r("div",{class:"mono"},n.name),n.payload!==void 0&&r("div",{class:"meta"},S(n.payload,1))),r("div",{class:"side"},q(n.at))),"Filter events")}function V(e){let t=k(e,"cache");if(!t||t.operations.length===0)return w("The cache was not touched during this request.");let n={hit:"tag ok",miss:"tag warn",write:"tag accent",forget:"tag"};return z(t.operations,(s)=>`${s.type} ${s.key}`,(s)=>r("li",{class:"row"},r("div",{class:"main"},r("span",{class:"mono"},s.key)),r("div",{class:"side"},s.ttl!==void 0&&r("span",{class:"dim"},s.ttl===0?"forever":`ttl ${s.ttl}s`),r("span",{class:n[s.type]??"tag"},s.type),s.duration!==void 0&&r("span",{class:"num"},x(s.duration)),q(s.at))),"Filter keys",(s)=>{s.append(r("span",{class:"stat"},r("b",null,String(t.hits))," hits, ",r("b",null,String(t.misses))," misses, ",r("b",null,String(t.writes))," writes"))})}function G(e){let t=k(e,"mail")??[];if(t.length===0)return w("No mail was sent during this request.");return r("ul",{class:"rows"},t.map((n)=>r("li",{class:"row"},r("div",{class:"main"},r("div",null,r("b",null,n.subject||"(no subject)")),r("div",{class:"meta mono"},`to ${n.to.join(", ")||"-"}`,n.from&&` from ${n.from}`,n.message&&!n.success&&r("span",{class:"tag bad"},n.message))),r("div",{class:"side"},r("span",{class:"tag"},n.driver),r("span",{class:n.success?"tag ok":"tag bad"},n.success?"sent":"failed"),r("span",{class:"num"},x(n.duration)),q(n.at)))))}function Y(e){let t=k(e,"jobs")??[];if(t.length===0)return w("No jobs were dispatched during this request.");return r("ul",{class:"rows"},t.map((n)=>r("li",{class:"row"},r("div",{class:"main"},r("div",{class:"mono"},n.name),r("div",{class:"meta"},n.payload!==void 0&&S(n.payload,1),n.error&&r("span",{class:"tag bad"},n.error))),r("div",{class:"side"},r("span",{class:"tag"},n.queue),r("span",{class:n.event.endsWith("failed")?"tag bad":"tag accent"},n.event.replace(/^job:/,"")),q(n.at)))))}function Z(e){let t=k(e,"route"),n=k(e,"views"),s=[];if(t)s.push(["method",t.method],["pattern",t.path],["handler",t.handler],["middleware",t.middleware.length>0?t.middleware.join(", "):"none"]);if(n)s.push(["template",n.template??"not resolved (dynamic route)"],["layout",n.layout],["response",n.fragment?"fragment for a router navigation":"full document"],["render",x(n.renderMs)]);if(s.length===0)return w("No route matched this request.");return r("div",{class:"pad"},T(s))}function ee(e){let t=k(e,"auth");if(!t)return w("Nothing is known about who made this request.");return r("div",{class:"pad"},T([["authenticated",t.authenticated?"yes":"no"],["identified by",t.guard],["id",t.user?.id],["name",t.user?.name],["email",t.user?.email]]))}function te(e){let t=k(e,"request");if(!t)return w("The request section was not collected.");let n=(s)=>Object.entries(s).sort(([a],[i])=>a.localeCompare(i));return r("div",{class:"pad"},r("h3",null,"Request"),T([["method",t.method],["url",t.url],["host",t.host],["content type",t.contentType],["record",e.id],["served by",e.summary.process==="views"?"views server":"API server"]]),Object.keys(t.query).length>0&&[r("h3",null,"Query"),T(n(t.query))],t.input!==void 0&&[r("h3",null,"Input"),S(t.input)],r("h3",null,"Request headers"),T(n(t.headers)),t.cookies.length>0&&[r("h3",null,"Cookies (names only)"),r("div",{class:"mono"},t.cookies.join(", "))],r("h3",null,"Response"),T([["status",t.response.status],["content type",t.response.contentType],["size",t.response.size===void 0?"streamed":R(t.response.size)]]),r("h3",null,"Response headers"),T(n(t.response.headers)))}function ne(e){let t=k(e,"environment");if(!t)return w("The environment section was not collected.");let n=t.git;return r("div",{class:"pad"},T([["environment",t.environment],["stacks",t.stacks],["bun",t.bun],["platform",t.platform],["git",n?.branch||n?.sha?`${n.branch??"detached"}${n.sha?` @ ${n.sha}`:""}`:void 0],["process",`${String(t.process)} (pid ${String(t.pid)})`]]),r("h3",null,"Config"),S(t.config))}function re(e,t){let n=e.collectors[t];return n===void 0?w("This collector returned nothing for this request."):r("div",{class:"pad"},S(n))}function be(e){if(!e)return"tag";if(e>=500)return"tag bad";if(e>=400)return"tag warn";return"tag ok"}function se(e){let t=r("tbody"),n=r("table",{class:"grid"},r("thead",null,r("tr",null,r("th",null,"Status"),r("th",null,"Method"),r("th",null,"URL"),r("th",null,"Kind"),r("th",{class:"num"},"Time"),r("th",{class:"num"},"Queries"))),t),s=r("span",{class:"stat"}),a=()=>{E(t);let l=e.entries(),g=new Set(l.map((c)=>c.id)),m=e.serverEntries,b=[...l].reverse().concat((m??[]).filter((c)=>!g.has(c.id)));for(let c of b){let p=c.record?.summary,h=r("tr",{tabindex:"0","data-current":c.id===e.currentId()},r("td",null,r("span",{class:be(c.status)},c.status?String(c.status):"...")),r("td",{class:"mono"},c.method),r("td",{class:"mono"},c.url),r("td",null,c.kind),r("td",{class:"num"},x(p?.duration??c.duration)),r("td",{class:"num"},p?String(p.queries):"-")),f=()=>e.select(c.id);h.addEventListener("click",u(f)),h.addEventListener("keydown",u((y)=>{if(y.key==="Enter"||y.key===" ")y.preventDefault(),f()})),t.appendChild(h)}s.textContent=`${P(l.length,"request")} from this page${m?`, ${m.length} recent on the server`:""}`},i=r("input",{type:"checkbox"});i.checked=e.prefs.follow,i.addEventListener("change",u(()=>{e.prefs.follow=i.checked,e.savePrefs()}));let o=r("button",{class:"btn",type:"button"},"Load recent");o.addEventListener("click",u(async()=>{o.disabled=!0;try{e.serverEntries=(await e.recent()).map((l)=>({id:l.id,method:l.summary.method,url:l.summary.url,status:l.summary.status,kind:l.summary.kind,duration:l.summary.duration,at:Date.parse(l.startedAt)}))}finally{o.disabled=!1}a()}));let d=r("button",{class:"btn",type:"button",title:"Delete every stored record"},"Clear stored");return d.addEventListener("click",u(async()=>{await e.clearRecords(),e.serverEntries=[],a()})),a(),r("div",null,r("div",{class:"toolbar"},r("label",{class:"check"},i,"Follow the latest request"),r("span",{class:"grow"}),s,o,d),n)}function ie(e,t){let n=r("div"),s=r("p",{class:"error",role:"alert",hidden:!0}),a=r("input",{class:"input",type:"search",placeholder:"Filter users","aria-label":"Filter users"}),i=r("span",{class:"stat"}),o=r("button",{class:"btn",type:"button",hidden:!0},"Sign out"),d,l=(f)=>{s.textContent=f,s.hidden=!1},g=()=>{try{return e.options.tokenStorageKey?localStorage.getItem(e.options.tokenStorageKey):null}catch{return null}},m=async(f,y)=>{s.hidden=!0;let v=await e.request(f,{method:"POST",headers:{"Content-Type":"application/json","X-Debugbar-Token":e.token},body:JSON.stringify(y??{})}),L=await v.json().catch(()=>({}));if(!v.ok){l(typeof L.error==="string"?L.error:`The request failed with status ${v.status}.`);return}return L},b=async(f)=>{let y=await m("sign-in-as",{id:f});if(!y)return;let v=typeof y.tokenStorageKey==="string"?y.tokenStorageKey:e.options.tokenStorageKey;try{if(v&&typeof y.token==="string")localStorage.setItem(v,y.token)}catch{}window.dispatchEvent(new CustomEvent("stacks:debugbar:signed-in",{detail:{user:y.user,token:y.token}})),t(),location.reload()};o.addEventListener("click",u(async()=>{if(!await m("sign-out"))return;try{if(e.options.tokenStorageKey)localStorage.removeItem(e.options.tokenStorageKey)}catch{}window.dispatchEvent(new CustomEvent("stacks:debugbar:signed-out")),t(),location.reload()}));let c=()=>{if(E(n),!d)return;i.textContent=d.current?`Signed in as ${d.current.name}`:"Not signed in",o.hidden=!d.current;let f=a.value.trim().toLowerCase(),y=d.users.filter((v)=>!f||`${v.name} ${v.email??""} ${v.badge??""} ${v.description??""} ${v.id}`.toLowerCase().includes(f));if(d.users.length===0)n.appendChild(w("No users to offer. Seed the users table, or return some from debugbar.signInAs.users."));else if(y.length===0)n.appendChild(w("Nothing matches."));for(let v of y){let L=d.current!==null&&String(d.current.id)===String(v.id),M=r("button",{class:L?"btn":"btn primary",type:"button",disabled:L},L?"Current":"Sign in");M.addEventListener("click",u(async()=>{M.disabled=!0,await b(v.id).finally(()=>{M.disabled=L})})),n.appendChild(r("div",{class:"user","data-current":L},r("div",{style:"min-width:0"},r("div",null,r("span",{class:"name"},v.name)," ",v.badge&&r("span",{class:"tag accent"},v.badge)," ",r("span",{class:"dim mono"},`#${v.id}`)),r("div",{class:"sub"},[v.email,v.description].filter(Boolean).join(" · "))),M))}},p=async()=>{let f=g(),y=await e.request("users",f?{headers:{Authorization:`Bearer ${f}`}}:void 0);if(!y.ok){l(`Could not load users (status ${y.status}).`);return}if(d=await y.json(),!d.enabled)l("Sign in as is disabled in config/debugbar.ts.");c()};a.addEventListener("input",u(c));let h=r("button",{class:"btn",type:"button"},"Refresh");return h.addEventListener("click",u(p)),p().catch(()=>l("Could not load users.")),r("div",null,r("div",{class:"toolbar"},a,r("span",{class:"grow"}),i,o,h),s,n)}var I=`
7
+ `)}`;return s("div",{class:"ex"},s("div",{class:"toolbar",style:"position:static;padding:0 0 4px;border:0"},s("p",{class:"ex-title"},`${n.name}: ${n.message}`),s("span",{class:"grow"}),q(n.at),A(r)),n.excerpt&&s("div",null,s("div",{class:"mono dim"},`${n.excerpt.file}:${n.excerpt.line}`),s("div",{class:"excerpt"},n.excerpt.lines.map((a,i)=>{let o=n.excerpt.start+i;return s("div",{"data-hit":o===n.excerpt.line},s("span",null,String(o)),s("span",null,a||" "))}))),n.context!==void 0&&s("div",null,s("span",{class:"dim"},"Context "),S(n.context)),s("ol",{class:"frames"},n.frames.map((a)=>s("li",{"data-app":a.app},`${a.function??"<anonymous>"} `,s("span",{class:"dim"},`${a.file}${a.line?`:${a.line}`:""}`)))))}))}function V(e){let t=k(e,"events")??[];if(t.length===0)return y("No events were dispatched during this request.");return P(t,(n)=>n.name,(n)=>s("li",{class:"row"},s("div",{class:"main"},s("div",{class:"mono"},n.name),n.payload!==void 0&&s("div",{class:"meta"},S(n.payload,1))),s("div",{class:"side"},q(n.at))),"Filter events")}function G(e){let t=k(e,"cache");if(!t||t.operations.length===0)return y("The cache was not touched during this request.");let n={hit:"tag ok",miss:"tag warn",write:"tag accent",forget:"tag"};return P(t.operations,(r)=>`${r.type} ${r.key}`,(r)=>s("li",{class:"row"},s("div",{class:"main"},s("span",{class:"mono"},r.key)),s("div",{class:"side"},r.ttl!==void 0&&s("span",{class:"dim"},r.ttl===0?"forever":`ttl ${r.ttl}s`),s("span",{class:n[r.type]??"tag"},r.type),r.duration!==void 0&&s("span",{class:"num"},x(r.duration)),q(r.at))),"Filter keys",(r)=>{r.append(s("span",{class:"stat"},s("b",null,String(t.hits))," hits, ",s("b",null,String(t.misses))," misses, ",s("b",null,String(t.writes))," writes"))})}function Y(e){let t=k(e,"mail")??[];if(t.length===0)return y("No mail was sent during this request.");return s("ul",{class:"rows"},t.map((n)=>s("li",{class:"row"},s("div",{class:"main"},s("div",null,s("b",null,n.subject||"(no subject)")),s("div",{class:"meta mono"},`to ${n.to.join(", ")||"-"}`,n.from&&` from ${n.from}`,n.message&&!n.success&&s("span",{class:"tag bad"},n.message))),s("div",{class:"side"},s("span",{class:"tag"},n.driver),s("span",{class:n.success?"tag ok":"tag bad"},n.success?"sent":"failed"),s("span",{class:"num"},x(n.duration)),q(n.at)))))}function Z(e){let t=k(e,"jobs")??[];if(t.length===0)return y("No jobs were dispatched during this request.");return s("ul",{class:"rows"},t.map((n)=>s("li",{class:"row"},s("div",{class:"main"},s("div",{class:"mono"},n.name),s("div",{class:"meta"},n.payload!==void 0&&S(n.payload,1),n.error&&s("span",{class:"tag bad"},n.error))),s("div",{class:"side"},s("span",{class:"tag"},n.queue),s("span",{class:n.event.endsWith("failed")?"tag bad":"tag accent"},n.event.replace(/^job:/,"")),q(n.at)))))}function ee(e){let t=k(e,"route"),n=k(e,"views"),r=[];if(t)r.push(["method",t.method],["pattern",t.path],["handler",t.handler],["middleware",t.middleware.length>0?t.middleware.join(", "):"none"]);if(n)r.push(["template",n.template??"not resolved (dynamic route)"],["layout",n.layout],["response",n.fragment?"fragment for a router navigation":"full document"],["render",x(n.renderMs)]);if(r.length===0)return y("No route matched this request.");return s("div",{class:"pad"},T(r))}function te(e){let t=k(e,"auth");if(!t)return y("Nothing is known about who made this request.");return s("div",{class:"pad"},T([["authenticated",t.authenticated?"yes":"no"],["identified by",t.guard],["id",t.user?.id],["name",t.user?.name],["email",t.user?.email]]))}function ne(e){let t=k(e,"request");if(!t)return y("The request section was not collected.");let n=(r)=>Object.entries(r).sort(([a],[i])=>a.localeCompare(i));return s("div",{class:"pad"},s("h3",null,"Request"),T([["method",t.method],["url",t.url],["host",t.host],["content type",t.contentType],["record",e.id],["served by",e.summary.process==="views"?"views server":"API server"]]),Object.keys(t.query).length>0&&[s("h3",null,"Query"),T(n(t.query))],t.input!==void 0&&[s("h3",null,"Input"),S(t.input)],s("h3",null,"Request headers"),T(n(t.headers)),t.cookies.length>0&&[s("h3",null,"Cookies (names only)"),s("div",{class:"mono"},t.cookies.join(", "))],s("h3",null,"Response"),T([["status",t.response.status],["content type",t.response.contentType],["size",t.response.size===void 0?"streamed":M(t.response.size)]]),s("h3",null,"Response headers"),T(n(t.response.headers)))}function se(e){let t=k(e,"environment");if(!t)return y("The environment section was not collected.");let n=t.git;return s("div",{class:"pad"},T([["environment",t.environment],["stacks",t.stacks],["bun",t.bun],["platform",t.platform],["git",n?.branch||n?.sha?`${n.branch??"detached"}${n.sha?` @ ${n.sha}`:""}`:void 0],["process",`${String(t.process)} (pid ${String(t.pid)})`]]),s("h3",null,"Config"),S(t.config))}function re(e,t){let n=e.collectors[t];return n===void 0?y("This collector returned nothing for this request."):s("div",{class:"pad"},S(n))}function ve(e){if(!e)return"tag";if(e>=500)return"tag bad";if(e>=400)return"tag warn";return"tag ok"}function ie(e){let t=s("tbody"),n=s("table",{class:"grid"},s("thead",null,s("tr",null,s("th",null,"Status"),s("th",null,"Method"),s("th",null,"URL"),s("th",null,"Kind"),s("th",{class:"num"},"Time"),s("th",{class:"num"},"Queries"))),t),r=s("span",{class:"stat"}),a=()=>{E(t);let l=e.entries(),g=new Set(l.map((c)=>c.id)),f=e.serverEntries,b=[...l].reverse().concat((f??[]).filter((c)=>!g.has(c.id)));for(let c of b){let p=c.record?.summary,h=s("tr",{tabindex:"0","data-current":c.id===e.currentId()},s("td",null,s("span",{class:ve(c.status)},c.status?String(c.status):"...")),s("td",{class:"mono"},c.method),s("td",{class:"mono"},c.url),s("td",null,c.kind),s("td",{class:"num"},x(p?.duration??c.duration)),s("td",{class:"num"},p?String(p.queries):"-")),m=()=>e.select(c.id);h.addEventListener("click",u(m)),h.addEventListener("keydown",u((w)=>{if(w.key==="Enter"||w.key===" ")w.preventDefault(),m()})),t.appendChild(h)}r.textContent=`${R(l.length,"request")} from this page${f?`, ${f.length} recent on the server`:""}`},i=s("input",{type:"checkbox"});i.checked=e.prefs.follow,i.addEventListener("change",u(()=>{e.prefs.follow=i.checked,e.savePrefs()}));let o=s("button",{class:"btn",type:"button"},"Load recent");o.addEventListener("click",u(async()=>{o.disabled=!0;try{e.serverEntries=(await e.recent()).map((l)=>({id:l.id,method:l.summary.method,url:l.summary.url,status:l.summary.status,kind:l.summary.kind,duration:l.summary.duration,at:Date.parse(l.startedAt)}))}finally{o.disabled=!1}a()}));let d=s("button",{class:"btn",type:"button",title:"Delete every stored record"},"Clear stored");return d.addEventListener("click",u(async()=>{await e.clearRecords(),e.serverEntries=[],a()})),a(),s("div",null,s("div",{class:"toolbar"},s("label",{class:"check"},i,"Follow the latest request"),s("span",{class:"grow"}),r,o,d),n)}function ae(e,t){let n=s("div"),r=s("p",{class:"error",role:"alert",hidden:!0}),a=s("input",{class:"input",type:"search",placeholder:"Filter users","aria-label":"Filter users"}),i=s("span",{class:"stat"}),o=s("button",{class:"btn",type:"button",hidden:!0},"Sign out"),d,l=(m)=>{r.textContent=m,r.hidden=!1},g=()=>{try{return e.options.tokenStorageKey?localStorage.getItem(e.options.tokenStorageKey):null}catch{return null}},f=async(m,w)=>{r.hidden=!0;let v=await e.request(m,{method:"POST",headers:{"Content-Type":"application/json","X-Debugbar-Token":e.token},body:JSON.stringify(w??{})}),L=await v.json().catch(()=>({}));if(!v.ok){l(typeof L.error==="string"?L.error:`The request failed with status ${v.status}.`);return}return L},b=async(m)=>{let w=await f("sign-in-as",{id:m});if(!w)return;let v=typeof w.tokenStorageKey==="string"?w.tokenStorageKey:e.options.tokenStorageKey;try{if(v&&typeof w.token==="string")localStorage.setItem(v,w.token)}catch{}window.dispatchEvent(new CustomEvent("stacks:debugbar:signed-in",{detail:{user:w.user,token:w.token}})),t(),location.reload()};o.addEventListener("click",u(async()=>{if(!await f("sign-out"))return;try{if(e.options.tokenStorageKey)localStorage.removeItem(e.options.tokenStorageKey)}catch{}window.dispatchEvent(new CustomEvent("stacks:debugbar:signed-out")),t(),location.reload()}));let c=()=>{if(E(n),!d)return;i.textContent=d.current?`Signed in as ${d.current.name}`:"Not signed in",o.hidden=!d.current;let m=a.value.trim().toLowerCase(),w=d.users.filter((v)=>!m||`${v.name} ${v.email??""} ${v.badge??""} ${v.description??""} ${v.id}`.toLowerCase().includes(m));if(d.users.length===0)n.appendChild(y("No users to offer. Seed the users table, or return some from debugbar.signInAs.users."));else if(w.length===0)n.appendChild(y("Nothing matches."));for(let v of w){let L=d.current!==null&&String(d.current.id)===String(v.id),C=s("button",{class:L?"btn":"btn primary",type:"button",disabled:L},L?"Current":"Sign in");C.addEventListener("click",u(async()=>{C.disabled=!0,await b(v.id).finally(()=>{C.disabled=L})})),n.appendChild(s("div",{class:"user","data-current":L},s("div",{style:"min-width:0"},s("div",null,s("span",{class:"name"},v.name)," ",v.badge&&s("span",{class:"tag accent"},v.badge)," ",s("span",{class:"dim mono"},`#${v.id}`)),s("div",{class:"sub"},[v.email,v.description].filter(Boolean).join(" · "))),C))}},p=async()=>{let m=g(),w=await e.request("users",m?{headers:{Authorization:`Bearer ${m}`}}:void 0);if(!w.ok){l(`Could not load users (status ${w.status}).`);return}if(d=await w.json(),!d.enabled)l("Sign in as is disabled in config/debugbar.ts.");c()};a.addEventListener("input",u(c));let h=s("button",{class:"btn",type:"button"},"Refresh");return h.addEventListener("click",u(p)),p().catch(()=>l("Could not load users.")),s("div",null,s("div",{class:"toolbar"},a,s("span",{class:"grow"}),i,o,h),r,n)}var I=`
8
8
  :host {
9
9
  all: initial;
10
10
  --bg: #ffffff;
@@ -231,4 +231,4 @@ table { border-collapse: collapse; width: 100%; }
231
231
  .tl-row, .tl-axis { grid-template-columns: 110px minmax(0, 1fr) 60px; }
232
232
  }
233
233
  @media print { :host { display: none; } }
234
- `;var ve="x-debugbar-id",oe="/__debugbar/",le="stacks-debugbar",ye=60,j=34,ae=[["messages","Messages"],["timeline","Timeline"],["queries","Queries"],["exceptions","Exceptions"],["logs","Logs"],["route","Route"],["events","Events"],["cache","Cache"],["mail","Mail"],["jobs","Jobs"],["auth","Auth"],["request","Request"],["environment","Environment"]],we=new Set(["views"]),xe=new Set(["timeline","queries","request"]);function ke(){let e={open:!1,minimized:!1,tab:"queries",height:320,follow:!1,interpolate:!1};try{let t=JSON.parse(localStorage.getItem(le)??"{}");return{open:t.open===!0,minimized:t.minimized===!0,tab:typeof t.tab==="string"?t.tab:e.tab,height:typeof t.height==="number"&&t.height>=120?t.height:e.height,follow:t.follow===!0,interpolate:t.interpolate===!0}}catch{return e}}function Ee(e){let t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("aria-hidden","true");let n=document.createElementNS("http://www.w3.org/2000/svg","path");return n.setAttribute("d",e),t.appendChild(n),t}function Se(e){if(!e)return;let t=e.toLowerCase().split("+").map((a)=>a.trim()).filter(Boolean),n=t.pop();if(!n)return;let s=(a)=>t.includes(a);return(a)=>a.altKey===s("alt")&&a.shiftKey===s("shift")&&a.ctrlKey===(s("ctrl")||s("control"))&&a.metaKey===(s("meta")||s("cmd"))&&(a.key.toLowerCase()===n||a.code.toLowerCase()===`key${n}`||a.code.toLowerCase()===n)}class de{options;token;prefs;serverEntries;nativeFetch;list=[];current;pageId;host;root;chips;tabs;body;panel;switcher;badge;brand;resizer;originalPadding;renderedFor;tabsSignature;listVersion=0;signInDirty=!0;constructor(e,t,n,s){this.options=n,this.token=t,this.pageId=e,this.nativeFetch=s,this.prefs=ke(),this.host=document.createElement("stacks-debugbar"),this.host.setAttribute("data-stacks-debugbar-host","");let a=this.host.attachShadow({mode:"closed"});this.adoptStyles(a),this.brand=r("button",{class:"brand",type:"button","aria-expanded":"false",title:this.shortcutHint("Toggle the panel")},"Stacks",r("span",{class:"caret"})),this.chips=r("div",{class:"chips"}),this.switcher=r("select",{class:"switch","aria-label":"Request to inspect",title:"Requests made by this page"}),this.resizer=r("div",{class:"resize",role:"separator",tabindex:"0","aria-orientation":"horizontal","aria-label":"Resize the panel"}),this.tabs=r("div",{class:"tabs",role:"tablist","aria-label":"Debugbar sections"}),this.body=r("div",{class:"body",role:"tabpanel",tabindex:"0"}),this.panel=r("div",{class:"panel"},this.resizer,this.tabs,this.body);let i=r("button",{class:"icon",type:"button","aria-label":"Minimise the debugbar",title:"Minimise"},Ee("M3 12h10"));this.badge=r("button",{class:"badge",type:"button","aria-label":"Show the debugbar"}),this.root=r("div",{class:"root"},this.panel,r("div",{class:"bar",role:"toolbar","aria-label":"Stacks debugbar"},this.brand,this.chips,r("div",{class:"tools"},this.switcher,i))),a.append(this.root,this.badge),this.brand.addEventListener("click",u(()=>this.toggle())),i.addEventListener("click",u(()=>this.setMinimized(!0))),this.badge.addEventListener("click",u(()=>this.setMinimized(!1))),this.switcher.addEventListener("change",u(()=>this.select(this.switcher.value))),this.root.addEventListener("keydown",u((o)=>this.onKey(o))),this.bindResize(),this.bindShortcut(),this.mount(),this.note({id:e,method:"GET",url:location.pathname+location.search,kind:"page",status:void 0}),this.current=e,this.apply(),this.load(e)}entries(){return this.list}currentId(){return this.current}select(e){if(!this.list.some((t)=>t.id===e))this.list.push({id:e,method:"",url:"",kind:"api",at:Date.now()});this.current=e,this.render(),this.load(e)}savePrefs(){try{localStorage.setItem(le,JSON.stringify(this.prefs))}catch{}}request(e,t){return this.nativeFetch(oe+e,{credentials:"same-origin",...t})}async recent(){let e=await this.request("requests?limit=50");return e.ok?(await e.json()).requests:[]}async clearRecords(){await this.request("requests",{method:"DELETE",headers:{"X-Debugbar-Token":this.token}})}page(e,t){if(t)this.token=t;this.pageId=e,this.signInDirty=!0;let n=this.list.find((s)=>s.id===e);if(n)n.kind=n.kind==="api"?"fragment":n.kind;else this.note({id:e,method:"GET",url:location.pathname+location.search,kind:"page",status:void 0});this.mount(),this.select(e)}note(e){let t=this.list.find((n)=>n.id===e.id);if(t){t.status??=e.status;return}if(this.list.push({...e,at:Date.now()}),!e.method)this.load(e.id);if(this.list.length>ye){let n=this.list.findIndex((s)=>s.id!==this.pageId&&s.id!==this.current);if(n>=0)this.list.splice(n,1)}if(this.prefs.follow&&e.kind==="api"&&this.current!==void 0)this.select(e.id);else if(this.current!==void 0)this.render()}navigated(e){let t;try{let a=new URL(e??location.href,location.href);t=a.pathname+a.search}catch{}let n=this.list.filter((a)=>a.kind!=="api"&&a.id!==this.pageId),s=[...n].reverse().find((a)=>a.url===t)??n[n.length-1];if(s)this.page(s.id);else this.mount()}mount(){if(!this.host.isConnected)(document.documentElement??document.body).appendChild(this.host)}adoptStyles(e){try{let t=new CSSStyleSheet;t.replaceSync(I),e.adoptedStyleSheets=[t]}catch{e.appendChild(r("style",null,I))}}async load(e){let t=this.list.find((n)=>n.id===e);if(!t||t.record)return;for(let n of[0,60,140,300,600,1200]){if(n>0)await new Promise((s)=>setTimeout(s,n));try{let s=await this.request(`requests/${e}`);if(s.ok){t.record=await s.json(),t.status=t.record.summary.status,t.method=t.record.summary.method,t.url=t.record.summary.url,t.kind=t.record.summary.kind;break}if(s.status!==404)break}catch{break}}if(!t.record)t.missing=!0;this.listVersion++,this.render()}toggle(e){if(e&&(this.prefs.tab!==e||!this.prefs.open))this.prefs.tab=e,this.prefs.open=!0;else this.prefs.open=!this.prefs.open;this.prefs.minimized=!1,this.savePrefs(),this.apply()}setMinimized(e){this.prefs.minimized=e,this.savePrefs(),this.apply(),(e?this.badge:this.brand).focus()}maxHeight(){return Math.max(160,window.innerHeight-j-40)}apply(){let e=this.prefs.open&&!this.prefs.minimized;this.root.toggleAttribute("data-open",e),this.root.toggleAttribute("data-min",this.prefs.minimized),this.badge.toggleAttribute("data-show",this.prefs.minimized),this.brand.setAttribute("aria-expanded",String(e));let t=Math.min(this.prefs.height,this.maxHeight());this.panel.style.height=`${t}px`,this.resizer.setAttribute("aria-valuenow",String(Math.round(t))),this.resizer.setAttribute("aria-valuemin","120"),this.resizer.setAttribute("aria-valuemax",String(this.maxHeight())),this.pad(e?t+j:0),this.render()}pad(e){let t=document.documentElement;if(e>0){if(this.originalPadding===void 0)this.originalPadding=t.style.paddingBottom;t.style.paddingBottom=`${e}px`}else if(this.originalPadding!==void 0)t.style.paddingBottom=this.originalPadding,this.originalPadding=void 0}shortcutHint(e){return this.options.shortcut?`${e} (${this.options.shortcut})`:e}bindShortcut(){let e=Se(this.options.shortcut);if(!e)return;window.addEventListener("keydown",u((t)=>{if(!e(t))return;if(t.preventDefault(),this.prefs.minimized)this.setMinimized(!1);else this.toggle();if(this.prefs.open)this.brand.focus()}),!0)}onKey(e){if(e.key==="Escape"&&this.prefs.open){e.stopPropagation(),this.toggle(),this.brand.focus();return}let t=e.target;if(t?.getAttribute("role")!=="tab")return;let n=[...this.tabs.querySelectorAll('[role="tab"]')],s=n.indexOf(t),a=e.key==="ArrowRight"?n[(s+1)%n.length]:e.key==="ArrowLeft"?n[(s-1+n.length)%n.length]:e.key==="Home"?n[0]:e.key==="End"?n[n.length-1]:void 0;if(!a)return;e.preventDefault(),this.prefs.tab=a.dataset.tab??this.prefs.tab,this.savePrefs(),this.render(),this.tabs.querySelector('[aria-selected="true"]')?.focus()}bindResize(){let e=(t)=>{this.prefs.height=Math.round(Math.min(this.maxHeight(),Math.max(120,t))),this.apply()};this.resizer.addEventListener("pointerdown",u((t)=>{t.preventDefault();let n=t.clientY,s=this.panel.getBoundingClientRect().height;this.resizer.setAttribute("data-drag",""),this.resizer.setPointerCapture(t.pointerId);let a=u((o)=>{this.prefs.height=Math.round(Math.min(this.maxHeight(),Math.max(120,s+n-o.clientY))),this.panel.style.height=`${this.prefs.height}px`,this.pad(this.prefs.height+j)}),i=u(()=>{this.resizer.removeAttribute("data-drag"),this.resizer.removeEventListener("pointermove",a),this.resizer.removeEventListener("pointerup",i),this.resizer.removeEventListener("pointercancel",i),this.savePrefs(),this.apply()});this.resizer.addEventListener("pointermove",a),this.resizer.addEventListener("pointerup",i),this.resizer.addEventListener("pointercancel",i)})),this.resizer.addEventListener("keydown",u((t)=>{let n=t.shiftKey?80:24;if(t.key==="ArrowUp")e(this.prefs.height+n);else if(t.key==="ArrowDown")e(this.prefs.height-n);else return;t.preventDefault(),this.savePrefs()})),window.addEventListener("resize",u(()=>{if(this.prefs.open&&!this.prefs.minimized)this.apply()}))}record(){return this.list.find((e)=>e.id===this.current)?.record}tabSpecs(e){let t=[],n=e?.collectors??{},s=(i)=>Array.isArray(n[i])?n[i].length:void 0;for(let[i,o]of ae){if(!(i==="route"?n.route!==void 0||n.views!==void 0:n[i]!==void 0)&&!xe.has(i))continue;let l={id:i,label:o};if(i==="queries"){let g=n.queries;if(l.count=g?.count??0,(g?.failed??0)>0)l.tone="bad";else if((g?.nPlusOne?.length??0)>0||(g?.slow??0)>0)l.tone="warn"}else if(i==="cache")l.count=n.cache?.operations?.length;else if(i==="exceptions")l.count=s(i),l.tone="bad";else if(i==="messages"||i==="logs"||i==="events"||i==="mail"||i==="jobs")l.count=s(i);t.push(l)}let a=new Set(ae.map(([i])=>i));for(let i of Object.keys(n))if(!a.has(i)&&!we.has(i))t.push({id:`custom:${i}`,label:e?.labels?.[i]??i});if(t.push({id:"requests",label:"Requests",count:this.list.length}),this.options.signInAs!==!1)t.push({id:"signin",label:"Sign in as"});return t}render(){let e=this.record();if(this.renderChips(e),this.renderSwitcher(),this.renderBadge(e),!this.prefs.open||this.prefs.minimized)return;let t=this.tabSpecs(e);if(!t.some((i)=>i.id===this.prefs.tab))this.prefs.tab=t.some((i)=>i.id==="queries")?"queries":t[0].id;let n=JSON.stringify([t,this.prefs.tab]),s=n===this.tabsSignature;if(this.tabsSignature=n,!s)E(this.tabs);for(let i of s?[]:t){let o=i.id===this.prefs.tab,d=r("button",{class:"tab",type:"button",role:"tab","aria-selected":String(o),tabindex:o?"0":"-1","data-tab":i.id},i.label,i.count!==void 0&&i.count>0&&r("span",{class:`count${i.tone?` ${i.tone}`:""}`},String(i.count)));d.addEventListener("click",u(()=>{this.prefs.tab=i.id,this.savePrefs(),this.render()})),this.tabs.appendChild(d)}let a=`${this.prefs.tab}|${this.current}|${e?"r":"n"}|${this.prefs.tab==="requests"?`${this.list.length}.${this.listVersion}`:0}`;if(this.prefs.tab==="signin"&&this.renderedFor?.startsWith("signin|")&&!this.signInDirty)return;if(a===this.renderedFor)return;this.renderedFor=a,E(this.body),this.body.scrollTop=0,this.body.setAttribute("aria-label",t.find((i)=>i.id===this.prefs.tab)?.label??"Section"),this.body.appendChild(this.panelFor(this.prefs.tab,e))}panelFor(e,t){try{if(e==="requests")return se(this);if(e==="signin")return this.signInDirty=!1,ie(this,()=>{this.signInDirty=!0});if(!t){let n=this.list.find((s)=>s.id===this.current);return w(n?.missing?"This request's record is not on disk. It may have been pruned, or the server restarted before it was written.":"Loading the record...")}switch(e){case"messages":return _(t);case"timeline":return W(t);case"queries":return U(t,this);case"exceptions":return X(t);case"logs":return Q(t);case"route":return Z(t);case"events":return J(t);case"cache":return V(t);case"mail":return G(t);case"jobs":return Y(t);case"auth":return ee(t);case"request":return te(t);case"environment":return ne(t)}if(e.startsWith("custom:"))return re(t,e.slice(7));return w("Nothing to show.")}catch{return w("This section could not be drawn.")}}chip(e,t,n,...s){let a=this.prefs.open&&!this.prefs.minimized&&this.prefs.tab===e,i=r("button",{class:`chip${n?` ${n}`:""}`,type:"button",title:t,"aria-pressed":String(a)},...s);return i.addEventListener("click",u(()=>this.toggle(e))),i}renderChips(e){if(E(this.chips),!e){let i=this.list.find((o)=>o.id===this.current);this.chips.appendChild(r("span",{class:"chip"},r("span",{class:"lbl"},i?.missing?"No record for this request":"Loading...")));return}let t=e.summary,n=e.collectors.queries,s=t.status>=500?"bad":t.status>=400?"warn":"ok",a=(n?.failed??0)>0?"bad":(n?.nPlusOne?.length??0)>0||(n?.slow??0)>0?"warn":"";if(this.chips.append(this.chip("request","Response status. Opens Request.",s,r("b",null,String(t.status))),this.chip("route","Route. Opens Route.","",r("span",{class:"route"},t.route??`${t.method} ${t.path}`)),this.chip("timeline","Total time. Opens Timeline.","",r("b",null,x(t.duration))),this.chip("queries","Queries. Opens Queries.",a,r("span",{class:"lbl"},"SQL"),r("b",null,String(t.queries)),t.queries>0&&r("span",{class:"lbl"},x(t.queryDuration))),this.chip("timeline","Resident memory of the server process. Opens Timeline.","",r("span",{class:"lbl"},"MEM"),r("b",null,R(t.memory*1048576)))),t.logs>0)this.chips.appendChild(this.chip(e.collectors.messages?"messages":"logs","Messages and log lines.","",r("span",{class:"lbl"},"LOG"),r("b",null,String(t.logs))));if(t.exceptions>0)this.chips.appendChild(this.chip("exceptions","Exceptions. Opens Exceptions.","bad",r("span",{class:"lbl"},"ERR"),r("b",null,String(t.exceptions))));this.chips.appendChild(this.chip(this.options.signInAs!==!1?"signin":"auth","Who this request was signed in as.","",r("span",{class:"lbl"},"USER"),r("b",null,t.user?t.user.name??`#${t.user.id}`:"guest")))}renderSwitcher(){let e=[...this.list].reverse().map((n)=>{let s=n.id===this.pageId?"page":n.kind,a=`${n.status??"..."} ${n.method} ${n.url.length>60?`${n.url.slice(0,57)}...`:n.url} (${s})`,i=r("option",{value:n.id},a);return i.selected=n.id===this.current,i});E(this.switcher),this.switcher.append(...e);let t=this.list.length-1;this.switcher.title=t>0?`${t} more ${t===1?"request":"requests"} made by this page`:"Requests made by this page"}renderBadge(e){E(this.badge);let t=e?.summary.status??0,n=t>=500||(e?.summary.exceptions??0)>0?"bad":t>=400?"warn":"";this.badge.title=this.shortcutHint("Show the debugbar"),this.badge.append(r("span",{class:`dot ${n}`}),e?`${x(e.summary.duration)} ${e.summary.queries} SQL`:"Stacks")}}function ce(e){try{let t=new URL(e,location.href);return{path:t.origin===location.origin?t.pathname+t.search:t.href,internal:t.origin===location.origin&&t.pathname.startsWith(oe)}}catch{return}}function Le(e,t){let n=(o,d,l,g,m)=>{try{let b=ce(l);if(!o||!b||b.internal||!/^[0-9a-z]{20,32}$/.test(o))return;e()?.note({id:o,method:d.toUpperCase(),url:b.path,status:g,kind:m?"fragment":"api"})}catch{}};window.fetch=function(d,l){let g=t(d,l);try{let m=typeof Request<"u"&&d instanceof Request?d:void 0,b=m?m.url:String(d),c=l?.method??m?.method??"GET";g.then((p)=>{let h=p.headers.get("content-type")??"";n(p.headers.get(ve),c,b,p.status,h.startsWith("text/html"))},()=>{})}catch{}return g};let s=XMLHttpRequest.prototype.open,a=XMLHttpRequest.prototype.send,i=new WeakMap;XMLHttpRequest.prototype.open=function(d,l,...g){try{i.set(this,{method:d,url:String(l)})}catch{}return s.call(this,d,l,...g)},XMLHttpRequest.prototype.send=function(d){try{this.addEventListener("loadend",()=>{try{let l=i.get(this),g=/^x-debugbar-id:\s*(\S+)/im.exec(this.getAllResponseHeaders()||"");if(l&&g)n(g[1],l.method,l.url,this.status,(this.getResponseHeader("content-type")??"").startsWith("text/html"))}catch{}})}catch{}return a.call(this,d)}}function Te(e){let t=(n)=>{for(let s of n){if(s.initiatorType!=="fetch"&&s.initiatorType!=="xmlhttprequest")continue;let a=s.serverTiming?.find((o)=>o.name==="debugbar")?.description,i=a?ce(s.name):void 0;if(!a||!i||i.internal||!/^[0-9a-z]{20,32}$/.test(a))continue;e.note({id:a,method:"",url:i.path,status:s.responseStatus||void 0,kind:"api"})}};try{new PerformanceObserver(u((n)=>t(n.getEntries()))).observe({type:"resource",buffered:!0})}catch{try{t(performance.getEntriesByType("resource"))}catch{}}}function $e(){let e=window,t=document.currentScript??document.querySelector("script[data-stacks-debugbar]:last-of-type"),n=t?.dataset.id,s=t?.dataset.token??"";if(!n)return;if(e.__stacksDebugbar){e.__stacksDebugbar.page(n,s);return}let a={};try{a=JSON.parse(t?.dataset.options??"{}")}catch{}let i=window.fetch.bind(window),o;Le(()=>o,i),e.__stacksDebugbar={page:(l,g)=>o?.page(l,g)};let d=()=>{o=new de(n,s,a,i),Te(o),window.addEventListener("stx:navigate",u((l)=>{o?.navigated(l.detail?.url)}))};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",u(d),{once:!0});else d()}try{$e()}catch{}})();
234
+ `;var ye="x-debugbar-id",le="/__debugbar/",de="stacks-debugbar",we=60,j=34,oe=[["messages","Messages"],["timeline","Timeline"],["queries","Queries"],["models","Models"],["exceptions","Exceptions"],["logs","Logs"],["route","Route"],["events","Events"],["cache","Cache"],["mail","Mail"],["jobs","Jobs"],["auth","Auth"],["request","Request"],["environment","Environment"]],xe=new Set(["views"]),ke=new Set(["timeline","queries","request"]);function Ee(){let e={open:!1,minimized:!1,tab:"queries",height:320,follow:!1,interpolate:!1};try{let t=JSON.parse(localStorage.getItem(de)??"{}");return{open:t.open===!0,minimized:t.minimized===!0,tab:typeof t.tab==="string"?t.tab:e.tab,height:typeof t.height==="number"&&t.height>=120?t.height:e.height,follow:t.follow===!0,interpolate:t.interpolate===!0}}catch{return e}}function Se(e){let t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("aria-hidden","true");let n=document.createElementNS("http://www.w3.org/2000/svg","path");return n.setAttribute("d",e),t.appendChild(n),t}function Le(e){if(!e)return;let t=e.toLowerCase().split("+").map((a)=>a.trim()).filter(Boolean),n=t.pop();if(!n)return;let r=(a)=>t.includes(a);return(a)=>a.altKey===r("alt")&&a.shiftKey===r("shift")&&a.ctrlKey===(r("ctrl")||r("control"))&&a.metaKey===(r("meta")||r("cmd"))&&(a.key.toLowerCase()===n||a.code.toLowerCase()===`key${n}`||a.code.toLowerCase()===n)}class ce{options;token;prefs;serverEntries;nativeFetch;list=[];current;pageId;host;root;chips;tabs;body;panel;switcher;badge;brand;resizer;originalPadding;renderedFor;tabsSignature;listVersion=0;signInDirty=!0;constructor(e,t,n,r){this.options=n,this.token=t,this.pageId=e,this.nativeFetch=r,this.prefs=Ee(),this.host=document.createElement("stacks-debugbar"),this.host.setAttribute("data-stacks-debugbar-host","");let a=this.host.attachShadow({mode:"closed"});this.adoptStyles(a),this.brand=s("button",{class:"brand",type:"button","aria-expanded":"false",title:this.shortcutHint("Toggle the panel")},"Stacks",s("span",{class:"caret"})),this.chips=s("div",{class:"chips"}),this.switcher=s("select",{class:"switch","aria-label":"Request to inspect",title:"Requests made by this page"}),this.resizer=s("div",{class:"resize",role:"separator",tabindex:"0","aria-orientation":"horizontal","aria-label":"Resize the panel"}),this.tabs=s("div",{class:"tabs",role:"tablist","aria-label":"Debugbar sections"}),this.body=s("div",{class:"body",role:"tabpanel",tabindex:"0"}),this.panel=s("div",{class:"panel"},this.resizer,this.tabs,this.body);let i=s("button",{class:"icon",type:"button","aria-label":"Minimise the debugbar",title:"Minimise"},Se("M3 12h10"));this.badge=s("button",{class:"badge",type:"button","aria-label":"Show the debugbar"}),this.root=s("div",{class:"root"},this.panel,s("div",{class:"bar",role:"toolbar","aria-label":"Stacks debugbar"},this.brand,this.chips,s("div",{class:"tools"},this.switcher,i))),a.append(this.root,this.badge),this.brand.addEventListener("click",u(()=>this.toggle())),i.addEventListener("click",u(()=>this.setMinimized(!0))),this.badge.addEventListener("click",u(()=>this.setMinimized(!1))),this.switcher.addEventListener("change",u(()=>this.select(this.switcher.value))),this.root.addEventListener("keydown",u((o)=>this.onKey(o))),this.bindResize(),this.bindShortcut(),this.mount(),this.note({id:e,method:"GET",url:location.pathname+location.search,kind:"page",status:void 0}),this.current=e,this.apply(),this.load(e)}entries(){return this.list}currentId(){return this.current}select(e){if(!this.list.some((t)=>t.id===e))this.list.push({id:e,method:"",url:"",kind:"api",at:Date.now()});this.current=e,this.render(),this.load(e)}savePrefs(){try{localStorage.setItem(de,JSON.stringify(this.prefs))}catch{}}request(e,t){return this.nativeFetch(le+e,{credentials:"same-origin",...t})}async recent(){let e=await this.request("requests?limit=50");return e.ok?(await e.json()).requests:[]}async clearRecords(){await this.request("requests",{method:"DELETE",headers:{"X-Debugbar-Token":this.token}})}page(e,t){if(t)this.token=t;this.pageId=e,this.signInDirty=!0;let n=this.list.find((r)=>r.id===e);if(n)n.kind=n.kind==="api"?"fragment":n.kind;else this.note({id:e,method:"GET",url:location.pathname+location.search,kind:"page",status:void 0});this.mount(),this.select(e)}note(e){let t=this.list.find((n)=>n.id===e.id);if(t){t.status??=e.status;return}if(this.list.push({...e,at:Date.now()}),!e.method)this.load(e.id);if(this.list.length>we){let n=this.list.findIndex((r)=>r.id!==this.pageId&&r.id!==this.current);if(n>=0)this.list.splice(n,1)}if(this.prefs.follow&&e.kind==="api"&&this.current!==void 0)this.select(e.id);else if(this.current!==void 0)this.render()}navigated(e){let t;try{let a=new URL(e??location.href,location.href);t=a.pathname+a.search}catch{}let n=this.list.filter((a)=>a.kind!=="api"&&a.id!==this.pageId),r=[...n].reverse().find((a)=>a.url===t)??n[n.length-1];if(r)this.page(r.id);else this.mount()}mount(){if(!this.host.isConnected)(document.documentElement??document.body).appendChild(this.host)}adoptStyles(e){try{let t=new CSSStyleSheet;t.replaceSync(I),e.adoptedStyleSheets=[t]}catch{e.appendChild(s("style",null,I))}}async load(e){let t=this.list.find((n)=>n.id===e);if(!t||t.record)return;for(let n of[0,60,140,300,600,1200]){if(n>0)await new Promise((r)=>setTimeout(r,n));try{let r=await this.request(`requests/${e}`);if(r.ok){t.record=await r.json(),t.status=t.record.summary.status,t.method=t.record.summary.method,t.url=t.record.summary.url,t.kind=t.record.summary.kind;break}if(r.status!==404)break}catch{break}}if(!t.record)t.missing=!0;this.listVersion++,this.render()}toggle(e){if(e&&(this.prefs.tab!==e||!this.prefs.open))this.prefs.tab=e,this.prefs.open=!0;else this.prefs.open=!this.prefs.open;this.prefs.minimized=!1,this.savePrefs(),this.apply()}setMinimized(e){this.prefs.minimized=e,this.savePrefs(),this.apply(),(e?this.badge:this.brand).focus()}maxHeight(){return Math.max(160,window.innerHeight-j-40)}apply(){let e=this.prefs.open&&!this.prefs.minimized;this.root.toggleAttribute("data-open",e),this.root.toggleAttribute("data-min",this.prefs.minimized),this.badge.toggleAttribute("data-show",this.prefs.minimized),this.brand.setAttribute("aria-expanded",String(e));let t=Math.min(this.prefs.height,this.maxHeight());this.panel.style.height=`${t}px`,this.resizer.setAttribute("aria-valuenow",String(Math.round(t))),this.resizer.setAttribute("aria-valuemin","120"),this.resizer.setAttribute("aria-valuemax",String(this.maxHeight())),this.pad(e?t+j:0),this.render()}pad(e){let t=document.documentElement;if(e>0){if(this.originalPadding===void 0)this.originalPadding=t.style.paddingBottom;t.style.paddingBottom=`${e}px`}else if(this.originalPadding!==void 0)t.style.paddingBottom=this.originalPadding,this.originalPadding=void 0}shortcutHint(e){return this.options.shortcut?`${e} (${this.options.shortcut})`:e}bindShortcut(){let e=Le(this.options.shortcut);if(!e)return;window.addEventListener("keydown",u((t)=>{if(!e(t))return;if(t.preventDefault(),this.prefs.minimized)this.setMinimized(!1);else this.toggle();if(this.prefs.open)this.brand.focus()}),!0)}onKey(e){if(e.key==="Escape"&&this.prefs.open){e.stopPropagation(),this.toggle(),this.brand.focus();return}let t=e.target;if(t?.getAttribute("role")!=="tab")return;let n=[...this.tabs.querySelectorAll('[role="tab"]')],r=n.indexOf(t),a=e.key==="ArrowRight"?n[(r+1)%n.length]:e.key==="ArrowLeft"?n[(r-1+n.length)%n.length]:e.key==="Home"?n[0]:e.key==="End"?n[n.length-1]:void 0;if(!a)return;e.preventDefault(),this.prefs.tab=a.dataset.tab??this.prefs.tab,this.savePrefs(),this.render(),this.tabs.querySelector('[aria-selected="true"]')?.focus()}bindResize(){let e=(t)=>{this.prefs.height=Math.round(Math.min(this.maxHeight(),Math.max(120,t))),this.apply()};this.resizer.addEventListener("pointerdown",u((t)=>{t.preventDefault();let n=t.clientY,r=this.panel.getBoundingClientRect().height;this.resizer.setAttribute("data-drag",""),this.resizer.setPointerCapture(t.pointerId);let a=u((o)=>{this.prefs.height=Math.round(Math.min(this.maxHeight(),Math.max(120,r+n-o.clientY))),this.panel.style.height=`${this.prefs.height}px`,this.pad(this.prefs.height+j)}),i=u(()=>{this.resizer.removeAttribute("data-drag"),this.resizer.removeEventListener("pointermove",a),this.resizer.removeEventListener("pointerup",i),this.resizer.removeEventListener("pointercancel",i),this.savePrefs(),this.apply()});this.resizer.addEventListener("pointermove",a),this.resizer.addEventListener("pointerup",i),this.resizer.addEventListener("pointercancel",i)})),this.resizer.addEventListener("keydown",u((t)=>{let n=t.shiftKey?80:24;if(t.key==="ArrowUp")e(this.prefs.height+n);else if(t.key==="ArrowDown")e(this.prefs.height-n);else return;t.preventDefault(),this.savePrefs()})),window.addEventListener("resize",u(()=>{if(this.prefs.open&&!this.prefs.minimized)this.apply()}))}record(){return this.list.find((e)=>e.id===this.current)?.record}tabSpecs(e){let t=[],n=e?.collectors??{},r=(i)=>Array.isArray(n[i])?n[i].length:void 0;for(let[i,o]of oe){if(!(i==="route"?n.route!==void 0||n.views!==void 0:n[i]!==void 0)&&!ke.has(i))continue;let l={id:i,label:o};if(i==="queries"){let g=n.queries;if(l.count=g?.count??0,(g?.failed??0)>0)l.tone="bad";else if((g?.nPlusOne?.length??0)>0||(g?.slow??0)>0)l.tone="warn"}else if(i==="models")l.count=n.models?.total;else if(i==="cache")l.count=n.cache?.operations?.length;else if(i==="exceptions")l.count=r(i),l.tone="bad";else if(i==="messages"||i==="logs"||i==="events"||i==="mail"||i==="jobs")l.count=r(i);t.push(l)}let a=new Set(oe.map(([i])=>i));for(let i of Object.keys(n))if(!a.has(i)&&!xe.has(i))t.push({id:`custom:${i}`,label:e?.labels?.[i]??i});if(t.push({id:"requests",label:"Requests",count:this.list.length}),this.options.signInAs!==!1)t.push({id:"signin",label:"Sign in as"});return t}render(){let e=this.record();if(this.renderChips(e),this.renderSwitcher(),this.renderBadge(e),!this.prefs.open||this.prefs.minimized)return;let t=this.tabSpecs(e);if(!t.some((i)=>i.id===this.prefs.tab))this.prefs.tab=t.some((i)=>i.id==="queries")?"queries":t[0].id;let n=JSON.stringify([t,this.prefs.tab]),r=n===this.tabsSignature;if(this.tabsSignature=n,!r)E(this.tabs);for(let i of r?[]:t){let o=i.id===this.prefs.tab,d=s("button",{class:"tab",type:"button",role:"tab","aria-selected":String(o),tabindex:o?"0":"-1","data-tab":i.id},i.label,i.count!==void 0&&i.count>0&&s("span",{class:`count${i.tone?` ${i.tone}`:""}`},String(i.count)));d.addEventListener("click",u(()=>{this.prefs.tab=i.id,this.savePrefs(),this.render()})),this.tabs.appendChild(d)}let a=`${this.prefs.tab}|${this.current}|${e?"r":"n"}|${this.prefs.tab==="requests"?`${this.list.length}.${this.listVersion}`:0}`;if(this.prefs.tab==="signin"&&this.renderedFor?.startsWith("signin|")&&!this.signInDirty)return;if(a===this.renderedFor)return;this.renderedFor=a,E(this.body),this.body.scrollTop=0,this.body.setAttribute("aria-label",t.find((i)=>i.id===this.prefs.tab)?.label??"Section"),this.body.appendChild(this.panelFor(this.prefs.tab,e))}panelFor(e,t){try{if(e==="requests")return ie(this);if(e==="signin")return this.signInDirty=!1,ae(this,()=>{this.signInDirty=!0});if(!t){let n=this.list.find((r)=>r.id===this.current);return y(n?.missing?"This request's record is not on disk. It may have been pruned, or the server restarted before it was written.":"Loading the record...")}switch(e){case"messages":return _(t);case"timeline":return X(t);case"queries":return U(t,this);case"models":return W(t);case"exceptions":return J(t);case"logs":return Q(t);case"route":return ee(t);case"events":return V(t);case"cache":return G(t);case"mail":return Y(t);case"jobs":return Z(t);case"auth":return te(t);case"request":return ne(t);case"environment":return se(t)}if(e.startsWith("custom:"))return re(t,e.slice(7));return y("Nothing to show.")}catch{return y("This section could not be drawn.")}}chip(e,t,n,...r){let a=this.prefs.open&&!this.prefs.minimized&&this.prefs.tab===e,i=s("button",{class:`chip${n?` ${n}`:""}`,type:"button",title:t,"aria-pressed":String(a)},...r);return i.addEventListener("click",u(()=>this.toggle(e))),i}renderChips(e){if(E(this.chips),!e){let i=this.list.find((o)=>o.id===this.current);this.chips.appendChild(s("span",{class:"chip"},s("span",{class:"lbl"},i?.missing?"No record for this request":"Loading...")));return}let t=e.summary,n=e.collectors.queries,r=t.status>=500?"bad":t.status>=400?"warn":"ok",a=(n?.failed??0)>0?"bad":(n?.nPlusOne?.length??0)>0||(n?.slow??0)>0?"warn":"";if(this.chips.append(this.chip("request","Response status. Opens Request.",r,s("b",null,String(t.status))),this.chip("route","Route. Opens Route.","",s("span",{class:"route"},t.route??`${t.method} ${t.path}`)),this.chip("timeline","Total time. Opens Timeline.","",s("b",null,x(t.duration))),this.chip("queries","Queries. Opens Queries.",a,s("span",{class:"lbl"},"SQL"),s("b",null,String(t.queries)),t.queries>0&&s("span",{class:"lbl"},x(t.queryDuration))),this.chip("timeline","Resident memory of the server process. Opens Timeline.","",s("span",{class:"lbl"},"MEM"),s("b",null,M(t.memory*1048576)))),(t.models??0)>0)this.chips.appendChild(this.chip("models","Hydrated models. Opens Models.","",s("span",{class:"lbl"},"MOD"),s("b",null,String(t.models))));if(t.logs>0)this.chips.appendChild(this.chip(e.collectors.messages?"messages":"logs","Messages and log lines.","",s("span",{class:"lbl"},"LOG"),s("b",null,String(t.logs))));if(t.exceptions>0)this.chips.appendChild(this.chip("exceptions","Exceptions. Opens Exceptions.","bad",s("span",{class:"lbl"},"ERR"),s("b",null,String(t.exceptions))));this.chips.appendChild(this.chip(this.options.signInAs!==!1?"signin":"auth","Who this request was signed in as.","",s("span",{class:"lbl"},"USER"),s("b",null,t.user?t.user.name??`#${t.user.id}`:"guest")))}renderSwitcher(){let e=[...this.list].reverse().map((n)=>{let r=n.id===this.pageId?"page":n.kind,a=`${n.status??"..."} ${n.method} ${n.url.length>60?`${n.url.slice(0,57)}...`:n.url} (${r})`,i=s("option",{value:n.id},a);return i.selected=n.id===this.current,i});E(this.switcher),this.switcher.append(...e);let t=this.list.length-1;this.switcher.title=t>0?`${t} more ${t===1?"request":"requests"} made by this page`:"Requests made by this page"}renderBadge(e){E(this.badge);let t=e?.summary.status??0,n=t>=500||(e?.summary.exceptions??0)>0?"bad":t>=400?"warn":"";this.badge.title=this.shortcutHint("Show the debugbar"),this.badge.append(s("span",{class:`dot ${n}`}),e?`${x(e.summary.duration)} ${e.summary.queries} SQL`:"Stacks")}}function ue(e){try{let t=new URL(e,location.href);return{path:t.origin===location.origin?t.pathname+t.search:t.href,internal:t.origin===location.origin&&t.pathname.startsWith(le)}}catch{return}}function Te(e,t){let n=(o,d,l,g,f)=>{try{let b=ue(l);if(!o||!b||b.internal||!/^[0-9a-z]{20,32}$/.test(o))return;e()?.note({id:o,method:d.toUpperCase(),url:b.path,status:g,kind:f?"fragment":"api"})}catch{}};window.fetch=function(d,l){let g=t(d,l);try{let f=typeof Request<"u"&&d instanceof Request?d:void 0,b=f?f.url:String(d),c=l?.method??f?.method??"GET";g.then((p)=>{let h=p.headers.get("content-type")??"";n(p.headers.get(ye),c,b,p.status,h.startsWith("text/html"))},()=>{})}catch{}return g};let r=XMLHttpRequest.prototype.open,a=XMLHttpRequest.prototype.send,i=new WeakMap;XMLHttpRequest.prototype.open=function(d,l,...g){try{i.set(this,{method:d,url:String(l)})}catch{}return r.call(this,d,l,...g)},XMLHttpRequest.prototype.send=function(d){try{this.addEventListener("loadend",()=>{try{let l=i.get(this),g=/^x-debugbar-id:\s*(\S+)/im.exec(this.getAllResponseHeaders()||"");if(l&&g)n(g[1],l.method,l.url,this.status,(this.getResponseHeader("content-type")??"").startsWith("text/html"))}catch{}})}catch{}return a.call(this,d)}}function $e(e){let t=(n)=>{for(let r of n){if(r.initiatorType!=="fetch"&&r.initiatorType!=="xmlhttprequest")continue;let a=r.serverTiming?.find((o)=>o.name==="debugbar")?.description,i=a?ue(r.name):void 0;if(!a||!i||i.internal||!/^[0-9a-z]{20,32}$/.test(a))continue;e.note({id:a,method:"",url:i.path,status:r.responseStatus||void 0,kind:"api"})}};try{new PerformanceObserver(u((n)=>t(n.getEntries()))).observe({type:"resource",buffered:!0})}catch{try{t(performance.getEntriesByType("resource"))}catch{}}}function qe(){let e=window,t=document.currentScript??document.querySelector("script[data-stacks-debugbar]:last-of-type"),n=t?.dataset.id,r=t?.dataset.token??"";if(!n)return;if(e.__stacksDebugbar){e.__stacksDebugbar.page(n,r);return}let a={};try{a=JSON.parse(t?.dataset.options??"{}")}catch{}let i=window.fetch.bind(window),o;Te(()=>o,i),e.__stacksDebugbar={page:(l,g)=>o?.page(l,g)};let d=()=>{o=new ce(n,r,a,i),$e(o),window.addEventListener("stx:navigate",u((l)=>{o?.navigated(l.detail?.url)}))};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",u(d),{once:!0});else d()}try{qe()}catch{}})();
@@ -0,0 +1,8 @@
1
+ import type { Collector, CollectorContext } from '../collectors';
2
+ /** The ORM hydration hook handed to `@stacksjs/query-builder`. Separate so tests can drive it directly. */
3
+ export declare function createModelHydrationHook({ current }: Pick<CollectorContext, 'current'>): (event: ModelHydrateEvent) => void;
4
+ export declare const modelsCollector: Collector;
5
+ export declare interface ModelHydrateEvent {
6
+ model: string
7
+ table?: string
8
+ }
package/dist/guard.d.ts CHANGED
@@ -1,12 +1,3 @@
1
- /**
2
- * Who may talk to the debugbar.
3
- *
4
- * A dev server is often reachable from more than the machine it runs on: a
5
- * `0.0.0.0` bind, a tunnel, a phone on the same network. The records hold
6
- * request data and one endpoint issues sign-in tokens, so by default
7
- * everything under `/__debugbar/` answers only a client on this machine,
8
- * asking for this machine by a local name.
9
- */
10
1
  export declare function isLoopbackAddress(address: string | null | undefined): boolean;
11
2
  /** A hostname that can only resolve to this machine, or the app's own dev host. */
12
3
  export declare function isLocalHostname(host: string | null | undefined, appUrl?: string): boolean;
package/dist/index.d.ts CHANGED
@@ -34,7 +34,7 @@ export { BUILT_IN_COLLECTOR_NAMES } from './collectors/index';
34
34
  export { Collection, createRecordId, currentCollection, isRecordId, runWithCollection, withoutCollection } from './context';
35
35
  export { DEBUGBAR_PREFIX, handleDebugbarRequest, isDebugbarPath, signInAsUsers } from './endpoints';
36
36
  export { isLocalHostname, isLocalRequest, isLoopbackAddress, isSameOriginRequest } from './guard';
37
- export { DEBUGBAR_ASSET_PATH, DEBUGBAR_ID_HEADER, debugbarScriptTag, injectDebugbar, isInjectableDocument, withRecordId } from './inject';
37
+ export { DEBUGBAR_ASSET_PATH, DEBUGBAR_ID_HEADER, debugbarScriptTag, extractCspScriptNonce, injectDebugbar, injectDebugbarResponse, isInjectableDocument, withRecordId } from './inject';
38
38
  export { createApiDebugbarMiddleware, installApiDebugbar } from './middleware';
39
39
  export { isSensitiveName, redact, redactBindings, redactHeaders, redactQuery, redactUrl, REDACTED } from './redact';
40
40
  export { capturedSocketPeer, captureSocketPeers, peerAwareServer } from './peer';
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  // @bun
2
- import{AsyncLocalStorage as br}from"async_hooks";var hr=Symbol.for("stacks.debugbar.collection"),X=globalThis[hr]??=new br,yr=1000,me=0;function it(e=Date.now()){me=(me+1)%1296;let t=crypto.getRandomValues(new Uint32Array(2));return e.toString(36).padStart(9,"0")+me.toString(36).padStart(2,"0")+t[0].toString(36).padStart(7,"0").slice(-7)+t[1].toString(36).padStart(7,"0").slice(-6)}var wr=/^[0-9a-z]{20,32}$/;function q(e){return typeof e==="string"&&wr.test(e)}class Z{id;process;request;url;config;startedAt;startedMs;kind;finished=!1;duration;bags=new Map;overflow=new Map;values=new Map;constructor(e,t,r){this.id=it(),this.process=t,this.request=e,this.url=new URL(e.url),this.config=r,this.startedAt=Date.now(),this.startedMs=performance.now(),this.kind=t==="api"?"api":"page"}elapsed(){return this.duration??performance.now()-this.startedMs}push(e,t,r=yr){if(this.finished)return;let n=this.bags.get(e);if(!n)n=[],this.bags.set(e,n);if(n.length>=r){this.overflow.set(e,(this.overflow.get(e)??0)+1);return}n.push(t)}list(e){return this.bags.get(e)??[]}dropped(e){return this.overflow.get(e)??0}set(e,t){if(!this.finished)this.values.set(e,t)}get(e){return this.values.get(e)}}function w(){let e=X.getStore();return e&&!e.finished?e:void 0}function ge(e,t){return X.run(e,t)}function at(e){X.enterWith(e)}function k(e){return X.run(void 0,e)}var xr="[redacted]",kr=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-csrf-token","x-xsrf-token","x-api-key","x-auth-token","x-debugbar-token"]),Rr=new Set(["password","passwd","passphrase","pwd","secret","secrets","token","tokens","key","keys","apikey","authorization","auth","credential","credentials","signature","cookie","cookies","session","csrf","xsrf","dsn","otp","pin","cvv","cvc","ssn"]),be=new Map;function L(e){let t=be.get(e);if(t!==void 0)return t;let n=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).some((o)=>Rr.has(o))||/password|secret|token|apikey/i.test(e);if(be.size<2000)be.set(e,n);return n}function he(e){if(e.length<20)return!1;if(/^\$(?:2[aby]|argon2(?:id|i|d)|scrypt|pbkdf2)[$-]/.test(e))return!0;if(/^eyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]*$/.test(e))return!0;if(/^(?:sk|pk|rk|whsec|ghp|gho|xox[abp])[-_][\w-]{16,}$/.test(e))return!0;return e.length>=40&&/^[a-f0-9]+$/i.test(e)}function Y(e){let t={};if(!e)return t;return e.forEach((r,n)=>{let o=n.toLowerCase();t[o]=kr.has(o)||L(o)?"[redacted]":U(r,2000)}),t}function ct(e){if(!e)return[];let t=[];for(let r of e.split(";")){let n=r.split("=",1)[0]?.trim();if(n)t.push(n)}return t}function ye(e){let t={};for(let r of new Set(e.keys())){let n=L(r)?["[redacted]"]:e.getAll(r).map((o)=>he(o)?"[redacted]":U(o,500));t[r]=n.length===1?n[0]:n}return t}function j(e){if(!e.search)return e.pathname;let t=[];for(let[r,n]of e.searchParams){let o=L(r)||he(n)?"[redacted]":n;t.push(`${encodeURIComponent(r)}=${o==="[redacted]"?"[redacted]":encodeURIComponent(o)}`)}return`${e.pathname}?${t.join("&")}`}function U(e,t){return e.length>t?`${e.slice(0,t)}... (${e.length} chars)`:e}function m(e,t={}){let r={maxDepth:t.maxDepth??6,maxKeys:t.maxKeys??60,maxItems:t.maxItems??60,maxString:t.maxString??2000};return S(e,r,0,new WeakSet)}function S(e,t,r,n){if(e===null||e===void 0)return e??null;switch(typeof e){case"string":return U(e,t.maxString);case"number":return Number.isFinite(e)?e:String(e);case"boolean":return e;case"bigint":return`${e}n`;case"symbol":return e.toString();case"function":return`[function ${e.name||"anonymous"}]`}let o=e;if(n.has(o))return"[circular]";if(r>=t.maxDepth)return Array.isArray(o)?`[array(${o.length})]`:"[object]";if(o instanceof Date)return Number.isNaN(o.getTime())?"Invalid Date":o.toISOString();if(o instanceof Error)return{name:o.name,message:U(o.message,t.maxString)};if(o instanceof URL)return j(o);if(typeof Request<"u"&&o instanceof Request)return`[Request ${o.method} ${Cr(o.url)}]`;if(typeof Response<"u"&&o instanceof Response)return`[Response ${o.status}]`;if(ArrayBuffer.isView(o)||o instanceof ArrayBuffer)return`[binary ${o.byteLength} bytes]`;n.add(o);try{if(Array.isArray(o)){let u=o.slice(0,t.maxItems).map((c)=>S(c,t,r+1,n));if(o.length>t.maxItems)u.push(`... ${o.length-t.maxItems} more`);return u}if(o instanceof Map)return S(Object.fromEntries([...o.entries()].slice(0,t.maxKeys).map(([u,c])=>[String(u),c])),t,r,n);if(o instanceof Set)return S([...o],t,r,n);let s=typeof o.toJSON==="function"?ut(()=>o.toJSON()):o;if(s===null||typeof s!=="object")return S(s,t,r+1,n);if(s!==o&&Array.isArray(s))return S(s,t,r,n);let i={},a=0;for(let u of Object.keys(s)){if(a++>=t.maxKeys){i["..."]=`${Object.keys(s).length-t.maxKeys} more keys`;break}i[u]=L(u)?"[redacted]":S(ut(()=>s[u]),t,r+1,n)}return i}finally{n.delete(o)}}function ut(e){try{return e()}catch{return"[unreadable]"}}function Cr(e){try{return new URL(e).pathname}catch{return""}}function we(e){if(!e)return[];return e.slice(0,100).map((t)=>{if(typeof t==="string")return he(t)?"[redacted]":U(t,500);if(t===null||typeof t==="number"||typeof t==="boolean")return t;if(typeof t==="bigint")return`${t}n`;if(t instanceof Date)return Number.isNaN(t.getTime())?"Invalid Date":t.toISOString();if(ArrayBuffer.isView(t)||t instanceof ArrayBuffer)return`[binary ${t.byteLength} bytes]`;return m(t,{maxDepth:3,maxString:500})})}function Er(e){if(typeof e==="string")return e;if(e instanceof Error)return`${e.name}: ${e.message}`;try{return JSON.stringify(m(e))??String(e)}catch{return String(e)}}function v(e,t,r="info",n){let o=w();if(!o)return;o.push("messages",{level:r,label:t,message:Er(e).slice(0,4000),context:n===void 0?void 0:m(n),at:o.elapsed()})}function xe(e,t){v(e,void 0,"debug",t)}function ke(e,t){v(e,void 0,"info",t)}function Re(e,t){v(e,void 0,"warning",t)}function Ce(e,t){v(e,void 0,"error",t)}function Ee(e,t){let r=w();if(!r)return;let n=r.get("measures:open");if(!n)n=new Map,r.set("measures:open",n);n.set(e,{label:t??e,start:r.elapsed()})}function Se(e){let t=w(),r=t?.get("measures:open"),n=r?.get(e);if(!t||!r||!n)return;r.delete(e),t.push("measures",{label:n.label,start:n.start,duration:t.elapsed()-n.start,group:"measure"})}function ve(e,t,r,n="measure"){w()?.push("measures",{label:e,start:t,duration:r,group:n})}function De(e,t){let r=w();if(!r)return t();let n=r.elapsed(),o=()=>{r.push("measures",{label:e,start:n,duration:r.elapsed()-n,group:"measure"})},s;try{s=t()}catch(i){throw o(),i}if(s instanceof Promise)return s.finally(o);return o(),s}var R=new Map,ee=new Map,C;function lt(e,t){if(!e.install)return;try{let r=e.install(t),n=(o)=>{if(typeof o!=="function")return;if(C!==t||R.get(e.name)!==e)o();else ee.set(e.name,o)};if(r instanceof Promise)r.then(n,()=>{});else n(r)}catch{}}function Ae(e){let t=ee.get(e);ee.delete(e);try{t?.()}catch{}}function _(e){if(!e||typeof e.name!=="string"||!/^[\w-]{1,40}$/.test(e.name))throw TypeError("A debugbar collector needs a name of letters, digits, dashes or underscores.");if(Ae(e.name),R.set(e.name,e),C)lt(e,C);return()=>{if(R.get(e.name)!==e)return;Ae(e.name),R.delete(e.name)}}function Pe(){return[...R.values()]}function dt(e,t){if(C)return;C={config:e,process:t,current:w};for(let r of R.values())lt(r,C)}function ft(){C=void 0;for(let e of[...ee.keys()])Ae(e)}function pt(e){if(!C)return;for(let t of R.values()){if(!t.begin)continue;try{t.begin(e)}catch{}}}async function mt(e,t){let r={},n={};for(let o of R.values()){if(!o.collect)continue;try{let s=await o.collect(e,t);if(s===void 0||s===null)continue;if(r[o.name]=s,o.label)n[o.name]=o.label}catch(s){r[o.name]={error:s instanceof Error?s.message:String(s)}}}return{sections:r,labels:n}}import{randomBytes as tr}from"crypto";import{chmodSync as wn,existsSync as xn,readFileSync as kn,writeFileSync as Rn}from"fs";import{join as rr}from"path";import Cn from"process";import{config as Ke}from"@stacksjs/config";import{projectPath as En,storagePath as Sn}from"@stacksjs/path";var Q=new Map,Sr=3000;function te(e){if(!e||typeof e!=="object")return null;let t=(i)=>{try{return e[i]}catch{return}},r=t("id");if(typeof r!=="number"&&typeof r!=="string")return null;let n=(i)=>{let a=t(i);return typeof a==="string"&&a.trim()?a.trim():void 0},o=n("email"),s=n("name")??([n("first_name")??n("firstName"),n("last_name")??n("lastName")].filter(Boolean).join(" ")||void 0)??n("username")??o??`User #${r}`;return{id:r,name:s,...o&&{email:o}}}function vr(e,t){let r=e.headers.get("authorization");if(r&&/^bearer\s+\S/i.test(r))return{token:r.replace(/^bearer\s+/i,"").trim(),via:"bearer"};let n=t?.(e);return n?{token:n,via:"cookie"}:void 0}async function re(e){try{let t=await import("@stacksjs/auth"),r=vr(e,t.authCookieToken);if(!r)return{user:null,via:"none"};let n=Q.get(r.token);if(n&&Date.now()-n.at<Sr)return{user:n.user,via:r.via};let o=await k(()=>t.Auth.getUserFromToken(r.token)),s=te(o);if(Q.size>100)Q.clear();return Q.set(r.token,{user:s,at:Date.now()}),{user:s,via:r.via}}catch{return{user:null,via:"none"}}}function Me(){Q.clear()}var gt={name:"auth",label:"Auth",async collect(e){let{user:t,via:r}=await re(e.request);return{authenticated:t!==null,guard:r==="none"?"guest":r==="bearer"?"token":"cookie",user:t}}};import{subscribe as Dr,unsubscribe as Ar}from"diagnostics_channel";var bt="stacks:cache:operation",ht={name:"cache",label:"Cache",install({current:e}){let t=(r)=>{let n=e(),o=r;if(!n||typeof o?.key!=="string")return;n.push("cache",{type:o.type,key:o.key.slice(0,500),ttl:o.ttl,duration:o.durationMs,at:n.elapsed()})};return Dr(bt,t),()=>{Ar(bt,t)}},collect(e){let t=e.list("cache");if(t.length===0)return;let r=(n)=>t.filter((o)=>o.type===n).length;return{hits:r("hit"),misses:r("miss"),writes:r("write"),forgets:r("forget"),operations:t}}};import{existsSync as ne,readFileSync as H,statSync as Ir}from"fs";import{join as W,resolve as kt}from"path";import oe from"process";import{config as Rt}from"@stacksjs/config";var yt={name:"@stacksjs/debugbar",type:"module",sideEffects:!1,version:"0.75.735",description:"The Stacks debugbar: a request inspector for development.",author:"Chris Breuer",contributors:["Chris Breuer <chris@stacksjs.com>"],license:"MIT",funding:"https://github.com/sponsors/chrisbbreuer",homepage:"https://github.com/stacksjs/stacks/tree/main/storage/framework/core/debugbar#readme",repository:{type:"git",url:"git+https://github.com/stacksjs/stacks.git",directory:"./storage/framework/core/debugbar"},bugs:{url:"https://github.com/stacksjs/stacks/issues"},keywords:["debugbar","debug","profiler","queries","stacks"],exports:{".":{types:"./dist/index.d.ts",bun:"./dist/index.js",import:"./dist/index.js",default:"./dist/index.js"},"./*":{types:"./dist/*.d.ts",bun:"./dist/*.js",import:"./dist/*.js",default:"./dist/*.js"},"./*.js":{types:"./dist/*.d.ts",bun:"./dist/*.js",import:"./dist/*.js",default:"./dist/*.js"}},module:"dist/index.js",types:"dist/index.d.ts",files:["README.md","dist"],scripts:{build:"bun build.ts",typecheck:"bun tsc --noEmit",prepublishOnly:"bun run build"},devDependencies:{"better-dx":"^0.2.39"},dependencies:{"@stacksjs/auth":"workspace:*","@stacksjs/config":"workspace:*","@stacksjs/database":"workspace:*","@stacksjs/error-handling":"workspace:*","@stacksjs/events":"workspace:*","@stacksjs/logging":"workspace:*","@stacksjs/path":"workspace:*","@stacksjs/query-builder":"workspace:*","@stacksjs/queue":"workspace:*","@stacksjs/router":"workspace:*","@stacksjs/types":"workspace:*"}};import je from"process";var Te=new Set(["production","prod","live"]),Mr=new Set(["local","development","dev"]);function D(e){return typeof e==="string"?e.trim().toLowerCase():""}function wt(e={}){let t=e.env??je.env,r=D(t.APP_ENV);if(Te.has(r)||Te.has(D(e.appEnv)))return!0;return!r&&Te.has(D(t.NODE_ENV))}function Ie(e={}){let t=e.env??je.env;return D(t.APP_ENV)||D(e.appEnv)||D(t.NODE_ENV)}function Tr(e){let t=D((e.env??je.env).APP_DEBUG);return t==="false"||t==="0"||t==="off"||t==="no"}function Ne(e,t={}){if(wt(t))return!1;if(e?.enabled===!1)return!1;if(e?.enabled===!0)return!0;return Mr.has(Ie(t))&&!Tr(t)}function Oe(e,t){let r=e?.queries??{};return{...e,storage:{path:e?.storage?.path||t,maxRequests:qe(e?.storage?.maxRequests,200)},except:Array.isArray(e?.except)?e.except.filter((n)=>typeof n==="string"):[],queries:{slowThresholdMs:qr(r.slowThresholdMs,100),nPlusOneThreshold:Math.max(2,qe(r.nPlusOneThreshold,5)),backtrace:r.backtrace!==!1,maxQueries:qe(r.maxQueries,500)}}}function qe(e,t){let r=Number(e);return Number.isFinite(r)&&r>=1?Math.floor(r):t}function qr(e,t){let r=Number(e);return Number.isFinite(r)&&r>=0?r:t}var jr=/^\/(?:__debugbar|_stx|__deps|__hmr|__stx|@|node_modules)(?:\/|$)|^\/favicon\.|\.(?:js|mjs|css|map|png|jpe?g|gif|svg|ico|webp|avif|woff2?|ttf|otf|eot|mp4|webm|mp3|wasm|txt|xml|webmanifest)$/i;function xt(e,t){if(jr.test(e))return!0;for(let r of t)if(r.endsWith("*")?e.startsWith(r.slice(0,-1)):e===r)return!0;return!1}function Nr(e){try{let t=W(e,".git");if(!ne(t))return{};if(Ir(t).isFile()){let u=/^gitdir:\s*(.+)$/m.exec(H(t,"utf8"));if(!u)return{};t=kt(e,u[1].trim())}let r=H(W(t,"HEAD"),"utf8").trim(),n=/^ref:\s*(.+)$/.exec(r);if(!n)return{sha:r.slice(0,12)};let o=n[1].replace(/^refs\/heads\//,""),s=W(t,"commondir"),i=ne(s)?kt(t,H(s,"utf8").trim()):t;for(let u of[t,i]){let c=W(u,n[1]);if(ne(c))return{branch:o,sha:H(c,"utf8").trim().slice(0,12)}}let a=W(i,"packed-refs");if(ne(a)){let u=H(a,"utf8").split(`
3
- `).find((c)=>c.endsWith(` ${n[1]}`));if(u)return{branch:o,sha:u.slice(0,12)}}return{branch:o}}catch{return{}}}var z;function Or(){if(!z||Date.now()-z.at>5000)z={...Nr(oe.cwd()),at:Date.now()};return{branch:z.branch,sha:z.sha}}function $r(){let e=(r)=>{try{return r()}catch{return}},t=Rt;return m({app:e(()=>({name:t.app?.name,env:t.app?.env,url:t.app?.url,debug:t.app?.debug,timezone:t.app?.timezone,locale:t.app?.locale})),database:e(()=>({default:t.database?.default})),cache:e(()=>({driver:t.cache?.driver})),queue:e(()=>({default:t.queue?.default})),email:e(()=>({default:t.email?.default,from:t.email?.from})),searchEngine:e(()=>({driver:t.searchEngine?.driver})),ports:e(()=>t.ports)},{maxDepth:4})}var Ct={name:"environment",label:"Environment",collect(e){return{environment:Ie({appEnv:Rt.app?.env})||"unknown",process:e.process,pid:oe.pid,stacks:yt.version,bun:typeof Bun<"u"?Bun.version:void 0,platform:`${oe.platform} ${oe.arch}`,git:Or(),config:$r()}}};var Et={name:"events",label:"Events",async install({current:e}){let{listen:t,off:r}=await import("@stacksjs/events"),n=(o,s)=>{let i=e();if(!i)return;i.push("events",{name:String(o),at:i.elapsed(),payload:s===void 0?void 0:m(s,{maxDepth:4,maxKeys:30})})};return t("*",n),()=>{r("*",n)}},collect(e){let t=e.list("events");return t.length>0?t:void 0}};import{readFile as Br}from"fs/promises";import{relative as Ur,sep as g}from"path";import Lr from"process";var St;function vt(e){St=e.endsWith(g)?e.slice(0,-1):e}function se(){return St??=Lr.cwd()}var _r=[`${g}node_modules${g}`,`${g}storage${g}framework${g}`,`${g}pantry${g}`];function Dt(e){let t=se();if(!e.startsWith(t+g))return!1;let r=e.slice(t.length);return!_r.some((n)=>r.includes(n))}function $e(e){let t=se();return e.startsWith(t+g)?Ur(t,e):e}var At=/^\s*at\s+(?:async\s+)?(?:(.+?)\s+\()?((?:\/|[A-Za-z]:\\|file:\/\/)[^)]*?):(\d+)(?::(\d+))?\)?\s*$/;function Pt(e,t=30){if(!e)return[];let r=[];for(let n of e.split(`
4
- `)){let o=At.exec(n);if(!o)continue;let s=o[2].replace(/^file:\/\//,"");if(r.push({function:o[1]&&o[1]!=="<anonymous>"?o[1]:void 0,file:$e(s),line:Number(o[3]),column:o[4]?Number(o[4]):void 0,app:Dt(s)}),r.length>=t)break}return r}function ie(){let e={},t=Error.stackTraceLimit;Error.stackTraceLimit=40;try{Error.captureStackTrace(e,ie)}finally{Error.stackTraceLimit=t}if(!e.stack)return;for(let r of e.stack.split(`
5
- `)){let n=At.exec(r);if(!n)continue;let o=n[2].replace(/^file:\/\//,"");if(Dt(o))return`${$e(o)}:${n[3]}`}return}async function Mt(e,t,r=5){let n=e.startsWith(g)?e:`${se()}${g}${e}`;if(!n.startsWith(se()+g)||n.includes(`${g}..${g}`))return;try{let o=(await Br(n,"utf8")).split(`
6
- `);if(t<1||t>o.length)return;let s=Math.max(1,t-r),i=Math.min(o.length,t+r);return{file:$e(n),line:t,start:s,lines:o.slice(s-1,i).map((a)=>a.length>400?`${a.slice(0,400)}...`:a)}}catch{return}}var Tt=new WeakMap;function Be(e,t,r){let n=t instanceof Error?t:Error(typeof t==="string"?t:"Non-error value thrown"),o=Tt.get(e);if(!o)o=new WeakSet,Tt.set(e,o);if(o.has(n))return;o.add(n),e.push("exceptions",{name:n.name||"Error",message:String(n.message??"").slice(0,4000),at:e.elapsed(),frames:Pt(n.stack),context:r===void 0?void 0:m(r,{maxDepth:4})},50)}var qt={name:"exceptions",label:"Exceptions",async install({current:e}){let{registerErrorReporter:t}=await import("@stacksjs/error-handling");return t({name:"debugbar",report({error:r,context:n}){let o=e();if(o)Be(o,r,n)}})},async collect(e){let t=e.list("exceptions");if(t.length===0)return;for(let r of t){let n=r.frames.find((o)=>o.app&&o.line);if(n)r.excerpt=await Mt(n.file,n.line)}return t}};var jt={name:"jobs",label:"Jobs",async install({current:e}){let{onQueueEvent:t}=await import("@stacksjs/queue");return t("*",(r,n)=>{let o=e();if(!o||!r.startsWith("job:")&&!r.startsWith("batch:"))return;o.push("jobs",{event:r,name:n?.jobName??n?.jobId??"unknown",queue:n?.queueName??"default",at:o.elapsed(),payload:n?.data===void 0?void 0:m(n.data,{maxDepth:4,maxKeys:30}),error:n?.error?String(n.error.message??n.error):void 0},200)})},collect(e){let t=e.list("jobs");return t.length>0?t:void 0}};var Qr=/\u001B\[[0-9;]*[A-Za-z]/g,It={name:"logs",label:"Logs",async install({current:e}){let{registerTransport:t}=await import("@stacksjs/logging");return t({name:"debugbar",log(r){let n=e();if(!n)return;n.push("logs",{level:r.level,message:String(r.message??"").replace(Qr,"").slice(0,4000),at:n.elapsed(),context:r.args.length>1?m(r.args.slice(1),{maxDepth:4}):void 0})}})},collect(e){let t=e.list("logs");return t.length>0?t:void 0}};import{subscribe as Hr,unsubscribe as Wr}from"diagnostics_channel";var Nt="stacks:mail:sent";function Ot(e){return(Array.isArray(e)?e:e?[e]:[]).map((r)=>typeof r==="string"?r:r?.address??"").filter(Boolean).slice(0,50)}var $t={name:"mail",label:"Mail",install({current:e}){let t=(r)=>{let n=e(),o=r;if(!n||!o?.message)return;n.push("mail",{to:Ot(o.message.to),from:Ot(o.message.from)[0],subject:String(o.message.subject??"").slice(0,500),driver:String(o.driver??""),success:o.result?.success===!0,message:typeof o.result?.message==="string"?o.result.message.slice(0,500):void 0,duration:Number(o.durationMs)||0,at:n.elapsed()},200)};return Hr(Nt,t),()=>{Wr(Nt,t)}},collect(e){let t=e.list("mail");return t.length>0?t:void 0}};var Bt={name:"messages",label:"Messages",collect(e){let t=e.list("messages");return t.length>0?t:void 0}};function Ut(e){return e.replace(/'(?:[^']|'')*'/g,"?").replace(/\$\d+/g,"?").replace(/\b\d+(?:\.\d+)?\b/g,"?").replace(/\bIN\s*\([^)]*\)/gi,"IN (?)").replace(/\s+/g," ").trim().toLowerCase()}function zr(e){return e.startsWith("select")||e.startsWith("with")}function Ue(e){return/^\s*(?:explain\b|pragma\b)/i.test(e)||/\b(?:from|into|update|join)\s+[`"']?query_logs\b/i.test(e)}function Le(e,t){let r=new Map,n=new Map,o=[];for(let l of e){let f=Ut(l.sql),b=`${l.sql}\x00${Vr(l.params)}`;o.push({exact:b,shape:f}),r.set(b,(r.get(b)??0)+1);let T=n.get(f);if(T)T.count++;else n.set(f,{count:1,sample:l.sql,source:l.source})}let s=0,i=0,a=0,u=0;e.forEach((l,f)=>{let{exact:b,shape:T}=o[f],d=r.get(b)??1,p=n.get(T)?.count??1;if(s+=l.duration,d>1)l.duplicates=d;if(p>1)l.similar=p;if(l.duration>=t.slowThresholdMs)l.slow=!0,a++;if(l.error)u++});for(let l of r.values())i+=l-1;let c=[...n.entries()].filter(([l,f])=>f.count>=t.nPlusOneThreshold&&zr(l)).map(([l,f])=>({shape:l,count:f.count,sample:f.sample,source:f.source})).sort((l,f)=>f.count-l.count);return{count:e.length+(t.dropped??0),duration:s,dropped:t.dropped??0,duplicates:i,slow:a,failed:u,slowThresholdMs:t.slowThresholdMs,nPlusOne:c,statements:e}}function Vr(e){try{return JSON.stringify(e)??""}catch{return""}}function Fr(e,t){let r=e.get("queries:pending");if(!r)r=[],e.set("queries:pending",r);if(r.length<200)r.push({sql:t,source:ie()})}function Kr(e,t){let r=e.get("queries:pending");if(!r)return;for(let n=r.length-1;n>=0;n--)if(r[n].sql===t)return r.splice(n,1)[0].source;return}function Gr({current:e,config:t}){let r=t.queries.maxQueries,n=(o,s,i)=>{let a=e();if(!a||typeof o?.sql!=="string"||Ue(o.sql))return;let u=typeof o.durationMs==="number"?o.durationMs:0;a.push("queries",{sql:o.sql.length>8000?`${o.sql.slice(0,8000)} ...`:o.sql,params:we(o.params),start:Math.max(0,a.elapsed()-u),duration:u,rows:typeof o.rowCount==="number"?o.rowCount:void 0,kind:o.kind,source:i?i():Kr(a,o.sql),error:s?o.error instanceof Error?o.error.message:String(o.error??"failed"):void 0},r)};return{...t.queries.backtrace&&{onQueryStart(o){let s=e();if(s&&typeof o?.sql==="string"&&!Ue(o.sql))Fr(s,o.sql)}},onQueryEnd(o){n(o,!1)},onQueryError(o){n(o,!0)},onModelQuery(o){n(o,o.error!==void 0,t.queries.backtrace?ie:void 0)}}}var _e,Lt={name:"queries",label:"Queries",async install(e){let{ensureModelQueryObservation:t,observeModelQueries:r,registerPersistentQueryHooks:n}=await import("@stacksjs/query-builder");_e=t;let{onModelQuery:o,...s}=Gr(e),i=n(s),a=r(o);return()=>{_e=void 0,i(),a()}},begin(){_e?.()},collect(e){return Le(e.list("queries"),{slowThresholdMs:e.config.queries.slowThresholdMs,nPlusOneThreshold:e.config.queries.nPlusOneThreshold,dropped:e.dropped("queries")})}};function Jr(e){let t=e,r=t.jsonBody??t.formBody;return r&&typeof r==="object"?m(r,{maxDepth:5}):void 0}var _t={name:"request",label:"Request",collect(e,t){let{request:r,url:n}=e,o=t.headers.get("content-length");return{method:r.method,url:j(n),path:n.pathname,host:n.host,query:ye(n.searchParams),headers:Y(r.headers),cookies:ct(r.headers.get("cookie")),contentType:r.headers.get("content-type")??void 0,input:Jr(r),response:{status:t.status,headers:Y(t.headers),contentType:t.headers.get("content-type")??void 0,size:o&&/^\d+$/.test(o)?Number(o):void 0}}}};import{subscribe as Xr,unsubscribe as Zr}from"diagnostics_channel";var Qt="stacks:router:route-matched",Ht={name:"route",label:"Route",install({current:e}){let t=(r)=>{let n=r;e()?.set("route",{method:n.method,path:n.path,handler:n.handler,middleware:Array.isArray(n.middleware)?n.middleware:[]})};return Xr(Qt,t),()=>{Zr(Qt,t)}},collect(e){return e.get("route")}};import Yr from"process";function en(e){if(!e)return[];let t=[];for(let r of e.split(",")){let[n,...o]=r.trim().split(";"),s=o.map((a)=>a.trim()).find((a)=>a.startsWith("dur=")),i=s?Number(s.slice(4)):Number.NaN;if(n&&Number.isFinite(i))t.push({name:n.trim(),duration:i})}return t}var Wt={name:"timeline",label:"Timeline",collect(e,t){let r=e.elapsed(),n=[],o=en(t.headers.get("server-timing")),s=o.find((u)=>u.name==="total"),i=s?Math.max(0,r-s.duration):0;for(let u of o){if(!u.name.startsWith("mw_"))continue;n.push({label:u.name.slice(3),start:i,duration:u.duration,group:"middleware"}),i+=u.duration}if(s&&n.length>0)n.push({label:"handler",start:i,duration:Math.max(0,r-i),group:"handler"});if(e.process==="views")n.push({label:t.kind==="fragment"?"render fragment":"render page",start:0,duration:r,group:"render"});n.push(...e.list("measures")),n.sort((u,c)=>u.start-c.start);let a=Yr.memoryUsage();return{duration:r,measures:n,memory:{rss:a.rss,heapUsed:a.heapUsed}}}};import{existsSync as tn}from"fs";import{join as zt}from"path";import rn from"process";var I=new Map,Vt;function Ft(e){Vt=e,I.clear()}function nn(e){if(I.has(e))return I.get(e);let t=Vt??zt(rn.cwd(),"resources/views"),r=e.replace(/\/+$/,"").replace(/^\/+/,""),n=r?[`${r}.stx`,`${r}/index.stx`]:["index.stx"],o;if(!r.split("/").includes("..")){for(let s of n)if(tn(zt(t,s))){o=`resources/views/${s}`;break}}if(I.size>500)I.clear();return I.set(e,o),o}var Kt={name:"views",label:"Views",collect(e,t){if(e.process!=="views")return;return{template:nn(e.url.pathname),layout:t.headers.get("x-stx-layout")??void 0,fragment:t.kind==="fragment",renderMs:e.elapsed()}}};var Qe={messages:Bt,timeline:Wt,queries:Lt,exceptions:qt,logs:It,views:Kt,route:Ht,events:Et,cache:ht,mail:$t,jobs:jt,auth:gt,request:_t,environment:Ct};function Gt(e){return Object.keys(Qe).filter((t)=>e.collectors?.[t]!==!1).map((t)=>Qe[t])}var on=Object.keys(Qe);import{AsyncLocalStorage as sn}from"async_hooks";var an=Symbol.for("stacks.debugbar.socketPeer"),Xt=globalThis[an]??=new sn,ae=!1,He;function Zt(){return Xt.getStore()??null}function We(){if(ae||typeof Bun>"u"||typeof Bun.serve!=="function")return;ae=!0;let e=Bun.serve,t=()=>{if(Bun.serve===r)Bun.serve=e;ae=!1,He=void 0};He=t;let r=function(o,...s){let i=o?.fetch;if(typeof i!=="function")return Reflect.apply(e,Bun,[o,...s]);let a=Reflect.apply(e,Bun,[{...o,fetch(u,c,...l){let f=null;try{f=c?.requestIP?.(u)??null}catch{}return Xt.run(f,()=>Reflect.apply(i,this,[u,c,...l]))}},...s]);return t(),a};try{Bun.serve=r}catch{ae=!1}}function Yt(){He?.()}var Jt=new WeakMap;function ze(e){let t=e,r=t&&typeof t==="object"?Jt.get(t):void 0;if(r)return r;let n={requestIP(o){let s=null;try{s=t?.requestIP?.(o)??null}catch{}return s??Zt()}};if(t&&typeof t==="object")Jt.set(t,n);return n}import{existsSync as un,mkdirSync as cn,writeFileSync as ln}from"fs";import{mkdir as dn,readdir as fn,readFile as pn,rename as mn,rm as gn,unlink as bn,writeFile as er}from"fs/promises";import{join as N}from"path";import hn from"process";function Ve(e){try{cn(e,{recursive:!0});let t=N(e,".gitignore");if(!un(t))ln(t,`*
2
+ import{AsyncLocalStorage as xr}from"async_hooks";var kr=Symbol.for("stacks.debugbar.collection"),Y=globalThis[kr]??=new xr,Rr=1000,be=0;function at(e=Date.now()){be=(be+1)%1296;let t=crypto.getRandomValues(new Uint32Array(2));return e.toString(36).padStart(9,"0")+be.toString(36).padStart(2,"0")+t[0].toString(36).padStart(7,"0").slice(-7)+t[1].toString(36).padStart(7,"0").slice(-6)}var Cr=/^[0-9a-z]{20,32}$/;function I(e){return typeof e==="string"&&Cr.test(e)}class ee{id;process;request;url;config;startedAt;startedMs;kind;finished=!1;duration;bags=new Map;overflow=new Map;values=new Map;constructor(e,t,r){this.id=at(),this.process=t,this.request=e,this.url=new URL(e.url),this.config=r,this.startedAt=Date.now(),this.startedMs=performance.now(),this.kind=t==="api"?"api":"page"}elapsed(){return this.duration??performance.now()-this.startedMs}push(e,t,r=Rr){if(this.finished)return;let n=this.bags.get(e);if(!n)n=[],this.bags.set(e,n);if(n.length>=r){this.overflow.set(e,(this.overflow.get(e)??0)+1);return}n.push(t)}list(e){return this.bags.get(e)??[]}dropped(e){return this.overflow.get(e)??0}set(e,t){if(!this.finished)this.values.set(e,t)}get(e){return this.values.get(e)}}function x(){let e=Y.getStore();return e&&!e.finished?e:void 0}function he(e,t){return Y.run(e,t)}function ut(e){Y.enterWith(e)}function R(e){return Y.run(void 0,e)}var Sr="[redacted]",Er=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-csrf-token","x-xsrf-token","x-api-key","x-auth-token","x-debugbar-token"]),vr=new Set(["password","passwd","passphrase","pwd","secret","secrets","token","tokens","key","keys","apikey","authorization","auth","credential","credentials","signature","cookie","cookies","session","csrf","xsrf","dsn","otp","pin","cvv","cvc","ssn"]),ye=new Map;function _(e){let t=ye.get(e);if(t!==void 0)return t;let n=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).some((o)=>vr.has(o))||/password|secret|token|apikey/i.test(e);if(ye.size<2000)ye.set(e,n);return n}function te(e){if(e.length<20)return!1;if(/^\$(?:2[aby]|argon2(?:id|i|d)|scrypt|pbkdf2)[$-]/.test(e))return!0;if(/^eyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]*$/.test(e))return!0;if(/^(?:sk|pk|rk|whsec|ghp|gho|xox[abp])[-_][\w-]{16,}$/.test(e))return!0;return e.length>=40&&/^[a-f0-9]+$/i.test(e)}function re(e){let t={};if(!e)return t;return e.forEach((r,n)=>{let o=n.toLowerCase();t[o]=Er.has(o)||_(o)?"[redacted]":U(r,2000)}),t}function lt(e){if(!e)return[];let t=[];for(let r of e.split(";")){let n=r.split("=",1)[0]?.trim();if(n)t.push(n)}return t}function we(e){let t={};for(let r of new Set(e.keys())){let n=_(r)?["[redacted]"]:e.getAll(r).map((o)=>te(o)?"[redacted]":U(o,500));t[r]=n.length===1?n[0]:n}return t}function q(e){if(!e.search)return e.pathname;let t=[];for(let[r,n]of e.searchParams){let o=_(r)||te(n)?"[redacted]":n;t.push(`${encodeURIComponent(r)}=${o==="[redacted]"?"[redacted]":encodeURIComponent(o)}`)}return`${e.pathname}?${t.join("&")}`}function U(e,t){return e.length>t?`${e.slice(0,t)}... (${e.length} chars)`:e}function m(e,t={}){let r={maxDepth:t.maxDepth??6,maxKeys:t.maxKeys??60,maxItems:t.maxItems??60,maxString:t.maxString??2000};return D(e,r,0,new WeakSet)}function D(e,t,r,n){if(e===null||e===void 0)return e??null;switch(typeof e){case"string":return te(e)?"[redacted]":U(e,t.maxString);case"number":return Number.isFinite(e)?e:String(e);case"boolean":return e;case"bigint":return`${e}n`;case"symbol":return e.toString();case"function":return`[function ${e.name||"anonymous"}]`}let o=e;if(n.has(o))return"[circular]";if(r>=t.maxDepth)return Array.isArray(o)?`[array(${o.length})]`:"[object]";if(o instanceof Date)return Number.isNaN(o.getTime())?"Invalid Date":o.toISOString();if(o instanceof Error)return{name:o.name,message:U(o.message,t.maxString)};if(o instanceof URL)return q(o);if(typeof Request<"u"&&o instanceof Request)return`[Request ${o.method} ${Dr(o.url)}]`;if(typeof Response<"u"&&o instanceof Response)return`[Response ${o.status}]`;if(ArrayBuffer.isView(o)||o instanceof ArrayBuffer)return`[binary ${o.byteLength} bytes]`;n.add(o);try{if(Array.isArray(o)){let u=o.slice(0,t.maxItems).map((c)=>D(c,t,r+1,n));if(o.length>t.maxItems)u.push(`... ${o.length-t.maxItems} more`);return u}if(o instanceof Map)return D(Object.fromEntries([...o.entries()].slice(0,t.maxKeys).map(([u,c])=>[String(u),c])),t,r,n);if(o instanceof Set)return D([...o],t,r,n);let s=typeof o.toJSON==="function"?ct(()=>o.toJSON()):o;if(s===null||typeof s!=="object")return D(s,t,r+1,n);if(s!==o&&Array.isArray(s))return D(s,t,r,n);let i={},a=0;for(let u of Object.keys(s)){if(a++>=t.maxKeys){i["..."]=`${Object.keys(s).length-t.maxKeys} more keys`;break}i[u]=_(u)?"[redacted]":D(ct(()=>s[u]),t,r+1,n)}return i}finally{n.delete(o)}}function ct(e){try{return e()}catch{return"[unreadable]"}}function Dr(e){try{return new URL(e).pathname}catch{return""}}function xe(e){if(!e)return[];return e.slice(0,100).map((t)=>{if(typeof t==="string")return te(t)?"[redacted]":U(t,500);if(t===null||typeof t==="number"||typeof t==="boolean")return t;if(typeof t==="bigint")return`${t}n`;if(t instanceof Date)return Number.isNaN(t.getTime())?"Invalid Date":t.toISOString();if(ArrayBuffer.isView(t)||t instanceof ArrayBuffer)return`[binary ${t.byteLength} bytes]`;return m(t,{maxDepth:3,maxString:500})})}function Ar(e){if(typeof e==="string")return e;if(e instanceof Error)return`${e.name}: ${e.message}`;try{return JSON.stringify(m(e))??String(e)}catch{return String(e)}}function A(e,t,r="info",n){let o=x();if(!o)return;o.push("messages",{level:r,label:t,message:Ar(e).slice(0,4000),context:n===void 0?void 0:m(n),at:o.elapsed()})}function ke(e,t){A(e,void 0,"debug",t)}function Re(e,t){A(e,void 0,"info",t)}function Ce(e,t){A(e,void 0,"warning",t)}function Se(e,t){A(e,void 0,"error",t)}function Ee(e,t){let r=x();if(!r)return;let n=r.get("measures:open");if(!n)n=new Map,r.set("measures:open",n);n.set(e,{label:t??e,start:r.elapsed()})}function ve(e){let t=x(),r=t?.get("measures:open"),n=r?.get(e);if(!t||!r||!n)return;r.delete(e),t.push("measures",{label:n.label,start:n.start,duration:t.elapsed()-n.start,group:"measure"})}function De(e,t,r,n="measure"){x()?.push("measures",{label:e,start:t,duration:r,group:n})}function Ae(e,t){let r=x();if(!r)return t();let n=r.elapsed(),o=()=>{r.push("measures",{label:e,start:n,duration:r.elapsed()-n,group:"measure"})},s;try{s=t()}catch(i){throw o(),i}if(s instanceof Promise)return s.finally(o);return o(),s}var C=new Map,ne=new Map,S;function dt(e,t){if(!e.install)return;try{let r=e.install(t),n=(o)=>{if(typeof o!=="function")return;if(S!==t||C.get(e.name)!==e)o();else ne.set(e.name,o)};if(r instanceof Promise)r.then(n,()=>{});else n(r)}catch{}}function Pe(e){let t=ne.get(e);ne.delete(e);try{t?.()}catch{}}function Q(e){if(!e||typeof e.name!=="string"||!/^[\w-]{1,40}$/.test(e.name))throw TypeError("A debugbar collector needs a name of letters, digits, dashes or underscores.");if(Pe(e.name),C.set(e.name,e),S)dt(e,S);return()=>{if(C.get(e.name)!==e)return;Pe(e.name),C.delete(e.name)}}function Me(){return[...C.values()]}function ft(e,t){if(S)return;S={config:e,process:t,current:x};for(let r of C.values())dt(r,S)}function pt(){S=void 0;for(let e of[...ne.keys()])Pe(e)}function mt(e){if(!S)return;for(let t of C.values()){if(!t.begin)continue;try{t.begin(e)}catch{}}}async function gt(e,t){let r={},n={};for(let o of C.values()){if(!o.collect)continue;try{let s=await o.collect(e,t);if(s===void 0||s===null)continue;if(r[o.name]=s,o.label)n[o.name]=o.label}catch(s){r[o.name]={error:s instanceof Error?s.message:String(s)}}}return{sections:r,labels:n}}import{randomBytes as nr}from"crypto";import{chmodSync as Sn,existsSync as En,readFileSync as vn,writeFileSync as Dn}from"fs";import{join as or}from"path";import An from"process";import{config as Ke}from"@stacksjs/config";import{projectPath as Pn,storagePath as Mn}from"@stacksjs/path";var H=new Map,Pr=3000;function oe(e){if(!e||typeof e!=="object")return null;let t=(i)=>{try{return e[i]}catch{return}},r=t("id");if(typeof r!=="number"&&typeof r!=="string")return null;let n=(i)=>{let a=t(i);return typeof a==="string"&&a.trim()?a.trim():void 0},o=n("email"),s=n("name")??([n("first_name")??n("firstName"),n("last_name")??n("lastName")].filter(Boolean).join(" ")||void 0)??n("username")??o??`User #${r}`;return{id:r,name:s,...o&&{email:o}}}function Mr(e,t){let r=e.headers.get("authorization");if(r&&/^bearer\s+\S/i.test(r))return{token:r.replace(/^bearer\s+/i,"").trim(),via:"bearer"};let n=t?.(e);return n?{token:n,via:"cookie"}:void 0}async function se(e){try{let t=await import("@stacksjs/auth"),r=Mr(e,t.authCookieToken);if(!r)return{user:null,via:"none"};let n=H.get(r.token);if(n&&Date.now()-n.at<Pr)return{user:n.user,via:r.via};let o=await R(()=>t.Auth.getUserFromToken(r.token)),s=oe(o);if(H.size>100)H.clear();return H.set(r.token,{user:s,at:Date.now()}),{user:s,via:r.via}}catch{return{user:null,via:"none"}}}function Te(){H.clear()}var bt={name:"auth",label:"Auth",async collect(e){let{user:t,via:r}=await se(e.request);return{authenticated:t!==null,guard:r==="none"?"guest":r==="bearer"?"token":"cookie",user:t}}};import{subscribe as Tr,unsubscribe as jr}from"diagnostics_channel";var ht="stacks:cache:operation",yt={name:"cache",label:"Cache",install({current:e}){let t=(r)=>{let n=e(),o=r;if(!n||typeof o?.key!=="string")return;n.push("cache",{type:o.type,key:o.key.slice(0,500),ttl:o.ttl,duration:o.durationMs,at:n.elapsed()})};return Tr(ht,t),()=>{jr(ht,t)}},collect(e){let t=e.list("cache");if(t.length===0)return;let r=(n)=>t.filter((o)=>o.type===n).length;return{hits:r("hit"),misses:r("miss"),writes:r("write"),forgets:r("forget"),operations:t}}};import{existsSync as ie,readFileSync as W,statSync as Lr}from"fs";import{join as z,resolve as Rt}from"path";import ae from"process";import{config as Ct}from"@stacksjs/config";var wt={name:"@stacksjs/debugbar",type:"module",sideEffects:!1,version:"0.75.755",description:"The Stacks debugbar: a request inspector for development.",author:"Chris Breuer",contributors:["Chris Breuer <chris@stacksjs.com>"],license:"MIT",funding:"https://github.com/sponsors/chrisbbreuer",homepage:"https://github.com/stacksjs/stacks/tree/main/storage/framework/core/debugbar#readme",repository:{type:"git",url:"git+https://github.com/stacksjs/stacks.git",directory:"./storage/framework/core/debugbar"},bugs:{url:"https://github.com/stacksjs/stacks/issues"},keywords:["debugbar","debug","profiler","queries","stacks"],exports:{".":{types:"./dist/index.d.ts",bun:"./dist/index.js",import:"./dist/index.js",default:"./dist/index.js"},"./*":{types:"./dist/*.d.ts",bun:"./dist/*.js",import:"./dist/*.js",default:"./dist/*.js"},"./*.js":{types:"./dist/*.d.ts",bun:"./dist/*.js",import:"./dist/*.js",default:"./dist/*.js"}},module:"dist/index.js",types:"dist/index.d.ts",files:["README.md","dist"],scripts:{build:"bun build.ts",typecheck:"bun tsc --noEmit",prepublishOnly:"bun run build"},devDependencies:{"better-dx":"^0.2.41"},dependencies:{"@stacksjs/auth":"workspace:*","@stacksjs/config":"workspace:*","@stacksjs/database":"workspace:*","@stacksjs/error-handling":"workspace:*","@stacksjs/events":"workspace:*","@stacksjs/logging":"workspace:*","@stacksjs/path":"workspace:*","@stacksjs/query-builder":"workspace:*","@stacksjs/queue":"workspace:*","@stacksjs/router":"workspace:*","@stacksjs/types":"workspace:*"}};import qe from"process";var je=new Set(["production","prod","live"]),qr=new Set(["local","development","dev"]);function P(e){return typeof e==="string"?e.trim().toLowerCase():""}function xt(e={}){let t=e.env??qe.env,r=P(t.APP_ENV);if(je.has(r)||je.has(P(e.appEnv)))return!0;return!r&&je.has(P(t.NODE_ENV))}function Oe(e={}){let t=e.env??qe.env;return P(t.APP_ENV)||P(e.appEnv)||P(t.NODE_ENV)}function Or(e){let t=P((e.env??qe.env).APP_DEBUG);return t==="false"||t==="0"||t==="off"||t==="no"}function $e(e,t={}){if(xt(t))return!1;if(e?.enabled===!1)return!1;if(e?.enabled===!0)return!0;return qr.has(Oe(t))&&!Or(t)}function Ne(e,t){let r=e?.queries??{};return{...e,storage:{path:e?.storage?.path||t,maxRequests:Ie(e?.storage?.maxRequests,200)},except:Array.isArray(e?.except)?e.except.filter((n)=>typeof n==="string"):[],queries:{slowThresholdMs:$r(r.slowThresholdMs,100),nPlusOneThreshold:Math.max(2,Ie(r.nPlusOneThreshold,5)),backtrace:r.backtrace!==!1,maxQueries:Ie(r.maxQueries,500)}}}function Ie(e,t){let r=Number(e);return Number.isFinite(r)&&r>=1?Math.floor(r):t}function $r(e,t){let r=Number(e);return Number.isFinite(r)&&r>=0?r:t}var Nr=/^\/(?:__debugbar|_stx|__deps|__hmr|__stx|@|node_modules)(?:\/|$)|^\/favicon\.|\.(?:js|mjs|css|map|png|jpe?g|gif|svg|ico|webp|avif|woff2?|ttf|otf|eot|mp4|webm|mp3|wasm|txt|xml|webmanifest)$/i;function kt(e,t){if(Nr.test(e))return!0;for(let r of t)if(r.endsWith("*")?e.startsWith(r.slice(0,-1)):e===r)return!0;return!1}function Br(e){try{let t=z(e,".git");if(!ie(t))return{};if(Lr(t).isFile()){let u=/^gitdir:\s*(.+)$/m.exec(W(t,"utf8"));if(!u)return{};t=Rt(e,u[1].trim())}let r=W(z(t,"HEAD"),"utf8").trim(),n=/^ref:\s*(.+)$/.exec(r);if(!n)return{sha:r.slice(0,12)};let o=n[1].replace(/^refs\/heads\//,""),s=z(t,"commondir"),i=ie(s)?Rt(t,W(s,"utf8").trim()):t;for(let u of[t,i]){let c=z(u,n[1]);if(ie(c))return{branch:o,sha:W(c,"utf8").trim().slice(0,12)}}let a=z(i,"packed-refs");if(ie(a)){let u=W(a,"utf8").split(`
3
+ `).find((c)=>c.endsWith(` ${n[1]}`));if(u)return{branch:o,sha:u.slice(0,12)}}return{branch:o}}catch{return{}}}var V;function Ur(){if(!V||Date.now()-V.at>5000)V={...Br(ae.cwd()),at:Date.now()};return{branch:V.branch,sha:V.sha}}function _r(){let e=(r)=>{try{return r()}catch{return}},t=Ct;return m({app:e(()=>({name:t.app?.name,env:t.app?.env,url:t.app?.url,debug:t.app?.debug,timezone:t.app?.timezone,locale:t.app?.locale})),database:e(()=>({default:t.database?.default})),cache:e(()=>({driver:t.cache?.driver})),queue:e(()=>({default:t.queue?.default})),email:e(()=>({default:t.email?.default,from:t.email?.from})),searchEngine:e(()=>({driver:t.searchEngine?.driver})),ports:e(()=>t.ports)},{maxDepth:4})}var St={name:"environment",label:"Environment",collect(e){return{environment:Oe({appEnv:Ct.app?.env})||"unknown",process:e.process,pid:ae.pid,stacks:wt.version,bun:typeof Bun<"u"?Bun.version:void 0,platform:`${ae.platform} ${ae.arch}`,git:Ur(),config:_r()}}};var Et={name:"events",label:"Events",async install({current:e}){let{listen:t,off:r}=await import("@stacksjs/events"),n=(o,s)=>{let i=e();if(!i)return;i.push("events",{name:String(o),at:i.elapsed(),payload:s===void 0?void 0:m(s,{maxDepth:4,maxKeys:30})})};return t("*",n),()=>{r("*",n)}},collect(e){let t=e.list("events");return t.length>0?t:void 0}};import{readFile as Qr}from"fs/promises";import{relative as Hr,sep as g}from"path";import Wr from"process";var vt;function Dt(e){vt=e.endsWith(g)?e.slice(0,-1):e}function ue(){return vt??=Wr.cwd()}var zr=[`${g}node_modules${g}`,`${g}storage${g}framework${g}`,`${g}pantry${g}`];function At(e){let t=ue();if(!e.startsWith(t+g))return!1;let r=e.slice(t.length);return!zr.some((n)=>r.includes(n))}function Le(e){let t=ue();return e.startsWith(t+g)?Hr(t,e):e}var Pt=/^\s*at\s+(?:async\s+)?(?:(.+?)\s+\()?((?:\/|[A-Za-z]:\\|file:\/\/)[^)]*?):(\d+)(?::(\d+))?\)?\s*$/;function Mt(e,t=30){if(!e)return[];let r=[];for(let n of e.split(`
4
+ `)){let o=Pt.exec(n);if(!o)continue;let s=o[2].replace(/^file:\/\//,"");if(r.push({function:o[1]&&o[1]!=="<anonymous>"?o[1]:void 0,file:Le(s),line:Number(o[3]),column:o[4]?Number(o[4]):void 0,app:At(s)}),r.length>=t)break}return r}function ce(){let e={},t=Error.stackTraceLimit;Error.stackTraceLimit=40;try{Error.captureStackTrace(e,ce)}finally{Error.stackTraceLimit=t}if(!e.stack)return;for(let r of e.stack.split(`
5
+ `)){let n=Pt.exec(r);if(!n)continue;let o=n[2].replace(/^file:\/\//,"");if(At(o))return`${Le(o)}:${n[3]}`}return}async function Tt(e,t,r=5){let n=e.startsWith(g)?e:`${ue()}${g}${e}`;if(!n.startsWith(ue()+g)||n.includes(`${g}..${g}`))return;try{let o=(await Qr(n,"utf8")).split(`
6
+ `);if(t<1||t>o.length)return;let s=Math.max(1,t-r),i=Math.min(o.length,t+r);return{file:Le(n),line:t,start:s,lines:o.slice(s-1,i).map((a)=>a.length>400?`${a.slice(0,400)}...`:a)}}catch{return}}var jt=new WeakMap;function Be(e,t,r){let n=t instanceof Error?t:Error(typeof t==="string"?t:"Non-error value thrown"),o=jt.get(e);if(!o)o=new WeakSet,jt.set(e,o);if(o.has(n))return;o.add(n),e.push("exceptions",{name:n.name||"Error",message:String(n.message??"").slice(0,4000),at:e.elapsed(),frames:Mt(n.stack),context:r===void 0?void 0:m(r,{maxDepth:4})},50)}var It={name:"exceptions",label:"Exceptions",async install({current:e}){let{registerErrorReporter:t}=await import("@stacksjs/error-handling");return t({name:"debugbar",report({error:r,context:n}){let o=e();if(o)Be(o,r,n)}})},async collect(e){let t=e.list("exceptions");if(t.length===0)return;for(let r of t){let n=r.frames.find((o)=>o.app&&o.line);if(n)r.excerpt=await Tt(n.file,n.line)}return t}};var qt={name:"jobs",label:"Jobs",async install({current:e}){let{onQueueEvent:t}=await import("@stacksjs/queue");return t("*",(r,n)=>{let o=e();if(!o||!r.startsWith("job:")&&!r.startsWith("batch:"))return;o.push("jobs",{event:r,name:n?.jobName??n?.jobId??"unknown",queue:n?.queueName??"default",at:o.elapsed(),payload:n?.data===void 0?void 0:m(n.data,{maxDepth:4,maxKeys:30}),error:n?.error?String(n.error.message??n.error):void 0},200)})},collect(e){let t=e.list("jobs");return t.length>0?t:void 0}};var Vr=/\u001B\[[0-9;]*[A-Za-z]/g,Ot={name:"logs",label:"Logs",async install({current:e}){let{registerTransport:t}=await import("@stacksjs/logging");return t({name:"debugbar",log(r){let n=e();if(!n)return;n.push("logs",{level:r.level,message:String(r.message??"").replace(Vr,"").slice(0,4000),at:n.elapsed(),context:r.args.length>1?m(r.args.slice(1),{maxDepth:4}):void 0})}})},collect(e){let t=e.list("logs");return t.length>0?t:void 0}};import{subscribe as Fr,unsubscribe as Kr}from"diagnostics_channel";var $t="stacks:mail:sent";function Nt(e){return(Array.isArray(e)?e:e?[e]:[]).map((r)=>typeof r==="string"?r:r?.address??"").filter(Boolean).slice(0,50)}var Lt={name:"mail",label:"Mail",install({current:e}){let t=(r)=>{let n=e(),o=r;if(!n||!o?.message)return;n.push("mail",{to:Nt(o.message.to),from:Nt(o.message.from)[0],subject:String(o.message.subject??"").slice(0,500),driver:String(o.driver??""),success:o.result?.success===!0,message:typeof o.result?.message==="string"?o.result.message.slice(0,500):void 0,duration:Number(o.durationMs)||0,at:n.elapsed()},200)};return Fr($t,t),()=>{Kr($t,t)}},collect(e){let t=e.list("mail");return t.length>0?t:void 0}};var Bt={name:"messages",label:"Messages",collect(e){let t=e.list("messages");return t.length>0?t:void 0}};function Gr({current:e}){return(t)=>{let r=e();if(!r||typeof t?.model!=="string"||!t.model)return;let n=r.get("models:counts");if(!n)n=new Map,r.set("models:counts",n);let o=n.get(t.model);if(o){if(o.count++,!o.table&&t.table)o.table=t.table}else n.set(t.model,{model:t.model,...t.table?{table:t.table}:{},count:1})}}var Ut={name:"models",label:"Models",async install(e){let{registerPersistentQueryHooks:t}=await import("@stacksjs/query-builder"),r=Gr(e);return t({onModelHydrate:r})},collect(e){let t=e.get("models:counts");if(!t||t.size===0)return;let r=[...t.values()].sort((o,s)=>s.count-o.count||o.model.localeCompare(s.model));return{total:r.reduce((o,s)=>o+s.count,0),models:r}}};function _t(e){return e.replace(/'(?:[^']|'')*'/g,"?").replace(/\$\d+/g,"?").replace(/\b\d+(?:\.\d+)?\b/g,"?").replace(/\bIN\s*\([^)]*\)/gi,"IN (?)").replace(/\s+/g," ").trim().toLowerCase()}function Jr(e){return e.startsWith("select")||e.startsWith("with")}function Ue(e){return/^\s*(?:explain\b|pragma\b)/i.test(e)||/\b(?:from|into|update|join)\s+[`"']?query_logs\b/i.test(e)}function _e(e,t){let r=new Map,n=new Map,o=[];for(let l of e){let p=_t(l.sql),h=`${l.sql}\x00${Xr(l.params)}`;o.push({exact:h,shape:p}),r.set(h,(r.get(h)??0)+1);let b=n.get(p);if(b)b.count++;else n.set(p,{count:1,sample:l.sql,source:l.source})}let s=0,i=0,a=0,u=0;e.forEach((l,p)=>{let{exact:h,shape:b}=o[p],d=r.get(h)??1,f=n.get(b)?.count??1;if(s+=l.duration,d>1)l.duplicates=d;if(f>1)l.similar=f;if(l.duration>=t.slowThresholdMs)l.slow=!0,a++;if(l.error)u++});for(let l of r.values())i+=l-1;let c=[...n.entries()].filter(([l,p])=>p.count>=t.nPlusOneThreshold&&Jr(l)).map(([l,p])=>({shape:l,count:p.count,sample:p.sample,source:p.source})).sort((l,p)=>p.count-l.count);return{count:e.length+(t.dropped??0),duration:s,dropped:t.dropped??0,duplicates:i,slow:a,failed:u,slowThresholdMs:t.slowThresholdMs,nPlusOne:c,statements:e}}function Xr(e){try{return JSON.stringify(e)??""}catch{return""}}function Zr(e,t){let r=e.get("queries:pending");if(!r)r=[],e.set("queries:pending",r);if(r.length<200)r.push({sql:t,source:ce()})}function Yr(e,t){let r=e.get("queries:pending");if(!r)return;for(let n=r.length-1;n>=0;n--)if(r[n].sql===t)return r.splice(n,1)[0].source;return}function en({current:e,config:t}){let r=t.queries.maxQueries,n=(o,s,i)=>{let a=e();if(!a||typeof o?.sql!=="string"||Ue(o.sql))return;let u=typeof o.durationMs==="number"?o.durationMs:0;a.push("queries",{sql:o.sql.length>8000?`${o.sql.slice(0,8000)} ...`:o.sql,params:xe(o.params),start:Math.max(0,a.elapsed()-u),duration:u,rows:typeof o.rowCount==="number"?o.rowCount:void 0,kind:o.kind,source:i?i():Yr(a,o.sql),error:s?o.error instanceof Error?o.error.message:String(o.error??"failed"):void 0},r)};return{...t.queries.backtrace&&{onQueryStart(o){let s=e();if(s&&typeof o?.sql==="string"&&!Ue(o.sql))Zr(s,o.sql)}},onQueryEnd(o){n(o,!1)},onQueryError(o){n(o,!0)},onModelQuery(o){n(o,o.error!==void 0,t.queries.backtrace?ce:void 0)}}}var Qt={name:"queries",label:"Queries",async install(e){let{registerPersistentQueryHooks:t}=await import("@stacksjs/query-builder"),r=en(e);return t({...r.onQueryStart?{onQueryStart:r.onQueryStart}:{},onQueryEnd:r.onQueryEnd,onQueryError:r.onQueryError})},collect(e){return _e(e.list("queries"),{slowThresholdMs:e.config.queries.slowThresholdMs,nPlusOneThreshold:e.config.queries.nPlusOneThreshold,dropped:e.dropped("queries")})}};function tn(e){let t=e,r=t.jsonBody??t.formBody;return r&&typeof r==="object"?m(r,{maxDepth:5}):void 0}var Ht={name:"request",label:"Request",collect(e,t){let{request:r,url:n}=e,o=t.headers.get("content-length");return{method:r.method,url:q(n),path:n.pathname,host:n.host,query:we(n.searchParams),headers:re(r.headers),cookies:lt(r.headers.get("cookie")),contentType:r.headers.get("content-type")??void 0,input:tn(r),response:{status:t.status,headers:re(t.headers),contentType:t.headers.get("content-type")??void 0,size:o&&/^\d+$/.test(o)?Number(o):void 0}}}};import{subscribe as rn,unsubscribe as nn}from"diagnostics_channel";var Wt="stacks:router:route-matched",zt={name:"route",label:"Route",install({current:e}){let t=(r)=>{let n=r;e()?.set("route",{method:n.method,path:n.path,handler:n.handler,middleware:Array.isArray(n.middleware)?n.middleware:[]})};return rn(Wt,t),()=>{nn(Wt,t)}},collect(e){return e.get("route")}};import on from"process";function sn(e){if(!e)return[];let t=[];for(let r of e.split(",")){let[n,...o]=r.trim().split(";"),s=o.map((a)=>a.trim()).find((a)=>a.startsWith("dur=")),i=s?Number(s.slice(4)):Number.NaN;if(n&&Number.isFinite(i))t.push({name:n.trim(),duration:i})}return t}var Vt={name:"timeline",label:"Timeline",collect(e,t){let r=e.elapsed(),n=[],o=sn(t.headers.get("server-timing")),s=o.find((u)=>u.name==="total"),i=s?Math.max(0,r-s.duration):0;for(let u of o){if(!u.name.startsWith("mw_"))continue;n.push({label:u.name.slice(3),start:i,duration:u.duration,group:"middleware"}),i+=u.duration}if(s&&n.length>0)n.push({label:"handler",start:i,duration:Math.max(0,r-i),group:"handler"});if(e.process==="views")n.push({label:t.kind==="fragment"?"render fragment":"render page",start:0,duration:r,group:"render"});n.push(...e.list("measures")),n.sort((u,c)=>u.start-c.start);let a=on.memoryUsage();return{duration:r,measures:n,memory:{rss:a.rss,heapUsed:a.heapUsed}}}};import{existsSync as an}from"fs";import{join as Ft}from"path";import un from"process";var O=new Map,Kt;function Gt(e){Kt=e,O.clear()}function cn(e){if(O.has(e))return O.get(e);let t=Kt??Ft(un.cwd(),"resources/views"),r=e.replace(/\/+$/,"").replace(/^\/+/,""),n=r?[`${r}.stx`,`${r}/index.stx`]:["index.stx"],o;if(!r.split("/").includes("..")){for(let s of n)if(an(Ft(t,s))){o=`resources/views/${s}`;break}}if(O.size>500)O.clear();return O.set(e,o),o}var Jt={name:"views",label:"Views",collect(e,t){if(e.process!=="views")return;return{template:cn(e.url.pathname),layout:t.headers.get("x-stx-layout")??void 0,fragment:t.kind==="fragment",renderMs:e.elapsed()}}};var Qe={messages:Bt,timeline:Vt,queries:Qt,models:Ut,exceptions:It,logs:Ot,views:Jt,route:zt,events:Et,cache:yt,mail:Lt,jobs:qt,auth:bt,request:Ht,environment:St};function Xt(e){return Object.keys(Qe).filter((t)=>e.collectors?.[t]!==!1).map((t)=>Qe[t])}var ln=Object.keys(Qe);import{AsyncLocalStorage as dn}from"async_hooks";var fn=Symbol.for("stacks.debugbar.socketPeer"),Yt=globalThis[fn]??=new dn,le=!1,He;function er(){return Yt.getStore()??null}function We(){if(le||typeof Bun>"u"||typeof Bun.serve!=="function")return;le=!0;let e=Bun.serve,t=()=>{if(Bun.serve===r)Bun.serve=e;le=!1,He=void 0};He=t;let r=function(o,...s){let i=o?.fetch;if(typeof i!=="function")return Reflect.apply(e,Bun,[o,...s]);let a=Reflect.apply(e,Bun,[{...o,fetch(u,c,...l){let p=null;try{p=c?.requestIP?.(u)??null}catch{}return Yt.run(p,()=>Reflect.apply(i,this,[u,c,...l]))}},...s]);return t(),a};try{Bun.serve=r}catch{le=!1}}function tr(){He?.()}var Zt=new WeakMap;function ze(e){let t=e,r=t&&typeof t==="object"?Zt.get(t):void 0;if(r)return r;let n={requestIP(o){let s=null;try{s=t?.requestIP?.(o)??null}catch{}return s??er()}};if(t&&typeof t==="object")Zt.set(t,n);return n}import{existsSync as pn,mkdirSync as mn,writeFileSync as gn}from"fs";import{mkdir as bn,readdir as hn,readFile as yn,rename as wn,rm as xn,unlink as kn,writeFile as rr}from"fs/promises";import{join as N}from"path";import Rn from"process";function Ve(e){try{mn(e,{recursive:!0});let t=N(e,".gitignore");if(!pn(t))gn(t,`*
7
7
  !.gitignore
8
- `)}catch{}}var yn=/^([0-9a-z]{20,32})\.json$/;function Fe(e){let{directory:t}=e,r=Math.max(1,e.maxRequests),n=new Map,o,s=0,i=Promise.resolve();function a(){return o??=(async()=>{await dn(t,{recursive:!0}),await er(N(t,".gitignore"),`*
8
+ `)}catch{}}var Cn=/^([0-9a-z]{20,32})\.json$/;function Fe(e){let{directory:t}=e,r=Math.max(1,e.maxRequests),n=new Map,o,s=0,i=new Set;function a(){return o??=(async()=>{await bn(t,{recursive:!0}),await rr(N(t,".gitignore"),`*
9
9
  !.gitignore
10
- `,{flag:"wx"}).catch(()=>{})})().catch(()=>{o=void 0})}async function u(){try{let d=[];for(let p of await fn(t)){let h=yn.exec(p);if(h)d.push(h[1])}return d.sort()}catch{return[]}}async function c(){let d=await u(),p=d.slice(0,Math.max(0,d.length-r));await Promise.all(p.map((h)=>bn(N(t,`${h}.json`)).catch(()=>{})));for(let h of p)n.delete(h);return p.length}async function l(d){if(!q(d.id))return;let p=(async()=>{try{await a();let h=N(t,`${d.id}.json`),x=`${h}.${hn.pid}.tmp`;if(await er(x,JSON.stringify(d)),await mn(x,h),n.set(d.id,{startedAt:d.startedAt,summary:d.summary}),++s>=20||n.size>r)s=0,await c()}catch{}})();return i=Promise.allSettled([i,p]),p}async function f(d){if(!q(d))return null;try{let p=JSON.parse(await pn(N(t,`${d}.json`),"utf8"));return p&&p.id===d?p:null}catch{return null}}async function b(d=50){let p=(await u()).reverse().slice(0,Math.max(1,Math.min(d,r))),h=[];for(let x of p){let E=n.get(x);if(!E){let pe=await f(x);if(!pe)continue;E={startedAt:pe.startedAt,summary:pe.summary},n.set(x,E)}h.push({id:x,...E})}if(n.size>r*2){let x=new Set(p);for(let E of n.keys())if(!x.has(E))n.delete(E)}return h}async function T(){n.clear();let d=await u();await Promise.all(d.map((p)=>gn(N(t,`${p}.json`),{force:!0}).catch(()=>{})))}return{directory:t,write:l,read:f,list:b,clear:T,prune:c,async flush(){await i}}}var B,Ge=new Set,nr=[];function or(){try{let e=Ke.app;return{env:e?.env,url:e?.url}}catch{return{}}}function ue(e={}){let t=or();return Ne(e.config??Ke.debugbar,{env:e.env,appEnv:e.appEnv??t.env})}function V(e,t={}){if(B)return B;if(!ue(t))return;let r=t.root??En(),n=Oe(t.config??Ke.debugbar,Sn("framework/debugbar"));vt(r),Ft(rr(r,"resources/views"));let o=new Set(Pe().map((s)=>s.name));for(let s of Gt(n)){if(o.has(s.name))continue;nr.push(_(s)),Ge.add(s.name)}return dt(n,e),Ve(n.storage.path),B={config:n,store:Fe({directory:n.storage.path,maxRequests:n.storage.maxRequests}),process:e,appUrl:or().url},B}function vn(){return B}function Dn(){ft();for(let e of nr.splice(0))e();Ge.clear(),Yt(),B=void 0,O=void 0}function ce(e,t){return!xt(t,e.config.except)}function le(e,t){let r=new Z(t,e.process,e.config);return pt(r),r}function An(e,t,r){let{queries:n,route:o,views:s,auth:i}=r,a=(u)=>Array.isArray(r[u])?r[u].length:0;return{method:e.request.method,url:j(e.url),path:e.url.pathname,status:t.status,kind:t.kind,process:e.process,duration:e.elapsed(),memory:Math.round(Cn.memoryUsage().rss/1048576*10)/10,queries:n?.count??0,queryDuration:n?.duration??0,logs:a("logs")+a("messages"),exceptions:a("exceptions"),route:o?`${o.method} ${o.path}`:s?.template,user:i?.user??void 0}}function F(e,t,r,n=t.kind){if(t.finished)return Promise.resolve();t.duration=performance.now()-t.startedMs,t.kind=n,t.finished=!0;let o={status:r.status,headers:new Headers(r.headers),kind:n};return k(async()=>{try{let{sections:s,labels:i}=await mt(t,o),a=Object.fromEntries(Object.entries(i).filter(([c])=>!Ge.has(c))),u={id:t.id,version:1,startedAt:new Date(t.startedAt).toISOString(),summary:An(t,o,s),collectors:s,...Object.keys(a).length>0&&{labels:a}};await e.store.write(u)}catch{}})}var O;function de(e){if(O)return O;let t=rr(e.config.storage.path,".token");try{if(xn(t)){let n=kn(t,"utf8").trim();if(/^[a-f0-9]{48}$/.test(n))return O=n}let r=tr(24).toString("hex");return Ve(e.config.storage.path),Rn(t,r,{mode:384}),wn(t,384),O=r}catch{return O=tr(24).toString("hex")}}import{existsSync as Pn}from"fs";import{join as sr}from"path";var Je,Xe="0";async function Mn(){let e=sr(import.meta.dir,"client","debugbar.js"),t;if(Pn(e))t=await Bun.file(e).text();else{let r=await Bun.build({entrypoints:[sr(import.meta.dir,"client","index.ts")],target:"browser",format:"iife",minify:!0}),n=r.outputs[0];if(!r.success||!n)throw Error("The debugbar client could not be bundled.");t=await n.text()}return Xe=Bun.hash(t).toString(36).slice(0,10),{body:t,version:Xe}}function ir(){return Xe}function K(){return Je??=Mn().catch((e)=>{throw Je=void 0,e})}function Tn(){Je=void 0}function G(e){if(!e)return!1;let t=e.trim().toLowerCase().replace(/^\[|\]$/g,"");if(t==="::1"||t==="localhost")return!0;let r=t.startsWith("::ffff:")?t.slice(7):t;return/^127(?:\.\d{1,3}){3}$/.test(r)}function Ze(e,t){if(!e)return!1;let r=e.trim().toLowerCase();if(r=r.startsWith("[")?r.slice(1,r.indexOf("]")):r.replace(/:\d+$/,""),G(r)||r==="localhost"||r.endsWith(".localhost")||r.endsWith(".test"))return!0;if(t)try{let n=new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`https://${t}`).hostname.toLowerCase();if(r===n&&(n==="localhost"||n.endsWith(".localhost")||n.endsWith(".test")||G(n)))return!0}catch{}return!1}function A(e,t={}){if(t.allowRemote===!0)return!0;if(t.peer!==void 0&&!G(t.peer))return!1;let r=e.headers.get("x-forwarded-for");if(r&&!r.split(",").every((s)=>G(s)))return!1;let n=e.headers.get("x-forwarded-host");if(n&&!n.split(",").every((s)=>Ze(s,t.appUrl)))return!1;let o=e.headers.get("host");if(!o)try{o=new URL(e.url).host}catch{return!1}return Ze(o,t.appUrl)}function Ye(e){let t=e.headers.get("sec-fetch-site");if(t&&t!=="same-origin")return!1;let r=e.headers.get("origin");if(r){let n;try{n=new URL(r).host.toLowerCase()}catch{return!1}let o=[e.headers.get("x-forwarded-host"),e.headers.get("host")].flatMap((s)=>s?s.split(","):[]).map((s)=>s.trim().toLowerCase());try{o.push(new URL(e.url).host.toLowerCase())}catch{}if(!o.includes(n))return!1}return!0}function ar(e,t){if(typeof e!=="string"||e.length!==t.length||t.length===0)return!1;let r=0;for(let n=0;n<t.length;n++)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}var et="/__debugbar/",qn="x-debugbar-token";function ur(e){return e.auth?e.auth():import("@stacksjs/auth")}var cr={"Cache-Control":"no-store","X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":"same-origin","X-Robots-Tag":"noindex"};function P(e,t=200,r={}){return new Response(JSON.stringify(e),{status:t,headers:{...cr,"Content-Type":"application/json; charset=utf-8",...r}})}function y(e,t){return P({error:t},e)}function tt(e){return e.startsWith(et)}async function jn(){let{db:e}=await import("@stacksjs/database/runtime");return(await e.selectFrom("users").selectAll().limit(25).execute()).map(te).filter((r)=>r!==null)}async function rt(e){let t=e.config.signInAs?.users,r=await k(async()=>typeof t==="function"?await t():await jn());if(!Array.isArray(r))return[];let n=[];for(let o of r.slice(0,500)){if(!o||typeof o.id!=="number"&&typeof o.id!=="string")continue;let s=(i)=>typeof i==="string"&&i?i.slice(0,200):void 0;n.push({id:o.id,name:s(o.name)??`User #${o.id}`,...s(o.email)&&{email:s(o.email)},...s(o.badge)&&{badge:s(o.badge)},...s(o.description)&&{description:s(o.description)}})}return n}function lr(e){return e.config.signInAs?.enabled!==!1}function nt(e,t){if(!Ye(e))return y(403,"Cross-origin requests are not accepted.");if(!ar(e.headers.get(qn),de(t)))return y(403,"Missing or invalid debugbar token. Reload the page.");return}function dr(e){return(e.headers.get("x-forwarded-proto")?.split(",")[0]?.trim()??new URL(e.url).protocol.replace(":",""))==="https"}async function In(e,t,r){if(!lr(t))return y(404,"Sign in as is disabled.");let n=nt(e,t);if(n)return n;let o;try{o=(await e.json())?.id}catch{return y(400,"Expected a JSON body with an id.")}if(typeof o!=="number"&&typeof o!=="string")return y(400,"Expected a JSON body with an id.");let s=(await rt(t)).find((c)=>String(c.id)===String(o));if(!s)return y(404,"That user is not offered for sign in.");let i=await ur(r),a=await k(()=>i.Auth.loginUsingId(s.id));if(!a)return y(404,"That user no longer exists.");Me();let u=String(a.token);return P({token:u,user:te(a.user)??s,tokenStorageKey:t.config.signInAs?.tokenStorageKey},200,{"Set-Cookie":i.authCookie(u,{secure:dr(e)})})}async function Nn(e,t,r){let n=nt(e,t);if(n)return n;let o=await ur(r);return Me(),P({tokenStorageKey:t.config.signInAs?.tokenStorageKey},200,{"Set-Cookie":o.clearAuthCookie({secure:dr(e)})})}async function On(e,t){let r=lr(t),[n,o]=await Promise.all([r?rt(t).catch(()=>[]):Promise.resolve([]),re(e)]);return P({enabled:r,users:n,current:o.user,tokenStorageKey:t.config.signInAs?.tokenStorageKey})}async function $n(e){let t=await K(),r=`"${t.version}"`,n={...cr,"Content-Type":"text/javascript; charset=utf-8",ETag:r,"Cache-Control":new URL(e.url).searchParams.get("v")===t.version?"private, max-age=31536000, immutable":"no-cache"};if(e.headers.get("if-none-match")===r)return new Response(null,{status:304,headers:n});return new Response(t.body,{headers:n})}async function ot(e,t,r={}){if(!t)return new Response("Not Found",{status:404});if(!A(e,{allowRemote:t.config.allowRemote,appUrl:t.appUrl,peer:r.peer}))return y(403,"The debugbar only answers requests from this machine. Set debugbar.allowRemote to change that.");let n=new URL(e.url),o=n.pathname.slice(et.length).replace(/\/+$/,""),s=e.method.toUpperCase();try{if(o==="assets/debugbar.js"&&(s==="GET"||s==="HEAD"))return await $n(e);if(o==="requests"){if(s==="GET")return P({requests:await t.store.list(Number(n.searchParams.get("limit"))||50)});if(s==="DELETE"){let i=nt(e,t);if(i)return i;return await t.store.clear(),P({cleared:!0})}return y(405,"Method not allowed.")}if(o.startsWith("requests/")&&s==="GET"){let i=o.slice(9),a=q(i)?await t.store.read(i):null;return a?P(a):y(404,"No record with that id.")}if(o==="users"&&s==="GET")return await On(e,t);if(o==="sign-in-as"&&s==="POST")return await In(e,t,r);if(o==="sign-out"&&s==="POST")return await Nn(e,t,r)}catch(i){return y(500,i instanceof Error?i.message:"The debugbar failed to answer.")}return y(404,"Not found.")}var M="X-Debugbar-Id",Bn="/__debugbar/assets/debugbar.js";function fe(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function pr(e){return`<script src="/__debugbar/assets/debugbar.js?v=${fe(e.version)}" defer data-stacks-debugbar data-id="${fe(e.id)}" data-token="${fe(e.token)}" data-options="${fe(JSON.stringify(e.client??{}))}"></script>`}function mr(e){if(!e.body||e.status===204||e.status===304)return!1;if(e.headers.has("content-encoding"))return!1;if(e.headers.get("x-stx-fragment")==="true")return!1;return e.headers.get("content-type")?.toLowerCase().startsWith("text/html")===!0}function st(e,t){if(!mr(e))return;let r=pr(t),n=!1,o=new HTMLRewriter().on("body",{element(s){if(n)return;n=!0,s.append(r,{html:!0})}}).transform(e);return o.headers.delete("content-length"),o}function J(e,t){let r=fr(e,"X-Debugbar-Id",t),n=r.headers.get("server-timing"),o=`debugbar;desc="${t}"`;return fr(r,"Server-Timing",n?`${n}, ${o}`:o)}function fr(e,t,r){try{return e.headers.set(t,r),e}catch{let n=new Headers(e.headers);return n.set(t,r),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}}import Un from"process";function Ln(e){if(!e.headers.has("access-control-allow-origin"))return;let t=e.headers.get("access-control-expose-headers");if(t&&t.toLowerCase().split(",").map((r)=>r.trim()).includes(M.toLowerCase()))return;try{e.headers.set("Access-Control-Expose-Headers",t?`${t}, ${M}`:M)}catch{}}function gr(e){let t={allowRemote:e.config.allowRemote,appUrl:e.appUrl};return async(r,n)=>{let o;try{o=new URL(r.url).pathname}catch{return n()}if(r.method==="OPTIONS"||!ce(e,o)||!A(r,t))return n();let s=le(e,r),i=r;if(i._startNs==null)i._startNs=Un.hrtime.bigint();let a;try{a=await ge(s,n)}catch(c){throw Be(s,c),F(e,s,{status:500,headers:new Headers}),c}if(!(a instanceof Response))return a;let u=J(a,s.id);return Ln(u),F(e,s,u),u}}function _n(e,t={}){let r=V("api",t);if(!r)return!1;return e.use(gr(r)),!0}function Qn(e={}){let t=V("views",e);if(!t)return;let r=new WeakMap,n={shortcut:t.config.shortcut??"alt+shift+d",signInAs:t.config.signInAs?.enabled!==!1,tokenStorageKey:t.config.signInAs?.tokenStorageKey,slowQueryMs:t.config.queries.slowThresholdMs};K().catch(()=>{}),We();let o=(s,i)=>{let a=ze(i),u;try{u=e.clientAddress?.(s,a)}catch{}if(u)return u;return a.requestIP(s)?.address||null};return{runtime:t,onRequest(s,i){let a;try{a=new URL(s.url).pathname}catch{return}if(tt(a))return ot(s,t,{peer:o(s,i)});if(!ce(t,a))return;if(!A(s,{allowRemote:t.config.allowRemote,appUrl:t.appUrl,peer:o(s,i)}))return;let u=le(t,s);r.set(s,u),at(u);return},onResponse(s,i){let a=r.get(s);if(!a)return;if(r.delete(s),i.headers.has(M)){a.finished=!0;return}let u=i.headers.get("content-type")?.toLowerCase()??"",c=u.startsWith("text/html");if(!c&&!u.includes("json")){a.finished=!0;return}let f=i.headers.get("x-stx-fragment")==="true"?"fragment":c?"page":"api",b=i;if(f==="page")b=st(i,{id:a.id,token:de(t),version:ir(),client:n})??i;return b=J(b,a.id),F(t,a,b,f),b}}}var Hn={enabled:()=>ue(),collecting:()=>w()!==void 0,addMessage:v,debug:xe,info:ke,warn:Re,error:Ce,measure:De,startMeasure:Ee,stopMeasure:Se,addMeasure:ve,registerCollector:_},Si=Hn;export{on as BUILT_IN_COLLECTOR_NAMES,Z as Collection,Bn as DEBUGBAR_ASSET_PATH,M as DEBUGBAR_ID_HEADER,et as DEBUGBAR_PREFIX,xr as REDACTED,ve as addMeasure,v as addMessage,Le as analyzeQueries,V as bootDebugbar,We as captureSocketPeers,Zt as capturedSocketPeer,K as clientBundle,Pe as collectors,gr as createApiDebugbarMiddleware,it as createRecordId,Fe as createStore,Qn as createViewsDebugbar,w as currentCollection,xe as debug,Hn as debugbar,ue as debugbarEnabled,vn as debugbarRuntime,pr as debugbarScriptTag,Si as default,Ce as error,ot as handleDebugbarRequest,ke as info,st as injectDebugbar,_n as installApiDebugbar,Ne as isDebugbarEnabled,tt as isDebugbarPath,mr as isInjectableDocument,Ze as isLocalHostname,A as isLocalRequest,G as isLoopbackAddress,wt as isProductionEnvironment,q as isRecordId,Ye as isSameOriginRequest,L as isSensitiveName,De as measure,Ut as normalizeSql,ze as peerAwareServer,m as redact,we as redactBindings,Y as redactHeaders,ye as redactQuery,j as redactUrl,_ as registerCollector,Tn as resetClientBundle,Oe as resolveDebugbarConfig,ge as runWithCollection,Dn as shutdownDebugbar,rt as signInAsUsers,Ee as startMeasure,Se as stopMeasure,Re as warn,J as withRecordId,k as withoutCollection};
10
+ `,{flag:"wx"}).catch(()=>{})})().catch(()=>{o=void 0})}async function u(){try{let d=[];for(let f of await hn(t)){let y=Cn.exec(f);if(y)d.push(y[1])}return d.sort()}catch{return[]}}async function c(){let d=await u(),f=d.slice(0,Math.max(0,d.length-r));await Promise.all(f.map((y)=>kn(N(t,`${y}.json`)).catch(()=>{})));for(let y of f)n.delete(y);return f.length}async function l(d){if(!I(d.id))return;let f=(async()=>{try{await a();let y=N(t,`${d.id}.json`),k=`${y}.${Rn.pid}.tmp`;if(await rr(k,JSON.stringify(d)),await wn(k,y),n.set(d.id,{startedAt:d.startedAt,summary:d.summary}),++s>=20||n.size>r)s=0,await c()}catch{}})();return i.add(f),f.finally(()=>{i.delete(f)}),f}async function p(d){if(!I(d))return null;try{let f=JSON.parse(await yn(N(t,`${d}.json`),"utf8"));return f&&f.id===d?f:null}catch{return null}}async function h(d=50){let f=(await u()).reverse().slice(0,Math.max(1,Math.min(d,r))),y=[];for(let k of f){let v=n.get(k);if(!v){let ge=await p(k);if(!ge)continue;v={startedAt:ge.startedAt,summary:ge.summary},n.set(k,v)}y.push({id:k,...v})}if(n.size>r*2){let k=new Set(f);for(let v of n.keys())if(!k.has(v))n.delete(v)}return y}async function b(){n.clear();let d=await u();await Promise.all(d.map((f)=>xn(N(t,`${f}.json`),{force:!0}).catch(()=>{})))}return{directory:t,write:l,read:p,list:h,clear:b,prune:c,async flush(){while(i.size>0)await Promise.allSettled([...i])}}}var B,Ge=new Set,sr=[];function ir(){try{let e=Ke.app;return{env:e?.env,url:e?.url}}catch{return{}}}function de(e={}){let t=ir();return $e(e.config??Ke.debugbar,{env:e.env,appEnv:e.appEnv??t.env})}function F(e,t={}){if(B)return B;if(!de(t))return;let r=t.root??Pn(),n=Ne(t.config??Ke.debugbar,Mn("framework/debugbar"));Dt(r),Gt(or(r,"resources/views"));let o=new Set(Me().map((s)=>s.name));for(let s of Xt(n)){if(o.has(s.name))continue;sr.push(Q(s)),Ge.add(s.name)}return ft(n,e),Ve(n.storage.path),B={config:n,store:Fe({directory:n.storage.path,maxRequests:n.storage.maxRequests}),process:e,appUrl:ir().url},B}function Tn(){return B}function jn(){pt();for(let e of sr.splice(0))e();Ge.clear(),tr(),B=void 0,L=void 0}function fe(e,t){return!kt(t,e.config.except)}function pe(e,t){let r=new ee(t,e.process,e.config);return mt(r),r}function In(e,t,r){let{queries:n,models:o,route:s,views:i,auth:a}=r,u=(c)=>Array.isArray(r[c])?r[c].length:0;return{method:e.request.method,url:q(e.url),path:e.url.pathname,status:t.status,kind:t.kind,process:e.process,duration:e.elapsed(),memory:Math.round(An.memoryUsage().rss/1048576*10)/10,queries:n?.count??0,queryDuration:n?.duration??0,...o?.total?{models:o.total}:{},logs:u("logs")+u("messages"),exceptions:u("exceptions"),route:s?`${s.method} ${s.path}`:i?.template,user:a?.user??void 0}}function K(e,t,r,n=t.kind){if(t.finished)return Promise.resolve();t.duration=performance.now()-t.startedMs,t.kind=n,t.finished=!0;let o={status:r.status,headers:new Headers(r.headers),kind:n};return R(async()=>{try{let{sections:s,labels:i}=await gt(t,o),a=Object.fromEntries(Object.entries(i).filter(([c])=>!Ge.has(c))),u={id:t.id,version:1,startedAt:new Date(t.startedAt).toISOString(),summary:In(t,o,s),collectors:s,...Object.keys(a).length>0&&{labels:a}};await e.store.write(u)}catch{}})}var L;function me(e){if(L)return L;let t=or(e.config.storage.path,".token");try{if(En(t)){let n=vn(t,"utf8").trim();if(/^[a-f0-9]{48}$/.test(n))return L=n}let r=nr(24).toString("hex");return Ve(e.config.storage.path),Dn(t,r,{mode:384}),Sn(t,384),L=r}catch{return L=nr(24).toString("hex")}}import{existsSync as qn}from"fs";import{join as ar}from"path";var Je,Xe="0";async function On(){let e=ar(import.meta.dir,"client","debugbar.js"),t;if(qn(e))t=await Bun.file(e).text();else{let r=await Bun.build({entrypoints:[ar(import.meta.dir,"client","index.ts")],target:"browser",format:"iife",minify:!0}),n=r.outputs[0];if(!r.success||!n)throw Error("The debugbar client could not be bundled.");t=await n.text()}return Xe=Bun.hash(t).toString(36).slice(0,10),{body:t,version:Xe}}function ur(){return Xe}function G(){return Je??=On().catch((e)=>{throw Je=void 0,e})}function $n(){Je=void 0}var Nn=new RegExp("^127(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}$");function M(e){if(!e)return!1;let t=e.trim().toLowerCase().replace(/^\[|\]$/g,"");if(t==="::1"||t==="localhost")return!0;let r=t.startsWith("::ffff:")?t.slice(7):t;return Nn.test(r)}function J(e,t){if(!e)return!1;let r=e.trim().toLowerCase();if(r.startsWith("[")){let n=r.indexOf("]");if(n===-1)return!1;r=r.slice(1,n)}else r=r.replace(/:\d+$/,"");if(M(r)||r==="localhost"||r.endsWith(".localhost")||r.endsWith(".test"))return!0;if(t)try{let n=new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:`https://${t}`).hostname.toLowerCase();if(r===n&&(n==="localhost"||n.endsWith(".localhost")||n.endsWith(".test")||M(n)))return!0}catch{}return!1}function T(e,t={}){if(t.allowRemote===!0)return!0;if(t.peer!==void 0&&!M(t.peer))return!1;let r=e.headers.get("x-forwarded-for");if(r&&!r.split(",").every((i)=>M(i)))return!1;for(let i of["x-real-ip","cf-connecting-ip","true-client-ip"]){let a=e.headers.get(i);if(a&&!M(a))return!1}let n=e.headers.get("forwarded");if(n)for(let i of n.split(",")){let a=/\bfor=(?:"([^"]+)"|([^;\s]+))/i.exec(i),u=(a?.[1]??a?.[2])?.replace(/^\[|\]$/g,"").replace(/:\d+$/,"");if(u&&!M(u))return!1;let c=/\bhost=(?:"([^"]+)"|([^;\s]+))/i.exec(i),l=c?.[1]??c?.[2];if(l&&!J(l,t.appUrl))return!1}let o=e.headers.get("x-forwarded-host");if(o&&!o.split(",").every((i)=>J(i,t.appUrl)))return!1;let s=e.headers.get("host");if(!s)try{s=new URL(e.url).host}catch{return!1}return J(s,t.appUrl)}function Ze(e){let t=e.headers.get("sec-fetch-site");if(t&&t!=="same-origin")return!1;let r=e.headers.get("origin");if(r){let n;try{n=new URL(r).host.toLowerCase()}catch{return!1}let o=e.headers.get("host")?.trim().toLowerCase(),s=[];if(o)s.push(o);let i=e.headers.get("x-forwarded-host");if(i)for(let a of i.split(",")){let u=a.trim().toLowerCase();if(u&&J(u))s.push(u)}try{s.push(new URL(e.url).host.toLowerCase())}catch{}if(!s.includes(n))return!1}return!0}function cr(e,t){if(typeof e!=="string"||e.length!==t.length||t.length===0)return!1;let r=0;for(let n=0;n<t.length;n++)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}var Ye="/__debugbar/",Ln="x-debugbar-token";function lr(e){return e.auth?e.auth():import("@stacksjs/auth")}var dr={"Cache-Control":"no-store","X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":"same-origin","X-Robots-Tag":"noindex"};function j(e,t=200,r={}){return new Response(JSON.stringify(e),{status:t,headers:{...dr,"Content-Type":"application/json; charset=utf-8",...r}})}function w(e,t){return j({error:t},e)}function et(e){return e.startsWith(Ye)}async function Bn(){let{db:e}=await import("@stacksjs/database/runtime");return(await e.selectFrom("users").selectAll().limit(25).execute()).map(oe).filter((r)=>r!==null)}async function tt(e){let t=e.config.signInAs?.users,r=await R(async()=>typeof t==="function"?await t():await Bn());if(!Array.isArray(r))return[];let n=[];for(let o of r.slice(0,500)){if(!o||typeof o.id!=="number"&&typeof o.id!=="string")continue;let s=(i)=>typeof i==="string"&&i?i.slice(0,200):void 0;n.push({id:o.id,name:s(o.name)??`User #${o.id}`,...s(o.email)&&{email:s(o.email)},...s(o.badge)&&{badge:s(o.badge)},...s(o.description)&&{description:s(o.description)}})}return n}function fr(e){if(e.config.allowRemote===!0)return e.config.signInAs?.enabled===!0;return e.config.signInAs?.enabled!==!1}function rt(e,t){if(!Ze(e))return w(403,"Cross-origin requests are not accepted.");if(!cr(e.headers.get(Ln),me(t)))return w(403,"Missing or invalid debugbar token. Reload the page.");return}function pr(e){return(e.headers.get("x-forwarded-proto")?.split(",")[0]?.trim()??new URL(e.url).protocol.replace(":",""))==="https"}async function Un(e,t,r){if(!fr(t))return w(404,"Sign in as is disabled.");let n=rt(e,t);if(n)return n;let o;try{o=(await e.json())?.id}catch{return w(400,"Expected a JSON body with an id.")}if(typeof o!=="number"&&typeof o!=="string")return w(400,"Expected a JSON body with an id.");let s=(await tt(t)).find((c)=>String(c.id)===String(o));if(!s)return w(404,"That user is not offered for sign in.");let i=await lr(r),a=await R(()=>i.Auth.loginUsingId(s.id));if(!a)return w(404,"That user no longer exists.");Te();let u=String(a.token);return j({token:u,user:oe(a.user)??s,tokenStorageKey:t.config.signInAs?.tokenStorageKey},200,{"Set-Cookie":i.authCookie(u,{secure:pr(e)})})}async function _n(e,t,r){let n=rt(e,t);if(n)return n;let o=await lr(r);return Te(),j({tokenStorageKey:t.config.signInAs?.tokenStorageKey},200,{"Set-Cookie":o.clearAuthCookie({secure:pr(e)})})}async function Qn(e,t){let r=fr(t),[n,o]=await Promise.all([r?tt(t).catch(()=>[]):Promise.resolve([]),se(e)]);return j({enabled:r,users:n,current:o.user,tokenStorageKey:t.config.signInAs?.tokenStorageKey})}async function Hn(e){let t=await G(),r=`"${t.version}"`,n={...dr,"Content-Type":"text/javascript; charset=utf-8",ETag:r,"Cache-Control":new URL(e.url).searchParams.get("v")===t.version?"private, max-age=31536000, immutable":"no-cache"};if(e.headers.get("if-none-match")===r)return new Response(null,{status:304,headers:n});return new Response(t.body,{headers:n})}async function nt(e,t,r={}){if(!t)return new Response("Not Found",{status:404});if(!T(e,{allowRemote:t.config.allowRemote,appUrl:t.appUrl,peer:r.peer}))return w(403,"The debugbar only answers requests from this machine. Set debugbar.allowRemote to change that.");let n=new URL(e.url),o=n.pathname.slice(Ye.length).replace(/\/+$/,""),s=e.method.toUpperCase();try{if(o==="assets/debugbar.js"&&(s==="GET"||s==="HEAD"))return await Hn(e);if(o==="requests"){if(s==="GET")return j({requests:await t.store.list(Number(n.searchParams.get("limit"))||50)});if(s==="DELETE"){let i=rt(e,t);if(i)return i;return await t.store.clear(),j({cleared:!0})}return w(405,"Method not allowed.")}if(o.startsWith("requests/")&&s==="GET"){let i=o.slice(9),a=I(i)?await t.store.read(i):null;return a?j(a):w(404,"No record with that id.")}if(o==="users"&&s==="GET")return await Qn(e,t);if(o==="sign-in-as"&&s==="POST")return await Un(e,t,r);if(o==="sign-out"&&s==="POST")return await _n(e,t,r)}catch(i){return w(500,i instanceof Error?i.message:"The debugbar failed to answer.")}return w(404,"Not found.")}import{brotliCompressSync as Wn,brotliDecompressSync as zn,deflateSync as Vn,gunzipSync as Fn,gzipSync as Kn,inflateSync as Gn}from"zlib";var E="X-Debugbar-Id",gr="/__debugbar/assets/debugbar.js";function X(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function ot(e){let t=e.get("content-security-policy");if(!t)return;let r=new Map;for(let s of t.split(";")){let i=s.trim();if(!i)continue;let a=i.search(/\s/);if(a<0)continue;let u=i.slice(0,a).toLowerCase(),c=i.slice(a+1).trim();if(!r.has(u))r.set(u,c)}let n=r.get("script-src")??r.get("default-src");if(!n)return;return n.match(/'nonce-([^'\s]+)'/i)?.[1]||void 0}function st(e){let t=e.nonce?` nonce="${X(e.nonce)}"`:"";return`<script src="${gr}?v=${X(e.version)}" defer${t} data-stacks-debugbar data-id="${X(e.id)}" data-token="${X(e.token)}" data-options="${X(JSON.stringify(e.client??{}))}"></script>`}function br(e){if(!e.body||e.status===204||e.status===304)return!1;if(e.headers.has("content-encoding"))return!1;if(e.headers.get("x-stx-fragment")==="true")return!1;return e.headers.get("content-type")?.toLowerCase().startsWith("text/html")===!0}function hr(e){let t=e.headers.get("content-encoding")?.trim().toLowerCase();if(t==="gzip"||t==="br"||t==="deflate")return t;return}function Jn(e){if(!e.body||e.status===204||e.status===304)return!1;if(!hr(e))return!1;if(e.headers.get("x-stx-fragment")==="true")return!1;return e.headers.get("content-type")?.toLowerCase().startsWith("text/html")===!0}function yr(e,t){if(!br(e))return;let r=t.nonce??ot(e.headers),n=st(r?{...t,nonce:r}:t),o=!1,s=new HTMLRewriter().on("body",{element(i){if(o)return;o=!0,i.append(n,{html:!0})}}).transform(e);return s.headers.delete("content-length"),s}function it(e,t){let r=yr(e,t);if(r)return r;if(!Jn(e))return;let n=hr(e),o=t.nonce??ot(e.headers),s=st(o?{...t,nonce:o}:t);return(async()=>{let i=new Uint8Array(await e.arrayBuffer()),a;try{let b=n==="gzip"?Fn(i):n==="br"?zn(i):Gn(i);a=new TextDecoder().decode(b)}catch{return new Response(i,{status:e.status,statusText:e.statusText,headers:new Headers(e.headers)})}let u=/<\/body>/i,c=u.test(a)?a.replace(u,(b)=>`${s}${b}`):a,l=new TextEncoder().encode(c),p=n==="gzip"?Kn(l):n==="br"?Wn(l):Vn(l),h=new Headers(e.headers);return h.delete("content-length"),new Response(p,{status:e.status,statusText:e.statusText,headers:h})})()}function Z(e,t){let r=mr(e,E,t),n=r.headers.get("server-timing"),o=`debugbar;desc="${t}"`;return mr(r,"Server-Timing",n?`${n}, ${o}`:o)}function mr(e,t,r){try{return e.headers.set(t,r),e}catch{let n=new Headers(e.headers);return n.set(t,r),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}}import Xn from"process";import{peerAddress as Zn}from"@stacksjs/router";function Yn(e){if(!e.headers.has("access-control-allow-origin"))return;let t=e.headers.get("access-control-expose-headers");if(t&&t.toLowerCase().split(",").map((r)=>r.trim()).includes(E.toLowerCase()))return;try{e.headers.set("Access-Control-Expose-Headers",t?`${t}, ${E}`:E)}catch{}}function wr(e){let t={allowRemote:e.config.allowRemote,appUrl:e.appUrl};return async(r,n)=>{let o;try{o=new URL(r.url).pathname}catch{return n()}let s=Zn(r);if(r.method==="OPTIONS"||!fe(e,o)||!T(r,s?{...t,peer:s}:t))return n();let i=pe(e,r),a=r;if(a._startNs==null)a._startNs=Xn.hrtime.bigint();let u;try{u=await he(i,n)}catch(l){throw Be(i,l),K(e,i,{status:500,headers:new Headers}),l}if(!(u instanceof Response))return u;let c=Z(u,i.id);return Yn(c),K(e,i,c),c}}function eo(e,t={}){let r=F("api",t);if(!r)return!1;return e.use(wr(r)),!0}function to(e={}){let t=F("views",e);if(!t)return;let r=new WeakMap,n={shortcut:t.config.shortcut??"alt+shift+d",signInAs:t.config.signInAs?.enabled!==!1,tokenStorageKey:t.config.signInAs?.tokenStorageKey,slowQueryMs:t.config.queries.slowThresholdMs};G().catch(()=>{}),We();let o=(s,i)=>{let a=ze(i),u;try{u=e.clientAddress?.(s,a)}catch{}if(u)return u;return a.requestIP(s)?.address||null};return{runtime:t,onRequest(s,i){let a;try{a=new URL(s.url).pathname}catch{return}if(et(a))return nt(s,t,{peer:o(s,i)});if(!fe(t,a))return;if(!T(s,{allowRemote:t.config.allowRemote,appUrl:t.appUrl,peer:o(s,i)}))return;let u=pe(t,s);r.set(s,u),ut(u);return},onResponse(s,i){let a=r.get(s);if(!a)return;if(r.delete(s),i.headers.has(E)){a.finished=!0;return}let u=i.headers.get("content-type")?.toLowerCase()??"",c=u.startsWith("text/html"),l=i.status>=300&&i.status<400&&i.headers.has("location");if(!c&&!u.includes("json")&&!l){a.finished=!0;return}let h=i.headers.get("x-stx-fragment")==="true"?"fragment":c||l?"page":"api",b=(d)=>{let f=Z(d,a.id);return K(t,a,f,h),f};if(h==="page"&&c){let d=it(i,{id:a.id,token:me(t),version:ur(),client:n});if(d instanceof Promise)return d.then(b);return b(d??i)}return b(i)}}}var ro={enabled:()=>de(),collecting:()=>x()!==void 0,addMessage:A,debug:ke,info:Re,warn:Ce,error:Se,measure:Ae,startMeasure:Ee,stopMeasure:ve,addMeasure:De,registerCollector:Q},Qi=ro;export{ln as BUILT_IN_COLLECTOR_NAMES,ee as Collection,gr as DEBUGBAR_ASSET_PATH,E as DEBUGBAR_ID_HEADER,Ye as DEBUGBAR_PREFIX,Sr as REDACTED,De as addMeasure,A as addMessage,_e as analyzeQueries,F as bootDebugbar,We as captureSocketPeers,er as capturedSocketPeer,G as clientBundle,Me as collectors,wr as createApiDebugbarMiddleware,at as createRecordId,Fe as createStore,to as createViewsDebugbar,x as currentCollection,ke as debug,ro as debugbar,de as debugbarEnabled,Tn as debugbarRuntime,st as debugbarScriptTag,Qi as default,Se as error,ot as extractCspScriptNonce,nt as handleDebugbarRequest,Re as info,yr as injectDebugbar,it as injectDebugbarResponse,eo as installApiDebugbar,$e as isDebugbarEnabled,et as isDebugbarPath,br as isInjectableDocument,J as isLocalHostname,T as isLocalRequest,M as isLoopbackAddress,xt as isProductionEnvironment,I as isRecordId,Ze as isSameOriginRequest,_ as isSensitiveName,Ae as measure,_t as normalizeSql,ze as peerAwareServer,m as redact,xe as redactBindings,re as redactHeaders,we as redactQuery,q as redactUrl,Q as registerCollector,$n as resetClientBundle,Ne as resolveDebugbarConfig,he as runWithCollection,jn as shutdownDebugbar,tt as signInAsUsers,Ee as startMeasure,ve as stopMeasure,Ce as warn,Z as withRecordId,R as withoutCollection};
package/dist/inject.d.ts CHANGED
@@ -1,5 +1,10 @@
1
+ /**
2
+ * Extract the CSP script nonce from `Content-Security-Policy` headers, checking
3
+ * `script-src` first and falling back to `default-src`.
4
+ */
5
+ export declare function extractCspScriptNonce(headers: Headers): string | undefined;
1
6
  export declare function debugbarScriptTag(options: InjectOptions): string;
2
- /** A full, uncompressed HTML document: the only response the script goes into. */
7
+ /** A full, uncompressed HTML document: the only response the sync stream rewriter touches. */
3
8
  export declare function isInjectableDocument(response: Response): boolean;
4
9
  /**
5
10
  * The response with the bar's script appended to its `<body>`, or undefined
@@ -10,6 +15,12 @@ export declare function isInjectableDocument(response: Response): boolean;
10
15
  * passes through untouched.
11
16
  */
12
17
  export declare function injectDebugbar(response: Response, options: InjectOptions): Response | undefined;
18
+ /**
19
+ * Inject the debugbar into either an uncompressed HTML document (synchronously)
20
+ * or a `gzip`/`br`/`deflate`-compressed HTML document (decompressing, injecting,
21
+ * and recompressing with the same `Content-Encoding`).
22
+ */
23
+ export declare function injectDebugbarResponse(response: Response, options: InjectOptions): Response | Promise<Response> | undefined;
13
24
  /**
14
25
  * `response` carrying the record id, as `X-Debugbar-Id` and as a
15
26
  * `Server-Timing` entry.
@@ -22,19 +33,14 @@ export declare function injectDebugbar(response: Response, options: InjectOption
22
33
  export declare function withRecordId(response: Response, id: string): Response;
23
34
  /** `response` carrying `name: value`, copied when its headers cannot be written. */
24
35
  export declare function withHeader(response: Response, name: string, value: string): Response;
25
- /**
26
- * Putting the bar on a page.
27
- *
28
- * One `<script>` before `</body>`, on full HTML documents only. An stx router
29
- * navigation answers with a fragment that is swapped into the page already
30
- * showing the bar, so a fragment gets the record id as a header and nothing
31
- * in its body.
32
- */
33
36
  export declare const DEBUGBAR_ID_HEADER: 'X-Debugbar-Id';
34
37
  export declare const DEBUGBAR_ASSET_PATH: '/__debugbar/assets/debugbar.js';
35
38
  export declare interface InjectOptions {
36
39
  id: string
37
40
  token: string
38
41
  version: string
42
+ nonce?: string
39
43
  client?: Record<string, unknown>
40
44
  }
45
+ declare type SupportedEncoding = 'gzip' | 'br' | 'deflate';
46
+ export {};
package/dist/types.d.ts CHANGED
@@ -37,6 +37,15 @@ export declare interface QueriesSection {
37
37
  nPlusOne: Array<{ shape: string, count: number, sample: string, source?: string }>
38
38
  statements: QueryEntry[]
39
39
  }
40
+ export declare interface ModelCountEntry {
41
+ model: string
42
+ table?: string
43
+ count: number
44
+ }
45
+ export declare interface ModelsSection {
46
+ total: number
47
+ models: ModelCountEntry[]
48
+ }
40
49
  export declare interface LogEntry {
41
50
  level: string
42
51
  message: string
@@ -111,6 +120,7 @@ export declare interface DebugbarSummary {
111
120
  memory: number
112
121
  queries: number
113
122
  queryDuration: number
123
+ models?: number
114
124
  logs: number
115
125
  exceptions: number
116
126
  route?: string
package/dist/views.d.ts CHANGED
@@ -14,5 +14,5 @@ export declare interface ViewsDebugbarOptions extends BootOptions {
14
14
  export declare interface ViewsDebugbar {
15
15
  readonly runtime: DebugbarRuntime
16
16
  onRequest: (request: Request, server?: unknown) => Promise<Response> | undefined
17
- onResponse: (request: Request, response: Response) => Response | undefined
17
+ onResponse: (request: Request, response: Response) => Response | Promise<Response> | undefined
18
18
  }
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/debugbar",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.735",
5
+ "version": "0.75.755",
6
6
  "description": "The Stacks debugbar: a request inspector for development.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -58,19 +58,19 @@
58
58
  "prepublishOnly": "bun run build"
59
59
  },
60
60
  "devDependencies": {
61
- "better-dx": "^0.2.39"
61
+ "better-dx": "^0.2.41"
62
62
  },
63
63
  "dependencies": {
64
- "@stacksjs/auth": "0.75.735",
65
- "@stacksjs/config": "0.75.735",
66
- "@stacksjs/database": "0.75.735",
67
- "@stacksjs/error-handling": "0.75.735",
68
- "@stacksjs/events": "0.75.735",
69
- "@stacksjs/logging": "0.75.735",
70
- "@stacksjs/path": "0.75.735",
71
- "@stacksjs/query-builder": "0.75.735",
72
- "@stacksjs/queue": "0.75.735",
73
- "@stacksjs/router": "0.75.735",
74
- "@stacksjs/types": "0.75.735"
64
+ "@stacksjs/auth": "0.75.755",
65
+ "@stacksjs/config": "0.75.755",
66
+ "@stacksjs/database": "0.75.755",
67
+ "@stacksjs/error-handling": "0.75.755",
68
+ "@stacksjs/events": "0.75.755",
69
+ "@stacksjs/logging": "0.75.755",
70
+ "@stacksjs/path": "0.75.755",
71
+ "@stacksjs/query-builder": "0.75.755",
72
+ "@stacksjs/queue": "0.75.755",
73
+ "@stacksjs/router": "0.75.755",
74
+ "@stacksjs/types": "0.75.755"
75
75
  }
76
76
  }