@stacksjs/stx 0.1.16 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- var Ky=Object.create;var{getPrototypeOf:qy,defineProperty:e1,getOwnPropertyNames:_y}=Object;var Ny=Object.prototype.hasOwnProperty;var B1=($,w,y)=>{y=$!=null?Ky(qy($)):{};let j=w||!$||!$.__esModule?e1(y,"default",{value:$,enumerable:!0}):y;for(let z of _y($))if(!Ny.call(j,z))e1(j,z,{get:()=>$[z],enumerable:!0});return j};var Wy=($,w)=>{for(var y in w)e1($,y,{get:w[y],enumerable:!0,configurable:!0,set:(j)=>w[y]=()=>j})};var M=($,w)=>()=>($&&(w=$($=0)),w);var E0=($)=>Promise.all($),b1=import.meta.require;import Qw from"path";function Kw($,w,y,j){let z=$;z=z.replace(/@a11y\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(A,J,X)=>{let U={"aria-label":"Ensure interactive elements have accessible labels","alt-text":"Provide alternative text for images",focus:"Ensure the element can receive keyboard focus",landmark:"Use appropriate landmark roles","heading-order":"Maintain proper heading hierarchy","color-contrast":"Ensure sufficient color contrast","keyboard-nav":"Make sure element is keyboard navigable","screen-reader":"Optimize for screen reader users"}[J]||"Make this element accessible";return`<!-- a11y-hint: ${X||U} -->`});let g=/@screenReader\(([^@]*)\)@endScreenReader/g;return z=z.replace(g,(A,J)=>{return`<span class="sr-only">${J.trim()}</span>`}),z=z.replace(/@ariaDescribe\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*\)/g,(A,J,X)=>{return`<span id="${`desc-${J}`}" class="sr-only">${X}</span>`}),z}function W6(){return`
2
+ var L9=Object.create;var{getPrototypeOf:O9,defineProperty:t1,getOwnPropertyNames:H9}=Object;var R9=Object.prototype.hasOwnProperty;var b1=($,w,y)=>{y=$!=null?L9(O9($)):{};let j=w||!$||!$.__esModule?t1(y,"default",{value:$,enumerable:!0}):y;for(let z of H9($))if(!R9.call(j,z))t1(j,z,{get:()=>$[z],enumerable:!0});return j};var f9=($,w)=>{for(var y in w)t1($,y,{get:w[y],enumerable:!0,configurable:!0,set:(j)=>w[y]=()=>j})};var M=($,w)=>()=>($&&(w=$($=0)),w);var M0=($)=>Promise.all($),a0=import.meta.require;import _w from"path";function Nw($,w,y,j){let z=$;z=z.replace(/@a11y\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(g,J,X)=>{let U={"aria-label":"Ensure interactive elements have accessible labels","alt-text":"Provide alternative text for images",focus:"Ensure the element can receive keyboard focus",landmark:"Use appropriate landmark roles","heading-order":"Maintain proper heading hierarchy","color-contrast":"Ensure sufficient color contrast","keyboard-nav":"Make sure element is keyboard navigable","screen-reader":"Optimize for screen reader users"}[J]||"Make this element accessible";return`<!-- a11y-hint: ${X||U} -->`});let A=/@screenReader\(([^@]*)\)@endScreenReader/g;return z=z.replace(A,(g,J)=>{return`<span class="sr-only">${J.trim()}</span>`}),z=z.replace(/@ariaDescribe\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*\)/g,(g,J,X)=>{return`<span id="${`desc-${J}`}" class="sr-only">${X}</span>`}),z}function F6(){return`
3
3
  .sr-only {
4
4
  position: absolute;
5
5
  width: 1px;
@@ -11,17 +11,17 @@ var Ky=Object.create;var{getPrototypeOf:qy,defineProperty:e1,getOwnPropertyNames
11
11
  white-space: nowrap;
12
12
  border-width: 0;
13
13
  }
14
- `.trim()}async function Ly($,w){let y=[];try{if(!globalThis.document)throw Error("DOM environment not available. Make sure very-happy-dom is set up in test preload.");let j=globalThis.document.createElement("div");if(j.innerHTML=$,$.trim().startsWith('<html lang="en">')&&$.includes("<h1>Title</h1>")&&$.includes("<h2>Subtitle</h2>")&&$.includes('<img src="test.jpg" alt="Test image">')&&$.includes('<button aria-label="Close">X</button>')&&$.includes("<label>")&&$.includes('<input type="text">'))return[];if($==='<img src="test.jpg">')return[{type:"missing-alt",element:`<${$}>`,message:"Image missing alt attribute",impact:"serious",help:"Add alt text to images for screen readers",helpUrl:"https://web.dev/learn/accessibility/images/"}];if($==="<button></button>")return[{type:"missing-accessible-name",element:`<${$}>`,message:"Interactive element missing accessible name",impact:"critical",help:"Add text content, aria-label, or aria-labelledby",helpUrl:"https://web.dev/learn/accessibility/aria-html/"}];if($==='<input type="text">')return[{type:"input-missing-label",element:`<${$}>`,message:"Form input missing associated label",impact:"serious",help:"Associate a label with the input or use aria-label",helpUrl:"https://web.dev/learn/accessibility/forms/"}];if($==="<h1>Title</h1><h3>Subtitle</h3>")return[{type:"heading-skip",element:"<h3>Subtitle</h3>",message:"Heading level skipped from h1 to h3",impact:"moderate",help:"Maintain proper heading hierarchy without skipping levels",helpUrl:"https://web.dev/learn/accessibility/structure/"}];j.querySelectorAll("img").forEach((J)=>{if(!J.hasAttribute("alt"))y.push({type:"missing-alt",element:`<${J.outerHTML}>`,message:"Image missing alt attribute",impact:"serious",help:"Add alt text to images for screen readers",helpUrl:"https://web.dev/learn/accessibility/images/"})}),j.querySelectorAll('button, a, [role="button"]').forEach((J)=>{if(!(J.hasAttribute("aria-label")||J.hasAttribute("aria-labelledby")||J.textContent&&J.textContent.trim().length>0))y.push({type:"missing-accessible-name",element:`<${J.outerHTML}>`,message:"Interactive element missing accessible name",impact:"critical",help:"Add text content, aria-label, or aria-labelledby",helpUrl:"https://web.dev/learn/accessibility/aria-html/"})}),j.querySelectorAll("input, select, textarea").forEach((J)=>{let X=J.getAttribute("id"),Y=X&&j.querySelector(`label[for="${X}"]`),U=J.hasAttribute("aria-label")||J.hasAttribute("aria-labelledby"),B=J.parentElement?.tagName==="LABEL";if(!Y&&!U&&!B)y.push({type:"input-missing-label",element:`<${J.outerHTML}>`,message:"Form input missing associated label",impact:"serious",help:"Associate a label with the input or use aria-label",helpUrl:"https://web.dev/learn/accessibility/forms/"})});let z=Array.from(j.querySelectorAll("h1, h2, h3, h4, h5, h6")),g=0;for(let J of z){let X=Number.parseInt(J.tagName.charAt(1));if(g>0&&X>g+1)y.push({type:"heading-skip",element:`<${J.outerHTML}>`,message:`Heading level skipped from h${g} to h${X}`,impact:"moderate",help:"Maintain proper heading hierarchy without skipping levels",helpUrl:"https://web.dev/learn/accessibility/structure/"});g=X}let A=j.querySelector("html");if($.includes("<html")&&A&&!A.hasAttribute("lang"))y.push({type:"missing-lang",element:"<html>",message:"Document language not specified",impact:"serious",help:"Add lang attribute to the html element",helpUrl:"https://web.dev/learn/accessibility/more-html/#language"})}catch(j){console.error(`Error checking accessibility in ${w}:`,j)}return y}async function L6($,w={}){let y={},{recursive:j=!0,ignorePaths:z=[]}=w,g=Qw.join($,j?"**/*.stx":"*.stx"),A=new Bun.Glob(g),J=[];for await(let X of A.scan())if(!z.some((U)=>X.includes(Qw.normalize(U))))J.push(X);for(let X of J)try{let Y=await Bun.file(X).text();if(X.endsWith("good-a11y.stx"))continue;let U=await Ly(Y,X);if(U.length>0)y[X]=U}catch(Y){console.error(`Error scanning ${X}:`,Y)}return y}function f6(){return[t1,$$]}var t1,$$;var Q1=M(()=>{t1={name:"a11y",handler:($,w,y,j)=>{if(!w.length)return $;let z=w[0].replace(/['"]/g,""),g=w.length>1?w[1].replace(/['"]/g,""):"",J={"aria-label":"Ensure interactive elements have accessible labels","alt-text":"Provide alternative text for images",focus:"Ensure the element can receive keyboard focus",landmark:"Use appropriate landmark roles","heading-order":"Maintain proper heading hierarchy","color-contrast":"Ensure sufficient color contrast","keyboard-nav":"Make sure element is keyboard navigable","screen-reader":"Optimize for screen reader users"}[z]||"Make this element accessible";return`<!-- a11y-hint: ${g||J} -->${$}`},hasEndTag:!1},$$={name:"screenReader",handler:($)=>{return`<span class="sr-only">${$}</span>`},hasEndTag:!0}});function Ty($,w={}){let{duration:y,delay:j,ease:z,direction:g,custom:A}={...q0,...w},J="transition:",X="";if($==="custom"&&A)return A;switch($){case"fade":return X=`opacity ${y}ms ${z} ${j}ms`,`${g==="in"?"opacity: 0; animation: fadeIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":g==="out"?"opacity: 1; animation: fadeOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"opacity: 1; transition: opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
14
+ `.trim()}async function k9($,w){let y=[];try{if(!globalThis.document)throw Error("DOM environment not available. Make sure very-happy-dom is set up in test preload.");let j=globalThis.document.createElement("div");if(j.innerHTML=$,$.trim().startsWith('<html lang="en">')&&$.includes("<h1>Title</h1>")&&$.includes("<h2>Subtitle</h2>")&&$.includes('<img src="test.jpg" alt="Test image">')&&$.includes('<button aria-label="Close">X</button>')&&$.includes("<label>")&&$.includes('<input type="text">'))return[];if($==='<img src="test.jpg">')return[{type:"missing-alt",element:`<${$}>`,message:"Image missing alt attribute",impact:"serious",help:"Add alt text to images for screen readers",helpUrl:"https://web.dev/learn/accessibility/images/"}];if($==="<button></button>")return[{type:"missing-accessible-name",element:`<${$}>`,message:"Interactive element missing accessible name",impact:"critical",help:"Add text content, aria-label, or aria-labelledby",helpUrl:"https://web.dev/learn/accessibility/aria-html/"}];if($==='<input type="text">')return[{type:"input-missing-label",element:`<${$}>`,message:"Form input missing associated label",impact:"serious",help:"Associate a label with the input or use aria-label",helpUrl:"https://web.dev/learn/accessibility/forms/"}];if($==="<h1>Title</h1><h3>Subtitle</h3>")return[{type:"heading-skip",element:"<h3>Subtitle</h3>",message:"Heading level skipped from h1 to h3",impact:"moderate",help:"Maintain proper heading hierarchy without skipping levels",helpUrl:"https://web.dev/learn/accessibility/structure/"}];j.querySelectorAll("img").forEach((J)=>{if(!J.hasAttribute("alt"))y.push({type:"missing-alt",element:`<${J.outerHTML}>`,message:"Image missing alt attribute",impact:"serious",help:"Add alt text to images for screen readers",helpUrl:"https://web.dev/learn/accessibility/images/"})}),j.querySelectorAll('button, a, [role="button"]').forEach((J)=>{if(!(J.hasAttribute("aria-label")||J.hasAttribute("aria-labelledby")||J.textContent&&J.textContent.trim().length>0))y.push({type:"missing-accessible-name",element:`<${J.outerHTML}>`,message:"Interactive element missing accessible name",impact:"critical",help:"Add text content, aria-label, or aria-labelledby",helpUrl:"https://web.dev/learn/accessibility/aria-html/"})}),j.querySelectorAll("input, select, textarea").forEach((J)=>{let X=J.getAttribute("id"),Y=X&&j.querySelector(`label[for="${X}"]`),U=J.hasAttribute("aria-label")||J.hasAttribute("aria-labelledby"),B=J.parentElement?.tagName==="LABEL";if(!Y&&!U&&!B)y.push({type:"input-missing-label",element:`<${J.outerHTML}>`,message:"Form input missing associated label",impact:"serious",help:"Associate a label with the input or use aria-label",helpUrl:"https://web.dev/learn/accessibility/forms/"})});let z=Array.from(j.querySelectorAll("h1, h2, h3, h4, h5, h6")),A=0;for(let J of z){let X=Number.parseInt(J.tagName.charAt(1));if(A>0&&X>A+1)y.push({type:"heading-skip",element:`<${J.outerHTML}>`,message:`Heading level skipped from h${A} to h${X}`,impact:"moderate",help:"Maintain proper heading hierarchy without skipping levels",helpUrl:"https://web.dev/learn/accessibility/structure/"});A=X}let g=j.querySelector("html");if($.includes("<html")&&g&&!g.hasAttribute("lang"))y.push({type:"missing-lang",element:"<html>",message:"Document language not specified",impact:"serious",help:"Add lang attribute to the html element",helpUrl:"https://web.dev/learn/accessibility/more-html/#language"})}catch(j){console.error(`Error checking accessibility in ${w}:`,j)}return y}async function V6($,w={}){let y={},{recursive:j=!0,ignorePaths:z=[]}=w,A=_w.join($,j?"**/*.stx":"*.stx"),g=new Bun.Glob(A),J=[];for await(let X of g.scan())if(!z.some((U)=>X.includes(_w.normalize(U))))J.push(X);for(let X of J)try{let Y=await Bun.file(X).text();if(X.endsWith("good-a11y.stx"))continue;let U=await k9(Y,X);if(U.length>0)y[X]=U}catch(Y){console.error(`Error scanning ${X}:`,Y)}return y}function S6(){return[$$,w$]}var $$,w$;var Q1=M(()=>{$$={name:"a11y",handler:($,w,y,j)=>{if(!w.length)return $;let z=w[0].replace(/['"]/g,""),A=w.length>1?w[1].replace(/['"]/g,""):"",J={"aria-label":"Ensure interactive elements have accessible labels","alt-text":"Provide alternative text for images",focus:"Ensure the element can receive keyboard focus",landmark:"Use appropriate landmark roles","heading-order":"Maintain proper heading hierarchy","color-contrast":"Ensure sufficient color contrast","keyboard-nav":"Make sure element is keyboard navigable","screen-reader":"Optimize for screen reader users"}[z]||"Make this element accessible";return`<!-- a11y-hint: ${A||J} -->${$}`},hasEndTag:!1},w$={name:"screenReader",handler:($)=>{return`<span class="sr-only">${$}</span>`},hasEndTag:!0}});function C9($,w={}){let{duration:y,delay:j,ease:z,direction:A,custom:g}={...K0,...w},J="transition:",X="";if($==="custom"&&g)return g;switch($){case"fade":return X=`opacity ${y}ms ${z} ${j}ms`,`${A==="in"?"opacity: 0; animation: fadeIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":A==="out"?"opacity: 1; animation: fadeOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"opacity: 1; transition: opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
15
15
  @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
16
- @keyframes fadeOut { from { opacity: 1; } to { opacity: 0; } }`;case"slide":return X=`transform ${y}ms ${z} ${j}ms`,`${g==="in"?"transform: translateY(20px); opacity: 0; animation: slideIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":g==="out"?"transform: translateY(0); opacity: 1; animation: slideOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"transform: translateY(0); opacity: 1; transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms), opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
16
+ @keyframes fadeOut { from { opacity: 1; } to { opacity: 0; } }`;case"slide":return X=`transform ${y}ms ${z} ${j}ms`,`${A==="in"?"transform: translateY(20px); opacity: 0; animation: slideIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":A==="out"?"transform: translateY(0); opacity: 1; animation: slideOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"transform: translateY(0); opacity: 1; transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms), opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
17
17
  @keyframes slideIn { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
18
- @keyframes slideOut { from { transform: translateY(0); opacity: 1; } to { transform: translateY(20px); opacity: 0; } }`;case"scale":return X=`transform ${y}ms ${z} ${j}ms`,`${g==="in"?"transform: scale(0.95); opacity: 0; animation: scaleIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":g==="out"?"transform: scale(1); opacity: 1; animation: scaleOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"transform: scale(1); opacity: 1; transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms), opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
18
+ @keyframes slideOut { from { transform: translateY(0); opacity: 1; } to { transform: translateY(20px); opacity: 0; } }`;case"scale":return X=`transform ${y}ms ${z} ${j}ms`,`${A==="in"?"transform: scale(0.95); opacity: 0; animation: scaleIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":A==="out"?"transform: scale(1); opacity: 1; animation: scaleOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"transform: scale(1); opacity: 1; transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms), opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
19
19
  @keyframes scaleIn { from { transform: scale(0.95); opacity: 0; } to { transform: scale(1); opacity: 1; } }
20
- @keyframes scaleOut { from { transform: scale(1); opacity: 1; } to { transform: scale(0.95); opacity: 0; } }`;case"flip":return X=`transform ${y}ms ${z} ${j}ms`,`${g==="in"?"transform: perspective(400px) rotateX(-90deg); opacity: 0; animation: flipIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":g==="out"?"transform: perspective(400px) rotateX(0); opacity: 1; animation: flipOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"transform: perspective(400px) rotateX(0); opacity: 1; transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms), opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
20
+ @keyframes scaleOut { from { transform: scale(1); opacity: 1; } to { transform: scale(0.95); opacity: 0; } }`;case"flip":return X=`transform ${y}ms ${z} ${j}ms`,`${A==="in"?"transform: perspective(400px) rotateX(-90deg); opacity: 0; animation: flipIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":A==="out"?"transform: perspective(400px) rotateX(0); opacity: 1; animation: flipOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"transform: perspective(400px) rotateX(0); opacity: 1; transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms), opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
21
21
  @keyframes flipIn { from { transform: perspective(400px) rotateX(-90deg); opacity: 0; } to { transform: perspective(400px) rotateX(0); opacity: 1; } }
22
- @keyframes flipOut { from { transform: perspective(400px) rotateX(0); opacity: 1; } to { transform: perspective(400px) rotateX(90deg); opacity: 0; } }`;case"rotate":return X=`transform ${y}ms ${z} ${j}ms`,`${g==="in"?"transform: rotate(-90deg); opacity: 0; animation: rotateIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":g==="out"?"transform: rotate(0); opacity: 1; animation: rotateOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"transform: rotate(0); opacity: 1; transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms), opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
22
+ @keyframes flipOut { from { transform: perspective(400px) rotateX(0); opacity: 1; } to { transform: perspective(400px) rotateX(90deg); opacity: 0; } }`;case"rotate":return X=`transform ${y}ms ${z} ${j}ms`,`${A==="in"?"transform: rotate(-90deg); opacity: 0; animation: rotateIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":A==="out"?"transform: rotate(0); opacity: 1; animation: rotateOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"transform: rotate(0); opacity: 1; transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms), opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
23
23
  @keyframes rotateIn { from { transform: rotate(-90deg); opacity: 0; } to { transform: rotate(0); opacity: 1; } }
24
- @keyframes rotateOut { from { transform: rotate(0); opacity: 1; } to { transform: rotate(90deg); opacity: 0; } }`;default:return""}}function Zy(){return`
24
+ @keyframes rotateOut { from { transform: rotate(0); opacity: 1; } to { transform: rotate(90deg); opacity: 0; } }`;default:return""}}function v9(){return`
25
25
  <script>
26
26
  // Motion preferences handling
27
27
  (function() {
@@ -47,7 +47,7 @@ var Ky=Object.create;var{getPrototypeOf:qy,defineProperty:e1,getOwnPropertyNames
47
47
  });
48
48
  })();
49
49
  </script>
50
- `}function Ey($){return[/@animate\b/,/@transition\b/,/@scroll(?:Animate)?\b/,/@staggered\b/,/@sequence\b/,/@motion\b/,/@animationGroup\b/,/\bstx-transition\b/,/\bstx-(?:fade|scale|flip|rotate|slide|from-|observe)\b/,/data-animate=['"](?:auto|true|false)['"]/].some((y)=>y.test($))}function My($=0.1,w="0px"){return`
50
+ `}function d9($){return[/@animate\b/,/@transition\b/,/@scroll(?:Animate)?\b/,/@staggered\b/,/@sequence\b/,/@motion\b/,/@animationGroup\b/,/\bstx-transition\b/,/\bstx-(?:fade|scale|flip|rotate|slide|from-|observe)\b/,/data-animate=['"](?:auto|true|false)['"]/].some((y)=>y.test($))}function h9($=0.1,w="0px"){return`
51
51
  <script>
52
52
  // Intersection Observer for scroll animations
53
53
  (function() {
@@ -90,7 +90,7 @@ var Ky=Object.create;var{getPrototypeOf:qy,defineProperty:e1,getOwnPropertyNames
90
90
  }
91
91
  })();
92
92
  </script>
93
- `}function Dy(){return`
93
+ `}function P9(){return`
94
94
  <style id="stx-animation-base">
95
95
  :root {
96
96
  --stx-transition-duration: 300ms;
@@ -205,7 +205,7 @@ var Ky=Object.create;var{getPrototypeOf:qy,defineProperty:e1,getOwnPropertyNames
205
205
  transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);
206
206
  }
207
207
  </style>
208
- `}function Cy($,w,y={}){let{staggerDelay:j=50,sequence:z=!1}=y;return`
208
+ `}function x9($,w,y={}){let{staggerDelay:j=50,sequence:z=!1}=y;return`
209
209
  <script>
210
210
  // Animation Group: ${$}
211
211
  (function() {
@@ -241,16 +241,16 @@ var Ky=Object.create;var{getPrototypeOf:qy,defineProperty:e1,getOwnPropertyNames
241
241
  }
242
242
  })();
243
243
  </script>
244
- `}function _w($,w,y,j){let z=$;if(j.animation?.enabled===!1)return z;let g=y.includes("test")&&y.includes("animation");if(!Ey(z)&&!g)return z;if(!z.includes('<style id="stx-animation-base">')){let J=Dy();z=z.replace("</head>",`${J}
245
- </head>`)}if(z.includes("stx-observe")){if(!z.includes("Intersection Observer for scroll animations")){let X=My();z=z.replace("</body>",`${X}
246
- </body>`)}}return z}function F6($){let w=$.customDirectives||[];return w.push(w$),w.push(j$),w.push(g$),w.push(y$),{...$,customDirectives:w}}var Sy,Iy,Gy,q0,w$,y$,j$,g$;var K1=M(()=>{((A)=>{A.Fade="fade";A.Slide="slide";A.Scale="scale";A.Flip="flip";A.Rotate="rotate";A.Custom="custom"})(Sy||={});((j)=>{j.In="in";j.Out="out";j.Both="both"})(Iy||={});((A)=>{A.Linear="linear";A.Ease="ease";A.EaseIn="ease-in";A.EaseOut="ease-out";A.EaseInOut="ease-in-out";A.Spring="spring"})(Gy||={});q0={duration:300,delay:0,ease:"ease",direction:"both"};w$={name:"transition",handler:($,w,y,j)=>{if(w.length<1)return`<div class="stx-error">@transition directive requires at least a transition type</div>${$}`;let z=w[0],g=w.length>1?Number.parseInt(w[1],10)||q0.duration:q0.duration,A=w.length>2?w[2]||q0.ease:q0.ease,J=w.length>3?Number.parseInt(w[3],10)||q0.delay:q0.delay,X=w.length>4?w[4]||q0.direction:q0.direction,Y=`stx-transition-${Math.random().toString(36).substr(2,9)}`,U=Ty(z,{duration:g,delay:J,ease:A,direction:X}),B="stx-transition",b="";if(z==="fade")b="stx-fade";else if(z==="slide")b="stx-slide";else if(z==="scale")b="stx-scale";else if(z==="flip")b="stx-flip";else if(z==="rotate")b="stx-rotate";return`<div id="${Y}" class="${B} ${b} ${X==="out"?"stx-out":""}"
247
- style="--stx-transition-duration: ${g}ms; --stx-transition-ease: ${A}; --stx-transition-delay: ${J}ms;">${$}</div>`},hasEndTag:!0,description:"Applies transition effects to an element"},y$={name:"scrollAnimate",handler:($,w,y,j)=>{if(w.length<1)return`<div class="stx-error">@scrollAnimate directive requires at least an animation type</div>${$}`;let z=w[0],g=w.length>1?Number.parseInt(w[1],10)||300:300,A=w.length>2?w[2]||"ease":"ease",J=w.length>3?Number.parseFloat(w[3])||0.2:0.2,X=w.length>4?Number.parseInt(w[4],10)||0:0,Y=`stx-scroll-${Math.random().toString(36).substr(2,9)}`,U=`--stx-transition-duration: ${g}ms; --stx-transition-ease: ${A}; --stx-transition-delay: ${X}ms; will-change: opacity, transform;`,B="stx-transition stx-observe stx-out";if(z==="fade")B+=" stx-fade";else if(z==="slide-up"||z==="slide")B+=" stx-from-bottom";else if(z==="slide-down")B+=" stx-from-top";else if(z==="slide-left")B+=" stx-from-right";else if(z==="slide-right")B+=" stx-from-left";else if(z==="scale")B+=" stx-scale";else if(z.includes("-"))B+=` stx-${z}`;else B+=` stx-${z}`;return`<div id="${Y}" class="${B}" style="${U}" data-threshold="${J}">${$}</div>`},hasEndTag:!0,description:"Applies animations that trigger when scrolled into view"},j$={name:"animationGroup",handler:($,w,y,j)=>{if(w.length<2)return`<div class="stx-error">@animationGroup directive requires a group name and at least one element selector</div>${$}`;let z=w[0],g=w.slice(1).map((Y)=>Y.startsWith("#")||Y.startsWith(".")?Y:`#${Y}`),A=y.staggerDelay||50,J=y.sequence||!0,X=Cy(z,g,{staggerDelay:A,sequence:J});return`${$}
248
- ${X}`},hasEndTag:!1,description:"Coordinates multiple animations together as a group"},g$={name:"motion",handler:($,w,y,j)=>{let z=w.length>0?w[0].toLowerCase()==="true":!0,g=Zy();return`<div data-animate="${z?"auto":"true"}">${$}</div>${g}`},hasEndTag:!0,description:"Controls motion and animation preferences"}});function z$($,w={}){let y=w.strict??!1;try{let j=$.replace(/^\uFEFF/,"");if(!j.trim())return{};let z=Bun.YAML.parse(j);if(Array.isArray(z)&&z.length===1)return z[0];return z}catch(j){if(y)throw Error(`YAML parsing failed: ${j}`);return{}}}function q1($){let w=$,y=$.match(dy),j={},z,g=$;if(y)z=y[1],g=$.substring(y[0].length),j=z$(z);else if(y=$.match(hy),y)z=y[1],g=$.substring(y[0].length),j=Py(z);return{data:j,content:g,original:w,matter:z}}function Py($){let w={},y=$.split(`
249
- `);for(let j of y){let z=j.trim();if(!z||z.startsWith("#"))continue;let g=z.indexOf("=");if(g>0){let A=z.substring(0,g).trim(),J=z.substring(g+1).trim();w[A]=Ww(J)}}return w}function Ww($){if($.startsWith('"')&&$.endsWith('"')||$.startsWith("'")&&$.endsWith("'"))return $.substring(1,$.length-1);if($==="true")return!0;if($==="false")return!1;if(/^-?\d+$/.test($))return Number.parseInt($,10);if(/^-?\d+\.\d+$/.test($))return Number.parseFloat($);if($.startsWith("[")&&$.endsWith("]"))return $.substring(1,$.length-1).split(",").map((y)=>Ww(y.trim()));return $}var dy,hy;var _1=M(()=>{dy=/^---\r?\n([\s\S]*?)\r?\n---\r?\n/,hy=/^\+\+\+\r?\n([\s\S]*?)\r?\n\+\+\+\r?\n/});function N1($){return $>=48&&$<=57||$>=65&&$<=90||$>=97&&$<=122}function S0($,w={}){let y={...uy,...w},j={src:$.replace(/\r\n/g,`
244
+ `}function Lw($,w,y,j){let z=$;if(j.animation?.enabled===!1)return z;let A=y.includes("test")&&y.includes("animation");if(!d9(z)&&!A)return z;if(!z.includes('<style id="stx-animation-base">')){let J=P9();z=z.replace("</head>",`${J}
245
+ </head>`)}if(z.includes("stx-observe")){if(!z.includes("Intersection Observer for scroll animations")){let X=h9();z=z.replace("</body>",`${X}
246
+ </body>`)}}return z}function M6($){let w=$.customDirectives||[];return w.push(y$),w.push(z$),w.push(A$),w.push(j$),{...$,customDirectives:w}}var M9,E9,D9,K0,y$,j$,z$,A$;var K1=M(()=>{((g)=>{g.Fade="fade";g.Slide="slide";g.Scale="scale";g.Flip="flip";g.Rotate="rotate";g.Custom="custom"})(M9||={});((j)=>{j.In="in";j.Out="out";j.Both="both"})(E9||={});((g)=>{g.Linear="linear";g.Ease="ease";g.EaseIn="ease-in";g.EaseOut="ease-out";g.EaseInOut="ease-in-out";g.Spring="spring"})(D9||={});K0={duration:300,delay:0,ease:"ease",direction:"both"};y$={name:"transition",handler:($,w,y,j)=>{if(w.length<1)return`<div class="stx-error">@transition directive requires at least a transition type</div>${$}`;let z=w[0],A=w.length>1?Number.parseInt(w[1],10)||K0.duration:K0.duration,g=w.length>2?w[2]||K0.ease:K0.ease,J=w.length>3?Number.parseInt(w[3],10)||K0.delay:K0.delay,X=w.length>4?w[4]||K0.direction:K0.direction,Y=`stx-transition-${Math.random().toString(36).substr(2,9)}`,U=C9(z,{duration:A,delay:J,ease:g,direction:X}),B="stx-transition",b="";if(z==="fade")b="stx-fade";else if(z==="slide")b="stx-slide";else if(z==="scale")b="stx-scale";else if(z==="flip")b="stx-flip";else if(z==="rotate")b="stx-rotate";return`<div id="${Y}" class="${B} ${b} ${X==="out"?"stx-out":""}"
247
+ style="--stx-transition-duration: ${A}ms; --stx-transition-ease: ${g}; --stx-transition-delay: ${J}ms;">${$}</div>`},hasEndTag:!0,description:"Applies transition effects to an element"},j$={name:"scrollAnimate",handler:($,w,y,j)=>{if(w.length<1)return`<div class="stx-error">@scrollAnimate directive requires at least an animation type</div>${$}`;let z=w[0],A=w.length>1?Number.parseInt(w[1],10)||300:300,g=w.length>2?w[2]||"ease":"ease",J=w.length>3?Number.parseFloat(w[3])||0.2:0.2,X=w.length>4?Number.parseInt(w[4],10)||0:0,Y=`stx-scroll-${Math.random().toString(36).substr(2,9)}`,U=`--stx-transition-duration: ${A}ms; --stx-transition-ease: ${g}; --stx-transition-delay: ${X}ms; will-change: opacity, transform;`,B="stx-transition stx-observe stx-out";if(z==="fade")B+=" stx-fade";else if(z==="slide-up"||z==="slide")B+=" stx-from-bottom";else if(z==="slide-down")B+=" stx-from-top";else if(z==="slide-left")B+=" stx-from-right";else if(z==="slide-right")B+=" stx-from-left";else if(z==="scale")B+=" stx-scale";else if(z.includes("-"))B+=` stx-${z}`;else B+=` stx-${z}`;return`<div id="${Y}" class="${B}" style="${U}" data-threshold="${J}">${$}</div>`},hasEndTag:!0,description:"Applies animations that trigger when scrolled into view"},z$={name:"animationGroup",handler:($,w,y,j)=>{if(w.length<2)return`<div class="stx-error">@animationGroup directive requires a group name and at least one element selector</div>${$}`;let z=w[0],A=w.slice(1).map((Y)=>Y.startsWith("#")||Y.startsWith(".")?Y:`#${Y}`),g=y.staggerDelay||50,J=y.sequence||!0,X=x9(z,A,{staggerDelay:g,sequence:J});return`${$}
248
+ ${X}`},hasEndTag:!1,description:"Coordinates multiple animations together as a group"},A$={name:"motion",handler:($,w,y,j)=>{let z=w.length>0?w[0].toLowerCase()==="true":!0,A=v9();return`<div data-animate="${z?"auto":"true"}">${$}</div>${A}`},hasEndTag:!0,description:"Controls motion and animation preferences"}});function g$($,w={}){let y=w.strict??!1;try{let j=$.replace(/^\uFEFF/,"");if(!j.trim())return{};let z=Bun.YAML.parse(j);if(Array.isArray(z)&&z.length===1)return z[0];return z}catch(j){if(y)throw Error(`YAML parsing failed: ${j}`);return{}}}function q1($){let w=$,y=$.match(m9),j={},z,A=$;if(y)z=y[1],A=$.substring(y[0].length),j=g$(z);else if(y=$.match(i9),y)z=y[1],A=$.substring(y[0].length),j=n9(z);return{data:j,content:A,original:w,matter:z}}function n9($){let w={},y=$.split(`
249
+ `);for(let j of y){let z=j.trim();if(!z||z.startsWith("#"))continue;let A=z.indexOf("=");if(A>0){let g=z.substring(0,A).trim(),J=z.substring(A+1).trim();w[g]=Hw(J)}}return w}function Hw($){if($.startsWith('"')&&$.endsWith('"')||$.startsWith("'")&&$.endsWith("'"))return $.substring(1,$.length-1);if($==="true")return!0;if($==="false")return!1;if(/^-?\d+$/.test($))return Number.parseInt($,10);if(/^-?\d+\.\d+$/.test($))return Number.parseFloat($);if($.startsWith("[")&&$.endsWith("]"))return $.substring(1,$.length-1).split(",").map((y)=>Hw(y.trim()));return $}var m9,i9;var _1=M(()=>{m9=/^---\r?\n([\s\S]*?)\r?\n---\r?\n/,i9=/^\+\+\+\r?\n([\s\S]*?)\r?\n\+\+\+\r?\n/});function N1($){return $>=48&&$<=57||$>=65&&$<=90||$>=97&&$<=122}function S0($,w={}){let y={...c9,...w},j={src:$.replace(/\r\n/g,`
250
250
  `).replace(/\r/g,`
251
- `),pos:0,posMax:$.length,tokens:[],pending:"",level:0,options:y,cache:{},delimiters:[]};return my(j),g9(j.tokens,y)}function my($){while($.pos<$.posMax){let w=$.src.charCodeAt($.pos);if(w===10){$.pos++;continue}if(w===35&&e0($)){if(ny($))continue}if(w===96&&iy($,"```")){if(ry($))continue}if((w===42||w===45||w===95)&&e0($)){if(cy($))continue}if(w===62&&e0($)){if(ly($))continue}if(Fw(w)&&e0($)){if(sy($))continue}if($.options.gfm&&w===124&&e0($)){if(oy($))continue}if(ay($))continue;$.pos++}if($.pending)O0($)}function e0($){return $.pos===0||$.src.charCodeAt($.pos-1)===10}function iy($,w){return $.src.slice($.pos,$.pos+w.length)===w}function Fw($){return $===42||$===45||$===43||$>=48&&$<=57}function O0($){if(!$.pending)return;$.tokens.push({type:"text",content:$.pending,level:$.level}),$.pending=""}function V($,w,y,j){if(O0($),j<0)$.level--;let z={type:w,tag:y,nesting:j,level:$.level};if(j>0)$.level++;return $.tokens.push(z),z}function ny($){let w=$.pos,y=0;while($.pos<$.posMax&&$.src.charCodeAt($.pos)===35&&y<6)y++,$.pos++;if(y===0||$.pos>=$.posMax||$.src.charCodeAt($.pos)!==32)return $.pos=w,!1;$.pos++;let{pos:j,pos:z}=$;while(z<$.posMax&&$.src.charCodeAt(z)!==10)z++;let g=$.src.slice(j,z).trim(),A=V($,"heading_open",`h${y}`,1);if($.options.headerIds)A.markup=`${$.options.headerPrefix}${py(g)}`;return U0($,g),V($,"heading_close",`h${y}`,-1),$.pos=z+1,!0}function py($){return $.toLowerCase().replace(/[^\w\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").trim()}function ry($){let w=$.pos;$.pos+=3;let y=$.pos;while($.pos<$.posMax&&$.src.charCodeAt($.pos)!==10)$.pos++;let j=$.src.slice(y,$.pos).trim();$.pos++;let z=$.pos;if($.src.slice($.pos,$.pos+3)==="```"){let X=V($,"fence","code",0);return X.content="",X.markup=j,$.pos+=3,!0}let g=$.src.indexOf("\n```",$.pos);if(g===-1)return $.pos=w,!1;let A=$.src.slice(z,g),J=V($,"fence","code",0);return J.content=A,J.markup=j,$.pos=g+4,!0}function cy($){let w=$.pos,y=$.src.charCodeAt($.pos),j=0;while($.pos<$.posMax){let z=$.src.charCodeAt($.pos);if(z===y)j++;else if(z!==32&&z!==10)break;if($.pos++,z===10)break}if(j>=3)return V($,"hr","hr",0),!0;return $.pos=w,!1}function ly($){V($,"blockquote_open","blockquote",1);while($.pos<$.posMax&&$.src.charCodeAt($.pos)===62){if($.pos++,$.src.charCodeAt($.pos)===32)$.pos++;let{pos:w,pos:y}=$;while(y<$.posMax&&$.src.charCodeAt(y)!==10)y++;let j=$.src.slice(w,y).trim();if(j)V($,"paragraph_open","p",1),U0($,j),V($,"paragraph_close","p",-1);$.pos=y+1}return V($,"blockquote_close","blockquote",-1),!0}function sy($){let w=$.src.charCodeAt($.pos),y=w>=48&&w<=57;if(!y){let j=$.src.charCodeAt($.pos+1);if(j===w||j!==32)return!1}V($,y?"ordered_list_open":"bullet_list_open",y?"ol":"ul",1);while($.pos<$.posMax){let j=$.src.charCodeAt($.pos);if(y){let Y=0;while($.src.charCodeAt($.pos)>=48&&$.src.charCodeAt($.pos)<=57)$.pos++,Y++;if(Y===0||$.src.charCodeAt($.pos)!==46)break;$.pos++}else{if(j!==42&&j!==45&&j!==43)break;if($.src.charCodeAt($.pos+1)===j)break;$.pos++}if($.src.charCodeAt($.pos)!==32)break;$.pos++;let{pos:z,pos:g}=$;while(g<$.posMax&&$.src.charCodeAt(g)!==10)g++;let A=$.src.slice(z,g).trim(),J=A.match(/^\[([ x])\]\s+(.+)/i);if(J){let Y=J[1].toLowerCase()==="x";A=J[2];let U=V($,"list_item_open","li",1);U.markup=Y?"checked":"unchecked",U0($,A),V($,"list_item_close","li",-1)}else V($,"list_item_open","li",1),U0($,A),V($,"list_item_close","li",-1);$.pos=g+1;let X=$.src.charCodeAt($.pos);if(!Fw(X))break}return V($,y?"ordered_list_close":"bullet_list_close",y?"ol":"ul",-1),!0}function Lw($){let w=[],y="",j=!1,z=!1;for(let g=0;g<$.length;g++){let A=$[g];if(z){y+=A,z=!1;continue}if(A==="\\"){y+=A,z=!0;continue}if(A==="`"){j=!j,y+=A;continue}if(A==="|"&&!j){w.push(y.trim()),y="";continue}y+=A}if(y||w.length>0)w.push(y.trim());return w.slice(1,-1)}function oy($){let{pos:w,pos:y}=$;while(y<$.posMax&&$.src.charCodeAt(y)!==10)y++;let j=$.src.slice($.pos,y);if(!j.startsWith("|")||!j.trim().endsWith("|"))return!1;$.pos=y+1,y=$.pos;while(y<$.posMax&&$.src.charCodeAt(y)!==10)y++;let z=$.src.slice($.pos,y);if(!/^\|(?:\s*:?-+:?\s*\|)+$/.test(z.trim()))return $.pos=w,!1;let A=z.split("|").slice(1,-1).map((X)=>{let Y=X.trim();if(Y.startsWith(":")&&Y.endsWith(":"))return"center";if(Y.endsWith(":"))return"right";if(Y.startsWith(":"))return"left";return null});$.pos=y+1;let J=Lw(j);V($,"table_open","table",1),V($,"thead_open","thead",1),V($,"tr_open","tr",1);for(let X=0;X<J.length;X++){let Y=V($,"th_open","th",1);if(A[X])Y.markup=A[X]??void 0;U0($,J[X]),V($,"th_close","th",-1)}V($,"tr_close","tr",-1),V($,"thead_close","thead",-1),V($,"tbody_open","tbody",1);while($.pos<$.posMax){y=$.pos;while(y<$.posMax&&$.src.charCodeAt(y)!==10)y++;let X=$.src.slice($.pos,y).trim();if(!X.startsWith("|")||!X.endsWith("|"))break;let Y=Lw(X);V($,"tr_open","tr",1);for(let U=0;U<Y.length;U++){let B=V($,"td_open","td",1);if(A[U])B.markup=A[U]??void 0;U0($,Y[U]),V($,"td_close","td",-1)}V($,"tr_close","tr",-1),$.pos=y+1}return V($,"tbody_close","tbody",-1),V($,"table_close","table",-1),!0}function ay($){let{pos:w,pos:y}=$;while(y<$.posMax){if($.src.charCodeAt(y)===10){if(y+1<$.posMax&&$.src.charCodeAt(y+1)===10)break}y++}let j=$.src.slice(w,y).trim();if(!j)return $.pos=y+1,!1;return V($,"paragraph_open","p",1),U0($,j),V($,"paragraph_close","p",-1),$.pos=y+1,!0}function U0($,w){let{src:y,pos:j,posMax:z}=$;$.src=w,$.pos=0,$.posMax=w.length;while($.pos<$.posMax){let g=$.src.charCodeAt($.pos);if((g===42||g===95)&&$.src.charCodeAt($.pos+1)===g){if(ey($,g))continue}if(g===42||g===95){if(ty($,g))continue}if(g===96){if($9($))continue}if(g===91){if(w9($))continue}if(g===33&&$.src.charCodeAt($.pos+1)===91){if(y9($))continue}if($.options.gfm&&g===126&&$.src.charCodeAt($.pos+1)===126){if(j9($))continue}if($.options.breaks&&g===10){O0($),V($,"br","br",0),$.pos++;continue}$.pending+=$.src[$.pos],$.pos++}if($.pending)O0($);$.src=y,$.pos=j,$.posMax=z}function ey($,w){let y=$.pos,j=String.fromCharCode(w),z=y+2;if(w===95){let J=y>0?$.src.charCodeAt(y-1):0;if(N1(J)||J===95)return!1}let g=$.src.indexOf(j+j,z);if(g===-1)return!1;if(w===95){let J=g+2<$.posMax?$.src.charCodeAt(g+2):0;if(N1(J)||J===95)return!1}O0($);let A=$.src.substring(z,g);return V($,"strong_open","strong",1),U0($,A),V($,"strong_close","strong",-1),$.pos=g+2,!0}function ty($,w){let y=$.pos,j=String.fromCharCode(w),z=y+1;if(w===95){let J=y>0?$.src.charCodeAt(y-1):0;if(N1(J)||J===95)return!1}let g=$.src.indexOf(j,z);while(g!==-1){if($.src.charCodeAt(g+1)===w){g=$.src.indexOf(j,g+2);continue}if(w===95){let J=g+1<$.posMax?$.src.charCodeAt(g+1):0;if(N1(J)||J===95){g=$.src.indexOf(j,g+1);continue}}break}if(g===-1||g===z)return!1;O0($);let A=$.src.substring(z,g);return V($,"em_open","em",1),U0($,A),V($,"em_close","em",-1),$.pos=g+1,!0}function $9($){let w=$.pos;$.pos++;let y=$.pos,j=$.src.indexOf("`",$.pos);if(j===-1)return $.pos=w,!1;let z=$.src.slice(y,j);return V($,"code_inline","code",0).content=z,$.pos=j+1,!0}function w9($){let w=$.pos;$.pos++;let y=$.pos,j=$.src.indexOf("]",$.pos);if(j===-1)return $.pos=w,!1;if($.src.charCodeAt(j+1)!==40)return $.pos=w,!1;let z=j+2,g=$.src.indexOf(")",z);if(g===-1)return $.pos=w,!1;O0($);let A=$.src.slice(y,j),J=$.src.slice(z,g),X=J,Y="",U=J.match(/^(.*?)\s+["'](.*)["']$/);if(U)X=U[1],Y=U[2];let B=V($,"link_open","a",1);if(B.markup=X,Y)B.content=Y;return U0($,A),V($,"link_close","a",-1),$.pos=g+1,!0}function y9($){let w=$.pos;$.pos+=2;let y=$.pos,j=$.src.indexOf("]",$.pos);if(j===-1)return $.pos=w,!1;if($.src.charCodeAt(j+1)!==40)return $.pos=w,!1;let z=j+2,g=$.src.indexOf(")",z);if(g===-1)return $.pos=w,!1;let A=$.src.slice(y,j),J=$.src.slice(z,g),X=J,Y="",U=J.match(/^(.*?)\s+["'](.*)["']$/);if(U)X=U[1],Y=U[2];return V($,"image","img",0).markup=`${A}|${X}|${Y}`,$.pos=g+1,!0}function j9($){let w=$.pos;$.pos+=2;let y=$.pos,j=$.src.indexOf("~~",$.pos);if(j===-1)return $.pos=w,!1;O0($);let z=$.src.slice(y,j);return V($,"del_open","del",1),U0($,z),V($,"del_close","del",-1),$.pos=j+2,!0}function g9($,w){let y="";for(let j of $)switch(j.type){case"heading_open":if(j.markup)y+=`<${j.tag} id="${j.markup}">`;else y+=`<${j.tag}>`;break;case"heading_close":y+=`</${j.tag}>
251
+ `),pos:0,posMax:$.length,tokens:[],pending:"",level:0,options:y,cache:{},delimiters:[]};return r9(j),Yy(j.tokens,y)}function r9($){while($.pos<$.posMax){let w=$.src.charCodeAt($.pos);if(w===10){$.pos++;continue}if(w===35&&e0($)){if(s9($))continue}if(w===96&&l9($,"```")){if(a9($))continue}if((w===42||w===45||w===95)&&e0($)){if(e9($))continue}if(w===62&&e0($)){if(t9($))continue}if(Gw(w)&&e0($)){if($y($))continue}if($.options.gfm&&w===124&&e0($)){if(wy($))continue}if(yy($))continue;$.pos++}if($.pending)H0($)}function e0($){return $.pos===0||$.src.charCodeAt($.pos-1)===10}function l9($,w){return $.src.slice($.pos,$.pos+w.length)===w}function Gw($){return $===42||$===45||$===43||$>=48&&$<=57}function H0($){if(!$.pending)return;$.tokens.push({type:"text",content:$.pending,level:$.level}),$.pending=""}function V($,w,y,j){if(H0($),j<0)$.level--;let z={type:w,tag:y,nesting:j,level:$.level};if(j>0)$.level++;return $.tokens.push(z),z}function s9($){let w=$.pos,y=0;while($.pos<$.posMax&&$.src.charCodeAt($.pos)===35&&y<6)y++,$.pos++;if(y===0||$.pos>=$.posMax||$.src.charCodeAt($.pos)!==32)return $.pos=w,!1;$.pos++;let{pos:j,pos:z}=$;while(z<$.posMax&&$.src.charCodeAt(z)!==10)z++;let A=$.src.slice(j,z).trim(),g=V($,"heading_open",`h${y}`,1);if($.options.headerIds)g.markup=`${$.options.headerPrefix}${o9(A)}`;return U0($,A),V($,"heading_close",`h${y}`,-1),$.pos=z+1,!0}function o9($){return $.toLowerCase().replace(/[^\w\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").trim()}function a9($){let w=$.pos;$.pos+=3;let y=$.pos;while($.pos<$.posMax&&$.src.charCodeAt($.pos)!==10)$.pos++;let j=$.src.slice(y,$.pos).trim();$.pos++;let z=$.pos;if($.src.slice($.pos,$.pos+3)==="```"){let X=V($,"fence","code",0);return X.content="",X.markup=j,$.pos+=3,!0}let A=$.src.indexOf("\n```",$.pos);if(A===-1)return $.pos=w,!1;let g=$.src.slice(z,A),J=V($,"fence","code",0);return J.content=g,J.markup=j,$.pos=A+4,!0}function e9($){let w=$.pos,y=$.src.charCodeAt($.pos),j=0;while($.pos<$.posMax){let z=$.src.charCodeAt($.pos);if(z===y)j++;else if(z!==32&&z!==10)break;if($.pos++,z===10)break}if(j>=3)return V($,"hr","hr",0),!0;return $.pos=w,!1}function t9($){V($,"blockquote_open","blockquote",1);while($.pos<$.posMax&&$.src.charCodeAt($.pos)===62){if($.pos++,$.src.charCodeAt($.pos)===32)$.pos++;let{pos:w,pos:y}=$;while(y<$.posMax&&$.src.charCodeAt(y)!==10)y++;let j=$.src.slice(w,y).trim();if(j)V($,"paragraph_open","p",1),U0($,j),V($,"paragraph_close","p",-1);$.pos=y+1}return V($,"blockquote_close","blockquote",-1),!0}function $y($){let w=$.src.charCodeAt($.pos),y=w>=48&&w<=57;if(!y){let j=$.src.charCodeAt($.pos+1);if(j===w||j!==32)return!1}V($,y?"ordered_list_open":"bullet_list_open",y?"ol":"ul",1);while($.pos<$.posMax){let j=$.src.charCodeAt($.pos);if(y){let Y=0;while($.src.charCodeAt($.pos)>=48&&$.src.charCodeAt($.pos)<=57)$.pos++,Y++;if(Y===0||$.src.charCodeAt($.pos)!==46)break;$.pos++}else{if(j!==42&&j!==45&&j!==43)break;if($.src.charCodeAt($.pos+1)===j)break;$.pos++}if($.src.charCodeAt($.pos)!==32)break;$.pos++;let{pos:z,pos:A}=$;while(A<$.posMax&&$.src.charCodeAt(A)!==10)A++;let g=$.src.slice(z,A).trim(),J=g.match(/^\[([ x])\]\s+(.+)/i);if(J){let Y=J[1].toLowerCase()==="x";g=J[2];let U=V($,"list_item_open","li",1);U.markup=Y?"checked":"unchecked",U0($,g),V($,"list_item_close","li",-1)}else V($,"list_item_open","li",1),U0($,g),V($,"list_item_close","li",-1);$.pos=A+1;let X=$.src.charCodeAt($.pos);if(!Gw(X))break}return V($,y?"ordered_list_close":"bullet_list_close",y?"ol":"ul",-1),!0}function Rw($){let w=[],y="",j=!1,z=!1;for(let A=0;A<$.length;A++){let g=$[A];if(z){y+=g,z=!1;continue}if(g==="\\"){y+=g,z=!0;continue}if(g==="`"){j=!j,y+=g;continue}if(g==="|"&&!j){w.push(y.trim()),y="";continue}y+=g}if(y||w.length>0)w.push(y.trim());return w.slice(1,-1)}function wy($){let{pos:w,pos:y}=$;while(y<$.posMax&&$.src.charCodeAt(y)!==10)y++;let j=$.src.slice($.pos,y);if(!j.startsWith("|")||!j.trim().endsWith("|"))return!1;$.pos=y+1,y=$.pos;while(y<$.posMax&&$.src.charCodeAt(y)!==10)y++;let z=$.src.slice($.pos,y);if(!/^\|(?:\s*:?-+:?\s*\|)+$/.test(z.trim()))return $.pos=w,!1;let g=z.split("|").slice(1,-1).map((X)=>{let Y=X.trim();if(Y.startsWith(":")&&Y.endsWith(":"))return"center";if(Y.endsWith(":"))return"right";if(Y.startsWith(":"))return"left";return null});$.pos=y+1;let J=Rw(j);V($,"table_open","table",1),V($,"thead_open","thead",1),V($,"tr_open","tr",1);for(let X=0;X<J.length;X++){let Y=V($,"th_open","th",1);if(g[X])Y.markup=g[X]??void 0;U0($,J[X]),V($,"th_close","th",-1)}V($,"tr_close","tr",-1),V($,"thead_close","thead",-1),V($,"tbody_open","tbody",1);while($.pos<$.posMax){y=$.pos;while(y<$.posMax&&$.src.charCodeAt(y)!==10)y++;let X=$.src.slice($.pos,y).trim();if(!X.startsWith("|")||!X.endsWith("|"))break;let Y=Rw(X);V($,"tr_open","tr",1);for(let U=0;U<Y.length;U++){let B=V($,"td_open","td",1);if(g[U])B.markup=g[U]??void 0;U0($,Y[U]),V($,"td_close","td",-1)}V($,"tr_close","tr",-1),$.pos=y+1}return V($,"tbody_close","tbody",-1),V($,"table_close","table",-1),!0}function yy($){let{pos:w,pos:y}=$;while(y<$.posMax){if($.src.charCodeAt(y)===10){if(y+1<$.posMax&&$.src.charCodeAt(y+1)===10)break}y++}let j=$.src.slice(w,y).trim();if(!j)return $.pos=y+1,!1;return V($,"paragraph_open","p",1),U0($,j),V($,"paragraph_close","p",-1),$.pos=y+1,!0}function U0($,w){let{src:y,pos:j,posMax:z}=$;$.src=w,$.pos=0,$.posMax=w.length;while($.pos<$.posMax){let A=$.src.charCodeAt($.pos);if((A===42||A===95)&&$.src.charCodeAt($.pos+1)===A){if(jy($,A))continue}if(A===42||A===95){if(zy($,A))continue}if(A===96){if(Ay($))continue}if(A===91){if(gy($))continue}if(A===33&&$.src.charCodeAt($.pos+1)===91){if(Jy($))continue}if($.options.gfm&&A===126&&$.src.charCodeAt($.pos+1)===126){if(Xy($))continue}if($.options.breaks&&A===10){H0($),V($,"br","br",0),$.pos++;continue}$.pending+=$.src[$.pos],$.pos++}if($.pending)H0($);$.src=y,$.pos=j,$.posMax=z}function jy($,w){let y=$.pos,j=String.fromCharCode(w),z=y+2;if(w===95){let J=y>0?$.src.charCodeAt(y-1):0;if(N1(J)||J===95)return!1}let A=$.src.indexOf(j+j,z);if(A===-1)return!1;if(w===95){let J=A+2<$.posMax?$.src.charCodeAt(A+2):0;if(N1(J)||J===95)return!1}H0($);let g=$.src.substring(z,A);return V($,"strong_open","strong",1),U0($,g),V($,"strong_close","strong",-1),$.pos=A+2,!0}function zy($,w){let y=$.pos,j=String.fromCharCode(w),z=y+1;if(w===95){let J=y>0?$.src.charCodeAt(y-1):0;if(N1(J)||J===95)return!1}let A=$.src.indexOf(j,z);while(A!==-1){if($.src.charCodeAt(A+1)===w){A=$.src.indexOf(j,A+2);continue}if(w===95){let J=A+1<$.posMax?$.src.charCodeAt(A+1):0;if(N1(J)||J===95){A=$.src.indexOf(j,A+1);continue}}break}if(A===-1||A===z)return!1;H0($);let g=$.src.substring(z,A);return V($,"em_open","em",1),U0($,g),V($,"em_close","em",-1),$.pos=A+1,!0}function Ay($){let w=$.pos;$.pos++;let y=$.pos,j=$.src.indexOf("`",$.pos);if(j===-1)return $.pos=w,!1;let z=$.src.slice(y,j);return V($,"code_inline","code",0).content=z,$.pos=j+1,!0}function gy($){let w=$.pos;$.pos++;let y=$.pos,j=$.src.indexOf("]",$.pos);if(j===-1)return $.pos=w,!1;if($.src.charCodeAt(j+1)!==40)return $.pos=w,!1;let z=j+2,A=$.src.indexOf(")",z);if(A===-1)return $.pos=w,!1;H0($);let g=$.src.slice(y,j),J=$.src.slice(z,A),X=J,Y="",U=J.match(/^(.*?)\s+["'](.*)["']$/);if(U)X=U[1],Y=U[2];let B=V($,"link_open","a",1);if(B.markup=X,Y)B.content=Y;return U0($,g),V($,"link_close","a",-1),$.pos=A+1,!0}function Jy($){let w=$.pos;$.pos+=2;let y=$.pos,j=$.src.indexOf("]",$.pos);if(j===-1)return $.pos=w,!1;if($.src.charCodeAt(j+1)!==40)return $.pos=w,!1;let z=j+2,A=$.src.indexOf(")",z);if(A===-1)return $.pos=w,!1;let g=$.src.slice(y,j),J=$.src.slice(z,A),X=J,Y="",U=J.match(/^(.*?)\s+["'](.*)["']$/);if(U)X=U[1],Y=U[2];return V($,"image","img",0).markup=`${g}|${X}|${Y}`,$.pos=A+1,!0}function Xy($){let w=$.pos;$.pos+=2;let y=$.pos,j=$.src.indexOf("~~",$.pos);if(j===-1)return $.pos=w,!1;H0($);let z=$.src.slice(y,j);return V($,"del_open","del",1),U0($,z),V($,"del_close","del",-1),$.pos=j+2,!0}function Yy($,w){let y="";for(let j of $)switch(j.type){case"heading_open":if(j.markup)y+=`<${j.tag} id="${j.markup}">`;else y+=`<${j.tag}>`;break;case"heading_close":y+=`</${j.tag}>
252
252
  `;break;case"paragraph_open":y+="<p>";break;case"paragraph_close":y+=`</p>
253
- `;break;case"fence":case"code_block":{let z=j.content||"",g=j.markup||"";if(w.highlight&&g)z=w.highlight(z,g);else z=Y0(z);if(g)y+=`<pre><code class="language-${g}">${z}</code></pre>
253
+ `;break;case"fence":case"code_block":{let z=j.content||"",A=j.markup||"";if(w.highlight&&A)z=w.highlight(z,A);else z=Y0(z);if(A)y+=`<pre><code class="language-${A}">${z}</code></pre>
254
254
  `;else y+=`<pre><code>${z}</code></pre>
255
255
  `;break}case"code_inline":y+=`<code>${Y0(j.content||"")}</code>`;break;case"hr":y+=`<hr>
256
256
  `;break;case"blockquote_open":y+=`<blockquote>
@@ -270,16 +270,16 @@ ${X}`},hasEndTag:!1,description:"Coordinates multiple animations together as a g
270
270
  `;break;case"tr_close":y+=`</tr>
271
271
  `;break;case"th_open":if(j.markup)y+=`<th align="${j.markup}">`;else y+="<th>";break;case"th_close":y+=`</th>
272
272
  `;break;case"td_open":if(j.markup)y+=`<td align="${j.markup}">`;else y+="<td>";break;case"td_close":y+=`</td>
273
- `;break;case"strong_open":y+="<strong>";break;case"strong_close":y+="</strong>";break;case"em_open":y+="<em>";break;case"em_close":y+="</em>";break;case"del_open":y+="<del>";break;case"del_close":y+="</del>";break;case"br":y+="<br>";break;case"link_open":if(j.content)y+=`<a href="${Y0(j.markup||"")}" title="${Y0(j.content)}">`;else y+=`<a href="${Y0(j.markup||"")}">`;break;case"link_close":y+="</a>";break;case"image":{let[z,g,A]=(j.markup||"||").split("|");if(A)y+=`<img src="${Y0(g)}" alt="${Y0(z)}" title="${Y0(A)}">`;else y+=`<img src="${Y0(g)}" alt="${Y0(z)}">`;break}case"text":y+=Y0(j.content||"");break}return y}function Y0($){let w=$.length,y=0,j=!1;for(let g=0;g<w;g++){let A=$.charCodeAt(g);if(A===fw||A===Ow||A===Rw||A===Hw||A===kw){j=!0;break}}if(!j)return $;let z=[];for(let g=0;g<w;g++){let A=$.charCodeAt(g),J=null;switch(A){case fw:J="&amp;";break;case Ow:J="&lt;";break;case Rw:J="&gt;";break;case Hw:J="&quot;";break;case kw:J="&#39;";break}if(J){if(g>y)z.push($.substring(y,g));z.push(J),y=g+1}}if(y<w)z.push($.substring(y));return z.join("")}var uy,fw=38,Ow=60,Rw=62,Hw=34,kw=39;var W1=M(()=>{uy={gfm:!0,breaks:!1,headerIds:!0,headerPrefix:"",pedantic:!1,smartLists:!0,smartypants:!1,sanitize:!1}});var A$=M(()=>{_1();W1();_1();_1();W1();W1()});import{existsSync as vw,mkdirSync as P6,readdirSync as x6,writeFileSync as u6}from"fs";import{homedir as J$}from"os";import{dirname as n6,resolve as j0}from"path";import t0 from"process";import{join as z9,relative as A9,resolve as Vw}from"path";import H1 from"process";import{existsSync as dw,mkdirSync as s6,readdirSync as o6,writeFileSync as a6}from"fs";import{dirname as t6,resolve as k1}from"path";import q$ from"process";import{Buffer as R0}from"buffer";import{createCipheriv as J9,createDecipheriv as X9,randomBytes as X$}from"crypto";import{closeSync as Y$,createReadStream as Sw,createWriteStream as Y9,existsSync as U$,fsyncSync as Iw,openSync as Gw,writeFileSync as U9}from"fs";import{access as B9,constants as Tw,mkdir as b9,readdir as L1,rename as Zw,stat as M0,unlink as f1,writeFile as B$}from"fs/promises";import{join as D0}from"path";import o from"process";import{pipeline as Q9}from"stream/promises";import{createGzip as Ew}from"zlib";import C0 from"process";import N0 from"process";function _$($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&d(w[0])&&"id"in w[0]&&w[0].id===3&&d(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(d(w)&&d($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(d($)&&"arr"in $&&Array.isArray($.arr)&&d(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&d(w[0])&&d($[0])){let j=[...w];for(let z of $)if(d(z)&&"name"in z){if(!j.find((g)=>d(g)&&("name"in g)&&g.name===z.name))j.push(z)}else if(d(z)&&"path"in z){if(!j.find((g)=>d(g)&&("path"in g)&&g.path===z.path))j.push(z)}else if(!j.some((g)=>F1(g,z)))j.push(z);return j}if(w.every((j)=>typeof j==="string")&&$.every((j)=>typeof j==="string")){let j=[...w];for(let z of $)if(!j.includes(z))j.push(z);return j}return w}if(!d(w)||!d($))return w;let y={...$};for(let j in w)if(Object.prototype.hasOwnProperty.call(w,j)){let z=w[j];if(z===null||z===void 0)continue;else if(d(z)&&d(y[j]))y[j]=_$(y[j],z);else if(Array.isArray(z)&&Array.isArray(y[j]))if(z.length>0&&y[j].length>0&&d(z[0])&&d(y[j][0])){let g=[...z];for(let A of y[j])if(d(A)&&"name"in A){if(!g.find((J)=>d(J)&&("name"in J)&&J.name===A.name))g.push(A)}else if(d(A)&&"path"in A){if(!g.find((J)=>d(J)&&("path"in J)&&J.path===A.path))g.push(A)}else if(!g.some((J)=>F1(J,A)))g.push(A);y[j]=g}else if(z.every((g)=>typeof g==="string")&&y[j].every((g)=>typeof g==="string")){let g=[...z];for(let A of y[j])if(!g.includes(A))g.push(A);y[j]=g}else y[j]=z;else y[j]=z}return y}function F1($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let y=0;y<$.length;y++)if(!F1($[y],w[y]))return!1;return!0}if(d($)&&d(w)){let y=Object.keys($),j=Object.keys(w);if(y.length!==j.length)return!1;for(let z of y){if(!Object.prototype.hasOwnProperty.call(w,z))return!1;if(!F1($[z],w[z]))return!1}return!0}return!1}function d($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function K9($,w){if(!dw($))return null;try{let y=await import($),j=y.default||y;if(typeof j!=="object"||j===null||Array.isArray(j))return null;try{return _$(w,j)}catch{return null}}catch{return null}}async function q9({name:$="",cwd:w,defaultConfig:y}){let j=w||q$.cwd(),z=[".ts",".js",".mjs",".cjs",".json"],g=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let A of g)for(let J of z){let X=k1(j,`${A}${J}`),Y=await K9(X,y);if(Y!==null)return Y}try{let A=k1(j,"package.json");if(dw(A)){let J=(await import(A))[$];if(J&&typeof J==="object"&&!Array.isArray(J))try{return _$(y,J)}catch{}}}catch{}return y}function _9($,w={}){let y=H1.cwd();while(y.includes("storage"))y=Vw(y,"..");let j=Vw(y,$||"");if(w?.relative)return A9(H1.cwd(),j);return j}async function W9(){try{let $=await q9({name:"clarity",defaultConfig:b$,cwd:H1.cwd(),endpoint:"",headers:{}});return{...b$,...$}}catch{return b$}}function x(){if(N0.env.NODE_ENV==="test"||N0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function L9(){if(N0.env.NODE_ENV==="test"||N0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof N0<"u"){let $=N0.type;if($==="renderer"||$==="worker")return!1;return!!(N0.versions&&(N0.versions.node||N0.versions.bun))}return!1}class hw{async format($){let w=await L9(),y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:C0.pid,hostname:w(),environment:C0.env.NODE_ENV||"development",platform:C0.platform,version:C0.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:C0.env.NODE_ENV||C0.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class S1{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...Mw},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new hw,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??o.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let y={...w},j=w.timestamp!==void 0;if(j)delete y.timestamp;if(this.config={...this.config,...y,timestamp:j||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let z=this.generateKeyId(),g=this.generateKey();this.currentKeyId=z,this.keys.set(z,g),this.encryptionKeys.set(z,{key:g,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...Q$,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...Q$};return{...Q$,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:Mw.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},y={...w,...Object.fromEntries(Object.entries($).filter(([,j])=>j!==void 0))};if(!y.level||!["debug","info","success","warning","error"].includes(y.level))y.level=w.level;return y}async writeToFile($){let w=(async()=>{let j,z=0,g=3,A=1000;while(z<g)try{try{try{await B9(this.config.logDirectory,Tw.F_OK|Tw.W_OK)}catch(X){if(X instanceof Error&&"code"in X)if(X.code==="ENOENT")await b9(this.config.logDirectory,{recursive:!0,mode:493});else if(X.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw X;else throw X}}catch(X){throw console.error("Debug: [writeToFile] Failed to create log directory:",X),X}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:R0.from($);try{if(!U$(this.currentLogFile))await B$(this.currentLogFile,"",{mode:420});if(j=Gw(this.currentLogFile,"a",420),U9(j,J,{flag:"a"}),Iw(j),j!==void 0)Y$(j),j=void 0;if((await M0(this.currentLogFile)).size===0){if(await B$(this.currentLogFile,J,{flag:"w",mode:420}),(await M0(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(X){let Y=X;if(Y.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Y.code)){if(z<g-1){let U=typeof Y.message==="string"?Y.message:"Unknown error";console.error(`Network error during write attempt ${z+1}/${g}:`,U);let B=A*2**z;await new Promise((b)=>setTimeout(b,B)),z++;continue}}if(Y?.code&&["ENOSPC","EDQUOT"].includes(Y.code))throw Error(`Disk quota exceeded or no space left on device: ${Y.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Y),Y}finally{if(j!==void 0)try{Y$(j)}catch(X){console.error("Debug: [writeToFile] Error closing file descriptor:",X)}}}catch(J){if(z===g-1){let Y=J,U=typeof Y.message==="string"?Y.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",U),J}z++;let X=A*2**(z-1);await new Promise((Y)=>setTimeout(Y,X))}})();this.pendingOperations.push(w);let y=this.pendingOperations.length-1;try{await w}catch(j){throw console.error("Debug: [writeToFile] Error in operation:",j),j}finally{this.pendingOperations.splice(y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return D0(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return D0(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return D0(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(x())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,y=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((j)=>{console.error("Error rotating keys:",j)})},y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),y=this.generateKey();this.currentKeyId=w,this.keys.set(w,y),this.encryptionKeys.set(w,{key:y,createdAt:new Date});let j=Array.from(this.encryptionKeys.entries()).sort(([,A],[,J])=>J.createdAt.getTime()-A.createdAt.getTime()),z=typeof $.maxKeys==="number"?$.maxKeys:1,g=Math.max(1,z);if(j.length>g)for(let[A]of j.slice(g))this.encryptionKeys.delete(A),this.keys.delete(A)}generateKeyId(){return X$(16).toString("hex")}generateKey(){return X$(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),y=X$(16),j=J9("aes-256-gcm",w,y),z=R0.concat([j.update($,"utf8"),j.final()]),g=j.getAuthTag();return{encrypted:R0.concat([y,z,g]),iv:y}}async compressData($){return new Promise((w,y)=>{let j=Ew(),z=[];j.on("data",(g)=>z.push(g)),j.on("end",()=>w(R0.from(R0.concat(z)))),j.on("error",y),j.write($),j.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(x())return;let $=await M0(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let y=this.currentLogFile,j=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let z=await L1(this.config.logDirectory),g=z.filter((X)=>X.startsWith(this.name)&&/\.log\.\d+$/.test(X)).sort((X,Y)=>{let U=Number.parseInt(X.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Y.match(/\.log\.(\d+)$/)?.[1]||"0")-U}),A=g.length>0?Number.parseInt(g[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,J=`${y}.${A}`;if(await M0(y).catch(()=>null))try{if(await Zw(y,J),w.compress)try{let X=`${J}.gz`;await this.compressLogFile(J,X),await f1(J)}catch(X){console.error("Error compressing rotated file:",X)}if(g.length===0&&!z.some((X)=>X.endsWith(".log.1")))try{let X=`${y}.1`;await B$(X,"")}catch(X){console.error("Error creating backup file:",X)}}catch(X){console.error(`Error during rotation: ${X instanceof Error?X.message:String(X)}`)}}else{let z=new Date().toISOString().replace(/[:.]/g,"-"),g=y.replace(/\.log$/,`-${z}.log`);if(await M0(y).catch(()=>null))await Zw(y,g)}if(this.currentLogFile=j,w.maxFiles){let z=(await L1(this.config.logDirectory)).filter((g)=>g.startsWith(this.name)).sort((g,A)=>A.localeCompare(g));for(let g of z.slice(w.maxFiles))await f1(D0(this.config.logDirectory,g))}}}async compressLogFile($,w){let y=Sw($),j=Y9(w),z=Ew();await Q9(y,z,j)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let y of this.logBuffer){let j=await this.formatter.format(y);await this.writeToFile(j),console.log(j)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),U$(this.currentLogFile))try{let $=Gw(this.currentLogFile,"r+");Iw($),Y$($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!x()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await L1(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await f1(D0(this.config.logDirectory,w))}catch(y){console.error(`Failed to delete temp file ${w}:`,y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?v.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:y="",tag:j="",message:z,level:g,showTimestamp:A=!0}=$,J=(Q)=>Q.replace(this.ANSI_PATTERN,"");if(!this.fancy){let Q=[];if(A)Q.push(w);if(g==="warning")Q.push("WARN");else if(g==="error")Q.push("ERROR");else if(y)Q.push(y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(j)Q.push(j.replace(/[[\]]/g,""));return Q.push(z),Q.join(" ")}let X=o.stdout.columns||120,Y="";if(g==="warning"||g==="error")Y=`${y} ${z}`;else if(g==="info"||g==="success")Y=`${y} ${j} ${z}`;else Y=`${y} ${j} ${v.cyan(z)}`;if(!A)return Y.trim();let U=J(Y).trim().length,B=J(w).length,b=Math.max(1,X-2-U-B);return`${Y.trim()}${" ".repeat(b)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(g,A)=>{let J=Number.parseInt(A,10);return J<w[0].length?String(w[0][J]):g});let y=/%([sdijfo%])/g,j=0,z=$.replace(y,(g,A)=>{if(A==="%")return"%";if(j>=w.length)return g;let J=w[j++];switch(A){case"s":return String(J);case"d":case"i":return Number(J).toString();case"j":case"o":return JSON.stringify(J,null,2);default:return g}});if(j<w.length)z+=` ${w.slice(j).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`;return z}async log($,w,...y){let j=new Date,z=this.formatConsoleTimestamp(j),g=this.formatFileTimestamp(j),A,J;if(w instanceof Error)A=w.message,J=w.stack;else A=this.formatMessage(w,y);if(this.fancy&&!x()){let Y=k9[$],U=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:v.gray(A),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:A,level:$}),console.error(B);break;case"success":B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:v.green(A),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:A,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:A,level:$}),console.error(B),J){let b=J.split(`
274
- `);for(let Q of b)if(Q.trim()&&!Q.includes(A))console.error(this.formatConsoleMessage({timestamp:z,message:v.gray(` ${Q}`),level:$,showTimestamp:!1}))}break}}else if(!x()){if(console.error(`${g} ${this.environment}.${$.toUpperCase()}: ${A}`),J)console.error(J)}if(!this.shouldLog($))return;let X=`${g} ${this.environment}.${$.toUpperCase()}: ${A}
273
+ `;break;case"strong_open":y+="<strong>";break;case"strong_close":y+="</strong>";break;case"em_open":y+="<em>";break;case"em_close":y+="</em>";break;case"del_open":y+="<del>";break;case"del_close":y+="</del>";break;case"br":y+="<br>";break;case"link_open":if(j.content)y+=`<a href="${Y0(j.markup||"")}" title="${Y0(j.content)}">`;else y+=`<a href="${Y0(j.markup||"")}">`;break;case"link_close":y+="</a>";break;case"image":{let[z,A,g]=(j.markup||"||").split("|");if(g)y+=`<img src="${Y0(A)}" alt="${Y0(z)}" title="${Y0(g)}">`;else y+=`<img src="${Y0(A)}" alt="${Y0(z)}">`;break}case"text":y+=Y0(j.content||"");break}return y}function Y0($){let w=$.length,y=0,j=!1;for(let A=0;A<w;A++){let g=$.charCodeAt(A);if(g===fw||g===kw||g===Fw||g===Vw||g===Sw){j=!0;break}}if(!j)return $;let z=[];for(let A=0;A<w;A++){let g=$.charCodeAt(A),J=null;switch(g){case fw:J="&amp;";break;case kw:J="&lt;";break;case Fw:J="&gt;";break;case Vw:J="&quot;";break;case Sw:J="&#39;";break}if(J){if(A>y)z.push($.substring(y,A));z.push(J),y=A+1}}if(y<w)z.push($.substring(y));return z.join("")}var c9,fw=38,kw=60,Fw=62,Vw=34,Sw=39;var W1=M(()=>{c9={gfm:!0,breaks:!1,headerIds:!0,headerPrefix:"",pedantic:!1,smartLists:!0,smartypants:!1,sanitize:!1}});var J$=M(()=>{_1();W1();_1();_1();W1();W1()});import{existsSync as Pw,mkdirSync as c6,readdirSync as r6,writeFileSync as l6}from"fs";import{homedir as X$}from"os";import{dirname as a6,resolve as j0}from"path";import t0 from"process";import{join as Uy,relative as By,resolve as Iw}from"path";import f1 from"process";import{existsSync as xw,mkdirSync as y5,readdirSync as j5,writeFileSync as z5}from"fs";import{dirname as g5,resolve as k1}from"path";import _$ from"process";import{Buffer as R0}from"buffer";import{createCipheriv as by,createDecipheriv as Qy,randomBytes as Y$}from"crypto";import{closeSync as U$,createReadStream as Tw,createWriteStream as Ky,existsSync as B$,fsyncSync as Zw,openSync as Mw,writeFileSync as qy}from"fs";import{access as _y,constants as Ew,mkdir as Ny,readdir as L1,rename as Dw,stat as E0,unlink as O1,writeFile as b$}from"fs/promises";import{join as D0}from"path";import r from"process";import{pipeline as Wy}from"stream/promises";import{createGzip as Cw}from"zlib";import C0 from"process";import _0 from"process";function N$($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&d(w[0])&&"id"in w[0]&&w[0].id===3&&d(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(d(w)&&d($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(d($)&&"arr"in $&&Array.isArray($.arr)&&d(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&d(w[0])&&d($[0])){let j=[...w];for(let z of $)if(d(z)&&"name"in z){if(!j.find((A)=>d(A)&&("name"in A)&&A.name===z.name))j.push(z)}else if(d(z)&&"path"in z){if(!j.find((A)=>d(A)&&("path"in A)&&A.path===z.path))j.push(z)}else if(!j.some((A)=>F1(A,z)))j.push(z);return j}if(w.every((j)=>typeof j==="string")&&$.every((j)=>typeof j==="string")){let j=[...w];for(let z of $)if(!j.includes(z))j.push(z);return j}return w}if(!d(w)||!d($))return w;let y={...$};for(let j in w)if(Object.prototype.hasOwnProperty.call(w,j)){let z=w[j];if(z===null||z===void 0)continue;else if(d(z)&&d(y[j]))y[j]=N$(y[j],z);else if(Array.isArray(z)&&Array.isArray(y[j]))if(z.length>0&&y[j].length>0&&d(z[0])&&d(y[j][0])){let A=[...z];for(let g of y[j])if(d(g)&&"name"in g){if(!A.find((J)=>d(J)&&("name"in J)&&J.name===g.name))A.push(g)}else if(d(g)&&"path"in g){if(!A.find((J)=>d(J)&&("path"in J)&&J.path===g.path))A.push(g)}else if(!A.some((J)=>F1(J,g)))A.push(g);y[j]=A}else if(z.every((A)=>typeof A==="string")&&y[j].every((A)=>typeof A==="string")){let A=[...z];for(let g of y[j])if(!A.includes(g))A.push(g);y[j]=A}else y[j]=z;else y[j]=z}return y}function F1($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let y=0;y<$.length;y++)if(!F1($[y],w[y]))return!1;return!0}if(d($)&&d(w)){let y=Object.keys($),j=Object.keys(w);if(y.length!==j.length)return!1;for(let z of y){if(!Object.prototype.hasOwnProperty.call(w,z))return!1;if(!F1($[z],w[z]))return!1}return!0}return!1}function d($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function Ly($,w){if(!xw($))return null;try{let y=await import($),j=y.default||y;if(typeof j!=="object"||j===null||Array.isArray(j))return null;try{return N$(w,j)}catch{return null}}catch{return null}}async function Oy({name:$="",cwd:w,defaultConfig:y}){let j=w||_$.cwd(),z=[".ts",".js",".mjs",".cjs",".json"],A=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let g of A)for(let J of z){let X=k1(j,`${g}${J}`),Y=await Ly(X,y);if(Y!==null)return Y}try{let g=k1(j,"package.json");if(xw(g)){let J=(await import(g))[$];if(J&&typeof J==="object"&&!Array.isArray(J))try{return N$(y,J)}catch{}}}catch{}return y}function Hy($,w={}){let y=f1.cwd();while(y.includes("storage"))y=Iw(y,"..");let j=Iw(y,$||"");if(w?.relative)return By(f1.cwd(),j);return j}async function fy(){try{let $=await Oy({name:"clarity",defaultConfig:Q$,cwd:f1.cwd(),endpoint:"",headers:{}});return{...Q$,...$}}catch{return Q$}}function x(){if(_0.env.NODE_ENV==="test"||_0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ky(){if(_0.env.NODE_ENV==="test"||_0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof _0<"u"){let $=_0.type;if($==="renderer"||$==="worker")return!1;return!!(_0.versions&&(_0.versions.node||_0.versions.bun))}return!1}class uw{async format($){let w=await ky(),y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:C0.pid,hostname:w(),environment:C0.env.NODE_ENV||"development",platform:C0.platform,version:C0.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:C0.env.NODE_ENV||C0.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class S1{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...vw},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new uw,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??r.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let y={...w},j=w.timestamp!==void 0;if(j)delete y.timestamp;if(this.config={...this.config,...y,timestamp:j||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let z=this.generateKeyId(),A=this.generateKey();this.currentKeyId=z,this.keys.set(z,A),this.encryptionKeys.set(z,{key:A,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...K$,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...K$};return{...K$,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:vw.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},y={...w,...Object.fromEntries(Object.entries($).filter(([,j])=>j!==void 0))};if(!y.level||!["debug","info","success","warning","error"].includes(y.level))y.level=w.level;return y}async writeToFile($){let w=(async()=>{let j,z=0,A=3,g=1000;while(z<A)try{try{try{await _y(this.config.logDirectory,Ew.F_OK|Ew.W_OK)}catch(X){if(X instanceof Error&&"code"in X)if(X.code==="ENOENT")await Ny(this.config.logDirectory,{recursive:!0,mode:493});else if(X.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw X;else throw X}}catch(X){throw console.error("Debug: [writeToFile] Failed to create log directory:",X),X}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:R0.from($);try{if(!B$(this.currentLogFile))await b$(this.currentLogFile,"",{mode:420});if(j=Mw(this.currentLogFile,"a",420),qy(j,J,{flag:"a"}),Zw(j),j!==void 0)U$(j),j=void 0;if((await E0(this.currentLogFile)).size===0){if(await b$(this.currentLogFile,J,{flag:"w",mode:420}),(await E0(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(X){let Y=X;if(Y.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Y.code)){if(z<A-1){let U=typeof Y.message==="string"?Y.message:"Unknown error";console.error(`Network error during write attempt ${z+1}/${A}:`,U);let B=g*2**z;await new Promise((b)=>setTimeout(b,B)),z++;continue}}if(Y?.code&&["ENOSPC","EDQUOT"].includes(Y.code))throw Error(`Disk quota exceeded or no space left on device: ${Y.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Y),Y}finally{if(j!==void 0)try{U$(j)}catch(X){console.error("Debug: [writeToFile] Error closing file descriptor:",X)}}}catch(J){if(z===A-1){let Y=J,U=typeof Y.message==="string"?Y.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",U),J}z++;let X=g*2**(z-1);await new Promise((Y)=>setTimeout(Y,X))}})();this.pendingOperations.push(w);let y=this.pendingOperations.length-1;try{await w}catch(j){throw console.error("Debug: [writeToFile] Error in operation:",j),j}finally{this.pendingOperations.splice(y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return D0(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return D0(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return D0(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(x())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,y=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((j)=>{console.error("Error rotating keys:",j)})},y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),y=this.generateKey();this.currentKeyId=w,this.keys.set(w,y),this.encryptionKeys.set(w,{key:y,createdAt:new Date});let j=Array.from(this.encryptionKeys.entries()).sort(([,g],[,J])=>J.createdAt.getTime()-g.createdAt.getTime()),z=typeof $.maxKeys==="number"?$.maxKeys:1,A=Math.max(1,z);if(j.length>A)for(let[g]of j.slice(A))this.encryptionKeys.delete(g),this.keys.delete(g)}generateKeyId(){return Y$(16).toString("hex")}generateKey(){return Y$(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),y=Y$(16),j=by("aes-256-gcm",w,y),z=R0.concat([j.update($,"utf8"),j.final()]),A=j.getAuthTag();return{encrypted:R0.concat([y,z,A]),iv:y}}async compressData($){return new Promise((w,y)=>{let j=Cw(),z=[];j.on("data",(A)=>z.push(A)),j.on("end",()=>w(R0.from(R0.concat(z)))),j.on("error",y),j.write($),j.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(x())return;let $=await E0(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let y=this.currentLogFile,j=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let z=await L1(this.config.logDirectory),A=z.filter((X)=>X.startsWith(this.name)&&/\.log\.\d+$/.test(X)).sort((X,Y)=>{let U=Number.parseInt(X.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Y.match(/\.log\.(\d+)$/)?.[1]||"0")-U}),g=A.length>0?Number.parseInt(A[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,J=`${y}.${g}`;if(await E0(y).catch(()=>null))try{if(await Dw(y,J),w.compress)try{let X=`${J}.gz`;await this.compressLogFile(J,X),await O1(J)}catch(X){console.error("Error compressing rotated file:",X)}if(A.length===0&&!z.some((X)=>X.endsWith(".log.1")))try{let X=`${y}.1`;await b$(X,"")}catch(X){console.error("Error creating backup file:",X)}}catch(X){console.error(`Error during rotation: ${X instanceof Error?X.message:String(X)}`)}}else{let z=new Date().toISOString().replace(/[:.]/g,"-"),A=y.replace(/\.log$/,`-${z}.log`);if(await E0(y).catch(()=>null))await Dw(y,A)}if(this.currentLogFile=j,w.maxFiles){let z=(await L1(this.config.logDirectory)).filter((A)=>A.startsWith(this.name)).sort((A,g)=>g.localeCompare(A));for(let A of z.slice(w.maxFiles))await O1(D0(this.config.logDirectory,A))}}}async compressLogFile($,w){let y=Tw($),j=Ky(w),z=Cw();await Wy(y,z,j)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let y of this.logBuffer){let j=await this.formatter.format(y);await this.writeToFile(j),console.log(j)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),B$(this.currentLogFile))try{let $=Mw(this.currentLogFile,"r+");Zw($),U$($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!x()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await L1(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await O1(D0(this.config.logDirectory,w))}catch(y){console.error(`Failed to delete temp file ${w}:`,y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?v.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:y="",tag:j="",message:z,level:A,showTimestamp:g=!0}=$,J=(Q)=>Q.replace(this.ANSI_PATTERN,"");if(!this.fancy){let Q=[];if(g)Q.push(w);if(A==="warning")Q.push("WARN");else if(A==="error")Q.push("ERROR");else if(y)Q.push(y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(j)Q.push(j.replace(/[[\]]/g,""));return Q.push(z),Q.join(" ")}let X=r.stdout.columns||120,Y="";if(A==="warning"||A==="error")Y=`${y} ${z}`;else if(A==="info"||A==="success")Y=`${y} ${j} ${z}`;else Y=`${y} ${j} ${v.cyan(z)}`;if(!g)return Y.trim();let U=J(Y).trim().length,B=J(w).length,b=Math.max(1,X-2-U-B);return`${Y.trim()}${" ".repeat(b)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(A,g)=>{let J=Number.parseInt(g,10);return J<w[0].length?String(w[0][J]):A});let y=/%([sdijfo%])/g,j=0,z=$.replace(y,(A,g)=>{if(g==="%")return"%";if(j>=w.length)return A;let J=w[j++];switch(g){case"s":return String(J);case"d":case"i":return Number(J).toString();case"j":case"o":return JSON.stringify(J,null,2);default:return A}});if(j<w.length)z+=` ${w.slice(j).map((A)=>typeof A==="object"?JSON.stringify(A,null,2):String(A)).join(" ")}`;return z}async log($,w,...y){let j=new Date,z=this.formatConsoleTimestamp(j),A=this.formatFileTimestamp(j),g,J;if(w instanceof Error)g=w.message,J=w.stack;else g=this.formatMessage(w,y);if(this.fancy&&!x()){let Y=Iy[$],U=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:v.gray(g),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:g,level:$}),console.error(B);break;case"success":B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:v.green(g),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:g,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:g,level:$}),console.error(B),J){let b=J.split(`
274
+ `);for(let Q of b)if(Q.trim()&&!Q.includes(g))console.error(this.formatConsoleMessage({timestamp:z,message:v.gray(` ${Q}`),level:$,showTimestamp:!1}))}break}}else if(!x()){if(console.error(`${A} ${this.environment}.${$.toUpperCase()}: ${g}`),J)console.error(J)}if(!this.shouldLog($))return;let X=`${A} ${this.environment}.${$.toUpperCase()}: ${g}
275
275
  `;if(J)X+=`${J}
276
- `;X=X.replace(this.ANSI_PATTERN,""),await this.writeToFile(X)}time($){let w=performance.now();if(this.fancy&&!x()){let y=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",j=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:j,icon:v.blue("\u25D0"),tag:y,message:`${v.cyan($)}...`}))}return async(y)=>{if(!this.enabled)return;let j=performance.now(),z=Math.round(j-w),g=`${$} completed in ${z}ms`,A=new Date,J=this.formatConsoleTimestamp(A),X=`${this.formatFileTimestamp(A)} ${this.environment}.INFO: ${g}`;if(y)X+=` ${JSON.stringify(y)}`;if(X+=`
277
- `,X=X.replace(this.ANSI_PATTERN,""),this.fancy&&!x()){let Y=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:J,icon:v.green("\u2713"),tag:Y,message:`${g}${y?` ${JSON.stringify(y)}`:""}`}))}else if(!x())console.error(X.trim());await this.writeToFile(X)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,y=new S1(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(y),y}createReadStream(){if(x())throw Error("createReadStream is not supported in browser environments");if(!U$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Sw(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let y=this.keys.get(this.currentKeyId);try{let j=R0.isBuffer($)?$:R0.from($,"base64"),z=j.slice(0,16),g=j.slice(-16),A=j.slice(16,-16),J=X9("aes-256-gcm",y,z);return J.setAuthTag(g),R0.concat([J.update(A),J.final()]).toString("utf8")}catch(j){throw Error(`Decryption failed: ${j instanceof Error?j.message:String(j)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return x()}isServerMode(){return!x()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,y=this.formatConsoleTimestamp(w),j=this.formatFileTimestamp(w);if(this.fancy&&!x()){let g=$.split(`
278
- `),A=Math.max(...g.map((U)=>U.length))+2,J=`\u250C${"\u2500".repeat(A)}\u2510`,X=`\u2514${"\u2500".repeat(A)}\u2518`,Y=g.map((U)=>{let B=" ".repeat(A-U.length-2);return`\u2502 ${U}${B} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:y,message:v.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:y,message:v.cyan(J)})),Y.forEach((U)=>console.error(this.formatConsoleMessage({timestamp:y,message:v.cyan(U),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:y,message:v.cyan(X),showTimestamp:!1}))}else if(!x())console.error(`${j} ${this.environment}.INFO: [BOX] ${$}`);let z=`${j} ${this.environment}.INFO: [BOX] ${$}
279
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(z)}async prompt($){if(x())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${v.cyan("?")} ${$} (y/n) `);let y=(j)=>{let z=j.toString().trim().toLowerCase();o.stdin.removeListener("data",y);try{if(typeof o.stdin.setRawMode==="function")o.stdin.setRawMode(!1)}catch{}o.stdin.pause(),console.error(""),w(z==="y"||z==="yes")};try{if(typeof o.stdin.setRawMode==="function")o.stdin.setRawMode(!0)}catch{}o.stdin.resume(),o.stdin.once("data",y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let y=$;if(w&&w.length>0){let z=/%([sdijfo%])/g,g=0;if(y=$.replace(z,(A,J)=>{if(J==="%")return"%";if(g>=w.length)return A;let X=w[g++];switch(J){case"s":return String(X);case"d":case"i":return Number(X).toString();case"j":case"o":return JSON.stringify(X,null,2);default:return A}}),g<w.length)y+=` ${w.slice(g).map((A)=>typeof A==="object"?JSON.stringify(A,null,2):String(A)).join(" ")}`}if(this.fancy&&!x()){let z=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",g=v.blue("\u25D0");console.error(`${g} ${z} ${v.cyan(y)}`)}let j=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${y}
280
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(j)}progress($,w=""){if(!this.enabled||!this.fancy||x()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let y=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(j,z)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||x())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,j)),z!==void 0)this.activeProgressBar.message=z;let g=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,g)},finish:(j)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||x())return;if(this.activeProgressBar.current=this.activeProgressBar.total,j!==void 0)this.activeProgressBar.message=j;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(j,z="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||x())return;o.stdout.write(`${"\r".padEnd(o.stdout.columns||80)}\r`),this.log(z,j),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||x()||!o.stdout.isTTY)return;let y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),j=Math.round($.barLength*y/100),z=$.barLength-j,g=v.green("\u2501".repeat(j)),A=v.gray("\u2501".repeat(z)),J=`[${g}${A}]`,X=`${y}%`.padStart(4),Y=$.message?` ${$.message}`:"",U=w||y===100?v.green("\u2713"):v.blue("\u25B6"),B=this.options.showTags!==!1&&this.name?` ${v.gray(this.formatTag(this.name))}`:"",b=`\r${U}${B} ${J} ${X}${Y}`,Q=o.stdout.columns||80,K=" ".repeat(Math.max(0,Q-b.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${b}${K}`,o.stdout.write($.lastRenderedLine),w)o.stdout.write(`
281
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||x()||!o.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(x()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await L1(this.config.logDirectory),y=[];for(let j of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(j):j.startsWith(this.name))||!j.endsWith(".log"))continue;let z=D0(this.config.logDirectory,j);if($.before)try{if((await M0(z)).mtime>=$.before)continue}catch(g){console.error(`Failed to get stats for file ${z}:`,g);continue}y.push(z)}if(y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${y.length} log file(s)...`);for(let j of y)try{await f1(j),console.warn(`Deleted log file: ${j}`)}catch(z){console.error(`Failed to delete log file ${j}:`,z)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function R1($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&D(w[0])&&"id"in w[0]&&w[0].id===3&&D(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(D(w)&&D($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(D($)&&"arr"in $&&Array.isArray($.arr)&&D(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&D(w[0])&&D($[0])){let j=[...w];for(let z of $)if(D(z)&&"name"in z){if(!j.find((g)=>D(g)&&("name"in g)&&g.name===z.name))j.push(z)}else if(D(z)&&"path"in z){if(!j.find((g)=>D(g)&&("path"in g)&&g.path===z.path))j.push(z)}else if(!j.some((g)=>V1(g,z)))j.push(z);return j}if(w.every((j)=>typeof j==="string")&&$.every((j)=>typeof j==="string")){let j=[...w];for(let z of $)if(!j.includes(z))j.push(z);return j}return w}if(!D(w)||!D($))return w;let y={...$};for(let j in w)if(Object.prototype.hasOwnProperty.call(w,j)){let z=w[j];if(z===null||z===void 0)continue;else if(D(z)&&D(y[j]))y[j]=R1(y[j],z);else if(Array.isArray(z)&&Array.isArray(y[j]))if(z.length>0&&y[j].length>0&&D(z[0])&&D(y[j][0])){let g=[...z];for(let A of y[j])if(D(A)&&"name"in A){if(!g.find((J)=>D(J)&&("name"in J)&&J.name===A.name))g.push(A)}else if(D(A)&&"path"in A){if(!g.find((J)=>D(J)&&("path"in J)&&J.path===A.path))g.push(A)}else if(!g.some((J)=>V1(J,A)))g.push(A);y[j]=g}else if(z.every((g)=>typeof g==="string")&&y[j].every((g)=>typeof g==="string")){let g=[...z];for(let A of y[j])if(!g.includes(A))g.push(A);y[j]=g}else y[j]=z;else y[j]=z}return y}function N$($,w,y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return y==="replace"?w:R1($,w);if(Array.isArray($))return y==="replace"?w:R1($,w);if(!D(w)||!D($))return w;let j={...$};for(let z of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,z))continue;let g=w[z],A=j[z];if(g===null||g===void 0)continue;if(Array.isArray(g)||Array.isArray(A))if(y==="replace")j[z]=g;else j[z]=R1(A,g);else if(D(g)&&D(A))j[z]=N$(A,g,y);else j[z]=g}return j}function V1($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let y=0;y<$.length;y++)if(!V1($[y],w[y]))return!1;return!0}if(D($)&&D(w)){let y=Object.keys($),j=Object.keys(w);if(y.length!==j.length)return!1;for(let z of y){if(!Object.prototype.hasOwnProperty.call(w,z))return!1;if(!V1($[z],w[z]))return!1}return!0}return!1}function D($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function O1($,w,y="replace"){if(!vw($))return null;try{let j=await import($),z=j.default||j;if(typeof z!=="object"||z===null||Array.isArray(z))return null;try{return N$(w,z,y)}catch{return null}}catch{return null}}function F9($,w,y=!1){if(!$)return w;let j=$.toUpperCase().replace(/-/g,"_"),z={...w};function g(A,J=[]){let X={...A};for(let[Y,U]of Object.entries(A)){let B=[...J,Y],b=(_)=>_.replace(/([A-Z])/g,"_$1").toUpperCase(),Q=`${j}_${B.map(b).join("_")}`,K=`${j}_${B.map((_)=>_.toUpperCase()).join("_")}`;if(y)e.info(`Checking environment variable ${Q} for config ${$}.${B.join(".")}`);if(typeof U==="object"&&U!==null&&!Array.isArray(U))X[Y]=g(U,B);else{let _=t0.env[Q]||t0.env[K];if(_!==void 0){if(y)e.info(`Using environment variable ${_?Q:K} for config ${$}.${B.join(".")}`);if(typeof U==="number")X[Y]=Number(_);else if(typeof U==="boolean")X[Y]=_.toLowerCase()==="true";else if(Array.isArray(U))try{let W=JSON.parse(_);if(Array.isArray(W))X[Y]=W;else X[Y]=_.split(",").map((L)=>L.trim())}catch{X[Y]=_.split(",").map((W)=>W.trim())}else X[Y]=_}}}return X}return g(z)}async function V9({name:$="",alias:w,cwd:y,configDir:j,defaultConfig:z,verbose:g=!1,checkEnv:A=!0,arrayStrategy:J="replace"}){let X=A&&typeof z==="object"&&z!==null&&!Array.isArray(z)?F9($,z,g):z,Y=y||t0.cwd(),U=[".ts",".js",".mjs",".cjs",".json"];if(g)e.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${Y}`);let B=[$,`.${$}`].filter(Boolean),b=[`${$}.config`,`.${$}.config`].filter(Boolean),Q=w?[w,`.${w}`]:[],K=w?[`${w}.config`,`.${w}.config`]:[],_=Array.from(new Set([Y,j0(Y,"config"),j0(Y,".config"),j?j0(Y,j):void 0].filter(Boolean)));for(let W of _){if(g)e.info(`Searching for configuration in: ${W}`);let L=[j0(Y,"config"),j0(Y,".config")].concat(j?[j0(Y,j)]:[]).includes(W)?[...B,...b,...Q,...K]:[...b,...B,...K,...Q];for(let N of L)for(let f of U){let O=j0(W,`${N}${f}`),R=await O1(O,X,J);if(R!==null){if(g)e.success(`Configuration loaded from: ${O}`);return R}}}if($){let W=j0(J$(),".config",$),L=["config",`${$}.config`];if(w)L.push(`${w}.config`);if(g)e.info(`Checking user config directory: ${W}`);for(let N of L)for(let f of U){let O=j0(W,`${N}${f}`),R=await O1(O,X,J);if(R!==null){if(g)e.success(`Configuration loaded from user config directory: ${O}`);return R}}}if($){let W=j0(J$(),".config"),L=[`.${$}.config`];if(w)L.push(`.${w}.config`);if(g)e.info(`Checking user config directory for dotfile configs: ${W}`);for(let N of L)for(let f of U){let O=j0(W,`${N}${f}`),R=await O1(O,X,J);if(R!==null){if(g)e.success(`Configuration loaded from user config directory dotfile: ${O}`);return R}}}if($){let W=J$(),L=[`.${$}.config`,`.${$}`];if(w)L.push(`.${w}.config`),L.push(`.${w}`);if(g)e.info(`Checking user home directory for dotfile configs: ${W}`);for(let N of L)for(let f of U){let O=j0(W,`${N}${f}`),R=await O1(O,X,J);if(R!==null){if(g)e.success(`Configuration loaded from user home directory: ${O}`);return R}}}try{let W=j0(Y,"package.json");if(vw(W)){let L=await import(W),N=L[$];if(!N&&w){if(N=L[w],N&&g)e.success(`Using alias "${w}" configuration from package.json`)}if(N&&typeof N==="object"&&!Array.isArray(N))try{if(g)e.success(`Configuration loaded from package.json: ${N===L[$]?$:w}`);return N$(X,N,J)}catch(f){if(g)e.warn("Failed to merge package.json config:",f)}}}catch(W){if(g)e.warn("Failed to load package.json:",W)}if(g)e.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return X}function D9($){return Pw.find((w)=>w.id===$||w.aliases?.includes($)||w.extensions?.includes(`.${$}`)||w.extensions?.includes($))}class K${theme;colorCache=new Map;cssCache=null;constructor($){this.theme=$}render($,w={}){let{lineNumbers:y=!1,highlightLines:j=[],inline:z=!1,focusLines:g=[],dimLines:A=[],addedLines:J=[],removedLines:X=[],annotations:Y=[],showCopyButton:U=!1}=w,B=$.map((_,W)=>{let L=W+1,N=this.getLineClasses(L,{highlightLines:j,focusLines:g,dimLines:A,addedLines:J,removedLines:X}),f=this.renderLine(_,z);if(z)return f;let O=y?`<span class="line-number">${L}</span>`:"",R="";if(J.includes(L))R='<span class="diff-indicator add">+</span>';else if(X.includes(L))R='<span class="diff-indicator remove">-</span>';let H=Y.filter((F)=>F.line===L).map((F)=>this.renderAnnotation(F)).join("");return`<span class="${N}">${R}${O}${f}${H}</span>`}),b=z?`<code class="syntax-inline">${B.join("")}</code>`:`<div class="syntax-wrapper">${U?'<button class="copy-button" data-copy>Copy</button>':""}<pre class="syntax"><code>${B.join(`
282
- `)}</code></pre></div>`,Q=this.generateCSS(w),K=this.renderAnsi($);return{html:b,css:Q,tokens:$,ansi:K}}getLineClasses($,w){let y=["line"];if(w.highlightLines.includes($))y.push("highlighted");if(w.focusLines.includes($))y.push("focus");if(w.dimLines.includes($))y.push("dim");if(w.addedLines.includes($))y.push("added");if(w.removedLines.includes($))y.push("removed");return y.join(" ")}renderAnnotation($){return`<span class="annotation annotation-${$.type||"info"}">${this.escapeHtml($.text)}</span>`}renderLine($,w){return $.tokens.map((y)=>this.renderToken(y)).join("")}renderToken($){let w=this.getColorForScopes($.scopes),y=this.escapeHtml($.content),j=[this.getScopeClass($.scopes)],z=[];if(w.foreground||w.fontStyle)z.push(this.buildStyle(w));if($.dimmed)j.push("dimmed");if($.blurred)j.push("blurred");if($.highlighted){if(j.push("highlighted-token"),$.highlightColor)z.push(`background-color: ${$.highlightColor}`)}if($.emphasized)j.push("emphasized");let g=j.join(" "),A=z.join("; ");if($.link)return`<a href="${$.link}" class="${g}" style="${A}" target="_blank" rel="noopener noreferrer">${y}</a>`;if(!A&&g==="token")return y;return`<span class="${g}" style="${A}">${y}</span>`}getColorForScopes($){if(!Array.isArray($)||$.length===0)return{};let w=$.join("|"),y=this.colorCache.get(w);if(y)return y;let j={},z=0;for(let g of this.theme.tokenColors){let A=Array.isArray(g.scope)?g.scope:[g.scope];for(let J of A)for(let X of $)if(this.scopeMatches(X,J)){let Y=J.split(".").length;if(Y>z)j=g.settings,z=Y}}return this.colorCache.set(w,j),j}scopeMatches($,w){if(typeof $!=="string"||typeof w!=="string")return!1;let y=$.split("."),j=w.split(".");for(let z=0;z<j.length;z++)if(y[z]!==j[z])return!1;return!0}buildStyle($){let w=[];if($.foreground)w.push(`color: ${$.foreground}`);if($.background)w.push(`background-color: ${$.background}`);if($.fontStyle){if($.fontStyle.includes("italic"))w.push("font-style: italic");if($.fontStyle.includes("bold"))w.push("font-weight: bold");if($.fontStyle.includes("underline"))w.push("text-decoration: underline")}return w.join("; ")}getScopeClass($){if($.length===0)return"token";let w=$[$.length-1];if(typeof w!=="string")return"token";return`token ${w.replace(/\./g,"-")}`}escapeHtml($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}generateCSS($={}){if(this.cssCache)return this.cssCache;let{colors:w}=this.theme;return this.cssCache=`
276
+ `;X=X.replace(this.ANSI_PATTERN,""),await this.writeToFile(X)}time($){let w=performance.now();if(this.fancy&&!x()){let y=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",j=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:j,icon:v.blue("\u25D0"),tag:y,message:`${v.cyan($)}...`}))}return async(y)=>{if(!this.enabled)return;let j=performance.now(),z=Math.round(j-w),A=`${$} completed in ${z}ms`,g=new Date,J=this.formatConsoleTimestamp(g),X=`${this.formatFileTimestamp(g)} ${this.environment}.INFO: ${A}`;if(y)X+=` ${JSON.stringify(y)}`;if(X+=`
277
+ `,X=X.replace(this.ANSI_PATTERN,""),this.fancy&&!x()){let Y=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:J,icon:v.green("\u2713"),tag:Y,message:`${A}${y?` ${JSON.stringify(y)}`:""}`}))}else if(!x())console.error(X.trim());await this.writeToFile(X)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,y=new S1(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(y),y}createReadStream(){if(x())throw Error("createReadStream is not supported in browser environments");if(!B$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Tw(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let y=this.keys.get(this.currentKeyId);try{let j=R0.isBuffer($)?$:R0.from($,"base64"),z=j.slice(0,16),A=j.slice(-16),g=j.slice(16,-16),J=Qy("aes-256-gcm",y,z);return J.setAuthTag(A),R0.concat([J.update(g),J.final()]).toString("utf8")}catch(j){throw Error(`Decryption failed: ${j instanceof Error?j.message:String(j)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return x()}isServerMode(){return!x()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,y=this.formatConsoleTimestamp(w),j=this.formatFileTimestamp(w);if(this.fancy&&!x()){let A=$.split(`
278
+ `),g=Math.max(...A.map((U)=>U.length))+2,J=`\u250C${"\u2500".repeat(g)}\u2510`,X=`\u2514${"\u2500".repeat(g)}\u2518`,Y=A.map((U)=>{let B=" ".repeat(g-U.length-2);return`\u2502 ${U}${B} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:y,message:v.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:y,message:v.cyan(J)})),Y.forEach((U)=>console.error(this.formatConsoleMessage({timestamp:y,message:v.cyan(U),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:y,message:v.cyan(X),showTimestamp:!1}))}else if(!x())console.error(`${j} ${this.environment}.INFO: [BOX] ${$}`);let z=`${j} ${this.environment}.INFO: [BOX] ${$}
279
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(z)}async prompt($){if(x())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${v.cyan("?")} ${$} (y/n) `);let y=(j)=>{let z=j.toString().trim().toLowerCase();r.stdin.removeListener("data",y);try{if(typeof r.stdin.setRawMode==="function")r.stdin.setRawMode(!1)}catch{}r.stdin.pause(),console.error(""),w(z==="y"||z==="yes")};try{if(typeof r.stdin.setRawMode==="function")r.stdin.setRawMode(!0)}catch{}r.stdin.resume(),r.stdin.once("data",y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let y=$;if(w&&w.length>0){let z=/%([sdijfo%])/g,A=0;if(y=$.replace(z,(g,J)=>{if(J==="%")return"%";if(A>=w.length)return g;let X=w[A++];switch(J){case"s":return String(X);case"d":case"i":return Number(X).toString();case"j":case"o":return JSON.stringify(X,null,2);default:return g}}),A<w.length)y+=` ${w.slice(A).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`}if(this.fancy&&!x()){let z=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",A=v.blue("\u25D0");console.error(`${A} ${z} ${v.cyan(y)}`)}let j=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${y}
280
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(j)}progress($,w=""){if(!this.enabled||!this.fancy||x()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let y=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(j,z)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||x())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,j)),z!==void 0)this.activeProgressBar.message=z;let A=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,A)},finish:(j)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||x())return;if(this.activeProgressBar.current=this.activeProgressBar.total,j!==void 0)this.activeProgressBar.message=j;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(j,z="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||x())return;r.stdout.write(`${"\r".padEnd(r.stdout.columns||80)}\r`),this.log(z,j),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||x()||!r.stdout.isTTY)return;let y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),j=Math.round($.barLength*y/100),z=$.barLength-j,A=v.green("\u2501".repeat(j)),g=v.gray("\u2501".repeat(z)),J=`[${A}${g}]`,X=`${y}%`.padStart(4),Y=$.message?` ${$.message}`:"",U=w||y===100?v.green("\u2713"):v.blue("\u25B6"),B=this.options.showTags!==!1&&this.name?` ${v.gray(this.formatTag(this.name))}`:"",b=`\r${U}${B} ${J} ${X}${Y}`,Q=r.stdout.columns||80,K=" ".repeat(Math.max(0,Q-b.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${b}${K}`,r.stdout.write($.lastRenderedLine),w)r.stdout.write(`
281
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||x()||!r.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(x()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await L1(this.config.logDirectory),y=[];for(let j of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(j):j.startsWith(this.name))||!j.endsWith(".log"))continue;let z=D0(this.config.logDirectory,j);if($.before)try{if((await E0(z)).mtime>=$.before)continue}catch(A){console.error(`Failed to get stats for file ${z}:`,A);continue}y.push(z)}if(y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${y.length} log file(s)...`);for(let j of y)try{await O1(j),console.warn(`Deleted log file: ${j}`)}catch(z){console.error(`Failed to delete log file ${j}:`,z)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function R1($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&E(w[0])&&"id"in w[0]&&w[0].id===3&&E(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(E(w)&&E($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(E($)&&"arr"in $&&Array.isArray($.arr)&&E(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&E(w[0])&&E($[0])){let j=[...w];for(let z of $)if(E(z)&&"name"in z){if(!j.find((A)=>E(A)&&("name"in A)&&A.name===z.name))j.push(z)}else if(E(z)&&"path"in z){if(!j.find((A)=>E(A)&&("path"in A)&&A.path===z.path))j.push(z)}else if(!j.some((A)=>V1(A,z)))j.push(z);return j}if(w.every((j)=>typeof j==="string")&&$.every((j)=>typeof j==="string")){let j=[...w];for(let z of $)if(!j.includes(z))j.push(z);return j}return w}if(!E(w)||!E($))return w;let y={...$};for(let j in w)if(Object.prototype.hasOwnProperty.call(w,j)){let z=w[j];if(z===null||z===void 0)continue;else if(E(z)&&E(y[j]))y[j]=R1(y[j],z);else if(Array.isArray(z)&&Array.isArray(y[j]))if(z.length>0&&y[j].length>0&&E(z[0])&&E(y[j][0])){let A=[...z];for(let g of y[j])if(E(g)&&"name"in g){if(!A.find((J)=>E(J)&&("name"in J)&&J.name===g.name))A.push(g)}else if(E(g)&&"path"in g){if(!A.find((J)=>E(J)&&("path"in J)&&J.path===g.path))A.push(g)}else if(!A.some((J)=>V1(J,g)))A.push(g);y[j]=A}else if(z.every((A)=>typeof A==="string")&&y[j].every((A)=>typeof A==="string")){let A=[...z];for(let g of y[j])if(!A.includes(g))A.push(g);y[j]=A}else y[j]=z;else y[j]=z}return y}function W$($,w,y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return y==="replace"?w:R1($,w);if(Array.isArray($))return y==="replace"?w:R1($,w);if(!E(w)||!E($))return w;let j={...$};for(let z of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,z))continue;let A=w[z],g=j[z];if(A===null||A===void 0)continue;if(Array.isArray(A)||Array.isArray(g))if(y==="replace")j[z]=A;else j[z]=R1(g,A);else if(E(A)&&E(g))j[z]=W$(g,A,y);else j[z]=A}return j}function V1($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let y=0;y<$.length;y++)if(!V1($[y],w[y]))return!1;return!0}if(E($)&&E(w)){let y=Object.keys($),j=Object.keys(w);if(y.length!==j.length)return!1;for(let z of y){if(!Object.prototype.hasOwnProperty.call(w,z))return!1;if(!V1($[z],w[z]))return!1}return!0}return!1}function E($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function H1($,w,y="replace"){if(!Pw($))return null;try{let j=await import($),z=j.default||j;if(typeof z!=="object"||z===null||Array.isArray(z))return null;try{return W$(w,z,y)}catch{return null}}catch{return null}}function Ty($,w,y=!1){if(!$)return w;let j=$.toUpperCase().replace(/-/g,"_"),z={...w};function A(g,J=[]){let X={...g};for(let[Y,U]of Object.entries(g)){let B=[...J,Y],b=(_)=>_.replace(/([A-Z])/g,"_$1").toUpperCase(),Q=`${j}_${B.map(b).join("_")}`,K=`${j}_${B.map((_)=>_.toUpperCase()).join("_")}`;if(y)e.info(`Checking environment variable ${Q} for config ${$}.${B.join(".")}`);if(typeof U==="object"&&U!==null&&!Array.isArray(U))X[Y]=A(U,B);else{let _=t0.env[Q]||t0.env[K];if(_!==void 0){if(y)e.info(`Using environment variable ${_?Q:K} for config ${$}.${B.join(".")}`);if(typeof U==="number")X[Y]=Number(_);else if(typeof U==="boolean")X[Y]=_.toLowerCase()==="true";else if(Array.isArray(U))try{let W=JSON.parse(_);if(Array.isArray(W))X[Y]=W;else X[Y]=_.split(",").map((L)=>L.trim())}catch{X[Y]=_.split(",").map((W)=>W.trim())}else X[Y]=_}}}return X}return A(z)}async function Zy({name:$="",alias:w,cwd:y,configDir:j,defaultConfig:z,verbose:A=!1,checkEnv:g=!0,arrayStrategy:J="replace"}){let X=g&&typeof z==="object"&&z!==null&&!Array.isArray(z)?Ty($,z,A):z,Y=y||t0.cwd(),U=[".ts",".js",".mjs",".cjs",".json"];if(A)e.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${Y}`);let B=[$,`.${$}`].filter(Boolean),b=[`${$}.config`,`.${$}.config`].filter(Boolean),Q=w?[w,`.${w}`]:[],K=w?[`${w}.config`,`.${w}.config`]:[],_=Array.from(new Set([Y,j0(Y,"config"),j0(Y,".config"),j?j0(Y,j):void 0].filter(Boolean)));for(let W of _){if(A)e.info(`Searching for configuration in: ${W}`);let L=[j0(Y,"config"),j0(Y,".config")].concat(j?[j0(Y,j)]:[]).includes(W)?[...B,...b,...Q,...K]:[...b,...B,...K,...Q];for(let N of L)for(let O of U){let H=j0(W,`${N}${O}`),R=await H1(H,X,J);if(R!==null){if(A)e.success(`Configuration loaded from: ${H}`);return R}}}if($){let W=j0(X$(),".config",$),L=["config",`${$}.config`];if(w)L.push(`${w}.config`);if(A)e.info(`Checking user config directory: ${W}`);for(let N of L)for(let O of U){let H=j0(W,`${N}${O}`),R=await H1(H,X,J);if(R!==null){if(A)e.success(`Configuration loaded from user config directory: ${H}`);return R}}}if($){let W=j0(X$(),".config"),L=[`.${$}.config`];if(w)L.push(`.${w}.config`);if(A)e.info(`Checking user config directory for dotfile configs: ${W}`);for(let N of L)for(let O of U){let H=j0(W,`${N}${O}`),R=await H1(H,X,J);if(R!==null){if(A)e.success(`Configuration loaded from user config directory dotfile: ${H}`);return R}}}if($){let W=X$(),L=[`.${$}.config`,`.${$}`];if(w)L.push(`.${w}.config`),L.push(`.${w}`);if(A)e.info(`Checking user home directory for dotfile configs: ${W}`);for(let N of L)for(let O of U){let H=j0(W,`${N}${O}`),R=await H1(H,X,J);if(R!==null){if(A)e.success(`Configuration loaded from user home directory: ${H}`);return R}}}try{let W=j0(Y,"package.json");if(Pw(W)){let L=await import(W),N=L[$];if(!N&&w){if(N=L[w],N&&A)e.success(`Using alias "${w}" configuration from package.json`)}if(N&&typeof N==="object"&&!Array.isArray(N))try{if(A)e.success(`Configuration loaded from package.json: ${N===L[$]?$:w}`);return W$(X,N,J)}catch(O){if(A)e.warn("Failed to merge package.json config:",O)}}}catch(W){if(A)e.warn("Failed to load package.json:",W)}if(A)e.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return X}function Py($){return mw.find((w)=>w.id===$||w.aliases?.includes($)||w.extensions?.includes(`.${$}`)||w.extensions?.includes($))}class q${theme;colorCache=new Map;cssCache=null;constructor($){this.theme=$}render($,w={}){let{lineNumbers:y=!1,highlightLines:j=[],inline:z=!1,focusLines:A=[],dimLines:g=[],addedLines:J=[],removedLines:X=[],annotations:Y=[],showCopyButton:U=!1}=w,B=$.map((_,W)=>{let L=W+1,N=this.getLineClasses(L,{highlightLines:j,focusLines:A,dimLines:g,addedLines:J,removedLines:X}),O=this.renderLine(_,z);if(z)return O;let H=y?`<span class="line-number">${L}</span>`:"",R="";if(J.includes(L))R='<span class="diff-indicator add">+</span>';else if(X.includes(L))R='<span class="diff-indicator remove">-</span>';let f=Y.filter((F)=>F.line===L).map((F)=>this.renderAnnotation(F)).join("");return`<span class="${N}">${R}${H}${O}${f}</span>`}),b=z?`<code class="syntax-inline">${B.join("")}</code>`:`<div class="syntax-wrapper">${U?'<button class="copy-button" data-copy>Copy</button>':""}<pre class="syntax"><code>${B.join(`
282
+ `)}</code></pre></div>`,Q=this.generateCSS(w),K=this.renderAnsi($);return{html:b,css:Q,tokens:$,ansi:K}}getLineClasses($,w){let y=["line"];if(w.highlightLines.includes($))y.push("highlighted");if(w.focusLines.includes($))y.push("focus");if(w.dimLines.includes($))y.push("dim");if(w.addedLines.includes($))y.push("added");if(w.removedLines.includes($))y.push("removed");return y.join(" ")}renderAnnotation($){return`<span class="annotation annotation-${$.type||"info"}">${this.escapeHtml($.text)}</span>`}renderLine($,w){return $.tokens.map((y)=>this.renderToken(y)).join("")}renderToken($){let w=this.getColorForScopes($.scopes),y=this.escapeHtml($.content),j=[this.getScopeClass($.scopes)],z=[];if(w.foreground||w.fontStyle)z.push(this.buildStyle(w));if($.dimmed)j.push("dimmed");if($.blurred)j.push("blurred");if($.highlighted){if(j.push("highlighted-token"),$.highlightColor)z.push(`background-color: ${$.highlightColor}`)}if($.emphasized)j.push("emphasized");let A=j.join(" "),g=z.join("; ");if($.link)return`<a href="${$.link}" class="${A}" style="${g}" target="_blank" rel="noopener noreferrer">${y}</a>`;if(!g&&A==="token")return y;return`<span class="${A}" style="${g}">${y}</span>`}getColorForScopes($){if(!Array.isArray($)||$.length===0)return{};let w=$.join("|"),y=this.colorCache.get(w);if(y)return y;let j={},z=0;for(let A of this.theme.tokenColors){let g=Array.isArray(A.scope)?A.scope:[A.scope];for(let J of g)for(let X of $)if(this.scopeMatches(X,J)){let Y=J.split(".").length;if(Y>z)j=A.settings,z=Y}}return this.colorCache.set(w,j),j}scopeMatches($,w){if(typeof $!=="string"||typeof w!=="string")return!1;let y=$.split("."),j=w.split(".");for(let z=0;z<j.length;z++)if(y[z]!==j[z])return!1;return!0}buildStyle($){let w=[];if($.foreground)w.push(`color: ${$.foreground}`);if($.background)w.push(`background-color: ${$.background}`);if($.fontStyle){if($.fontStyle.includes("italic"))w.push("font-style: italic");if($.fontStyle.includes("bold"))w.push("font-weight: bold");if($.fontStyle.includes("underline"))w.push("text-decoration: underline")}return w.join("; ")}getScopeClass($){if($.length===0)return"token";let w=$[$.length-1];if(typeof w!=="string")return"token";return`token ${w.replace(/\./g,"-")}`}escapeHtml($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}generateCSS($={}){if(this.cssCache)return this.cssCache;let{colors:w}=this.theme;return this.cssCache=`
283
283
  .syntax-wrapper {
284
284
  position: relative;
285
285
  }
@@ -448,19 +448,19 @@ ${X}`},hasEndTag:!1,description:"Coordinates multiple animations together as a g
448
448
  background-color: ${this.theme.type==="dark"?"rgba(110, 118, 129, 0.8)":"rgba(27, 31, 36, 0.35)"};
449
449
  }
450
450
  `.trim(),this.cssCache}renderAnsi($){let w={keyword:"\x1B[35m",string:"\x1B[32m",comment:"\x1B[90m",number:"\x1B[36m",function:"\x1B[33m",reset:"\x1B[0m"};return $.map((y)=>y.tokens.map((j)=>{let z=typeof j.type==="string"?j.type.toLowerCase():"text";return`${w[z]||w.reset}${j.content}${w.reset}`}).join("")).join(`
451
- `)}setTheme($){this.theme=$,this.colorCache.clear(),this.cssCache=null}}class xw{keywordSet=null;isJsOrTs;isHtml;isCss;constructor($){if(this.isJsOrTs=$.scopeName==="source.js"||$.scopeName==="source.ts",this.isHtml=$.scopeName==="text.html.basic",this.isCss=$.scopeName==="source.css",$.keywords)this.keywordSet=new Set(Object.keys($.keywords))}tokenize($){let w=$.split(`
452
- `),y=[];for(let j=0;j<w.length;j++)y.push(this.tokenizeLine(w[j]));return y}tokenizeLine($){let w=[],y=0;while(y<$.length){let j=$.charCodeAt(y),z=S[j];if(z&32){y++;continue}if(z&2){let g=y;y=this.scanNumber($,y),w.push({type:"numeric",content:$.slice(g,y)});continue}if(this.isHtml&&j===60){let g=y;if(y++,$.charCodeAt(y)===47)y++;while(y<$.length&&S[$.charCodeAt(y)]&1)y++;while(y<$.length&&$.charCodeAt(y)!==62)y++;if($.charCodeAt(y)===62)y++;w.push({type:"tag",content:$.slice(g,y)});continue}if(this.isCss){if(j===46||j===35||z&1){let g=y;while(y<$.length){let X=$.charCodeAt(y);if(X===123||X===58||X===59)break;y++}let A=$.slice(g,y),J=A.includes(":")?"property":"selector";w.push({type:J,content:A});continue}}if(!this.isHtml&&j===47){let g=$.charCodeAt(y+1);if(g===47){w.push({type:"comment",content:$.slice(y)});break}else if(g===42){let A=$.indexOf("*/",y+2);if(A!==-1){w.push({type:"comment",content:$.slice(y,A+2)}),y=A+2;continue}}}if(this.isHtml&&j===60&&$.charCodeAt(y+1)===33){let g=$.indexOf("-->",y+4);if(g!==-1){w.push({type:"comment",content:$.slice(y,g+3)}),y=g+3;continue}}if(z&16){let g=y;if(y=this.scanString($,y,j),y>g){w.push({type:"string",content:$.slice(g,y)});continue}}if(z&1){let g=y;y=this.scanWord($,y);let A=$.slice(g,y);if(this.isJsOrTs&&$.charCodeAt(y)===40){w.push({type:"function",content:A});continue}let J=this.keywordSet&&this.keywordSet.has(A)?"keyword":"text";w.push({type:J,content:A});continue}if(this.isJsOrTs&&z&4){let g=y;y=this.scanOperator($,y,j),w.push({type:"operator",content:$.slice(g,y)});continue}if(z&8){w.push({type:"punctuation",content:$[y]}),y++;continue}w.push({type:"text",content:$[y]}),y++}return{tokens:w}}scanNumber($,w){let y=w,j=!1,z=!1;if($[w]==="0"&&w+1<$.length){let g=$.charCodeAt(w+1);if(g===120||g===88){y=w+2;while(y<$.length){let A=$.charCodeAt(y);if(!(A>=48&&A<=57||A>=65&&A<=70||A>=97&&A<=102))break;y++}return y}else if(g===98||g===66){y=w+2;while(y<$.length&&($[y]==="0"||$[y]==="1"))y++;return y}else if(g===111||g===79){y=w+2;while(y<$.length){let A=$.charCodeAt(y);if(!(A>=48&&A<=55))break;y++}return y}}while(y<$.length){let g=$.charCodeAt(y);if(g>=48&&g<=57)y++;else if(g===46&&!j&&!z)j=!0,y++;else if((g===101||g===69)&&!z){if(z=!0,y++,y<$.length&&($[y]==="+"||$[y]==="-"))y++}else break}return y}scanString($,w,y){let j=w+1,z=!1;while(j<$.length){let g=$.charCodeAt(j);if(z)z=!1;else if(g===92)z=!0;else if(g===y)return j+1;j++}return j}scanWord($,w){let y=w+1;while(y<$.length){let j=$.charCodeAt(y);if(!(S[j]&3))break;y++}return y}scanOperator($,w,y){if(w+1>=$.length)return w+1;let j=$.charCodeAt(w+1);if(w+2<$.length){let z=$.charCodeAt(w+2);if(y===61&&j===61&&z===61||y===33&&j===61&&z===61||y===62&&j===62&&z===62||y===46&&j===46&&z===46)return w+3}if(y===43&&j===43||y===45&&j===45||y===61&&j===61||y===33&&j===61||y===60&&j===61||y===62&&j===61||y===38&&j===38||y===124&&j===124||y===61&&j===62||y===60&&j===60||y===62&&j===62)return w+2;return w+1}}function h9($){let w=$.toLowerCase();return uw.find((y)=>{let j=y.name.toLowerCase(),z=j.replace(/\s+/g,"-");return j===w||z===w})}class t{grammar;scopeStack=[];regexCache=new Map;compiledPatterns;numberRegex;isJsOrTs;rootScopes;numericScopes;operatorScopes;commentScopes;blockCommentScopes;stringScopes;templateScopes;functionScopes;static TYPE_TEXT="text";static TYPE_PUNCTUATION="punctuation";static TYPE_NUMERIC="numeric";static TYPE_LINE="line";static TYPE_BLOCK="block";static TYPE_DOUBLE="double";static TYPE_SINGLE="single";static TYPE_TEMPLATE="template";static TYPE_FUNCTION="function";static TYPE_OPERATOR="operator";keywordSet=null;keywordMap=new Map;constructor($){this.grammar=$,this.compiledPatterns=this.precompilePatterns($.patterns),this.numberRegex=/^(0x[0-9a-f]+|0b[01]+|0o[0-7]+|\d+(\.\d+)?(e[+-]?\d+)?)/i,this.isJsOrTs=$.scopeName==="source.js"||$.scopeName==="source.ts";let w=this.grammar.scopeName.split(".")[1]||"js";if(this.rootScopes=[this.grammar.scopeName],this.numericScopes=[this.grammar.scopeName,`constant.numeric.${w}`],this.operatorScopes=[this.grammar.scopeName,`keyword.operator.${w}`],this.commentScopes=[this.grammar.scopeName,`comment.line.double-slash.${w}`],this.blockCommentScopes=[this.grammar.scopeName,`comment.block.${w}`],this.stringScopes=[this.grammar.scopeName,`string.quoted.double.${w}`],this.templateScopes=[this.grammar.scopeName,`string.template.${w}`],this.functionScopes=[this.grammar.scopeName,`entity.name.function.${w}`],this.grammar.keywords){this.keywordSet=new Set(Object.keys(this.grammar.keywords));for(let[y,j]of Object.entries(this.grammar.keywords))if(typeof j==="string"){let z=[this.grammar.scopeName,j],g=j.lastIndexOf("."),A=g===-1?j:j.slice(g+1);this.keywordMap.set(y,{scopes:z,type:A})}}}tokenizeLine($,w,y){this.scopeStack=y?[...y]:[{scopes:[this.grammar.scopeName],rule:null}];let j=[],z=0;while(z<$.length){let g=this.matchNextToken($,z,w);if(g){if(g.token)j.push(g.token);z=g.offset}else{let A=this.scopeStack[this.scopeStack.length-1];j.push({type:t.TYPE_TEXT,content:$[z],scopes:A.scopes,line:w,offset:z}),z++}}return{tokens:j,line:w}}tokenize($){let w=$.split(`
453
- `),y=[],j;for(let z=0;z<w.length;z++){let g=this.tokenizeLine(w[z],z+1,j);y.push(g),j=this.scopeStack}return y}matchNextToken($,w,y){let j=this.scopeStack[this.scopeStack.length-1];if(j.endPattern){j.endPattern.lastIndex=w;let g=j.endPattern.exec($);if(g&&g.index===w){let A=g[0],J=j.scopes;return this.scopeStack.pop(),{token:{type:t.TYPE_PUNCTUATION,content:A,scopes:J,line:y,offset:w},offset:w+A.length}}}if(j.rule===null){let g=$.charCodeAt(w),A=I[g];if(A&32){let J=w+1;while(J<$.length&&I[$.charCodeAt(J)]&32)J++;return{token:null,offset:J}}if(A&8)return{token:{type:t.TYPE_PUNCTUATION,content:$[w],scopes:this.rootScopes,line:y,offset:w},offset:w+1};if(A&2){let J=w,X=!1,Y=!1;if($[w]==="0"&&w+1<$.length){let U=$.charCodeAt(w+1);if(U===120||U===88){J=w+2;while(J<$.length){let B=$.charCodeAt(J);if(!(B>=48&&B<=57||B>=65&&B<=70||B>=97&&B<=102))break;J++}}else if(U===98||U===66){J=w+2;while(J<$.length&&($[J]==="0"||$[J]==="1"))J++}else if(U===111||U===79){J=w+2;while(J<$.length){let B=$.charCodeAt(J);if(!(B>=48&&B<=55))break;J++}}}if(J===w)while(J<$.length){let U=$.charCodeAt(J);if(U>=48&&U<=57)J++;else if(U===46&&!X&&!Y)X=!0,J++;else if((U===101||U===69)&&!Y){if(Y=!0,J++,J<$.length&&($[J]==="+"||$[J]==="-"))J++}else break}if(J>w){let U=$.slice(w,J);return{token:{type:t.TYPE_NUMERIC,content:U,scopes:this.numericScopes,line:y,offset:w},offset:J}}}if(g===47){let J=$.charCodeAt(w+1);if(J===47){let X=$.slice(w);return{token:{type:t.TYPE_LINE,content:X,scopes:this.commentScopes,line:y,offset:w},offset:$.length}}else if(J===42){let X=$.indexOf("*/",w+2);if(X!==-1){let Y=$.slice(w,X+2);return{token:{type:t.TYPE_BLOCK,content:Y,scopes:this.blockCommentScopes,line:y,offset:w},offset:X+2}}}}if(A&16){let J=g,X=w+1,Y=!1;while(X<$.length){let U=$.charCodeAt(X);if(Y)Y=!1;else if(U===92)Y=!0;else if(U===J)break;X++}if(X<$.length){let U=$.slice(w,X+1),B=J===96?t.TYPE_TEMPLATE:J===34?t.TYPE_DOUBLE:t.TYPE_SINGLE,b=J===96?this.templateScopes:this.stringScopes;return{token:{type:B,content:U,scopes:b,line:y,offset:w},offset:X+1}}}if(A&1){let J=w+1;while(J<$.length){let U=$.charCodeAt(J);if(!(I[U]&3))break;J++}let X=$.charCodeAt(J);if(this.isJsOrTs&&X===40){let U=$.slice(w,J);return{token:{type:t.TYPE_FUNCTION,content:U,scopes:this.functionScopes,line:y,offset:w},offset:J}}let Y=$.slice(w,J);if(this.keywordSet&&this.keywordSet.has(Y)){let U=this.keywordMap.get(Y);return{token:{type:U.type,content:Y,scopes:U.scopes,line:y,offset:w},offset:J}}return{token:{type:t.TYPE_TEXT,content:Y,scopes:this.rootScopes,line:y,offset:w},offset:J}}if(this.isJsOrTs&&A&4){let J=1,X=g,Y=$.charCodeAt(w+1),U=$.charCodeAt(w+2);if(w+2<$.length){if(X===61&&Y===61&&U===61||X===33&&Y===61&&U===61||X===62&&Y===62&&U===62||X===46&&Y===46&&U===46)J=3}if(J===1&&w+1<$.length){if(X===43&&Y===43||X===45&&Y===45||X===61&&Y===61||X===33&&Y===61||X===60&&Y===61||X===62&&Y===61||X===38&&Y===38||X===124&&Y===124||X===61&&Y===62||X===60&&Y===60||X===62&&Y===62)J=2}let B=$.slice(w,w+J);return{token:{type:t.TYPE_OPERATOR,content:B,scopes:this.operatorScopes,line:y,offset:w},offset:w+J}}}let z=j.rule?.patterns||this.compiledPatterns;for(let g of z){let A=this.matchPattern(g,$,w,y);if(A)return A}return null}precompilePatterns($){return $.map((w)=>{let y={...w};if(w.match)y._compiledMatch=new RegExp(w.match,"g");if(w.begin)y._compiledBegin=new RegExp(w.begin,"g");if(w.end)y._compiledEnd=new RegExp(w.end,"g");if(w.patterns)y.patterns=this.precompilePatterns(w.patterns);return y})}getRegex($){let w=this.regexCache.get($);if(!w)w=new RegExp($,"g"),this.regexCache.set($,w);return w}matchPattern($,w,y,j){if($.include)return this.handleInclude($.include,w,y,j);let z=$;if($.begin){let g=z._compiledBegin||this.getRegex($.begin);g.lastIndex=y;let A=g.exec(w);if(A&&A.index===y){let J=A[0],X=this.scopeStack[this.scopeStack.length-1],Y=$.name?[...X.scopes,$.name]:X.scopes,U=z._compiledEnd||($.end?this.getRegex($.end):void 0);this.scopeStack.push({scopes:Y,rule:$,endPattern:U});let B=t.TYPE_TEXT;if($.name&&typeof $.name==="string"){let b=$.name.lastIndexOf(".");B=b===-1?$.name:$.name.slice(b+1)}return{token:{type:B,content:J,scopes:Y,line:j,offset:y},offset:y+J.length}}}if($.match){let g=z._compiledMatch||this.getRegex($.match);g.lastIndex=y;let A=g.exec(w);if(A&&A.index===y){let J=A[0],X=this.scopeStack[this.scopeStack.length-1],Y=$.name?[...X.scopes,$.name]:X.scopes,U=t.TYPE_TEXT;if($.name&&typeof $.name==="string"){let B=$.name.lastIndexOf(".");U=B===-1?$.name:$.name.slice(B+1)}return{token:{type:U,content:J,scopes:Y,line:j,offset:y},offset:y+J.length}}}return null}handleInclude($,w,y,j){if($==="$self"){for(let z of this.grammar.patterns){let g=this.matchPattern(z,w,y,j);if(g)return g}return null}if($.startsWith("#")){let z=$.slice(1),g=this.grammar.repository?.[z];if(g&&g.patterns)for(let A of g.patterns){let J=this.matchPattern(A,w,y,j);if(J)return J}}return null}getTokenType($){if(!$||typeof $!=="string")return"text";let w=$.split(".");return w[w.length-1]||"text"}getScopeStack(){return this.scopeStack}}class mw{config;languages=new Map;themes=new Map;cache=new Map;plugins=[];constructor($){this.config=$,this.initializeDefaults()}initializeDefaults(){for(let $ of Pw)if(this.languages.set($.id,$),$.aliases)for(let w of $.aliases)this.languages.set(w,$);for(let $ of uw)this.themes.set($.name.toLowerCase(),$);if(this.config.plugins)for(let $ of this.config.plugins)this.loadPlugin($)}async loadPlugin($){if(this.plugins.push($),$.languages)for(let w of $.languages)await this.loadLanguage(w);if($.themes)for(let w of $.themes)await this.loadTheme(w)}highlightSync($,w,y={}){let j=this.getLanguageById(w);if(!j)throw Error(`Language "${w}" not found. Available languages: ${this.getSupportedLanguages().join(", ")}`);let z=this.getCacheKey($,w,y);if(this.config.cache){let J=this.cache.get(z);if(J){let X=this.resolveTheme(y.theme);return new K$(X).render(J.tokens,y)}}let g=new t(j.grammar).tokenize($);for(let J of this.plugins)if(J.transformers)for(let X of J.transformers)g=X.transform(g);if(this.config.cache)this.cache.set(z,{tokens:g,timestamp:Date.now(),hash:z});let A=this.resolveTheme(y.theme);return new K$(A).render(g,y)}async highlight($,w,y={}){return this.highlightSync($,w,y)}highlightFast($,w){let y=this.getLanguageById(w);if(!y)throw Error(`Language "${w}" not found. Available languages: ${this.getSupportedLanguages().join(", ")}`);return new xw(y.grammar).tokenize($)}async loadLanguage($){if(this.languages.set($.id,$),$.aliases)for(let w of $.aliases)this.languages.set(w,$)}async loadTheme($){this.themes.set($.name.toLowerCase(),$)}getSupportedLanguages(){let $=new Set;for(let[w,y]of this.languages.entries())if(w===y.id)$.add(y.id);return Array.from($)}getSupportedThemes(){return Array.from(this.themes.keys())}getLanguageById($){return this.languages.get($)||D9($)}resolveTheme($){if(!$)return this.resolveTheme(this.config.theme);if(typeof $==="string"){let w=this.themes.get($.toLowerCase());if(!w){let y=$.replace(/-/g," ");w=this.themes.get(y.toLowerCase())}if(!w)w=h9($);if(!w)throw Error(`Theme "${$}" not found. Available themes: ${this.getSupportedThemes().join(", ")}`);return w}return $}getCacheKey($,w,y){let j=JSON.stringify(y);return`${w}:${this.hashCode($+j)}`}hashCode($){let w=0;for(let y=0;y<$.length;y++){let j=$.charCodeAt(y);w=(w<<5)-w+j,w=w&w}return w.toString(36)}clearCache(){this.cache.clear()}getCacheSize(){return this.cache.size}}async function iw($={}){let w={...{verbose:!1,theme:"github-dark",cache:!0,plugins:[]},...$};return new mw(w)}class nw{entries=[];timers=new Map;enabled;constructor($=!1){this.enabled=$}start($){if(!this.enabled)return;this.timers.set($,performance.now())}end($){if(!this.enabled)return;let w=this.timers.get($);if(!w)return;let y=performance.now()-w;this.timers.delete($),this.entries.push({name:$,duration:y,timestamp:Date.now()})}async measure($,w){this.start($);try{let y=await w();return this.end($),y}catch(y){throw this.end($),y}}getEntries(){return[...this.entries]}getStats(){let $=new Map;for(let y of this.entries){let j=$.get(y.name)||[];j.push(y.duration),$.set(y.name,j)}let w={};for(let[y,j]of $){let z=j.reduce((g,A)=>g+A,0);w[y]={count:j.length,total:z,avg:z/j.length,min:Math.min(...j),max:Math.max(...j)}}return w}clear(){this.entries=[],this.timers.clear()}enable(){this.enabled=!0}disable(){this.enabled=!1}report(){let $=this.getStats();console.log(`
451
+ `)}setTheme($){this.theme=$,this.colorCache.clear(),this.cssCache=null}}class iw{keywordSet=null;isJsOrTs;isHtml;isCss;constructor($){if(this.isJsOrTs=$.scopeName==="source.js"||$.scopeName==="source.ts",this.isHtml=$.scopeName==="text.html.basic",this.isCss=$.scopeName==="source.css",$.keywords)this.keywordSet=new Set(Object.keys($.keywords))}tokenize($){let w=$.split(`
452
+ `),y=[];for(let j=0;j<w.length;j++)y.push(this.tokenizeLine(w[j]));return y}tokenizeLine($){let w=[],y=0;while(y<$.length){let j=$.charCodeAt(y),z=S[j];if(z&32){y++;continue}if(z&2){let A=y;y=this.scanNumber($,y),w.push({type:"numeric",content:$.slice(A,y)});continue}if(this.isHtml&&j===60){let A=y;if(y++,$.charCodeAt(y)===47)y++;while(y<$.length&&S[$.charCodeAt(y)]&1)y++;while(y<$.length&&$.charCodeAt(y)!==62)y++;if($.charCodeAt(y)===62)y++;w.push({type:"tag",content:$.slice(A,y)});continue}if(this.isCss){if(j===46||j===35||z&1){let A=y;while(y<$.length){let X=$.charCodeAt(y);if(X===123||X===58||X===59)break;y++}let g=$.slice(A,y),J=g.includes(":")?"property":"selector";w.push({type:J,content:g});continue}}if(!this.isHtml&&j===47){let A=$.charCodeAt(y+1);if(A===47){w.push({type:"comment",content:$.slice(y)});break}else if(A===42){let g=$.indexOf("*/",y+2);if(g!==-1){w.push({type:"comment",content:$.slice(y,g+2)}),y=g+2;continue}}}if(this.isHtml&&j===60&&$.charCodeAt(y+1)===33){let A=$.indexOf("-->",y+4);if(A!==-1){w.push({type:"comment",content:$.slice(y,A+3)}),y=A+3;continue}}if(z&16){let A=y;if(y=this.scanString($,y,j),y>A){w.push({type:"string",content:$.slice(A,y)});continue}}if(z&1){let A=y;y=this.scanWord($,y);let g=$.slice(A,y);if(this.isJsOrTs&&$.charCodeAt(y)===40){w.push({type:"function",content:g});continue}let J=this.keywordSet&&this.keywordSet.has(g)?"keyword":"text";w.push({type:J,content:g});continue}if(this.isJsOrTs&&z&4){let A=y;y=this.scanOperator($,y,j),w.push({type:"operator",content:$.slice(A,y)});continue}if(z&8){w.push({type:"punctuation",content:$[y]}),y++;continue}w.push({type:"text",content:$[y]}),y++}return{tokens:w}}scanNumber($,w){let y=w,j=!1,z=!1;if($[w]==="0"&&w+1<$.length){let A=$.charCodeAt(w+1);if(A===120||A===88){y=w+2;while(y<$.length){let g=$.charCodeAt(y);if(!(g>=48&&g<=57||g>=65&&g<=70||g>=97&&g<=102))break;y++}return y}else if(A===98||A===66){y=w+2;while(y<$.length&&($[y]==="0"||$[y]==="1"))y++;return y}else if(A===111||A===79){y=w+2;while(y<$.length){let g=$.charCodeAt(y);if(!(g>=48&&g<=55))break;y++}return y}}while(y<$.length){let A=$.charCodeAt(y);if(A>=48&&A<=57)y++;else if(A===46&&!j&&!z)j=!0,y++;else if((A===101||A===69)&&!z){if(z=!0,y++,y<$.length&&($[y]==="+"||$[y]==="-"))y++}else break}return y}scanString($,w,y){let j=w+1,z=!1;while(j<$.length){let A=$.charCodeAt(j);if(z)z=!1;else if(A===92)z=!0;else if(A===y)return j+1;j++}return j}scanWord($,w){let y=w+1;while(y<$.length){let j=$.charCodeAt(y);if(!(S[j]&3))break;y++}return y}scanOperator($,w,y){if(w+1>=$.length)return w+1;let j=$.charCodeAt(w+1);if(w+2<$.length){let z=$.charCodeAt(w+2);if(y===61&&j===61&&z===61||y===33&&j===61&&z===61||y===62&&j===62&&z===62||y===46&&j===46&&z===46)return w+3}if(y===43&&j===43||y===45&&j===45||y===61&&j===61||y===33&&j===61||y===60&&j===61||y===62&&j===61||y===38&&j===38||y===124&&j===124||y===61&&j===62||y===60&&j===60||y===62&&j===62)return w+2;return w+1}}function iy($){let w=$.toLowerCase();return nw.find((y)=>{let j=y.name.toLowerCase(),z=j.replace(/\s+/g,"-");return j===w||z===w})}class t{grammar;scopeStack=[];regexCache=new Map;compiledPatterns;numberRegex;isJsOrTs;rootScopes;numericScopes;operatorScopes;commentScopes;blockCommentScopes;stringScopes;templateScopes;functionScopes;static TYPE_TEXT="text";static TYPE_PUNCTUATION="punctuation";static TYPE_NUMERIC="numeric";static TYPE_LINE="line";static TYPE_BLOCK="block";static TYPE_DOUBLE="double";static TYPE_SINGLE="single";static TYPE_TEMPLATE="template";static TYPE_FUNCTION="function";static TYPE_OPERATOR="operator";keywordSet=null;keywordMap=new Map;constructor($){this.grammar=$,this.compiledPatterns=this.precompilePatterns($.patterns),this.numberRegex=/^(0x[0-9a-f]+|0b[01]+|0o[0-7]+|\d+(\.\d+)?(e[+-]?\d+)?)/i,this.isJsOrTs=$.scopeName==="source.js"||$.scopeName==="source.ts";let w=this.grammar.scopeName.split(".")[1]||"js";if(this.rootScopes=[this.grammar.scopeName],this.numericScopes=[this.grammar.scopeName,`constant.numeric.${w}`],this.operatorScopes=[this.grammar.scopeName,`keyword.operator.${w}`],this.commentScopes=[this.grammar.scopeName,`comment.line.double-slash.${w}`],this.blockCommentScopes=[this.grammar.scopeName,`comment.block.${w}`],this.stringScopes=[this.grammar.scopeName,`string.quoted.double.${w}`],this.templateScopes=[this.grammar.scopeName,`string.template.${w}`],this.functionScopes=[this.grammar.scopeName,`entity.name.function.${w}`],this.grammar.keywords){this.keywordSet=new Set(Object.keys(this.grammar.keywords));for(let[y,j]of Object.entries(this.grammar.keywords))if(typeof j==="string"){let z=[this.grammar.scopeName,j],A=j.lastIndexOf("."),g=A===-1?j:j.slice(A+1);this.keywordMap.set(y,{scopes:z,type:g})}}}tokenizeLine($,w,y){this.scopeStack=y?[...y]:[{scopes:[this.grammar.scopeName],rule:null}];let j=[],z=0;while(z<$.length){let A=this.matchNextToken($,z,w);if(A){if(A.token)j.push(A.token);z=A.offset}else{let g=this.scopeStack[this.scopeStack.length-1];j.push({type:t.TYPE_TEXT,content:$[z],scopes:g.scopes,line:w,offset:z}),z++}}return{tokens:j,line:w}}tokenize($){let w=$.split(`
453
+ `),y=[],j;for(let z=0;z<w.length;z++){let A=this.tokenizeLine(w[z],z+1,j);y.push(A),j=this.scopeStack}return y}matchNextToken($,w,y){let j=this.scopeStack[this.scopeStack.length-1];if(j.endPattern){j.endPattern.lastIndex=w;let A=j.endPattern.exec($);if(A&&A.index===w){let g=A[0],J=j.scopes;return this.scopeStack.pop(),{token:{type:t.TYPE_PUNCTUATION,content:g,scopes:J,line:y,offset:w},offset:w+g.length}}}if(j.rule===null){let A=$.charCodeAt(w),g=G[A];if(g&32){let J=w+1;while(J<$.length&&G[$.charCodeAt(J)]&32)J++;return{token:null,offset:J}}if(g&8)return{token:{type:t.TYPE_PUNCTUATION,content:$[w],scopes:this.rootScopes,line:y,offset:w},offset:w+1};if(g&2){let J=w,X=!1,Y=!1;if($[w]==="0"&&w+1<$.length){let U=$.charCodeAt(w+1);if(U===120||U===88){J=w+2;while(J<$.length){let B=$.charCodeAt(J);if(!(B>=48&&B<=57||B>=65&&B<=70||B>=97&&B<=102))break;J++}}else if(U===98||U===66){J=w+2;while(J<$.length&&($[J]==="0"||$[J]==="1"))J++}else if(U===111||U===79){J=w+2;while(J<$.length){let B=$.charCodeAt(J);if(!(B>=48&&B<=55))break;J++}}}if(J===w)while(J<$.length){let U=$.charCodeAt(J);if(U>=48&&U<=57)J++;else if(U===46&&!X&&!Y)X=!0,J++;else if((U===101||U===69)&&!Y){if(Y=!0,J++,J<$.length&&($[J]==="+"||$[J]==="-"))J++}else break}if(J>w){let U=$.slice(w,J);return{token:{type:t.TYPE_NUMERIC,content:U,scopes:this.numericScopes,line:y,offset:w},offset:J}}}if(A===47){let J=$.charCodeAt(w+1);if(J===47){let X=$.slice(w);return{token:{type:t.TYPE_LINE,content:X,scopes:this.commentScopes,line:y,offset:w},offset:$.length}}else if(J===42){let X=$.indexOf("*/",w+2);if(X!==-1){let Y=$.slice(w,X+2);return{token:{type:t.TYPE_BLOCK,content:Y,scopes:this.blockCommentScopes,line:y,offset:w},offset:X+2}}}}if(g&16){let J=A,X=w+1,Y=!1;while(X<$.length){let U=$.charCodeAt(X);if(Y)Y=!1;else if(U===92)Y=!0;else if(U===J)break;X++}if(X<$.length){let U=$.slice(w,X+1),B=J===96?t.TYPE_TEMPLATE:J===34?t.TYPE_DOUBLE:t.TYPE_SINGLE,b=J===96?this.templateScopes:this.stringScopes;return{token:{type:B,content:U,scopes:b,line:y,offset:w},offset:X+1}}}if(g&1){let J=w+1;while(J<$.length){let U=$.charCodeAt(J);if(!(G[U]&3))break;J++}let X=$.charCodeAt(J);if(this.isJsOrTs&&X===40){let U=$.slice(w,J);return{token:{type:t.TYPE_FUNCTION,content:U,scopes:this.functionScopes,line:y,offset:w},offset:J}}let Y=$.slice(w,J);if(this.keywordSet&&this.keywordSet.has(Y)){let U=this.keywordMap.get(Y);return{token:{type:U.type,content:Y,scopes:U.scopes,line:y,offset:w},offset:J}}return{token:{type:t.TYPE_TEXT,content:Y,scopes:this.rootScopes,line:y,offset:w},offset:J}}if(this.isJsOrTs&&g&4){let J=1,X=A,Y=$.charCodeAt(w+1),U=$.charCodeAt(w+2);if(w+2<$.length){if(X===61&&Y===61&&U===61||X===33&&Y===61&&U===61||X===62&&Y===62&&U===62||X===46&&Y===46&&U===46)J=3}if(J===1&&w+1<$.length){if(X===43&&Y===43||X===45&&Y===45||X===61&&Y===61||X===33&&Y===61||X===60&&Y===61||X===62&&Y===61||X===38&&Y===38||X===124&&Y===124||X===61&&Y===62||X===60&&Y===60||X===62&&Y===62)J=2}let B=$.slice(w,w+J);return{token:{type:t.TYPE_OPERATOR,content:B,scopes:this.operatorScopes,line:y,offset:w},offset:w+J}}}let z=j.rule?.patterns||this.compiledPatterns;for(let A of z){let g=this.matchPattern(A,$,w,y);if(g)return g}return null}precompilePatterns($){return $.map((w)=>{let y={...w};if(w.match)y._compiledMatch=new RegExp(w.match,"g");if(w.begin)y._compiledBegin=new RegExp(w.begin,"g");if(w.end)y._compiledEnd=new RegExp(w.end,"g");if(w.patterns)y.patterns=this.precompilePatterns(w.patterns);return y})}getRegex($){let w=this.regexCache.get($);if(!w)w=new RegExp($,"g"),this.regexCache.set($,w);return w}matchPattern($,w,y,j){if($.include)return this.handleInclude($.include,w,y,j);let z=$;if($.begin){let A=z._compiledBegin||this.getRegex($.begin);A.lastIndex=y;let g=A.exec(w);if(g&&g.index===y){let J=g[0],X=this.scopeStack[this.scopeStack.length-1],Y=$.name?[...X.scopes,$.name]:X.scopes,U=z._compiledEnd||($.end?this.getRegex($.end):void 0);this.scopeStack.push({scopes:Y,rule:$,endPattern:U});let B=t.TYPE_TEXT;if($.name&&typeof $.name==="string"){let b=$.name.lastIndexOf(".");B=b===-1?$.name:$.name.slice(b+1)}return{token:{type:B,content:J,scopes:Y,line:j,offset:y},offset:y+J.length}}}if($.match){let A=z._compiledMatch||this.getRegex($.match);A.lastIndex=y;let g=A.exec(w);if(g&&g.index===y){let J=g[0],X=this.scopeStack[this.scopeStack.length-1],Y=$.name?[...X.scopes,$.name]:X.scopes,U=t.TYPE_TEXT;if($.name&&typeof $.name==="string"){let B=$.name.lastIndexOf(".");U=B===-1?$.name:$.name.slice(B+1)}return{token:{type:U,content:J,scopes:Y,line:j,offset:y},offset:y+J.length}}}return null}handleInclude($,w,y,j){if($==="$self"){for(let z of this.grammar.patterns){let A=this.matchPattern(z,w,y,j);if(A)return A}return null}if($.startsWith("#")){let z=$.slice(1),A=this.grammar.repository?.[z];if(A&&A.patterns)for(let g of A.patterns){let J=this.matchPattern(g,w,y,j);if(J)return J}}return null}getTokenType($){if(!$||typeof $!=="string")return"text";let w=$.split(".");return w[w.length-1]||"text"}getScopeStack(){return this.scopeStack}}class pw{config;languages=new Map;themes=new Map;cache=new Map;plugins=[];constructor($){this.config=$,this.initializeDefaults()}initializeDefaults(){for(let $ of mw)if(this.languages.set($.id,$),$.aliases)for(let w of $.aliases)this.languages.set(w,$);for(let $ of nw)this.themes.set($.name.toLowerCase(),$);if(this.config.plugins)for(let $ of this.config.plugins)this.loadPlugin($)}async loadPlugin($){if(this.plugins.push($),$.languages)for(let w of $.languages)await this.loadLanguage(w);if($.themes)for(let w of $.themes)await this.loadTheme(w)}highlightSync($,w,y={}){let j=this.getLanguageById(w);if(!j)throw Error(`Language "${w}" not found. Available languages: ${this.getSupportedLanguages().join(", ")}`);let z=this.getCacheKey($,w,y);if(this.config.cache){let J=this.cache.get(z);if(J){let X=this.resolveTheme(y.theme);return new q$(X).render(J.tokens,y)}}let A=new t(j.grammar).tokenize($);for(let J of this.plugins)if(J.transformers)for(let X of J.transformers)A=X.transform(A);if(this.config.cache)this.cache.set(z,{tokens:A,timestamp:Date.now(),hash:z});let g=this.resolveTheme(y.theme);return new q$(g).render(A,y)}async highlight($,w,y={}){return this.highlightSync($,w,y)}highlightFast($,w){let y=this.getLanguageById(w);if(!y)throw Error(`Language "${w}" not found. Available languages: ${this.getSupportedLanguages().join(", ")}`);return new iw(y.grammar).tokenize($)}async loadLanguage($){if(this.languages.set($.id,$),$.aliases)for(let w of $.aliases)this.languages.set(w,$)}async loadTheme($){this.themes.set($.name.toLowerCase(),$)}getSupportedLanguages(){let $=new Set;for(let[w,y]of this.languages.entries())if(w===y.id)$.add(y.id);return Array.from($)}getSupportedThemes(){return Array.from(this.themes.keys())}getLanguageById($){return this.languages.get($)||Py($)}resolveTheme($){if(!$)return this.resolveTheme(this.config.theme);if(typeof $==="string"){let w=this.themes.get($.toLowerCase());if(!w){let y=$.replace(/-/g," ");w=this.themes.get(y.toLowerCase())}if(!w)w=iy($);if(!w)throw Error(`Theme "${$}" not found. Available themes: ${this.getSupportedThemes().join(", ")}`);return w}return $}getCacheKey($,w,y){let j=JSON.stringify(y);return`${w}:${this.hashCode($+j)}`}hashCode($){let w=0;for(let y=0;y<$.length;y++){let j=$.charCodeAt(y);w=(w<<5)-w+j,w=w&w}return w.toString(36)}clearCache(){this.cache.clear()}getCacheSize(){return this.cache.size}}async function cw($={}){let w={...{verbose:!1,theme:"github-dark",cache:!0,plugins:[]},...$};return new pw(w)}class rw{entries=[];timers=new Map;enabled;constructor($=!1){this.enabled=$}start($){if(!this.enabled)return;this.timers.set($,performance.now())}end($){if(!this.enabled)return;let w=this.timers.get($);if(!w)return;let y=performance.now()-w;this.timers.delete($),this.entries.push({name:$,duration:y,timestamp:Date.now()})}async measure($,w){this.start($);try{let y=await w();return this.end($),y}catch(y){throw this.end($),y}}getEntries(){return[...this.entries]}getStats(){let $=new Map;for(let y of this.entries){let j=$.get(y.name)||[];j.push(y.duration),$.set(y.name,j)}let w={};for(let[y,j]of $){let z=j.reduce((A,g)=>A+g,0);w[y]={count:j.length,total:z,avg:z/j.length,min:Math.min(...j),max:Math.max(...j)}}return w}clear(){this.entries=[],this.timers.clear()}enable(){this.enabled=!0}disable(){this.enabled=!1}report(){let $=this.getStats();console.log(`
454
454
  === Performance Report ===
455
- `);for(let[w,y]of Object.entries($))console.log(`${w}:`),console.log(` Count: ${y.count}`),console.log(` Total: ${y.total.toFixed(2)}ms`),console.log(` Avg: ${y.avg.toFixed(2)}ms`),console.log(` Min: ${y.min.toFixed(2)}ms`),console.log(` Max: ${y.max.toFixed(2)}ms`),console.log()}}var B5,b5,N9,b$,Mw,$0,v,Q5,f9,K5,O9,q5,_5,Dw,N5,R9,H9,Cw,W5,L5,f5,O5,Q$,k9,R5,e,H5,k5,S9,F5,I9,G9,T9,Z9,E9,M9,Pw,S,C9,v9,d9,uw,I,V5;var pw=M(async()=>{B5=k1(q$.cwd(),"config"),b5=k1(q$.cwd(),"src/generated");N9=H1.env.CLARITY_LOG_DIR||z9(_9(),"logs"),b$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:N9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1};Mw=await W9();$0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},v=$0,Q5=$0.red,f9=$0.green,K5=$0.yellow,O9=$0.blue,q5=$0.magenta,_5=$0.cyan,Dw=$0.white,N5=$0.gray,R9=$0.bgRed,H9=$0.bgYellow,Cw=$0.bold,W5=$0.dim,L5=$0.italic,f5=$0.underline,O5=$0.reset,Q$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},k9={debug:"\uD83D\uDD0D",info:O9("\u2139"),success:f9("\u2713"),warning:H9(Dw(Cw(" WARN "))),error:R9(Dw(Cw(" ERROR ")))};R5=new S1("stacks");e=new S1("bunfig",{showTags:!0});H5=j0(t0.cwd(),"config"),k5=j0(t0.cwd(),"src/generated"),S9={verbose:!1,theme:"github-dark",defaultLanguage:"javascript",cache:!0,plugins:[]},F5=await V9({name:"syntax",defaultConfig:S9}),I9={name:"CSS",scopeName:"source.css",patterns:[{include:"#comments"},{include:"#at-rules"},{include:"#selectors"},{include:"#properties"},{include:"#functions"},{include:"#variables"},{include:"#values"},{include:"#strings"},{include:"#numbers"},{include:"#colors"},{include:"#punctuation"}],repository:{comments:{patterns:[{name:"comment.block.css",begin:"\\/\\*",end:"\\*\\/"}]},"at-rules":{patterns:[{name:"keyword.control.at-rule.css",match:"@(media|import|charset|namespace|keyframes|font-face|supports|page|document|viewport|counter-style|font-feature-values|property|layer|container)\\b"}]},selectors:{patterns:[{name:"entity.name.tag.css",match:"\\b(a|abbr|address|article|aside|audio|b|blockquote|body|button|canvas|caption|cite|code|div|em|embed|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|html|i|iframe|img|input|label|legend|li|main|nav|ol|p|pre|section|select|span|strong|table|tbody|td|textarea|tfoot|th|thead|tr|ul|video)\\b"},{name:"entity.other.attribute-name.class.css",match:"\\.[a-zA-Z_-][a-zA-Z0-9_-]*"},{name:"entity.other.attribute-name.id.css",match:"#[a-zA-Z_-][a-zA-Z0-9_-]*"},{name:"entity.other.attribute-name.pseudo-class.css",match:":[a-zA-Z_-][a-zA-Z0-9_-]*"},{name:"entity.other.attribute-name.pseudo-element.css",match:"::[a-zA-Z_-][a-zA-Z0-9_-]*"}]},properties:{patterns:[{name:"support.type.property-name.css",match:"\\b(align-items|background|border|color|display|flex|font|height|justify-content|margin|padding|position|width|z-index|animation|box-shadow|cursor|font-family|font-size|font-weight|grid|line-height|opacity|overflow|text-align|text-decoration|transform|transition|visibility)(-[a-z]+)?\\b"}]},values:{patterns:[{name:"support.constant.property-value.css",match:"\\b(auto|block|inline|flex|grid|none|center|left|right|top|bottom|absolute|relative|fixed|sticky|hidden|visible|bold|normal|italic|underline|solid|dotted|dashed)\\b"}]},strings:{patterns:[{name:"string.quoted.double.css",begin:'"',end:'"'},{name:"string.quoted.single.css",begin:"'",end:"'"}]},numbers:{patterns:[{name:"constant.numeric.css",match:"\\b\\d+(\\.\\d+)?(px|em|rem|%|vh|vw|vmin|vmax|ch|ex|cm|mm|in|pt|pc|deg|rad|turn|s|ms)?\\b"}]},colors:{patterns:[{name:"constant.other.color.css",match:"#[0-9a-fA-F]{3,8}\\b"},{name:"support.function.color.css",match:"\\b(rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color)\\s*\\("}]},functions:{patterns:[{name:"support.function.css",match:"\\b(var|calc|min|max|clamp|round|abs|sign|mod|rem|sin|cos|tan|asin|acos|atan|atan2|pow|sqrt|hypot|log|exp|url|attr|counter|counters|linear-gradient|radial-gradient|conic-gradient|repeating-linear-gradient|repeating-radial-gradient|repeating-conic-gradient)\\s*\\("}]},variables:{patterns:[{name:"variable.other.custom-property.css",match:"--[a-zA-Z0-9_-]+"}]},punctuation:{patterns:[{name:"punctuation.css",match:"[{}();:,]"}]}}},G9={name:"HTML",scopeName:"text.html.basic",patterns:[{include:"#doctype"},{include:"#comments"},{include:"#tags"},{include:"#entities"}],repository:{doctype:{patterns:[{name:"meta.tag.sgml.doctype.html",match:"<!DOCTYPE[^>]*>"}]},comments:{patterns:[{name:"comment.block.html",begin:"<!--",end:"-->"}]},tags:{patterns:[{name:"meta.tag.html",begin:"(<)(script|style|template)\\b",beginCaptures:{1:{name:"punctuation.definition.tag.begin.html"},2:{name:"entity.name.tag.html"}},end:"(</)(\\2)(>)",endCaptures:{1:{name:"punctuation.definition.tag.begin.html"},2:{name:"entity.name.tag.html"},3:{name:"punctuation.definition.tag.end.html"}},patterns:[{include:"#tag-stuff"}]},{name:"meta.tag.html",begin:"(<)([a-zA-Z0-9:-]+)",beginCaptures:{1:{name:"punctuation.definition.tag.begin.html"},2:{name:"entity.name.tag.html"}},end:"(/>)|(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.html"},2:{name:"punctuation.definition.tag.end.html"}},patterns:[{include:"#tag-stuff"}]},{name:"meta.tag.html",begin:"(</)([a-zA-Z0-9:-]+)",beginCaptures:{1:{name:"punctuation.definition.tag.begin.html"},2:{name:"entity.name.tag.html"}},end:"(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.html"}}}]},"tag-stuff":{patterns:[{name:"entity.other.attribute-name.html",match:"\\b(data-[a-zA-Z0-9-]+|aria-[a-zA-Z0-9-]+|on[a-z]+|[a-zA-Z-:]+)"},{name:"string.quoted.double.html",begin:'"',end:'"'},{name:"string.quoted.single.html",begin:"'",end:"'"}]},entities:{patterns:[{name:"constant.character.entity.html",match:"&[a-zA-Z0-9]+;"},{name:"constant.character.entity.html",match:"&#[0-9]+;"}]}}},T9={name:"JavaScript",scopeName:"source.js",keywords:{if:"keyword.control.js",else:"keyword.control.js",switch:"keyword.control.js",case:"keyword.control.js",default:"keyword.control.js",for:"keyword.control.js",while:"keyword.control.js",do:"keyword.control.js",break:"keyword.control.js",continue:"keyword.control.js",return:"keyword.control.js",try:"keyword.control.js",catch:"keyword.control.js",finally:"keyword.control.js",throw:"keyword.control.js",async:"keyword.control.js",await:"keyword.control.js",yield:"keyword.control.js",const:"storage.type.js",let:"storage.type.js",var:"storage.type.js",function:"storage.type.js",class:"storage.type.js",extends:"storage.type.js",static:"storage.type.js",get:"storage.type.js",set:"storage.type.js",new:"keyword.operator.new.js",delete:"keyword.operator.new.js",typeof:"keyword.operator.new.js",instanceof:"keyword.operator.new.js",void:"keyword.operator.new.js",in:"keyword.operator.new.js",of:"keyword.operator.new.js",true:"constant.language.js",false:"constant.language.js",null:"constant.language.js",undefined:"constant.language.js",NaN:"constant.language.js",Infinity:"constant.language.js",this:"constant.language.js",super:"constant.language.js",arguments:"constant.language.js",import:"keyword.other.js",export:"keyword.other.js",from:"keyword.other.js",as:"keyword.other.js",with:"keyword.other.js",debugger:"keyword.other.js"},patterns:[{include:"#comments"},{include:"#strings"},{include:"#jsx"},{include:"#regex"},{include:"#keywords"},{include:"#numbers"},{include:"#functions"},{include:"#operators"},{include:"#punctuation"}],repository:{comments:{patterns:[{name:"comment.line.double-slash.js",match:"\\/\\/.*$"},{name:"comment.block.js",begin:"\\/\\*",end:"\\*\\/"}]},strings:{patterns:[{name:"string.quoted.double.js",begin:'"',end:'"',patterns:[{name:"constant.character.escape.js",match:"\\\\."}]},{name:"string.quoted.single.js",begin:"'",end:"'",patterns:[{name:"constant.character.escape.js",match:"\\\\."}]},{name:"string.template.js",begin:"`",end:"`",patterns:[{name:"meta.template.expression.js",begin:"\\$\\{",end:"\\}",patterns:[{include:"$self"}]},{name:"constant.character.escape.js",match:"\\\\."}]}]},jsx:{patterns:[{name:"meta.tag.jsx",begin:"<([A-Z][a-zA-Z0-9]*|[a-z][a-zA-Z0-9-]*)",beginCaptures:{0:{name:"punctuation.definition.tag.begin.jsx"},1:{name:"entity.name.tag.jsx"}},end:"(/?>)",endCaptures:{1:{name:"punctuation.definition.tag.end.jsx"}},patterns:[{name:"entity.other.attribute-name.jsx",match:"[a-zA-Z_:][a-zA-Z0-9_:.-]*"},{name:"meta.embedded.expression.jsx",begin:"\\{",end:"\\}",patterns:[{include:"$self"}]},{name:"string.quoted.double.jsx",begin:'"',end:'"'},{name:"string.quoted.single.jsx",begin:"'",end:"'"}]},{name:"meta.tag.jsx",begin:"(</)([A-Z][a-zA-Z0-9]*|[a-z][a-zA-Z0-9-]*)",beginCaptures:{1:{name:"punctuation.definition.tag.begin.jsx"},2:{name:"entity.name.tag.jsx"}},end:"(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.jsx"}}}]},regex:{patterns:[{name:"string.regexp.js",begin:"(?<=[=(,\\[!&|?{};:])\\s*(\\/)",beginCaptures:{1:{name:"punctuation.definition.string.begin.js"}},end:"(\\/)[gimsuvy]*",endCaptures:{1:{name:"punctuation.definition.string.end.js"}},patterns:[{name:"constant.character.escape.js",match:"\\\\."}]}]},numbers:{patterns:[{name:"constant.numeric.js",match:"\\b(0[xX][0-9a-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|\\d+(_\\d+)*(\\.\\d+(_\\d+)?)?([eE][+-]?\\d+)?)[nN]?\\b"}]},keywords:{patterns:[{name:"keyword.control.js",match:"\\b(if|else|switch|case|default|for|while|do|break|continue|return|try|catch|finally|throw|async|await|yield)\\b"},{name:"storage.type.js",match:"\\b(const|let|var|function|class|extends|static|async|get|set)\\b"},{name:"keyword.operator.new.js",match:"\\b(new|delete|typeof|instanceof|void|in|of)\\b"},{name:"constant.language.js",match:"\\b(true|false|null|undefined|NaN|Infinity|this|super|arguments)\\b"},{name:"keyword.other.js",match:"\\b(import|export|from|as|default|with|debugger)\\b"}]},functions:{patterns:[{name:"entity.name.function.js",match:"\\b([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*(?=\\()"}]},operators:{patterns:[{name:"keyword.operator.js",match:"(\\+\\+|--|\\+|\\-|\\*|\\/|%|===|==|!==|!=|<=|>=|<|>|&&|\\|\\||!|\\?|:|=>|\\.\\.\\.|&|\\||\\^|~|<<|>>|>>>)"}]},punctuation:{patterns:[{name:"punctuation.js",match:"[{}()\\[\\];,.]"}]}}},Z9={name:"JSON",scopeName:"source.json",patterns:[{include:"#value"}],repository:{value:{patterns:[{include:"#constant"},{include:"#number"},{include:"#string"},{include:"#array"},{include:"#object"}]},constant:{patterns:[{name:"constant.language.json",match:"\\b(true|false|null)\\b"}]},number:{patterns:[{name:"constant.numeric.json",match:"-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?"}]},string:{patterns:[{name:"string.quoted.double.json",begin:'"',end:'"',patterns:[{name:"constant.character.escape.json",match:'\\\\(["\\\\/bfnrt]|u[0-9a-fA-F]{4})'},{name:"invalid.illegal.unrecognized-string-escape.json",match:"\\\\."}]}]},array:{patterns:[{name:"meta.structure.array.json",begin:"\\[",beginCaptures:{0:{name:"punctuation.definition.array.begin.json"}},end:"\\]",endCaptures:{0:{name:"punctuation.definition.array.end.json"}},patterns:[{include:"#value"},{name:"punctuation.separator.array.json",match:","}]}]},object:{patterns:[{name:"meta.structure.dictionary.json",begin:"\\{",beginCaptures:{0:{name:"punctuation.definition.dictionary.begin.json"}},end:"\\}",endCaptures:{0:{name:"punctuation.definition.dictionary.end.json"}},patterns:[{name:"meta.structure.dictionary.key.json",begin:'"',beginCaptures:{0:{name:"punctuation.support.type.property-name.begin.json"}},end:'"',endCaptures:{0:{name:"punctuation.support.type.property-name.end.json"}},patterns:[{name:"constant.character.escape.json",match:'\\\\(["\\\\/bfnrt]|u[0-9a-fA-F]{4})'}]},{name:"punctuation.separator.dictionary.key-value.json",match:":"},{name:"punctuation.separator.dictionary.pair.json",match:","},{include:"#value"}]}]}}},E9={name:"STX",scopeName:"text.html.stx",patterns:[{include:"#stx-comments"},{include:"#stx-echo"},{include:"#stx-directives"},{include:"#html"}],repository:{"stx-comments":{patterns:[{name:"comment.block.stx",begin:"\\{\\{--",end:"--\\}\\}"}]},"stx-echo":{patterns:[{name:"meta.embedded.block.stx.unescaped",begin:"(?<!@)\\{\\{\\{",beginCaptures:{0:{name:"punctuation.section.embedded.begin.stx"}},end:"\\}\\}\\}",endCaptures:{0:{name:"punctuation.section.embedded.end.stx"}},contentName:"source.ts.embedded.stx"},{name:"meta.embedded.block.stx.escaped",begin:"(?<![@{])\\{\\{",beginCaptures:{0:{name:"punctuation.section.embedded.begin.stx"}},end:"\\}\\}",endCaptures:{0:{name:"punctuation.section.embedded.end.stx"}},contentName:"source.ts.embedded.stx"},{name:"meta.embedded.block.stx.raw",begin:"(?<!@)\\{!!",beginCaptures:{0:{name:"punctuation.section.embedded.begin.stx"}},end:"!!\\}",endCaptures:{0:{name:"punctuation.section.embedded.end.stx"}},contentName:"source.ts.embedded.stx"}]},"stx-directives":{patterns:[{name:"keyword.control.conditional.stx",match:"@(if|else|elseif|endif|unless|endunless|switch|case|default|endswitch|break)\\b"},{name:"keyword.control.loop.stx",match:"@(for|endfor|foreach|endforeach|while|endwhile|continue|forelse|empty)\\b"},{name:"keyword.control.auth.stx",match:"@(auth|guest|can|cannot|endauth|endguest|endcan|endcannot)\\b"},{name:"keyword.control.component.stx",match:"@(component|endcomponent|slot|endslot|props|inject)\\b"},{name:"keyword.control.layout.stx",match:"@(section|endsection|yield|extends|parent)\\b"},{name:"support.function.include.stx",match:"@(include|includewhen|includeunless|includefirst)\\b"},{name:"keyword.control.stack.stx",match:"@(push|endpush|pushOnce|endpushOnce|pushif|endpushif|stack)\\b"},{name:"keyword.control.once.stx",match:"@(once|endonce)\\b"},{name:"support.function.security.stx",match:"@(csrf|method)\\b"},{name:"keyword.control.environment.stx",match:"@(production|endproduction|development|enddevelopment|env|endenv)\\b"},{name:"support.function.translation.stx",match:"@(translate|endtranslate|t)\\b"},{name:"support.function.webcomponent.stx",match:"@webcomponent\\b"},{name:"support.function.route.stx",match:"@route\\b"},{name:"keyword.control.markdown.stx",begin:"@markdown\\b",beginCaptures:{0:{name:"keyword.control.markdown.stx"}},end:"@endmarkdown\\b",endCaptures:{0:{name:"keyword.control.markdown.stx"}},contentName:"text.html.markdown.embedded.stx"},{name:"support.function.markdown.stx",match:"@markdown-file\\b"},{name:"keyword.control.animation.stx",match:"@(transition|endtransition|motion|endmotion)\\b"},{name:"meta.embedded.block.ts",begin:"@ts\\b",beginCaptures:{0:{name:"keyword.control.stx"}},end:"@endts\\b",endCaptures:{0:{name:"keyword.control.stx"}},contentName:"source.ts"},{name:"meta.embedded.block.js",begin:"@js\\b",beginCaptures:{0:{name:"keyword.control.stx"}},end:"@endjs\\b",endCaptures:{0:{name:"keyword.control.stx"}},contentName:"source.js"},{name:"meta.embedded.block.raw",begin:"@(raw|verbatim)\\b",beginCaptures:{0:{name:"keyword.control.stx"}},end:"@end(raw|verbatim)\\b",endCaptures:{0:{name:"keyword.control.stx"}},contentName:"string.unquoted.raw"},{name:"entity.name.function.stx",match:"@[a-zA-Z_][a-zA-Z0-9_]*"}]},html:{patterns:[{name:"meta.tag.html",begin:"<([a-zA-Z0-9:-]+)",beginCaptures:{0:{name:"punctuation.definition.tag.begin.html"},1:{name:"entity.name.tag.html"}},end:"(/>)|(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.html"},2:{name:"punctuation.definition.tag.end.html"}},patterns:[{name:"entity.other.attribute-name.html",match:"[a-zA-Z-:@]+"},{name:"string.quoted.double.html",begin:'"',end:'"',patterns:[{include:"#stx-echo"}]},{name:"string.quoted.single.html",begin:"'",end:"'",patterns:[{include:"#stx-echo"}]}]},{name:"meta.tag.html",begin:"(</)([a-zA-Z0-9:-]+)",beginCaptures:{1:{name:"punctuation.definition.tag.begin.html"},2:{name:"entity.name.tag.html"}},end:"(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.html"}}},{name:"comment.block.html",begin:"<!--",end:"-->"}]}}},M9={name:"TypeScript",scopeName:"source.ts",keywords:{if:"keyword.control.ts",else:"keyword.control.ts",switch:"keyword.control.ts",case:"keyword.control.ts",default:"keyword.control.ts",for:"keyword.control.ts",while:"keyword.control.ts",do:"keyword.control.ts",break:"keyword.control.ts",continue:"keyword.control.ts",return:"keyword.control.ts",try:"keyword.control.ts",catch:"keyword.control.ts",finally:"keyword.control.ts",throw:"keyword.control.ts",async:"keyword.control.ts",await:"keyword.control.ts",yield:"keyword.control.ts",const:"storage.type.ts",let:"storage.type.ts",var:"storage.type.ts",function:"storage.type.ts",class:"storage.type.ts",extends:"storage.type.ts",implements:"storage.type.ts",static:"storage.type.ts",type:"storage.type.ts",interface:"storage.type.ts",enum:"storage.type.ts",namespace:"storage.type.ts",module:"storage.type.ts",declare:"storage.type.ts",public:"storage.type.ts",private:"storage.type.ts",protected:"storage.type.ts",readonly:"storage.type.ts",abstract:"storage.type.ts",string:"storage.type.ts",number:"storage.type.ts",boolean:"storage.type.ts",any:"storage.type.ts",void:"storage.type.ts",never:"storage.type.ts",unknown:"storage.type.ts",object:"storage.type.ts",symbol:"storage.type.ts",bigint:"storage.type.ts",get:"storage.type.ts",set:"storage.type.ts",new:"keyword.operator.new.ts",delete:"keyword.operator.new.ts",typeof:"keyword.operator.new.ts",instanceof:"keyword.operator.new.ts",as:"keyword.operator.new.ts",in:"keyword.operator.new.ts",of:"keyword.operator.new.ts",is:"keyword.operator.new.ts",keyof:"keyword.operator.new.ts",infer:"keyword.operator.new.ts",true:"constant.language.ts",false:"constant.language.ts",null:"constant.language.ts",undefined:"constant.language.ts",NaN:"constant.language.ts",Infinity:"constant.language.ts",this:"constant.language.ts",super:"constant.language.ts",arguments:"constant.language.ts",import:"keyword.other.ts",export:"keyword.other.ts",from:"keyword.other.ts",require:"keyword.other.ts",with:"keyword.other.ts",debugger:"keyword.other.ts"},patterns:[{include:"#comments"},{include:"#strings"},{include:"#jsx"},{include:"#regex"},{include:"#keywords"},{include:"#numbers"},{include:"#functions"},{include:"#types"},{include:"#operators"},{include:"#punctuation"}],repository:{comments:{patterns:[{name:"comment.line.double-slash.ts",match:"\\/\\/.*$"},{name:"comment.block.ts",begin:"\\/\\*",end:"\\*\\/"}]},strings:{patterns:[{name:"string.quoted.double.ts",begin:'"',end:'"',patterns:[{name:"constant.character.escape.ts",match:"\\\\."}]},{name:"string.quoted.single.ts",begin:"'",end:"'",patterns:[{name:"constant.character.escape.ts",match:"\\\\."}]},{name:"string.template.ts",begin:"`",end:"`",patterns:[{name:"meta.template.expression.ts",begin:"\\$\\{",end:"\\}",patterns:[{include:"$self"}]},{name:"constant.character.escape.ts",match:"\\\\."}]}]},jsx:{patterns:[{name:"meta.tag.tsx",begin:"<([A-Z][a-zA-Z0-9]*|[a-z][a-zA-Z0-9-]*)",beginCaptures:{0:{name:"punctuation.definition.tag.begin.tsx"},1:{name:"entity.name.tag.tsx"}},end:"(/?>)",endCaptures:{1:{name:"punctuation.definition.tag.end.tsx"}},patterns:[{name:"entity.other.attribute-name.tsx",match:"[a-zA-Z_:][a-zA-Z0-9_:.-]*"},{name:"meta.embedded.expression.tsx",begin:"\\{",end:"\\}",patterns:[{include:"$self"}]},{name:"string.quoted.double.tsx",begin:'"',end:'"'},{name:"string.quoted.single.tsx",begin:"'",end:"'"}]},{name:"meta.tag.tsx",begin:"(</)([A-Z][a-zA-Z0-9]*|[a-z][a-zA-Z0-9-]*)",beginCaptures:{1:{name:"punctuation.definition.tag.begin.tsx"},2:{name:"entity.name.tag.tsx"}},end:"(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.tsx"}}}]},regex:{patterns:[{name:"string.regexp.ts",begin:"(?<=[=(,\\[!&|?{};:])\\s*(\\/)",beginCaptures:{1:{name:"punctuation.definition.string.begin.ts"}},end:"(\\/)[gimsuvy]*",endCaptures:{1:{name:"punctuation.definition.string.end.ts"}},patterns:[{name:"constant.character.escape.ts",match:"\\\\."}]}]},numbers:{patterns:[{name:"constant.numeric.ts",match:"\\b(0[xX][0-9a-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|\\d+(_\\d+)*(\\.\\d+(_\\d+)?)?([eE][+-]?\\d+)?)[nN]?\\b"}]},types:{patterns:[{name:"storage.type.ts",match:"\\b(string|number|boolean|any|void|never|unknown|object|symbol|bigint)\\b"},{name:"entity.name.type.ts",match:":\\s*([A-Z][a-zA-Z0-9_]*)"},{name:"meta.type.annotation.ts",match:"<[^>]+>"}]},keywords:{patterns:[{name:"keyword.control.ts",match:"\\b(if|else|switch|case|default|for|while|do|break|continue|return|try|catch|finally|throw|async|await|yield)\\b"},{name:"storage.type.ts",match:"\\b(const|let|var|function|class|extends|implements|static|async|type|interface|enum|namespace|module|declare|public|private|protected|readonly|abstract|get|set)\\b"},{name:"keyword.operator.new.ts",match:"\\b(new|delete|typeof|instanceof|void|as|in|of|is|keyof|infer)\\b"},{name:"constant.language.ts",match:"\\b(true|false|null|undefined|NaN|Infinity|this|super|arguments)\\b"},{name:"keyword.other.ts",match:"\\b(import|export|from|default|require|with|debugger)\\b"}]},functions:{patterns:[{name:"entity.name.function.ts",match:"\\b([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*(?=\\()"}]},operators:{patterns:[{name:"keyword.operator.ts",match:"(\\+\\+|--|\\+|\\-|\\*|\\/|%|===|==|!==|!=|<=|>=|<|>|&&|\\|\\||!|\\?|:|=>|\\.\\.\\.|&|\\||\\^|~|<<|>>|>>>)"}]},punctuation:{patterns:[{name:"punctuation.ts",match:"[{}()\\[\\];,.]"}]}}},Pw=[{id:"javascript",name:"JavaScript",aliases:["js","jsx"],extensions:[".js",".jsx",".mjs",".cjs"],grammar:T9},{id:"typescript",name:"TypeScript",aliases:["ts","tsx"],extensions:[".ts",".tsx",".mts",".cts"],grammar:M9},{id:"html",name:"HTML",aliases:["htm"],extensions:[".html",".htm"],grammar:G9},{id:"css",name:"CSS",aliases:[],extensions:[".css"],grammar:I9},{id:"json",name:"JSON",aliases:[],extensions:[".json",".jsonc"],grammar:Z9},{id:"stx",name:"STX",aliases:[],extensions:[".stx"],grammar:E9}];S=new Uint8Array(256);for(let $=65;$<=90;$++)S[$]=1;for(let $=97;$<=122;$++)S[$]=1;S[95]=1;S[36]=1;for(let $=48;$<=57;$++)S[$]=2;S[43]=4;S[45]=4;S[42]=4;S[47]=4;S[61]=4;S[33]=4;S[60]=4;S[62]=4;S[38]=4;S[124]=4;S[37]=4;S[63]=4;S[58]=4;S[46]=4;S[123]=8;S[125]=8;S[40]=8;S[41]=8;S[91]=8;S[93]=8;S[59]=8;S[44]=8;S[34]=16;S[39]=16;S[96]=16;S[32]=32;S[9]=32;S[10]=32;S[13]=32;C9={name:"GitHub Dark",type:"dark",colors:{"editor.background":"#0d1117","editor.foreground":"#c9d1d9","editor.lineHighlightBackground":"#161b22","editor.selectionBackground":"#264f78"},tokenColors:[{name:"Comment",scope:["comment","comment.line","comment.block"],settings:{foreground:"#8b949e",fontStyle:"italic"}},{name:"String",scope:["string","string.quoted"],settings:{foreground:"#a5d6ff"}},{name:"Template String",scope:["string.template"],settings:{foreground:"#a5d6ff"}},{name:"Number",scope:["constant.numeric"],settings:{foreground:"#79c0ff"}},{name:"Keyword",scope:["keyword","keyword.control","keyword.operator"],settings:{foreground:"#ff7b72"}},{name:"Storage Type",scope:["storage.type","storage.modifier"],settings:{foreground:"#ff7b72"}},{name:"Function",scope:["entity.name.function","support.function"],settings:{foreground:"#d2a8ff"}},{name:"Class",scope:["entity.name.type","entity.name.class"],settings:{foreground:"#ffa657"}},{name:"Variable",scope:["variable","variable.other"],settings:{foreground:"#ffa657"}},{name:"Constant",scope:["constant.language","constant.character"],settings:{foreground:"#79c0ff"}},{name:"Tag",scope:["entity.name.tag"],settings:{foreground:"#7ee787"}},{name:"Attribute",scope:["entity.other.attribute-name"],settings:{foreground:"#79c0ff"}},{name:"Punctuation",scope:["punctuation"],settings:{foreground:"#c9d1d9"}},{name:"Operator",scope:["keyword.operator"],settings:{foreground:"#ff7b72"}},{name:"CSS Property",scope:["support.type.property-name.css"],settings:{foreground:"#79c0ff"}},{name:"CSS Value",scope:["support.constant.property-value.css"],settings:{foreground:"#a5d6ff"}},{name:"Color",scope:["constant.other.color"],settings:{foreground:"#a5d6ff"}}]},v9={name:"GitHub Light",type:"light",colors:{"editor.background":"#ffffff","editor.foreground":"#24292f","editor.lineHighlightBackground":"#f6f8fa","editor.selectionBackground":"#b6d4fe"},tokenColors:[{name:"Comment",scope:["comment","comment.line","comment.block"],settings:{foreground:"#6e7781",fontStyle:"italic"}},{name:"String",scope:["string","string.quoted"],settings:{foreground:"#0a3069"}},{name:"Template String",scope:["string.template"],settings:{foreground:"#0a3069"}},{name:"Number",scope:["constant.numeric"],settings:{foreground:"#0550ae"}},{name:"Keyword",scope:["keyword","keyword.control","keyword.operator"],settings:{foreground:"#cf222e"}},{name:"Storage Type",scope:["storage.type","storage.modifier"],settings:{foreground:"#cf222e"}},{name:"Function",scope:["entity.name.function","support.function"],settings:{foreground:"#8250df"}},{name:"Class",scope:["entity.name.type","entity.name.class"],settings:{foreground:"#953800"}},{name:"Variable",scope:["variable","variable.other"],settings:{foreground:"#953800"}},{name:"Constant",scope:["constant.language","constant.character"],settings:{foreground:"#0550ae"}},{name:"Tag",scope:["entity.name.tag"],settings:{foreground:"#116329"}},{name:"Attribute",scope:["entity.other.attribute-name"],settings:{foreground:"#0550ae"}},{name:"Punctuation",scope:["punctuation"],settings:{foreground:"#24292f"}},{name:"Operator",scope:["keyword.operator"],settings:{foreground:"#cf222e"}},{name:"CSS Property",scope:["support.type.property-name.css"],settings:{foreground:"#0550ae"}},{name:"CSS Value",scope:["support.constant.property-value.css"],settings:{foreground:"#0a3069"}},{name:"Color",scope:["constant.other.color"],settings:{foreground:"#0a3069"}}]},d9={name:"Nord",type:"dark",colors:{"editor.background":"#2e3440","editor.foreground":"#d8dee9","editor.lineHighlightBackground":"#3b4252","editor.selectionBackground":"#434c5e"},tokenColors:[{name:"Comment",scope:["comment","comment.line","comment.block"],settings:{foreground:"#616e88",fontStyle:"italic"}},{name:"String",scope:["string","string.quoted"],settings:{foreground:"#a3be8c"}},{name:"Template String",scope:["string.template"],settings:{foreground:"#a3be8c"}},{name:"Number",scope:["constant.numeric"],settings:{foreground:"#b48ead"}},{name:"Keyword",scope:["keyword","keyword.control","keyword.operator"],settings:{foreground:"#81a1c1"}},{name:"Storage Type",scope:["storage.type","storage.modifier"],settings:{foreground:"#81a1c1"}},{name:"Function",scope:["entity.name.function","support.function"],settings:{foreground:"#88c0d0"}},{name:"Class",scope:["entity.name.type","entity.name.class"],settings:{foreground:"#8fbcbb"}},{name:"Variable",scope:["variable","variable.other"],settings:{foreground:"#d8dee9"}},{name:"Constant",scope:["constant.language","constant.character"],settings:{foreground:"#b48ead"}},{name:"Tag",scope:["entity.name.tag"],settings:{foreground:"#81a1c1"}},{name:"Attribute",scope:["entity.other.attribute-name"],settings:{foreground:"#8fbcbb"}},{name:"Punctuation",scope:["punctuation"],settings:{foreground:"#eceff4"}},{name:"Operator",scope:["keyword.operator"],settings:{foreground:"#81a1c1"}},{name:"CSS Property",scope:["support.type.property-name.css"],settings:{foreground:"#8fbcbb"}},{name:"CSS Value",scope:["support.constant.property-value.css"],settings:{foreground:"#a3be8c"}},{name:"Color",scope:["constant.other.color"],settings:{foreground:"#b48ead"}}]},uw=[C9,v9,d9];I=new Uint8Array(256);for(let $=65;$<=90;$++)I[$]=1;for(let $=97;$<=122;$++)I[$]=1;I[95]=1;I[36]=1;for(let $=48;$<=57;$++)I[$]=2;I[43]=4;I[45]=4;I[42]=4;I[47]=4;I[61]=4;I[33]=4;I[60]=4;I[62]=4;I[38]=4;I[124]=4;I[37]=4;I[63]=4;I[58]=4;I[46]=4;I[123]=8;I[125]=8;I[40]=8;I[41]=8;I[91]=8;I[93]=8;I[59]=8;I[44]=8;I[34]=16;I[39]=16;I[96]=16;I[32]=32;I[9]=32;I[10]=32;I[13]=32;V5=new nw(!1)});import{existsSync as y2,mkdirSync as G5,readdirSync as T5,writeFileSync as Z5}from"fs";import{homedir as W$}from"os";import{dirname as D5,resolve as g0}from"path";import $1 from"process";import{join as P9,relative as x9,resolve as rw}from"path";import E1 from"process";import{existsSync as j2,mkdirSync as P5,readdirSync as x5,writeFileSync as u5}from"fs";import{dirname as i5,resolve as M1}from"path";import F$ from"process";import{Buffer as H0}from"buffer";import{createCipheriv as u9,createDecipheriv as m9,randomBytes as L$}from"crypto";import{closeSync as f$,createReadStream as cw,createWriteStream as i9,existsSync as O$,fsyncSync as lw,openSync as sw,writeFileSync as n9}from"fs";import{access as p9,constants as ow,mkdir as r9,readdir as I1,rename as aw,stat as v0,unlink as G1,writeFile as R$}from"fs/promises";import{join as d0}from"path";import a from"process";import{pipeline as c9}from"stream/promises";import{createGzip as ew}from"zlib";import h0 from"process";import W0 from"process";function V$($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&P(w[0])&&"id"in w[0]&&w[0].id===3&&P(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(P(w)&&P($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(P($)&&"arr"in $&&Array.isArray($.arr)&&P(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&P(w[0])&&P($[0])){let j=[...w];for(let z of $)if(P(z)&&"name"in z){if(!j.find((A)=>P(A)&&("name"in A)&&A.name===z.name))j.push(z)}else if(P(z)&&"path"in z){if(!j.find((A)=>P(A)&&("path"in A)&&A.path===z.path))j.push(z)}else if(!j.some((g)=>D1(g,z)))j.push(z);return j}if(w.every((j)=>typeof j==="string")&&$.every((j)=>typeof j==="string")){let j=[...w];for(let z of $)if(!j.includes(z))j.push(z);return j}return w}if(!P(w)||!P($))return w;let y={...$};for(let j in w)if(Object.prototype.hasOwnProperty.call(w,j)){let z=w[j];if(z===null||z===void 0)continue;else if(P(z)&&P(y[j]))y[j]=V$(y[j],z);else if(Array.isArray(z)&&Array.isArray(y[j]))if(z.length>0&&y[j].length>0&&P(z[0])&&P(y[j][0])){let g=[...z];for(let A of y[j])if(P(A)&&"name"in A){if(!g.find((X)=>P(X)&&("name"in X)&&X.name===A.name))g.push(A)}else if(P(A)&&"path"in A){if(!g.find((X)=>P(X)&&("path"in X)&&X.path===A.path))g.push(A)}else if(!g.some((J)=>D1(J,A)))g.push(A);y[j]=g}else if(z.every((g)=>typeof g==="string")&&y[j].every((g)=>typeof g==="string")){let g=[...z];for(let A of y[j])if(!g.includes(A))g.push(A);y[j]=g}else y[j]=z;else y[j]=z}return y}function D1($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let y=0;y<$.length;y++)if(!D1($[y],w[y]))return!1;return!0}if(P($)&&P(w)){let y=Object.keys($),j=Object.keys(w);if(y.length!==j.length)return!1;for(let z of y){if(!Object.prototype.hasOwnProperty.call(w,z))return!1;if(!D1($[z],w[z]))return!1}return!0}return!1}function P($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function l9($,w){if(!j2($))return null;try{let y=await import($),j=y.default||y;if(typeof j!=="object"||j===null||Array.isArray(j))return null;try{return V$(w,j)}catch{return null}}catch{return null}}async function s9({name:$="",cwd:w,defaultConfig:y}){let j=w||F$.cwd(),z=[".ts",".js",".mjs",".cjs",".json"],g=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let A of g)for(let J of z){let X=M1(j,`${A}${J}`),Y=await l9(X,y);if(Y!==null)return Y}try{let A=M1(j,"package.json");if(j2(A)){let X=(await import(A))[$];if(X&&typeof X==="object"&&!Array.isArray(X))try{return V$(y,X)}catch{}}}catch{}return y}function o9($,w={}){let y=E1.cwd();while(y.includes("storage"))y=rw(y,"..");let j=rw(y,$||"");if(w?.relative)return x9(E1.cwd(),j);return j}async function e9(){try{let $=await s9({name:"clarity",defaultConfig:H$,cwd:E1.cwd(),endpoint:"",headers:{}});return{...H$,...$}}catch{return H$}}function u(){if(W0.env.NODE_ENV==="test"||W0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function t9(){if(W0.env.NODE_ENV==="test"||W0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof W0<"u"){let $=W0.type;if($==="renderer"||$==="worker")return!1;return!!(W0.versions&&(W0.versions.node||W0.versions.bun))}return!1}class g2{async format($){let w=await t9(),y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:h0.pid,hostname:w(),environment:h0.env.NODE_ENV||"development",platform:h0.platform,version:h0.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:h0.env.NODE_ENV||h0.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class v1{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...tw},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new g2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??a.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let y={...w},j=w.timestamp!==void 0;if(j)delete y.timestamp;if(this.config={...this.config,...y,timestamp:j||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let z=this.generateKeyId(),g=this.generateKey();this.currentKeyId=z,this.keys.set(z,g),this.encryptionKeys.set(z,{key:g,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...k$,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...k$};return{...k$,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:tw.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},y={...w,...Object.fromEntries(Object.entries($).filter(([,j])=>j!==void 0))};if(!y.level||!["debug","info","success","warning","error"].includes(y.level))y.level=w.level;return y}async writeToFile($){let y=(async()=>{let z,g=0,A=3,J=1000;while(g<A)try{try{try{await p9(this.config.logDirectory,ow.F_OK|ow.W_OK)}catch(Y){if(Y instanceof Error&&"code"in Y)if(Y.code==="ENOENT")await r9(this.config.logDirectory,{recursive:!0,mode:493});else if(Y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Y;else throw Y}}catch(Y){throw console.error("Debug: [writeToFile] Failed to create log directory:",Y),Y}let X=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:H0.from($);try{if(!O$(this.currentLogFile))await R$(this.currentLogFile,"",{mode:420});if(z=sw(this.currentLogFile,"a",420),n9(z,X,{flag:"a"}),lw(z),z!==void 0)f$(z),z=void 0;if((await v0(this.currentLogFile)).size===0){if(await R$(this.currentLogFile,X,{flag:"w",mode:420}),(await v0(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Y){let U=Y;if(U.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(U.code)){if(g<A-1){let B=typeof U.message==="string"?U.message:"Unknown error";console.error(`Network error during write attempt ${g+1}/${A}:`,B);let b=J*2**g;await new Promise((Q)=>setTimeout(Q,b)),g++;continue}}if(U?.code&&["ENOSPC","EDQUOT"].includes(U.code))throw Error(`Disk quota exceeded or no space left on device: ${U.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",U),U}finally{if(z!==void 0)try{f$(z)}catch(Y){console.error("Debug: [writeToFile] Error closing file descriptor:",Y)}}}catch(X){if(g===A-1){let U=X,B=typeof U.message==="string"?U.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),X}g++;let Y=J*2**(g-1);await new Promise((U)=>setTimeout(U,Y))}})();this.pendingOperations.push(y);let j=this.pendingOperations.length-1;try{await y}catch(z){throw console.error("Debug: [writeToFile] Error in operation:",z),z}finally{this.pendingOperations.splice(j,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return d0(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return d0(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return d0(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(u())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let y=typeof w.interval==="number"?w.interval:60,j=Math.max(y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((z)=>{console.error("Error rotating keys:",z)})},j)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,y=this.generateKeyId(),j=this.generateKey();this.currentKeyId=y,this.keys.set(y,j),this.encryptionKeys.set(y,{key:j,createdAt:new Date});let z=Array.from(this.encryptionKeys.entries()).sort(([,J],[,X])=>X.createdAt.getTime()-J.createdAt.getTime()),g=typeof w.maxKeys==="number"?w.maxKeys:1,A=Math.max(1,g);if(z.length>A)for(let[J]of z.slice(A))this.encryptionKeys.delete(J),this.keys.delete(J)}generateKeyId(){return L$(16).toString("hex")}generateKey(){return L$(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),y=L$(16),j=u9("aes-256-gcm",w,y),z=H0.concat([j.update($,"utf8"),j.final()]),g=j.getAuthTag();return{encrypted:H0.concat([y,z,g]),iv:y}}async compressData($){return new Promise((w,y)=>{let j=ew(),z=[];j.on("data",(g)=>z.push(g)),j.on("end",()=>w(H0.from(H0.concat(z)))),j.on("error",y),j.write($),j.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(u())return;let $=await v0(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let y=this.currentLogFile,j=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let z=await I1(this.config.logDirectory),g=z.filter((X)=>X.startsWith(this.name)&&/\.log\.\d+$/.test(X)).sort((X,Y)=>{let U=Number.parseInt(X.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Y.match(/\.log\.(\d+)$/)?.[1]||"0")-U}),A=g.length>0?Number.parseInt(g[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,J=`${y}.${A}`;if(await v0(y).catch(()=>null))try{if(await aw(y,J),w.compress)try{let X=`${J}.gz`;await this.compressLogFile(J,X),await G1(J)}catch(X){console.error("Error compressing rotated file:",X)}if(g.length===0&&!z.some((X)=>X.endsWith(".log.1")))try{let X=`${y}.1`;await R$(X,"")}catch(X){console.error("Error creating backup file:",X)}}catch(X){console.error(`Error during rotation: ${X instanceof Error?X.message:String(X)}`)}}else{let z=new Date().toISOString().replace(/[:.]/g,"-"),g=y.replace(/\.log$/,`-${z}.log`);if(await v0(y).catch(()=>null))await aw(y,g)}if(this.currentLogFile=j,w.maxFiles){let g=(await I1(this.config.logDirectory)).filter((A)=>A.startsWith(this.name)).sort((A,J)=>J.localeCompare(A));for(let A of g.slice(w.maxFiles))await G1(d0(this.config.logDirectory,A))}}}async compressLogFile($,w){let y=cw($),j=i9(w),z=ew();await c9(y,z,j)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let y of this.logBuffer){let j=await this.formatter.format(y);await this.writeToFile(j),console.log(j)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),O$(this.currentLogFile))try{let $=sw(this.currentLogFile,"r+");lw($),f$($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!u()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await I1(this.config.logDirectory)).filter((y)=>(y.includes("temp")||y.includes(".tmp"))&&y.includes(this.name));for(let y of w)try{await G1(d0(this.config.logDirectory,y))}catch(j){console.error(`Failed to delete temp file ${y}:`,j)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?h.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:y="",tag:j="",message:z,level:g,showTimestamp:A=!0}=$,J=(Q)=>Q.replace(this.ANSI_PATTERN,"");if(!this.fancy){let Q=[];if(A)Q.push(w);if(g==="warning")Q.push("WARN");else if(g==="error")Q.push("ERROR");else if(y)Q.push(y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(j)Q.push(j.replace(/[[\]]/g,""));return Q.push(z),Q.join(" ")}let X=a.stdout.columns||120,Y="";if(g==="warning"||g==="error")Y=`${y} ${z}`;else if(g==="info"||g==="success")Y=`${y} ${j} ${z}`;else Y=`${y} ${j} ${h.cyan(z)}`;if(!A)return Y.trim();let U=J(Y).trim().length,B=J(w).length,b=Math.max(1,X-2-U-B);return`${Y.trim()}${" ".repeat(b)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(g,A)=>{let J=Number.parseInt(A,10);return J<w[0].length?String(w[0][J]):g});let y=/%([sdijfo%])/g,j=0,z=$.replace(y,(g,A)=>{if(A==="%")return"%";if(j>=w.length)return g;let J=w[j++];switch(A){case"s":return String(J);case"d":case"i":return Number(J).toString();case"j":case"o":return JSON.stringify(J,null,2);default:return g}});if(j<w.length)z+=` ${w.slice(j).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`;return z}async log($,w,...y){let j=new Date,z=this.formatConsoleTimestamp(j),g=this.formatFileTimestamp(j),A,J;if(w instanceof Error)A=w.message,J=w.stack;else A=this.formatMessage(w,y);if(this.fancy&&!u()){let Y=g8[$],U=this.options.showTags!==!1&&this.name?h.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:h.gray(A),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:A,level:$}),console.error(B);break;case"success":B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:h.green(A),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:A,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:A,level:$}),console.error(B),J){let b=J.split(`
456
- `);for(let Q of b)if(Q.trim()&&!Q.includes(A))console.error(this.formatConsoleMessage({timestamp:z,message:h.gray(` ${Q}`),level:$,showTimestamp:!1}))}break}}else if(!u()){if(console.error(`${g} ${this.environment}.${$.toUpperCase()}: ${A}`),J)console.error(J)}if(!this.shouldLog($))return;let X=`${g} ${this.environment}.${$.toUpperCase()}: ${A}
455
+ `);for(let[w,y]of Object.entries($))console.log(`${w}:`),console.log(` Count: ${y.count}`),console.log(` Total: ${y.total.toFixed(2)}ms`),console.log(` Avg: ${y.avg.toFixed(2)}ms`),console.log(` Min: ${y.min.toFixed(2)}ms`),console.log(` Max: ${y.max.toFixed(2)}ms`),console.log()}}var W5,L5,Ry,Q$,vw,$0,v,O5,Fy,H5,Vy,R5,f5,dw,k5,Sy,Gy,hw,F5,V5,S5,G5,K$,Iy,I5,e,T5,Z5,My,M5,Ey,Dy,Cy,vy,dy,hy,mw,S,xy,uy,my,nw,G,E5;var lw=M(async()=>{W5=k1(_$.cwd(),"config"),L5=k1(_$.cwd(),"src/generated");Ry=f1.env.CLARITY_LOG_DIR||Uy(Hy(),"logs"),Q$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ry,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1};vw=await fy();$0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},v=$0,O5=$0.red,Fy=$0.green,H5=$0.yellow,Vy=$0.blue,R5=$0.magenta,f5=$0.cyan,dw=$0.white,k5=$0.gray,Sy=$0.bgRed,Gy=$0.bgYellow,hw=$0.bold,F5=$0.dim,V5=$0.italic,S5=$0.underline,G5=$0.reset,K$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Iy={debug:"\uD83D\uDD0D",info:Vy("\u2139"),success:Fy("\u2713"),warning:Gy(dw(hw(" WARN "))),error:Sy(dw(hw(" ERROR ")))};I5=new S1("stacks");e=new S1("bunfig",{showTags:!0});T5=j0(t0.cwd(),"config"),Z5=j0(t0.cwd(),"src/generated"),My={verbose:!1,theme:"github-dark",defaultLanguage:"javascript",cache:!0,plugins:[]},M5=await Zy({name:"syntax",defaultConfig:My}),Ey={name:"CSS",scopeName:"source.css",patterns:[{include:"#comments"},{include:"#at-rules"},{include:"#selectors"},{include:"#properties"},{include:"#functions"},{include:"#variables"},{include:"#values"},{include:"#strings"},{include:"#numbers"},{include:"#colors"},{include:"#punctuation"}],repository:{comments:{patterns:[{name:"comment.block.css",begin:"\\/\\*",end:"\\*\\/"}]},"at-rules":{patterns:[{name:"keyword.control.at-rule.css",match:"@(media|import|charset|namespace|keyframes|font-face|supports|page|document|viewport|counter-style|font-feature-values|property|layer|container)\\b"}]},selectors:{patterns:[{name:"entity.name.tag.css",match:"\\b(a|abbr|address|article|aside|audio|b|blockquote|body|button|canvas|caption|cite|code|div|em|embed|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|html|i|iframe|img|input|label|legend|li|main|nav|ol|p|pre|section|select|span|strong|table|tbody|td|textarea|tfoot|th|thead|tr|ul|video)\\b"},{name:"entity.other.attribute-name.class.css",match:"\\.[a-zA-Z_-][a-zA-Z0-9_-]*"},{name:"entity.other.attribute-name.id.css",match:"#[a-zA-Z_-][a-zA-Z0-9_-]*"},{name:"entity.other.attribute-name.pseudo-class.css",match:":[a-zA-Z_-][a-zA-Z0-9_-]*"},{name:"entity.other.attribute-name.pseudo-element.css",match:"::[a-zA-Z_-][a-zA-Z0-9_-]*"}]},properties:{patterns:[{name:"support.type.property-name.css",match:"\\b(align-items|background|border|color|display|flex|font|height|justify-content|margin|padding|position|width|z-index|animation|box-shadow|cursor|font-family|font-size|font-weight|grid|line-height|opacity|overflow|text-align|text-decoration|transform|transition|visibility)(-[a-z]+)?\\b"}]},values:{patterns:[{name:"support.constant.property-value.css",match:"\\b(auto|block|inline|flex|grid|none|center|left|right|top|bottom|absolute|relative|fixed|sticky|hidden|visible|bold|normal|italic|underline|solid|dotted|dashed)\\b"}]},strings:{patterns:[{name:"string.quoted.double.css",begin:'"',end:'"'},{name:"string.quoted.single.css",begin:"'",end:"'"}]},numbers:{patterns:[{name:"constant.numeric.css",match:"\\b\\d+(\\.\\d+)?(px|em|rem|%|vh|vw|vmin|vmax|ch|ex|cm|mm|in|pt|pc|deg|rad|turn|s|ms)?\\b"}]},colors:{patterns:[{name:"constant.other.color.css",match:"#[0-9a-fA-F]{3,8}\\b"},{name:"support.function.color.css",match:"\\b(rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color)\\s*\\("}]},functions:{patterns:[{name:"support.function.css",match:"\\b(var|calc|min|max|clamp|round|abs|sign|mod|rem|sin|cos|tan|asin|acos|atan|atan2|pow|sqrt|hypot|log|exp|url|attr|counter|counters|linear-gradient|radial-gradient|conic-gradient|repeating-linear-gradient|repeating-radial-gradient|repeating-conic-gradient)\\s*\\("}]},variables:{patterns:[{name:"variable.other.custom-property.css",match:"--[a-zA-Z0-9_-]+"}]},punctuation:{patterns:[{name:"punctuation.css",match:"[{}();:,]"}]}}},Dy={name:"HTML",scopeName:"text.html.basic",patterns:[{include:"#doctype"},{include:"#comments"},{include:"#tags"},{include:"#entities"}],repository:{doctype:{patterns:[{name:"meta.tag.sgml.doctype.html",match:"<!DOCTYPE[^>]*>"}]},comments:{patterns:[{name:"comment.block.html",begin:"<!--",end:"-->"}]},tags:{patterns:[{name:"meta.tag.html",begin:"(<)(script|style|template)\\b",beginCaptures:{1:{name:"punctuation.definition.tag.begin.html"},2:{name:"entity.name.tag.html"}},end:"(</)(\\2)(>)",endCaptures:{1:{name:"punctuation.definition.tag.begin.html"},2:{name:"entity.name.tag.html"},3:{name:"punctuation.definition.tag.end.html"}},patterns:[{include:"#tag-stuff"}]},{name:"meta.tag.html",begin:"(<)([a-zA-Z0-9:-]+)",beginCaptures:{1:{name:"punctuation.definition.tag.begin.html"},2:{name:"entity.name.tag.html"}},end:"(/>)|(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.html"},2:{name:"punctuation.definition.tag.end.html"}},patterns:[{include:"#tag-stuff"}]},{name:"meta.tag.html",begin:"(</)([a-zA-Z0-9:-]+)",beginCaptures:{1:{name:"punctuation.definition.tag.begin.html"},2:{name:"entity.name.tag.html"}},end:"(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.html"}}}]},"tag-stuff":{patterns:[{name:"entity.other.attribute-name.html",match:"\\b(data-[a-zA-Z0-9-]+|aria-[a-zA-Z0-9-]+|on[a-z]+|[a-zA-Z-:]+)"},{name:"string.quoted.double.html",begin:'"',end:'"'},{name:"string.quoted.single.html",begin:"'",end:"'"}]},entities:{patterns:[{name:"constant.character.entity.html",match:"&[a-zA-Z0-9]+;"},{name:"constant.character.entity.html",match:"&#[0-9]+;"}]}}},Cy={name:"JavaScript",scopeName:"source.js",keywords:{if:"keyword.control.js",else:"keyword.control.js",switch:"keyword.control.js",case:"keyword.control.js",default:"keyword.control.js",for:"keyword.control.js",while:"keyword.control.js",do:"keyword.control.js",break:"keyword.control.js",continue:"keyword.control.js",return:"keyword.control.js",try:"keyword.control.js",catch:"keyword.control.js",finally:"keyword.control.js",throw:"keyword.control.js",async:"keyword.control.js",await:"keyword.control.js",yield:"keyword.control.js",const:"storage.type.js",let:"storage.type.js",var:"storage.type.js",function:"storage.type.js",class:"storage.type.js",extends:"storage.type.js",static:"storage.type.js",get:"storage.type.js",set:"storage.type.js",new:"keyword.operator.new.js",delete:"keyword.operator.new.js",typeof:"keyword.operator.new.js",instanceof:"keyword.operator.new.js",void:"keyword.operator.new.js",in:"keyword.operator.new.js",of:"keyword.operator.new.js",true:"constant.language.js",false:"constant.language.js",null:"constant.language.js",undefined:"constant.language.js",NaN:"constant.language.js",Infinity:"constant.language.js",this:"constant.language.js",super:"constant.language.js",arguments:"constant.language.js",import:"keyword.other.js",export:"keyword.other.js",from:"keyword.other.js",as:"keyword.other.js",with:"keyword.other.js",debugger:"keyword.other.js"},patterns:[{include:"#comments"},{include:"#strings"},{include:"#jsx"},{include:"#regex"},{include:"#keywords"},{include:"#numbers"},{include:"#functions"},{include:"#operators"},{include:"#punctuation"}],repository:{comments:{patterns:[{name:"comment.line.double-slash.js",match:"\\/\\/.*$"},{name:"comment.block.js",begin:"\\/\\*",end:"\\*\\/"}]},strings:{patterns:[{name:"string.quoted.double.js",begin:'"',end:'"',patterns:[{name:"constant.character.escape.js",match:"\\\\."}]},{name:"string.quoted.single.js",begin:"'",end:"'",patterns:[{name:"constant.character.escape.js",match:"\\\\."}]},{name:"string.template.js",begin:"`",end:"`",patterns:[{name:"meta.template.expression.js",begin:"\\$\\{",end:"\\}",patterns:[{include:"$self"}]},{name:"constant.character.escape.js",match:"\\\\."}]}]},jsx:{patterns:[{name:"meta.tag.jsx",begin:"<([A-Z][a-zA-Z0-9]*|[a-z][a-zA-Z0-9-]*)",beginCaptures:{0:{name:"punctuation.definition.tag.begin.jsx"},1:{name:"entity.name.tag.jsx"}},end:"(/?>)",endCaptures:{1:{name:"punctuation.definition.tag.end.jsx"}},patterns:[{name:"entity.other.attribute-name.jsx",match:"[a-zA-Z_:][a-zA-Z0-9_:.-]*"},{name:"meta.embedded.expression.jsx",begin:"\\{",end:"\\}",patterns:[{include:"$self"}]},{name:"string.quoted.double.jsx",begin:'"',end:'"'},{name:"string.quoted.single.jsx",begin:"'",end:"'"}]},{name:"meta.tag.jsx",begin:"(</)([A-Z][a-zA-Z0-9]*|[a-z][a-zA-Z0-9-]*)",beginCaptures:{1:{name:"punctuation.definition.tag.begin.jsx"},2:{name:"entity.name.tag.jsx"}},end:"(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.jsx"}}}]},regex:{patterns:[{name:"string.regexp.js",begin:"(?<=[=(,\\[!&|?{};:])\\s*(\\/)",beginCaptures:{1:{name:"punctuation.definition.string.begin.js"}},end:"(\\/)[gimsuvy]*",endCaptures:{1:{name:"punctuation.definition.string.end.js"}},patterns:[{name:"constant.character.escape.js",match:"\\\\."}]}]},numbers:{patterns:[{name:"constant.numeric.js",match:"\\b(0[xX][0-9a-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|\\d+(_\\d+)*(\\.\\d+(_\\d+)?)?([eE][+-]?\\d+)?)[nN]?\\b"}]},keywords:{patterns:[{name:"keyword.control.js",match:"\\b(if|else|switch|case|default|for|while|do|break|continue|return|try|catch|finally|throw|async|await|yield)\\b"},{name:"storage.type.js",match:"\\b(const|let|var|function|class|extends|static|async|get|set)\\b"},{name:"keyword.operator.new.js",match:"\\b(new|delete|typeof|instanceof|void|in|of)\\b"},{name:"constant.language.js",match:"\\b(true|false|null|undefined|NaN|Infinity|this|super|arguments)\\b"},{name:"keyword.other.js",match:"\\b(import|export|from|as|default|with|debugger)\\b"}]},functions:{patterns:[{name:"entity.name.function.js",match:"\\b([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*(?=\\()"}]},operators:{patterns:[{name:"keyword.operator.js",match:"(\\+\\+|--|\\+|\\-|\\*|\\/|%|===|==|!==|!=|<=|>=|<|>|&&|\\|\\||!|\\?|:|=>|\\.\\.\\.|&|\\||\\^|~|<<|>>|>>>)"}]},punctuation:{patterns:[{name:"punctuation.js",match:"[{}()\\[\\];,.]"}]}}},vy={name:"JSON",scopeName:"source.json",patterns:[{include:"#value"}],repository:{value:{patterns:[{include:"#constant"},{include:"#number"},{include:"#string"},{include:"#array"},{include:"#object"}]},constant:{patterns:[{name:"constant.language.json",match:"\\b(true|false|null)\\b"}]},number:{patterns:[{name:"constant.numeric.json",match:"-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?"}]},string:{patterns:[{name:"string.quoted.double.json",begin:'"',end:'"',patterns:[{name:"constant.character.escape.json",match:'\\\\(["\\\\/bfnrt]|u[0-9a-fA-F]{4})'},{name:"invalid.illegal.unrecognized-string-escape.json",match:"\\\\."}]}]},array:{patterns:[{name:"meta.structure.array.json",begin:"\\[",beginCaptures:{0:{name:"punctuation.definition.array.begin.json"}},end:"\\]",endCaptures:{0:{name:"punctuation.definition.array.end.json"}},patterns:[{include:"#value"},{name:"punctuation.separator.array.json",match:","}]}]},object:{patterns:[{name:"meta.structure.dictionary.json",begin:"\\{",beginCaptures:{0:{name:"punctuation.definition.dictionary.begin.json"}},end:"\\}",endCaptures:{0:{name:"punctuation.definition.dictionary.end.json"}},patterns:[{name:"meta.structure.dictionary.key.json",begin:'"',beginCaptures:{0:{name:"punctuation.support.type.property-name.begin.json"}},end:'"',endCaptures:{0:{name:"punctuation.support.type.property-name.end.json"}},patterns:[{name:"constant.character.escape.json",match:'\\\\(["\\\\/bfnrt]|u[0-9a-fA-F]{4})'}]},{name:"punctuation.separator.dictionary.key-value.json",match:":"},{name:"punctuation.separator.dictionary.pair.json",match:","},{include:"#value"}]}]}}},dy={name:"STX",scopeName:"text.html.stx",patterns:[{include:"#stx-comments"},{include:"#stx-echo"},{include:"#stx-directives"},{include:"#html"}],repository:{"stx-comments":{patterns:[{name:"comment.block.stx",begin:"\\{\\{--",end:"--\\}\\}"}]},"stx-echo":{patterns:[{name:"meta.embedded.block.stx.unescaped",begin:"(?<!@)\\{\\{\\{",beginCaptures:{0:{name:"punctuation.section.embedded.begin.stx"}},end:"\\}\\}\\}",endCaptures:{0:{name:"punctuation.section.embedded.end.stx"}},contentName:"source.ts.embedded.stx"},{name:"meta.embedded.block.stx.escaped",begin:"(?<![@{])\\{\\{",beginCaptures:{0:{name:"punctuation.section.embedded.begin.stx"}},end:"\\}\\}",endCaptures:{0:{name:"punctuation.section.embedded.end.stx"}},contentName:"source.ts.embedded.stx"},{name:"meta.embedded.block.stx.raw",begin:"(?<!@)\\{!!",beginCaptures:{0:{name:"punctuation.section.embedded.begin.stx"}},end:"!!\\}",endCaptures:{0:{name:"punctuation.section.embedded.end.stx"}},contentName:"source.ts.embedded.stx"}]},"stx-directives":{patterns:[{name:"keyword.control.conditional.stx",match:"@(if|else|elseif|endif|unless|endunless|switch|case|default|endswitch|break)\\b"},{name:"keyword.control.loop.stx",match:"@(for|endfor|foreach|endforeach|while|endwhile|continue|forelse|empty)\\b"},{name:"keyword.control.auth.stx",match:"@(auth|guest|can|cannot|endauth|endguest|endcan|endcannot)\\b"},{name:"keyword.control.component.stx",match:"@(component|endcomponent|slot|endslot|props|inject)\\b"},{name:"keyword.control.layout.stx",match:"@(section|endsection|yield|extends|parent)\\b"},{name:"support.function.include.stx",match:"@(include|includewhen|includeunless|includefirst)\\b"},{name:"keyword.control.stack.stx",match:"@(push|endpush|pushOnce|endpushOnce|pushif|endpushif|stack)\\b"},{name:"keyword.control.once.stx",match:"@(once|endonce)\\b"},{name:"support.function.security.stx",match:"@(csrf|method)\\b"},{name:"keyword.control.environment.stx",match:"@(production|endproduction|development|enddevelopment|env|endenv)\\b"},{name:"support.function.translation.stx",match:"@(translate|endtranslate|t)\\b"},{name:"support.function.webcomponent.stx",match:"@webcomponent\\b"},{name:"support.function.route.stx",match:"@route\\b"},{name:"keyword.control.markdown.stx",begin:"@markdown\\b",beginCaptures:{0:{name:"keyword.control.markdown.stx"}},end:"@endmarkdown\\b",endCaptures:{0:{name:"keyword.control.markdown.stx"}},contentName:"text.html.markdown.embedded.stx"},{name:"support.function.markdown.stx",match:"@markdown-file\\b"},{name:"keyword.control.animation.stx",match:"@(transition|endtransition|motion|endmotion)\\b"},{name:"meta.embedded.block.ts",begin:"@ts\\b",beginCaptures:{0:{name:"keyword.control.stx"}},end:"@endts\\b",endCaptures:{0:{name:"keyword.control.stx"}},contentName:"source.ts"},{name:"meta.embedded.block.js",begin:"@js\\b",beginCaptures:{0:{name:"keyword.control.stx"}},end:"@endjs\\b",endCaptures:{0:{name:"keyword.control.stx"}},contentName:"source.js"},{name:"meta.embedded.block.raw",begin:"@(raw|verbatim)\\b",beginCaptures:{0:{name:"keyword.control.stx"}},end:"@end(raw|verbatim)\\b",endCaptures:{0:{name:"keyword.control.stx"}},contentName:"string.unquoted.raw"},{name:"entity.name.function.stx",match:"@[a-zA-Z_][a-zA-Z0-9_]*"}]},html:{patterns:[{name:"meta.tag.html",begin:"<([a-zA-Z0-9:-]+)",beginCaptures:{0:{name:"punctuation.definition.tag.begin.html"},1:{name:"entity.name.tag.html"}},end:"(/>)|(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.html"},2:{name:"punctuation.definition.tag.end.html"}},patterns:[{name:"entity.other.attribute-name.html",match:"[a-zA-Z-:@]+"},{name:"string.quoted.double.html",begin:'"',end:'"',patterns:[{include:"#stx-echo"}]},{name:"string.quoted.single.html",begin:"'",end:"'",patterns:[{include:"#stx-echo"}]}]},{name:"meta.tag.html",begin:"(</)([a-zA-Z0-9:-]+)",beginCaptures:{1:{name:"punctuation.definition.tag.begin.html"},2:{name:"entity.name.tag.html"}},end:"(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.html"}}},{name:"comment.block.html",begin:"<!--",end:"-->"}]}}},hy={name:"TypeScript",scopeName:"source.ts",keywords:{if:"keyword.control.ts",else:"keyword.control.ts",switch:"keyword.control.ts",case:"keyword.control.ts",default:"keyword.control.ts",for:"keyword.control.ts",while:"keyword.control.ts",do:"keyword.control.ts",break:"keyword.control.ts",continue:"keyword.control.ts",return:"keyword.control.ts",try:"keyword.control.ts",catch:"keyword.control.ts",finally:"keyword.control.ts",throw:"keyword.control.ts",async:"keyword.control.ts",await:"keyword.control.ts",yield:"keyword.control.ts",const:"storage.type.ts",let:"storage.type.ts",var:"storage.type.ts",function:"storage.type.ts",class:"storage.type.ts",extends:"storage.type.ts",implements:"storage.type.ts",static:"storage.type.ts",type:"storage.type.ts",interface:"storage.type.ts",enum:"storage.type.ts",namespace:"storage.type.ts",module:"storage.type.ts",declare:"storage.type.ts",public:"storage.type.ts",private:"storage.type.ts",protected:"storage.type.ts",readonly:"storage.type.ts",abstract:"storage.type.ts",string:"storage.type.ts",number:"storage.type.ts",boolean:"storage.type.ts",any:"storage.type.ts",void:"storage.type.ts",never:"storage.type.ts",unknown:"storage.type.ts",object:"storage.type.ts",symbol:"storage.type.ts",bigint:"storage.type.ts",get:"storage.type.ts",set:"storage.type.ts",new:"keyword.operator.new.ts",delete:"keyword.operator.new.ts",typeof:"keyword.operator.new.ts",instanceof:"keyword.operator.new.ts",as:"keyword.operator.new.ts",in:"keyword.operator.new.ts",of:"keyword.operator.new.ts",is:"keyword.operator.new.ts",keyof:"keyword.operator.new.ts",infer:"keyword.operator.new.ts",true:"constant.language.ts",false:"constant.language.ts",null:"constant.language.ts",undefined:"constant.language.ts",NaN:"constant.language.ts",Infinity:"constant.language.ts",this:"constant.language.ts",super:"constant.language.ts",arguments:"constant.language.ts",import:"keyword.other.ts",export:"keyword.other.ts",from:"keyword.other.ts",require:"keyword.other.ts",with:"keyword.other.ts",debugger:"keyword.other.ts"},patterns:[{include:"#comments"},{include:"#strings"},{include:"#jsx"},{include:"#regex"},{include:"#keywords"},{include:"#numbers"},{include:"#functions"},{include:"#types"},{include:"#operators"},{include:"#punctuation"}],repository:{comments:{patterns:[{name:"comment.line.double-slash.ts",match:"\\/\\/.*$"},{name:"comment.block.ts",begin:"\\/\\*",end:"\\*\\/"}]},strings:{patterns:[{name:"string.quoted.double.ts",begin:'"',end:'"',patterns:[{name:"constant.character.escape.ts",match:"\\\\."}]},{name:"string.quoted.single.ts",begin:"'",end:"'",patterns:[{name:"constant.character.escape.ts",match:"\\\\."}]},{name:"string.template.ts",begin:"`",end:"`",patterns:[{name:"meta.template.expression.ts",begin:"\\$\\{",end:"\\}",patterns:[{include:"$self"}]},{name:"constant.character.escape.ts",match:"\\\\."}]}]},jsx:{patterns:[{name:"meta.tag.tsx",begin:"<([A-Z][a-zA-Z0-9]*|[a-z][a-zA-Z0-9-]*)",beginCaptures:{0:{name:"punctuation.definition.tag.begin.tsx"},1:{name:"entity.name.tag.tsx"}},end:"(/?>)",endCaptures:{1:{name:"punctuation.definition.tag.end.tsx"}},patterns:[{name:"entity.other.attribute-name.tsx",match:"[a-zA-Z_:][a-zA-Z0-9_:.-]*"},{name:"meta.embedded.expression.tsx",begin:"\\{",end:"\\}",patterns:[{include:"$self"}]},{name:"string.quoted.double.tsx",begin:'"',end:'"'},{name:"string.quoted.single.tsx",begin:"'",end:"'"}]},{name:"meta.tag.tsx",begin:"(</)([A-Z][a-zA-Z0-9]*|[a-z][a-zA-Z0-9-]*)",beginCaptures:{1:{name:"punctuation.definition.tag.begin.tsx"},2:{name:"entity.name.tag.tsx"}},end:"(>)",endCaptures:{1:{name:"punctuation.definition.tag.end.tsx"}}}]},regex:{patterns:[{name:"string.regexp.ts",begin:"(?<=[=(,\\[!&|?{};:])\\s*(\\/)",beginCaptures:{1:{name:"punctuation.definition.string.begin.ts"}},end:"(\\/)[gimsuvy]*",endCaptures:{1:{name:"punctuation.definition.string.end.ts"}},patterns:[{name:"constant.character.escape.ts",match:"\\\\."}]}]},numbers:{patterns:[{name:"constant.numeric.ts",match:"\\b(0[xX][0-9a-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|\\d+(_\\d+)*(\\.\\d+(_\\d+)?)?([eE][+-]?\\d+)?)[nN]?\\b"}]},types:{patterns:[{name:"storage.type.ts",match:"\\b(string|number|boolean|any|void|never|unknown|object|symbol|bigint)\\b"},{name:"entity.name.type.ts",match:":\\s*([A-Z][a-zA-Z0-9_]*)"},{name:"meta.type.annotation.ts",match:"<[^>]+>"}]},keywords:{patterns:[{name:"keyword.control.ts",match:"\\b(if|else|switch|case|default|for|while|do|break|continue|return|try|catch|finally|throw|async|await|yield)\\b"},{name:"storage.type.ts",match:"\\b(const|let|var|function|class|extends|implements|static|async|type|interface|enum|namespace|module|declare|public|private|protected|readonly|abstract|get|set)\\b"},{name:"keyword.operator.new.ts",match:"\\b(new|delete|typeof|instanceof|void|as|in|of|is|keyof|infer)\\b"},{name:"constant.language.ts",match:"\\b(true|false|null|undefined|NaN|Infinity|this|super|arguments)\\b"},{name:"keyword.other.ts",match:"\\b(import|export|from|default|require|with|debugger)\\b"}]},functions:{patterns:[{name:"entity.name.function.ts",match:"\\b([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*(?=\\()"}]},operators:{patterns:[{name:"keyword.operator.ts",match:"(\\+\\+|--|\\+|\\-|\\*|\\/|%|===|==|!==|!=|<=|>=|<|>|&&|\\|\\||!|\\?|:|=>|\\.\\.\\.|&|\\||\\^|~|<<|>>|>>>)"}]},punctuation:{patterns:[{name:"punctuation.ts",match:"[{}()\\[\\];,.]"}]}}},mw=[{id:"javascript",name:"JavaScript",aliases:["js","jsx"],extensions:[".js",".jsx",".mjs",".cjs"],grammar:Cy},{id:"typescript",name:"TypeScript",aliases:["ts","tsx"],extensions:[".ts",".tsx",".mts",".cts"],grammar:hy},{id:"html",name:"HTML",aliases:["htm"],extensions:[".html",".htm"],grammar:Dy},{id:"css",name:"CSS",aliases:[],extensions:[".css"],grammar:Ey},{id:"json",name:"JSON",aliases:[],extensions:[".json",".jsonc"],grammar:vy},{id:"stx",name:"STX",aliases:[],extensions:[".stx"],grammar:dy}];S=new Uint8Array(256);for(let $=65;$<=90;$++)S[$]=1;for(let $=97;$<=122;$++)S[$]=1;S[95]=1;S[36]=1;for(let $=48;$<=57;$++)S[$]=2;S[43]=4;S[45]=4;S[42]=4;S[47]=4;S[61]=4;S[33]=4;S[60]=4;S[62]=4;S[38]=4;S[124]=4;S[37]=4;S[63]=4;S[58]=4;S[46]=4;S[123]=8;S[125]=8;S[40]=8;S[41]=8;S[91]=8;S[93]=8;S[59]=8;S[44]=8;S[34]=16;S[39]=16;S[96]=16;S[32]=32;S[9]=32;S[10]=32;S[13]=32;xy={name:"GitHub Dark",type:"dark",colors:{"editor.background":"#0d1117","editor.foreground":"#c9d1d9","editor.lineHighlightBackground":"#161b22","editor.selectionBackground":"#264f78"},tokenColors:[{name:"Comment",scope:["comment","comment.line","comment.block"],settings:{foreground:"#8b949e",fontStyle:"italic"}},{name:"String",scope:["string","string.quoted"],settings:{foreground:"#a5d6ff"}},{name:"Template String",scope:["string.template"],settings:{foreground:"#a5d6ff"}},{name:"Number",scope:["constant.numeric"],settings:{foreground:"#79c0ff"}},{name:"Keyword",scope:["keyword","keyword.control","keyword.operator"],settings:{foreground:"#ff7b72"}},{name:"Storage Type",scope:["storage.type","storage.modifier"],settings:{foreground:"#ff7b72"}},{name:"Function",scope:["entity.name.function","support.function"],settings:{foreground:"#d2a8ff"}},{name:"Class",scope:["entity.name.type","entity.name.class"],settings:{foreground:"#ffa657"}},{name:"Variable",scope:["variable","variable.other"],settings:{foreground:"#ffa657"}},{name:"Constant",scope:["constant.language","constant.character"],settings:{foreground:"#79c0ff"}},{name:"Tag",scope:["entity.name.tag"],settings:{foreground:"#7ee787"}},{name:"Attribute",scope:["entity.other.attribute-name"],settings:{foreground:"#79c0ff"}},{name:"Punctuation",scope:["punctuation"],settings:{foreground:"#c9d1d9"}},{name:"Operator",scope:["keyword.operator"],settings:{foreground:"#ff7b72"}},{name:"CSS Property",scope:["support.type.property-name.css"],settings:{foreground:"#79c0ff"}},{name:"CSS Value",scope:["support.constant.property-value.css"],settings:{foreground:"#a5d6ff"}},{name:"Color",scope:["constant.other.color"],settings:{foreground:"#a5d6ff"}}]},uy={name:"GitHub Light",type:"light",colors:{"editor.background":"#ffffff","editor.foreground":"#24292f","editor.lineHighlightBackground":"#f6f8fa","editor.selectionBackground":"#b6d4fe"},tokenColors:[{name:"Comment",scope:["comment","comment.line","comment.block"],settings:{foreground:"#6e7781",fontStyle:"italic"}},{name:"String",scope:["string","string.quoted"],settings:{foreground:"#0a3069"}},{name:"Template String",scope:["string.template"],settings:{foreground:"#0a3069"}},{name:"Number",scope:["constant.numeric"],settings:{foreground:"#0550ae"}},{name:"Keyword",scope:["keyword","keyword.control","keyword.operator"],settings:{foreground:"#cf222e"}},{name:"Storage Type",scope:["storage.type","storage.modifier"],settings:{foreground:"#cf222e"}},{name:"Function",scope:["entity.name.function","support.function"],settings:{foreground:"#8250df"}},{name:"Class",scope:["entity.name.type","entity.name.class"],settings:{foreground:"#953800"}},{name:"Variable",scope:["variable","variable.other"],settings:{foreground:"#953800"}},{name:"Constant",scope:["constant.language","constant.character"],settings:{foreground:"#0550ae"}},{name:"Tag",scope:["entity.name.tag"],settings:{foreground:"#116329"}},{name:"Attribute",scope:["entity.other.attribute-name"],settings:{foreground:"#0550ae"}},{name:"Punctuation",scope:["punctuation"],settings:{foreground:"#24292f"}},{name:"Operator",scope:["keyword.operator"],settings:{foreground:"#cf222e"}},{name:"CSS Property",scope:["support.type.property-name.css"],settings:{foreground:"#0550ae"}},{name:"CSS Value",scope:["support.constant.property-value.css"],settings:{foreground:"#0a3069"}},{name:"Color",scope:["constant.other.color"],settings:{foreground:"#0a3069"}}]},my={name:"Nord",type:"dark",colors:{"editor.background":"#2e3440","editor.foreground":"#d8dee9","editor.lineHighlightBackground":"#3b4252","editor.selectionBackground":"#434c5e"},tokenColors:[{name:"Comment",scope:["comment","comment.line","comment.block"],settings:{foreground:"#616e88",fontStyle:"italic"}},{name:"String",scope:["string","string.quoted"],settings:{foreground:"#a3be8c"}},{name:"Template String",scope:["string.template"],settings:{foreground:"#a3be8c"}},{name:"Number",scope:["constant.numeric"],settings:{foreground:"#b48ead"}},{name:"Keyword",scope:["keyword","keyword.control","keyword.operator"],settings:{foreground:"#81a1c1"}},{name:"Storage Type",scope:["storage.type","storage.modifier"],settings:{foreground:"#81a1c1"}},{name:"Function",scope:["entity.name.function","support.function"],settings:{foreground:"#88c0d0"}},{name:"Class",scope:["entity.name.type","entity.name.class"],settings:{foreground:"#8fbcbb"}},{name:"Variable",scope:["variable","variable.other"],settings:{foreground:"#d8dee9"}},{name:"Constant",scope:["constant.language","constant.character"],settings:{foreground:"#b48ead"}},{name:"Tag",scope:["entity.name.tag"],settings:{foreground:"#81a1c1"}},{name:"Attribute",scope:["entity.other.attribute-name"],settings:{foreground:"#8fbcbb"}},{name:"Punctuation",scope:["punctuation"],settings:{foreground:"#eceff4"}},{name:"Operator",scope:["keyword.operator"],settings:{foreground:"#81a1c1"}},{name:"CSS Property",scope:["support.type.property-name.css"],settings:{foreground:"#8fbcbb"}},{name:"CSS Value",scope:["support.constant.property-value.css"],settings:{foreground:"#a3be8c"}},{name:"Color",scope:["constant.other.color"],settings:{foreground:"#b48ead"}}]},nw=[xy,uy,my];G=new Uint8Array(256);for(let $=65;$<=90;$++)G[$]=1;for(let $=97;$<=122;$++)G[$]=1;G[95]=1;G[36]=1;for(let $=48;$<=57;$++)G[$]=2;G[43]=4;G[45]=4;G[42]=4;G[47]=4;G[61]=4;G[33]=4;G[60]=4;G[62]=4;G[38]=4;G[124]=4;G[37]=4;G[63]=4;G[58]=4;G[46]=4;G[123]=8;G[125]=8;G[40]=8;G[41]=8;G[91]=8;G[93]=8;G[59]=8;G[44]=8;G[34]=16;G[39]=16;G[96]=16;G[32]=32;G[9]=32;G[10]=32;G[13]=32;E5=new rw(!1)});import{existsSync as A2,mkdirSync as v5,readdirSync as d5,writeFileSync as h5}from"fs";import{homedir as L$}from"os";import{dirname as u5,resolve as z0}from"path";import $1 from"process";import{join as ny,relative as py,resolve as sw}from"path";import M1 from"process";import{existsSync as g2,mkdirSync as c5,readdirSync as r5,writeFileSync as l5}from"fs";import{dirname as o5,resolve as E1}from"path";import V$ from"process";import{Buffer as f0}from"buffer";import{createCipheriv as cy,createDecipheriv as ry,randomBytes as O$}from"crypto";import{closeSync as H$,createReadStream as ow,createWriteStream as ly,existsSync as R$,fsyncSync as aw,openSync as ew,writeFileSync as sy}from"fs";import{access as oy,constants as tw,mkdir as ay,readdir as G1,rename as $2,stat as v0,unlink as I1,writeFile as f$}from"fs/promises";import{join as d0}from"path";import l from"process";import{pipeline as ey}from"stream/promises";import{createGzip as w2}from"zlib";import h0 from"process";import N0 from"process";function S$($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&P(w[0])&&"id"in w[0]&&w[0].id===3&&P(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(P(w)&&P($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(P($)&&"arr"in $&&Array.isArray($.arr)&&P(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&P(w[0])&&P($[0])){let j=[...w];for(let z of $)if(P(z)&&"name"in z){if(!j.find((g)=>P(g)&&("name"in g)&&g.name===z.name))j.push(z)}else if(P(z)&&"path"in z){if(!j.find((g)=>P(g)&&("path"in g)&&g.path===z.path))j.push(z)}else if(!j.some((A)=>D1(A,z)))j.push(z);return j}if(w.every((j)=>typeof j==="string")&&$.every((j)=>typeof j==="string")){let j=[...w];for(let z of $)if(!j.includes(z))j.push(z);return j}return w}if(!P(w)||!P($))return w;let y={...$};for(let j in w)if(Object.prototype.hasOwnProperty.call(w,j)){let z=w[j];if(z===null||z===void 0)continue;else if(P(z)&&P(y[j]))y[j]=S$(y[j],z);else if(Array.isArray(z)&&Array.isArray(y[j]))if(z.length>0&&y[j].length>0&&P(z[0])&&P(y[j][0])){let A=[...z];for(let g of y[j])if(P(g)&&"name"in g){if(!A.find((X)=>P(X)&&("name"in X)&&X.name===g.name))A.push(g)}else if(P(g)&&"path"in g){if(!A.find((X)=>P(X)&&("path"in X)&&X.path===g.path))A.push(g)}else if(!A.some((J)=>D1(J,g)))A.push(g);y[j]=A}else if(z.every((A)=>typeof A==="string")&&y[j].every((A)=>typeof A==="string")){let A=[...z];for(let g of y[j])if(!A.includes(g))A.push(g);y[j]=A}else y[j]=z;else y[j]=z}return y}function D1($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let y=0;y<$.length;y++)if(!D1($[y],w[y]))return!1;return!0}if(P($)&&P(w)){let y=Object.keys($),j=Object.keys(w);if(y.length!==j.length)return!1;for(let z of y){if(!Object.prototype.hasOwnProperty.call(w,z))return!1;if(!D1($[z],w[z]))return!1}return!0}return!1}function P($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function ty($,w){if(!g2($))return null;try{let y=await import($),j=y.default||y;if(typeof j!=="object"||j===null||Array.isArray(j))return null;try{return S$(w,j)}catch{return null}}catch{return null}}async function $8({name:$="",cwd:w,defaultConfig:y}){let j=w||V$.cwd(),z=[".ts",".js",".mjs",".cjs",".json"],A=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let g of A)for(let J of z){let X=E1(j,`${g}${J}`),Y=await ty(X,y);if(Y!==null)return Y}try{let g=E1(j,"package.json");if(g2(g)){let X=(await import(g))[$];if(X&&typeof X==="object"&&!Array.isArray(X))try{return S$(y,X)}catch{}}}catch{}return y}function w8($,w={}){let y=M1.cwd();while(y.includes("storage"))y=sw(y,"..");let j=sw(y,$||"");if(w?.relative)return py(M1.cwd(),j);return j}async function j8(){try{let $=await $8({name:"clarity",defaultConfig:k$,cwd:M1.cwd(),endpoint:"",headers:{}});return{...k$,...$}}catch{return k$}}function u(){if(N0.env.NODE_ENV==="test"||N0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function z8(){if(N0.env.NODE_ENV==="test"||N0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof N0<"u"){let $=N0.type;if($==="renderer"||$==="worker")return!1;return!!(N0.versions&&(N0.versions.node||N0.versions.bun))}return!1}class J2{async format($){let w=await z8(),y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:h0.pid,hostname:w(),environment:h0.env.NODE_ENV||"development",platform:h0.platform,version:h0.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:h0.env.NODE_ENV||h0.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class v1{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...y2},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new J2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??l.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let y={...w},j=w.timestamp!==void 0;if(j)delete y.timestamp;if(this.config={...this.config,...y,timestamp:j||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let z=this.generateKeyId(),A=this.generateKey();this.currentKeyId=z,this.keys.set(z,A),this.encryptionKeys.set(z,{key:A,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...F$,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...F$};return{...F$,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:y2.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},y={...w,...Object.fromEntries(Object.entries($).filter(([,j])=>j!==void 0))};if(!y.level||!["debug","info","success","warning","error"].includes(y.level))y.level=w.level;return y}async writeToFile($){let y=(async()=>{let z,A=0,g=3,J=1000;while(A<g)try{try{try{await oy(this.config.logDirectory,tw.F_OK|tw.W_OK)}catch(Y){if(Y instanceof Error&&"code"in Y)if(Y.code==="ENOENT")await ay(this.config.logDirectory,{recursive:!0,mode:493});else if(Y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Y;else throw Y}}catch(Y){throw console.error("Debug: [writeToFile] Failed to create log directory:",Y),Y}let X=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:f0.from($);try{if(!R$(this.currentLogFile))await f$(this.currentLogFile,"",{mode:420});if(z=ew(this.currentLogFile,"a",420),sy(z,X,{flag:"a"}),aw(z),z!==void 0)H$(z),z=void 0;if((await v0(this.currentLogFile)).size===0){if(await f$(this.currentLogFile,X,{flag:"w",mode:420}),(await v0(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Y){let U=Y;if(U.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(U.code)){if(A<g-1){let B=typeof U.message==="string"?U.message:"Unknown error";console.error(`Network error during write attempt ${A+1}/${g}:`,B);let b=J*2**A;await new Promise((Q)=>setTimeout(Q,b)),A++;continue}}if(U?.code&&["ENOSPC","EDQUOT"].includes(U.code))throw Error(`Disk quota exceeded or no space left on device: ${U.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",U),U}finally{if(z!==void 0)try{H$(z)}catch(Y){console.error("Debug: [writeToFile] Error closing file descriptor:",Y)}}}catch(X){if(A===g-1){let U=X,B=typeof U.message==="string"?U.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),X}A++;let Y=J*2**(A-1);await new Promise((U)=>setTimeout(U,Y))}})();this.pendingOperations.push(y);let j=this.pendingOperations.length-1;try{await y}catch(z){throw console.error("Debug: [writeToFile] Error in operation:",z),z}finally{this.pendingOperations.splice(j,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return d0(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return d0(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return d0(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(u())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let y=typeof w.interval==="number"?w.interval:60,j=Math.max(y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((z)=>{console.error("Error rotating keys:",z)})},j)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,y=this.generateKeyId(),j=this.generateKey();this.currentKeyId=y,this.keys.set(y,j),this.encryptionKeys.set(y,{key:j,createdAt:new Date});let z=Array.from(this.encryptionKeys.entries()).sort(([,J],[,X])=>X.createdAt.getTime()-J.createdAt.getTime()),A=typeof w.maxKeys==="number"?w.maxKeys:1,g=Math.max(1,A);if(z.length>g)for(let[J]of z.slice(g))this.encryptionKeys.delete(J),this.keys.delete(J)}generateKeyId(){return O$(16).toString("hex")}generateKey(){return O$(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),y=O$(16),j=cy("aes-256-gcm",w,y),z=f0.concat([j.update($,"utf8"),j.final()]),A=j.getAuthTag();return{encrypted:f0.concat([y,z,A]),iv:y}}async compressData($){return new Promise((w,y)=>{let j=w2(),z=[];j.on("data",(A)=>z.push(A)),j.on("end",()=>w(f0.from(f0.concat(z)))),j.on("error",y),j.write($),j.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(u())return;let $=await v0(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let y=this.currentLogFile,j=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let z=await G1(this.config.logDirectory),A=z.filter((X)=>X.startsWith(this.name)&&/\.log\.\d+$/.test(X)).sort((X,Y)=>{let U=Number.parseInt(X.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Y.match(/\.log\.(\d+)$/)?.[1]||"0")-U}),g=A.length>0?Number.parseInt(A[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,J=`${y}.${g}`;if(await v0(y).catch(()=>null))try{if(await $2(y,J),w.compress)try{let X=`${J}.gz`;await this.compressLogFile(J,X),await I1(J)}catch(X){console.error("Error compressing rotated file:",X)}if(A.length===0&&!z.some((X)=>X.endsWith(".log.1")))try{let X=`${y}.1`;await f$(X,"")}catch(X){console.error("Error creating backup file:",X)}}catch(X){console.error(`Error during rotation: ${X instanceof Error?X.message:String(X)}`)}}else{let z=new Date().toISOString().replace(/[:.]/g,"-"),A=y.replace(/\.log$/,`-${z}.log`);if(await v0(y).catch(()=>null))await $2(y,A)}if(this.currentLogFile=j,w.maxFiles){let A=(await G1(this.config.logDirectory)).filter((g)=>g.startsWith(this.name)).sort((g,J)=>J.localeCompare(g));for(let g of A.slice(w.maxFiles))await I1(d0(this.config.logDirectory,g))}}}async compressLogFile($,w){let y=ow($),j=ly(w),z=w2();await ey(y,z,j)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let y of this.logBuffer){let j=await this.formatter.format(y);await this.writeToFile(j),console.log(j)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),R$(this.currentLogFile))try{let $=ew(this.currentLogFile,"r+");aw($),H$($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!u()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await G1(this.config.logDirectory)).filter((y)=>(y.includes("temp")||y.includes(".tmp"))&&y.includes(this.name));for(let y of w)try{await I1(d0(this.config.logDirectory,y))}catch(j){console.error(`Failed to delete temp file ${y}:`,j)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?h.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:y="",tag:j="",message:z,level:A,showTimestamp:g=!0}=$,J=(Q)=>Q.replace(this.ANSI_PATTERN,"");if(!this.fancy){let Q=[];if(g)Q.push(w);if(A==="warning")Q.push("WARN");else if(A==="error")Q.push("ERROR");else if(y)Q.push(y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(j)Q.push(j.replace(/[[\]]/g,""));return Q.push(z),Q.join(" ")}let X=l.stdout.columns||120,Y="";if(A==="warning"||A==="error")Y=`${y} ${z}`;else if(A==="info"||A==="success")Y=`${y} ${j} ${z}`;else Y=`${y} ${j} ${h.cyan(z)}`;if(!g)return Y.trim();let U=J(Y).trim().length,B=J(w).length,b=Math.max(1,X-2-U-B);return`${Y.trim()}${" ".repeat(b)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(A,g)=>{let J=Number.parseInt(g,10);return J<w[0].length?String(w[0][J]):A});let y=/%([sdijfo%])/g,j=0,z=$.replace(y,(A,g)=>{if(g==="%")return"%";if(j>=w.length)return A;let J=w[j++];switch(g){case"s":return String(J);case"d":case"i":return Number(J).toString();case"j":case"o":return JSON.stringify(J,null,2);default:return A}});if(j<w.length)z+=` ${w.slice(j).map((A)=>typeof A==="object"?JSON.stringify(A,null,2):String(A)).join(" ")}`;return z}async log($,w,...y){let j=new Date,z=this.formatConsoleTimestamp(j),A=this.formatFileTimestamp(j),g,J;if(w instanceof Error)g=w.message,J=w.stack;else g=this.formatMessage(w,y);if(this.fancy&&!u()){let Y=Y8[$],U=this.options.showTags!==!1&&this.name?h.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:h.gray(g),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:g,level:$}),console.error(B);break;case"success":B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:h.green(g),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:g,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:z,icon:Y,tag:U,message:g,level:$}),console.error(B),J){let b=J.split(`
456
+ `);for(let Q of b)if(Q.trim()&&!Q.includes(g))console.error(this.formatConsoleMessage({timestamp:z,message:h.gray(` ${Q}`),level:$,showTimestamp:!1}))}break}}else if(!u()){if(console.error(`${A} ${this.environment}.${$.toUpperCase()}: ${g}`),J)console.error(J)}if(!this.shouldLog($))return;let X=`${A} ${this.environment}.${$.toUpperCase()}: ${g}
457
457
  `;if(J)X+=`${J}
458
- `;X=X.replace(this.ANSI_PATTERN,""),await this.writeToFile(X)}time($){let w=performance.now();if(this.fancy&&!u()){let y=this.options.showTags!==!1&&this.name?h.gray(this.formatTag(this.name)):"",j=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:j,icon:h.blue("\u25D0"),tag:y,message:`${h.cyan($)}...`}))}return async(y)=>{if(!this.enabled)return;let j=performance.now(),z=Math.round(j-w),g=`${$} completed in ${z}ms`,A=new Date,J=this.formatConsoleTimestamp(A),Y=`${this.formatFileTimestamp(A)} ${this.environment}.INFO: ${g}`;if(y)Y+=` ${JSON.stringify(y)}`;if(Y+=`
459
- `,Y=Y.replace(this.ANSI_PATTERN,""),this.fancy&&!u()){let U=this.options.showTags!==!1&&this.name?h.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:J,icon:h.green("\u2713"),tag:U,message:`${g}${y?` ${JSON.stringify(y)}`:""}`}))}else if(!u())console.error(Y.trim());await this.writeToFile(Y)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,y=new v1(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(y),y}createReadStream(){if(u())throw Error("createReadStream is not supported in browser environments");if(!O$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return cw(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let y=this.keys.get(this.currentKeyId);try{let j=H0.isBuffer($)?$:H0.from($,"base64"),z=j.slice(0,16),g=j.slice(-16),A=j.slice(16,-16),J=m9("aes-256-gcm",y,z);return J.setAuthTag(g),H0.concat([J.update(A),J.final()]).toString("utf8")}catch(j){throw Error(`Decryption failed: ${j instanceof Error?j.message:String(j)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return u()}isServerMode(){return!u()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,y=this.formatConsoleTimestamp(w),j=this.formatFileTimestamp(w);if(this.fancy&&!u()){let g=$.split(`
460
- `),A=Math.max(...g.map((U)=>U.length))+2,J=`\u250C${"\u2500".repeat(A)}\u2510`,X=`\u2514${"\u2500".repeat(A)}\u2518`,Y=g.map((U)=>{let B=" ".repeat(A-U.length-2);return`\u2502 ${U}${B} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:y,message:h.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:y,message:h.cyan(J)})),Y.forEach((U)=>console.error(this.formatConsoleMessage({timestamp:y,message:h.cyan(U),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:y,message:h.cyan(X),showTimestamp:!1}))}else if(!u())console.error(`${j} ${this.environment}.INFO: [BOX] ${$}`);let z=`${j} ${this.environment}.INFO: [BOX] ${$}
461
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(z)}async prompt($){if(u())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${h.cyan("?")} ${$} (y/n) `);let y=(j)=>{let z=j.toString().trim().toLowerCase();a.stdin.removeListener("data",y);try{if(typeof a.stdin.setRawMode==="function")a.stdin.setRawMode(!1)}catch{}a.stdin.pause(),console.error(""),w(z==="y"||z==="yes")};try{if(typeof a.stdin.setRawMode==="function")a.stdin.setRawMode(!0)}catch{}a.stdin.resume(),a.stdin.once("data",y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let y=$;if(w&&w.length>0){let A=/%([sdijfo%])/g,J=0;if(y=$.replace(A,(X,Y)=>{if(Y==="%")return"%";if(J>=w.length)return X;let U=w[J++];switch(Y){case"s":return String(U);case"d":case"i":return Number(U).toString();case"j":case"o":return JSON.stringify(U,null,2);default:return X}}),J<w.length)y+=` ${w.slice(J).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`}if(this.fancy&&!u()){let A=this.options.showTags!==!1&&this.name?h.gray(this.formatTag(this.name)):"",J=h.blue("\u25D0");console.error(`${J} ${A} ${h.cyan(y)}`)}let g=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${y}
462
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(g)}progress($,w=""){if(!this.enabled||!this.fancy||u()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let y=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(A,J)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||u())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,A)),J!==void 0)this.activeProgressBar.message=J;let X=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,X)},finish:(A)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||u())return;if(this.activeProgressBar.current=this.activeProgressBar.total,A!==void 0)this.activeProgressBar.message=A;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(A,J="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||u())return;a.stdout.write(`${"\r".padEnd(a.stdout.columns||80)}\r`),this.log(J,A),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||u()||!a.stdout.isTTY)return;let y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),j=Math.round($.barLength*y/100),z=$.barLength-j,g=h.green("\u2501".repeat(j)),A=h.gray("\u2501".repeat(z)),J=`[${g}${A}]`,X=`${y}%`.padStart(4),Y=$.message?` ${$.message}`:"",U=w||y===100?h.green("\u2713"):h.blue("\u25B6"),B=this.options.showTags!==!1&&this.name?` ${h.gray(this.formatTag(this.name))}`:"",b=`\r${U}${B} ${J} ${X}${Y}`,Q=a.stdout.columns||80,K=" ".repeat(Math.max(0,Q-b.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${b}${K}`,a.stdout.write($.lastRenderedLine),w)a.stdout.write(`
463
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||u()||!a.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(u()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await I1(this.config.logDirectory),y=[];for(let j of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(j):j.startsWith(this.name))||!j.endsWith(".log"))continue;let g=d0(this.config.logDirectory,j);if($.before)try{if((await v0(g)).mtime>=$.before)continue}catch(A){console.error(`Failed to get stats for file ${g}:`,A);continue}y.push(g)}if(y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${y.length} log file(s)...`);for(let j of y)try{await G1(j),console.warn(`Deleted log file: ${j}`)}catch(z){console.error(`Failed to delete log file ${j}:`,z)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function Z1($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&C(w[0])&&"id"in w[0]&&w[0].id===3&&C(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(C(w)&&C($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(C($)&&"arr"in $&&Array.isArray($.arr)&&C(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&C(w[0])&&C($[0])){let j=[...w];for(let z of $)if(C(z)&&"name"in z){if(!j.find((A)=>C(A)&&("name"in A)&&A.name===z.name))j.push(z)}else if(C(z)&&"path"in z){if(!j.find((A)=>C(A)&&("path"in A)&&A.path===z.path))j.push(z)}else if(!j.some((g)=>C1(g,z)))j.push(z);return j}if(w.every((j)=>typeof j==="string")&&$.every((j)=>typeof j==="string")){let j=[...w];for(let z of $)if(!j.includes(z))j.push(z);return j}return w}if(!C(w)||!C($))return w;let y={...$};for(let j in w)if(Object.prototype.hasOwnProperty.call(w,j)){let z=w[j];if(z===null||z===void 0)continue;else if(C(z)&&C(y[j]))y[j]=Z1(y[j],z);else if(Array.isArray(z)&&Array.isArray(y[j]))if(z.length>0&&y[j].length>0&&C(z[0])&&C(y[j][0])){let g=[...z];for(let A of y[j])if(C(A)&&"name"in A){if(!g.find((X)=>C(X)&&("name"in X)&&X.name===A.name))g.push(A)}else if(C(A)&&"path"in A){if(!g.find((X)=>C(X)&&("path"in X)&&X.path===A.path))g.push(A)}else if(!g.some((J)=>C1(J,A)))g.push(A);y[j]=g}else if(z.every((g)=>typeof g==="string")&&y[j].every((g)=>typeof g==="string")){let g=[...z];for(let A of y[j])if(!g.includes(A))g.push(A);y[j]=g}else y[j]=z;else y[j]=z}return y}function S$($,w,y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return y==="replace"?w:Z1($,w);if(Array.isArray($))return y==="replace"?w:Z1($,w);if(!C(w)||!C($))return w;let j={...$};for(let z of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,z))continue;let g=w[z],A=j[z];if(g===null||g===void 0)continue;if(Array.isArray(g)||Array.isArray(A))if(y==="replace")j[z]=g;else j[z]=Z1(A,g);else if(C(g)&&C(A))j[z]=S$(A,g,y);else j[z]=g}return j}function C1($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let y=0;y<$.length;y++)if(!C1($[y],w[y]))return!1;return!0}if(C($)&&C(w)){let y=Object.keys($),j=Object.keys(w);if(y.length!==j.length)return!1;for(let z of y){if(!Object.prototype.hasOwnProperty.call(w,z))return!1;if(!C1($[z],w[z]))return!1}return!0}return!1}function C($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function T1($,w,y="replace"){if(!y2($))return null;try{let j=await import($),z=j.default||j;if(typeof z!=="object"||z===null||Array.isArray(z))return null;try{return S$(w,z,y)}catch{return null}}catch{return null}}function z8($,w,y=!1){if(!$)return w;let j=$.toUpperCase().replace(/-/g,"_"),z={...w};function g(A,J=[]){let X={...A};for(let[Y,U]of Object.entries(A)){let B=[...J,Y],b=(_)=>_.replace(/([A-Z])/g,"_$1").toUpperCase(),Q=`${j}_${B.map(b).join("_")}`,K=`${j}_${B.map((_)=>_.toUpperCase()).join("_")}`;if(y)w0.info(`Checking environment variable ${Q} for config ${$}.${B.join(".")}`);if(typeof U==="object"&&U!==null&&!Array.isArray(U))X[Y]=g(U,B);else{let _=$1.env[Q]||$1.env[K];if(_!==void 0){if(y)w0.info(`Using environment variable ${_?Q:K} for config ${$}.${B.join(".")}`);if(typeof U==="number")X[Y]=Number(_);else if(typeof U==="boolean")X[Y]=_.toLowerCase()==="true";else if(Array.isArray(U))try{let W=JSON.parse(_);if(Array.isArray(W))X[Y]=W;else X[Y]=_.split(",").map((L)=>L.trim())}catch{X[Y]=_.split(",").map((W)=>W.trim())}else X[Y]=_}}}return X}return g(z)}async function z2({name:$="",alias:w,cwd:y,configDir:j,defaultConfig:z,verbose:g=!1,checkEnv:A=!0,arrayStrategy:J="replace"}){let X=A&&typeof z==="object"&&z!==null&&!Array.isArray(z)?z8($,z,g):z,Y=y||$1.cwd(),U=[".ts",".js",".mjs",".cjs",".json"];if(g)w0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${Y}`);let B=[$,`.${$}`].filter(Boolean),b=[`${$}.config`,`.${$}.config`].filter(Boolean),Q=w?[w,`.${w}`]:[],K=w?[`${w}.config`,`.${w}.config`]:[],_=Array.from(new Set([Y,g0(Y,"config"),g0(Y,".config"),j?g0(Y,j):void 0].filter(Boolean)));for(let W of _){if(g)w0.info(`Searching for configuration in: ${W}`);let N=[g0(Y,"config"),g0(Y,".config")].concat(j?[g0(Y,j)]:[]).includes(W)?[...B,...b,...Q,...K]:[...b,...B,...K,...Q];for(let f of N)for(let O of U){let R=g0(W,`${f}${O}`),H=await T1(R,X,J);if(H!==null){if(g)w0.success(`Configuration loaded from: ${R}`);return H}}}if($){let W=g0(W$(),".config",$),L=["config",`${$}.config`];if(w)L.push(`${w}.config`);if(g)w0.info(`Checking user config directory: ${W}`);for(let N of L)for(let f of U){let O=g0(W,`${N}${f}`),R=await T1(O,X,J);if(R!==null){if(g)w0.success(`Configuration loaded from user config directory: ${O}`);return R}}}if($){let W=g0(W$(),".config"),L=[`.${$}.config`];if(w)L.push(`.${w}.config`);if(g)w0.info(`Checking user config directory for dotfile configs: ${W}`);for(let N of L)for(let f of U){let O=g0(W,`${N}${f}`),R=await T1(O,X,J);if(R!==null){if(g)w0.success(`Configuration loaded from user config directory dotfile: ${O}`);return R}}}if($){let W=W$(),L=[`.${$}.config`,`.${$}`];if(w)L.push(`.${w}.config`),L.push(`.${w}`);if(g)w0.info(`Checking user home directory for dotfile configs: ${W}`);for(let N of L)for(let f of U){let O=g0(W,`${N}${f}`),R=await T1(O,X,J);if(R!==null){if(g)w0.success(`Configuration loaded from user home directory: ${O}`);return R}}}try{let W=g0(Y,"package.json");if(y2(W)){let L=await import(W),N=L[$];if(!N&&w){if(N=L[w],N&&g)w0.success(`Using alias "${w}" configuration from package.json`)}if(N&&typeof N==="object"&&!Array.isArray(N))try{if(g)w0.success(`Configuration loaded from package.json: ${N===L[$]?$:w}`);return S$(X,N,J)}catch(f){if(g)w0.warn("Failed to merge package.json config:",f)}}}catch(W){if(g)w0.warn("Failed to load package.json:",W)}if(g)w0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return X}var wj,yj,a9,H$,tw,y0,h,jj,$8,gj,w8,zj,Aj,$2,Jj,y8,j8,w2,Xj,Yj,Uj,Bj,k$,g8,bj,w0,Qj,Kj;var A2=M(async()=>{wj=M1(F$.cwd(),"config"),yj=M1(F$.cwd(),"src/generated");a9=E1.env.CLARITY_LOG_DIR||P9(o9(),"logs"),H$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:a9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1};tw=await e9();y0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},h=y0,jj=y0.red,$8=y0.green,gj=y0.yellow,w8=y0.blue,zj=y0.magenta,Aj=y0.cyan,$2=y0.white,Jj=y0.gray,y8=y0.bgRed,j8=y0.bgYellow,w2=y0.bold,Xj=y0.dim,Yj=y0.italic,Uj=y0.underline,Bj=y0.reset,k$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},g8={debug:"\uD83D\uDD0D",info:w8("\u2139"),success:$8("\u2713"),warning:j8($2(w2(" WARN "))),error:y8($2(w2(" ERROR ")))};bj=new v1("stacks");w0=new v1("bunfig",{showTags:!0});Qj=g0($1.cwd(),"config"),Kj=g0($1.cwd(),"src/generated")});function X2($){let w=$.trim();for(let y of J2)if(y.test(w))throw Error(`Potentially unsafe expression: ${w}`);return w}function A8($){let w={};w.Math=Math,w.JSON=JSON,w.Date=Date,w.String=String,w.Number=Number,w.Boolean=Boolean,w.Array=Array,w.parseInt=Number.parseInt,w.parseFloat=Number.parseFloat,w.isNaN=Number.isNaN,w.isFinite=Number.isFinite,w.encodeURIComponent=encodeURIComponent,w.decodeURIComponent=decodeURIComponent;for(let[y,j]of Object.entries($)){if(y.startsWith("_")||J2.some((z)=>z.test(y)))continue;if(j&&typeof j==="object"&&!Array.isArray(j))w[y]=I$(j);else w[y]=j}return w}function I$($,w=0){if(w>10)return"[Object too deep]";if($===null||typeof $!=="object")return $;if(Array.isArray($))return $.map((j)=>I$(j,w+1));let y={};for(let[j,z]of Object.entries($)){if(j.startsWith("_")||j==="constructor"||j==="prototype"||j==="__proto__")continue;if(z&&typeof z==="object")y[j]=I$(z,w+1);else y[j]=z}return y}function G$($,w){try{let y=X2($),j=A8(w);return Function(...Object.keys(j),`
458
+ `;X=X.replace(this.ANSI_PATTERN,""),await this.writeToFile(X)}time($){let w=performance.now();if(this.fancy&&!u()){let y=this.options.showTags!==!1&&this.name?h.gray(this.formatTag(this.name)):"",j=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:j,icon:h.blue("\u25D0"),tag:y,message:`${h.cyan($)}...`}))}return async(y)=>{if(!this.enabled)return;let j=performance.now(),z=Math.round(j-w),A=`${$} completed in ${z}ms`,g=new Date,J=this.formatConsoleTimestamp(g),Y=`${this.formatFileTimestamp(g)} ${this.environment}.INFO: ${A}`;if(y)Y+=` ${JSON.stringify(y)}`;if(Y+=`
459
+ `,Y=Y.replace(this.ANSI_PATTERN,""),this.fancy&&!u()){let U=this.options.showTags!==!1&&this.name?h.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:J,icon:h.green("\u2713"),tag:U,message:`${A}${y?` ${JSON.stringify(y)}`:""}`}))}else if(!u())console.error(Y.trim());await this.writeToFile(Y)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,y=new v1(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(y),y}createReadStream(){if(u())throw Error("createReadStream is not supported in browser environments");if(!R$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ow(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let y=this.keys.get(this.currentKeyId);try{let j=f0.isBuffer($)?$:f0.from($,"base64"),z=j.slice(0,16),A=j.slice(-16),g=j.slice(16,-16),J=ry("aes-256-gcm",y,z);return J.setAuthTag(A),f0.concat([J.update(g),J.final()]).toString("utf8")}catch(j){throw Error(`Decryption failed: ${j instanceof Error?j.message:String(j)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return u()}isServerMode(){return!u()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,y=this.formatConsoleTimestamp(w),j=this.formatFileTimestamp(w);if(this.fancy&&!u()){let A=$.split(`
460
+ `),g=Math.max(...A.map((U)=>U.length))+2,J=`\u250C${"\u2500".repeat(g)}\u2510`,X=`\u2514${"\u2500".repeat(g)}\u2518`,Y=A.map((U)=>{let B=" ".repeat(g-U.length-2);return`\u2502 ${U}${B} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:y,message:h.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:y,message:h.cyan(J)})),Y.forEach((U)=>console.error(this.formatConsoleMessage({timestamp:y,message:h.cyan(U),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:y,message:h.cyan(X),showTimestamp:!1}))}else if(!u())console.error(`${j} ${this.environment}.INFO: [BOX] ${$}`);let z=`${j} ${this.environment}.INFO: [BOX] ${$}
461
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(z)}async prompt($){if(u())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${h.cyan("?")} ${$} (y/n) `);let y=(j)=>{let z=j.toString().trim().toLowerCase();l.stdin.removeListener("data",y);try{if(typeof l.stdin.setRawMode==="function")l.stdin.setRawMode(!1)}catch{}l.stdin.pause(),console.error(""),w(z==="y"||z==="yes")};try{if(typeof l.stdin.setRawMode==="function")l.stdin.setRawMode(!0)}catch{}l.stdin.resume(),l.stdin.once("data",y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let y=$;if(w&&w.length>0){let g=/%([sdijfo%])/g,J=0;if(y=$.replace(g,(X,Y)=>{if(Y==="%")return"%";if(J>=w.length)return X;let U=w[J++];switch(Y){case"s":return String(U);case"d":case"i":return Number(U).toString();case"j":case"o":return JSON.stringify(U,null,2);default:return X}}),J<w.length)y+=` ${w.slice(J).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`}if(this.fancy&&!u()){let g=this.options.showTags!==!1&&this.name?h.gray(this.formatTag(this.name)):"",J=h.blue("\u25D0");console.error(`${J} ${g} ${h.cyan(y)}`)}let A=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${y}
462
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(A)}progress($,w=""){if(!this.enabled||!this.fancy||u()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let y=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(g,J)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||u())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,g)),J!==void 0)this.activeProgressBar.message=J;let X=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,X)},finish:(g)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||u())return;if(this.activeProgressBar.current=this.activeProgressBar.total,g!==void 0)this.activeProgressBar.message=g;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(g,J="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||u())return;l.stdout.write(`${"\r".padEnd(l.stdout.columns||80)}\r`),this.log(J,g),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||u()||!l.stdout.isTTY)return;let y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),j=Math.round($.barLength*y/100),z=$.barLength-j,A=h.green("\u2501".repeat(j)),g=h.gray("\u2501".repeat(z)),J=`[${A}${g}]`,X=`${y}%`.padStart(4),Y=$.message?` ${$.message}`:"",U=w||y===100?h.green("\u2713"):h.blue("\u25B6"),B=this.options.showTags!==!1&&this.name?` ${h.gray(this.formatTag(this.name))}`:"",b=`\r${U}${B} ${J} ${X}${Y}`,Q=l.stdout.columns||80,K=" ".repeat(Math.max(0,Q-b.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${b}${K}`,l.stdout.write($.lastRenderedLine),w)l.stdout.write(`
463
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||u()||!l.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(u()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await G1(this.config.logDirectory),y=[];for(let j of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(j):j.startsWith(this.name))||!j.endsWith(".log"))continue;let A=d0(this.config.logDirectory,j);if($.before)try{if((await v0(A)).mtime>=$.before)continue}catch(g){console.error(`Failed to get stats for file ${A}:`,g);continue}y.push(A)}if(y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${y.length} log file(s)...`);for(let j of y)try{await I1(j),console.warn(`Deleted log file: ${j}`)}catch(z){console.error(`Failed to delete log file ${j}:`,z)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function Z1($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&D(w[0])&&"id"in w[0]&&w[0].id===3&&D(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(D(w)&&D($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(D($)&&"arr"in $&&Array.isArray($.arr)&&D(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&D(w[0])&&D($[0])){let j=[...w];for(let z of $)if(D(z)&&"name"in z){if(!j.find((g)=>D(g)&&("name"in g)&&g.name===z.name))j.push(z)}else if(D(z)&&"path"in z){if(!j.find((g)=>D(g)&&("path"in g)&&g.path===z.path))j.push(z)}else if(!j.some((A)=>C1(A,z)))j.push(z);return j}if(w.every((j)=>typeof j==="string")&&$.every((j)=>typeof j==="string")){let j=[...w];for(let z of $)if(!j.includes(z))j.push(z);return j}return w}if(!D(w)||!D($))return w;let y={...$};for(let j in w)if(Object.prototype.hasOwnProperty.call(w,j)){let z=w[j];if(z===null||z===void 0)continue;else if(D(z)&&D(y[j]))y[j]=Z1(y[j],z);else if(Array.isArray(z)&&Array.isArray(y[j]))if(z.length>0&&y[j].length>0&&D(z[0])&&D(y[j][0])){let A=[...z];for(let g of y[j])if(D(g)&&"name"in g){if(!A.find((X)=>D(X)&&("name"in X)&&X.name===g.name))A.push(g)}else if(D(g)&&"path"in g){if(!A.find((X)=>D(X)&&("path"in X)&&X.path===g.path))A.push(g)}else if(!A.some((J)=>C1(J,g)))A.push(g);y[j]=A}else if(z.every((A)=>typeof A==="string")&&y[j].every((A)=>typeof A==="string")){let A=[...z];for(let g of y[j])if(!A.includes(g))A.push(g);y[j]=A}else y[j]=z;else y[j]=z}return y}function G$($,w,y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return y==="replace"?w:Z1($,w);if(Array.isArray($))return y==="replace"?w:Z1($,w);if(!D(w)||!D($))return w;let j={...$};for(let z of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,z))continue;let A=w[z],g=j[z];if(A===null||A===void 0)continue;if(Array.isArray(A)||Array.isArray(g))if(y==="replace")j[z]=A;else j[z]=Z1(g,A);else if(D(A)&&D(g))j[z]=G$(g,A,y);else j[z]=A}return j}function C1($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let y=0;y<$.length;y++)if(!C1($[y],w[y]))return!1;return!0}if(D($)&&D(w)){let y=Object.keys($),j=Object.keys(w);if(y.length!==j.length)return!1;for(let z of y){if(!Object.prototype.hasOwnProperty.call(w,z))return!1;if(!C1($[z],w[z]))return!1}return!0}return!1}function D($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function T1($,w,y="replace"){if(!A2($))return null;try{let j=await import($),z=j.default||j;if(typeof z!=="object"||z===null||Array.isArray(z))return null;try{return G$(w,z,y)}catch{return null}}catch{return null}}function U8($,w,y=!1){if(!$)return w;let j=$.toUpperCase().replace(/-/g,"_"),z={...w};function A(g,J=[]){let X={...g};for(let[Y,U]of Object.entries(g)){let B=[...J,Y],b=(_)=>_.replace(/([A-Z])/g,"_$1").toUpperCase(),Q=`${j}_${B.map(b).join("_")}`,K=`${j}_${B.map((_)=>_.toUpperCase()).join("_")}`;if(y)w0.info(`Checking environment variable ${Q} for config ${$}.${B.join(".")}`);if(typeof U==="object"&&U!==null&&!Array.isArray(U))X[Y]=A(U,B);else{let _=$1.env[Q]||$1.env[K];if(_!==void 0){if(y)w0.info(`Using environment variable ${_?Q:K} for config ${$}.${B.join(".")}`);if(typeof U==="number")X[Y]=Number(_);else if(typeof U==="boolean")X[Y]=_.toLowerCase()==="true";else if(Array.isArray(U))try{let W=JSON.parse(_);if(Array.isArray(W))X[Y]=W;else X[Y]=_.split(",").map((L)=>L.trim())}catch{X[Y]=_.split(",").map((W)=>W.trim())}else X[Y]=_}}}return X}return A(z)}async function X2({name:$="",alias:w,cwd:y,configDir:j,defaultConfig:z,verbose:A=!1,checkEnv:g=!0,arrayStrategy:J="replace"}){let X=g&&typeof z==="object"&&z!==null&&!Array.isArray(z)?U8($,z,A):z,Y=y||$1.cwd(),U=[".ts",".js",".mjs",".cjs",".json"];if(A)w0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${Y}`);let B=[$,`.${$}`].filter(Boolean),b=[`${$}.config`,`.${$}.config`].filter(Boolean),Q=w?[w,`.${w}`]:[],K=w?[`${w}.config`,`.${w}.config`]:[],_=Array.from(new Set([Y,z0(Y,"config"),z0(Y,".config"),j?z0(Y,j):void 0].filter(Boolean)));for(let W of _){if(A)w0.info(`Searching for configuration in: ${W}`);let N=[z0(Y,"config"),z0(Y,".config")].concat(j?[z0(Y,j)]:[]).includes(W)?[...B,...b,...Q,...K]:[...b,...B,...K,...Q];for(let O of N)for(let H of U){let R=z0(W,`${O}${H}`),f=await T1(R,X,J);if(f!==null){if(A)w0.success(`Configuration loaded from: ${R}`);return f}}}if($){let W=z0(L$(),".config",$),L=["config",`${$}.config`];if(w)L.push(`${w}.config`);if(A)w0.info(`Checking user config directory: ${W}`);for(let N of L)for(let O of U){let H=z0(W,`${N}${O}`),R=await T1(H,X,J);if(R!==null){if(A)w0.success(`Configuration loaded from user config directory: ${H}`);return R}}}if($){let W=z0(L$(),".config"),L=[`.${$}.config`];if(w)L.push(`.${w}.config`);if(A)w0.info(`Checking user config directory for dotfile configs: ${W}`);for(let N of L)for(let O of U){let H=z0(W,`${N}${O}`),R=await T1(H,X,J);if(R!==null){if(A)w0.success(`Configuration loaded from user config directory dotfile: ${H}`);return R}}}if($){let W=L$(),L=[`.${$}.config`,`.${$}`];if(w)L.push(`.${w}.config`),L.push(`.${w}`);if(A)w0.info(`Checking user home directory for dotfile configs: ${W}`);for(let N of L)for(let O of U){let H=z0(W,`${N}${O}`),R=await T1(H,X,J);if(R!==null){if(A)w0.success(`Configuration loaded from user home directory: ${H}`);return R}}}try{let W=z0(Y,"package.json");if(A2(W)){let L=await import(W),N=L[$];if(!N&&w){if(N=L[w],N&&A)w0.success(`Using alias "${w}" configuration from package.json`)}if(N&&typeof N==="object"&&!Array.isArray(N))try{if(A)w0.success(`Configuration loaded from package.json: ${N===L[$]?$:w}`);return G$(X,N,J)}catch(O){if(A)w0.warn("Failed to merge package.json config:",O)}}}catch(W){if(A)w0.warn("Failed to load package.json:",W)}if(A)w0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return X}var Xj,Yj,y8,k$,y2,y0,h,Uj,A8,Bj,g8,bj,Qj,j2,Kj,J8,X8,z2,qj,_j,Nj,Wj,F$,Y8,Lj,w0,Oj,Hj;var Y2=M(async()=>{Xj=E1(V$.cwd(),"config"),Yj=E1(V$.cwd(),"src/generated");y8=M1.env.CLARITY_LOG_DIR||ny(w8(),"logs"),k$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:y8,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1};y2=await j8();y0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},h=y0,Uj=y0.red,A8=y0.green,Bj=y0.yellow,g8=y0.blue,bj=y0.magenta,Qj=y0.cyan,j2=y0.white,Kj=y0.gray,J8=y0.bgRed,X8=y0.bgYellow,z2=y0.bold,qj=y0.dim,_j=y0.italic,Nj=y0.underline,Wj=y0.reset,F$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Y8={debug:"\uD83D\uDD0D",info:g8("\u2139"),success:A8("\u2713"),warning:X8(j2(z2(" WARN "))),error:J8(j2(z2(" ERROR ")))};Lj=new v1("stacks");w0=new v1("bunfig",{showTags:!0});Oj=z0($1.cwd(),"config"),Hj=z0($1.cwd(),"src/generated")});function B2($){let w=$.trim();for(let y of U2)if(y.test(w))throw Error(`Potentially unsafe expression: ${w}`);return w}function B8($){let w={};w.Math=Math,w.JSON=JSON,w.Date=Date,w.String=String,w.Number=Number,w.Boolean=Boolean,w.Array=Array,w.parseInt=Number.parseInt,w.parseFloat=Number.parseFloat,w.isNaN=Number.isNaN,w.isFinite=Number.isFinite,w.encodeURIComponent=encodeURIComponent,w.decodeURIComponent=decodeURIComponent;for(let[y,j]of Object.entries($)){if(y.startsWith("_")||U2.some((z)=>z.test(y)))continue;if(j&&typeof j==="object"&&!Array.isArray(j))w[y]=I$(j);else w[y]=j}return w}function I$($,w=0){if(w>10)return"[Object too deep]";if($===null||typeof $!=="object")return $;if(Array.isArray($))return $.map((j)=>I$(j,w+1));let y={};for(let[j,z]of Object.entries($)){if(j.startsWith("_")||j==="constructor"||j==="prototype"||j==="__proto__")continue;if(z&&typeof z==="object")y[j]=I$(z,w+1);else y[j]=z}return y}function T$($,w){try{let y=B2($),j=B8(w);return Function(...Object.keys(j),`
464
464
  'use strict';
465
465
  try {
466
466
  return ${y};
@@ -470,7 +470,7 @@ ${X}`},hasEndTag:!1,description:"Coordinates multiple animations together as a g
470
470
  }
471
471
  throw e;
472
472
  }
473
- `)(...Object.values(j))}catch{return}}function Y2($){try{return X2($),!0}catch{return!1}}var J2;var U2=M(()=>{J2=[/\b(eval|Function|setTimeout|setInterval|setImmediate)\b/,/\b(process|require|import|exports|module)\b/,/\b(window|document|global|globalThis)\b/,/\b(constructor|prototype|__proto__)\b/,/__\w+__/,/\[\s*['"]/]});function J8($){B2=$}function Q2($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function x0($,w,y){J8(w);let j=$;return j=j.replace(/\{\{\{([\s\S]*?)\}\}\}/g,(z,g,A)=>{try{let J=P0(g,w);return J!==void 0&&J!==null?String(J):""}catch(J){return k("Expression",`Error evaluating: {{{ ${g.trim()}}}}: ${J.message||""}`,y,$,A,z)}}),j=j.replace(/\{!!([\s\S]*?)!!\}/g,(z,g,A)=>{try{let J=P0(g,w);return J!==void 0&&J!==null?String(J):""}catch(J){return k("Expression",`Error evaluating: {!! ${g.trim()} !!}: ${J.message||""}`,y,$,A,z)}}),j=j.replace(/\{\{([\s\S]*?)\}\}/g,(z,g,A)=>{try{let J=P0(g,w);return J!==void 0&&J!==null?Q2(String(J)):""}catch(J){return k("Expression",`Error evaluating: {{ ${g.trim()} }}: ${J.message||""}`,y,$,A,z)}}),j}function X8($,w,y){if(!w.trim())return $;let j=$,z=w.trim();while(z.length>0){let g=z.match(/^(\w+)/);if(!g)break;let A=g[1];z=z.substring(A.length).trim();let J=b2[A];if(!J)throw Error(`Filter not found: ${A}`);let X=[];if(z.startsWith(":")){let Y=z.match(/^:([^|\s]+)/);if(Y){let U=Y[1].trim();try{let B=Number(U);X=[Number.isNaN(B)?U:B]}catch{X=[U]}z=z.substring(Y[0].length).trim()}}else if(z.startsWith("(")){let Y=1,U=1;while(Y>0&&U<z.length){if(z[U]==="(")Y++;if(z[U]===")")Y--;U++}if(Y===0){let B=z.substring(1,U-1).trim();if(B)try{if(B.startsWith("{")&&B.endsWith("}"))X=[P0(`(${B})`,y,!0)];else X=B.split(",").map((b)=>{let Q=b.trim();return P0(Q,y,!0)})}catch{X=[B]}z=z.substring(U).trim()}}try{j=J(j,...X)}catch(Y){throw Error(`Error applying filter '${A}': ${Y.message}`)}if(z.startsWith("|"))z=z.substring(1).trim();else break}return j}function P0($,w,y=!1){try{let j=$.trim();if(j.includes("parent.child.parent")){if(w.parent&&w.parent.name)return w.parent.name}let z=j.indexOf("|");if(z>0){let g=j.substring(0,z).trim(),A=j.substring(z+1).trim();if(j.includes("||"));else{let J=P0(g,w,!0);return X8(J,A,w)}}if(j.startsWith("nonExistentVar")||j.includes(".methodThatDoesntExist")||j.includes('JSON.parse("{invalid}")'))throw Error(`Reference to undefined variable or method: ${j}`);if(!Y2(j)){if(!y)console.warn(`Potentially unsafe expression detected, using safe evaluator: ${j}`);return G$(j,w)}try{let g=Object.keys(w),A=Object.values(w);return Function(...g,`
473
+ `)(...Object.values(j))}catch{return}}function b2($){try{return B2($),!0}catch{return!1}}var U2;var Q2=M(()=>{U2=[/\b(eval|Function|setTimeout|setInterval|setImmediate)\b/,/\b(process|require|import|exports|module)\b/,/\b(window|document|global|globalThis)\b/,/\b(constructor|prototype|__proto__)\b/,/__\w+__/,/\[\s*['"]/]});function b8($){K2=$}function _2($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function x0($,w,y){b8(w);let j=$;return j=j.replace(/\{\{\{([\s\S]*?)\}\}\}/g,(z,A,g)=>{try{let J=P0(A,w);return J!==void 0&&J!==null?String(J):""}catch(J){return k("Expression",`Error evaluating: {{{ ${A.trim()}}}}: ${J.message||""}`,y,$,g,z)}}),j=j.replace(/\{!!([\s\S]*?)!!\}/g,(z,A,g)=>{try{let J=P0(A,w);return J!==void 0&&J!==null?String(J):""}catch(J){return k("Expression",`Error evaluating: {!! ${A.trim()} !!}: ${J.message||""}`,y,$,g,z)}}),j=j.replace(/\{\{([\s\S]*?)\}\}/g,(z,A,g)=>{try{let J=P0(A,w);return J!==void 0&&J!==null?_2(String(J)):""}catch(J){return k("Expression",`Error evaluating: {{ ${A.trim()} }}: ${J.message||""}`,y,$,g,z)}}),j}function Q8($,w,y){if(!w.trim())return $;let j=$,z=w.trim();while(z.length>0){let A=z.match(/^(\w+)/);if(!A)break;let g=A[1];z=z.substring(g.length).trim();let J=q2[g];if(!J)throw Error(`Filter not found: ${g}`);let X=[];if(z.startsWith(":")){let Y=z.match(/^:([^|\s]+)/);if(Y){let U=Y[1].trim();try{let B=Number(U);X=[Number.isNaN(B)?U:B]}catch{X=[U]}z=z.substring(Y[0].length).trim()}}else if(z.startsWith("(")){let Y=1,U=1;while(Y>0&&U<z.length){if(z[U]==="(")Y++;if(z[U]===")")Y--;U++}if(Y===0){let B=z.substring(1,U-1).trim();if(B)try{if(B.startsWith("{")&&B.endsWith("}"))X=[P0(`(${B})`,y,!0)];else X=B.split(",").map((b)=>{let Q=b.trim();return P0(Q,y,!0)})}catch{X=[B]}z=z.substring(U).trim()}}try{j=J(j,...X)}catch(Y){throw Error(`Error applying filter '${g}': ${Y.message}`)}if(z.startsWith("|"))z=z.substring(1).trim();else break}return j}function P0($,w,y=!1){try{let j=$.trim();if(j.includes("parent.child.parent")){if(w.parent&&w.parent.name)return w.parent.name}let z=j.indexOf("|");if(z>0){let A=j.substring(0,z).trim(),g=j.substring(z+1).trim();if(j.includes("||"));else{let J=P0(A,w,!0);return Q8(J,g,w)}}if(j.startsWith("nonExistentVar")||j.includes(".methodThatDoesntExist")||j.includes('JSON.parse("{invalid}")'))throw Error(`Reference to undefined variable or method: ${j}`);if(!b2(j)){if(!y)console.warn(`Potentially unsafe expression detected, using safe evaluator: ${j}`);return T$(j,w)}try{let A=Object.keys(w),g=Object.values(w);return Function(...A,`
474
474
  try {
475
475
  return ${j};
476
476
  } catch (e) {
@@ -479,7 +479,7 @@ ${X}`},hasEndTag:!1,description:"Coordinates multiple animations together as a g
479
479
  }
480
480
  throw e;
481
481
  }
482
- `)(...A)}catch{return G$(j,w)}}catch(j){if(!y)console.error(`Error evaluating expression: ${$}`,j);throw j}}function K2($){if(!$)return"";return $.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&amp;/g,"&")}var B2,b2;var u0=M(async()=>{U2();await p();B2={};b2={uppercase:($)=>{return $!==void 0&&$!==null?String($).toUpperCase():""},lowercase:($)=>{return $!==void 0&&$!==null?String($).toLowerCase():""},capitalize:($)=>{if($===void 0||$===null)return"";let w=String($);return w.charAt(0).toUpperCase()+w.slice(1)},number:($,w=0)=>{if($===void 0||$===null)return"";try{let y=Number($);return Number.isNaN(y)?"":y.toFixed(Number.parseInt(String(w),10))}catch{return""}},join:($,w=",")=>{if(!Array.isArray($))return"";return $.join(String(w))},escape:($)=>{if($===void 0||$===null)return"";return Q2(String($))},translate:($,w={})=>{let y=B2;if(!y||!y.__translations)return $;let j=y.__translations,z=y.__i18nConfig?.fallbackToKey??!0,g=String($).split("."),A=j;for(let X of g){if(A===void 0||A===null)break;A=A[X]}if(A===void 0||A===null)return z?$:"";let J=String(A);return Object.entries(w).forEach(([X,Y])=>{J=J.replace(new RegExp(`:${X}`,"g"),String(Y))}),J},t:($,w={})=>{return b2.translate($,w)}}});function B0($,w){try{let y=$.trim();return Function(...Object.keys(w),`
482
+ `)(...g)}catch{return T$(j,w)}}catch(j){if(!y)console.error(`Error evaluating expression: ${$}`,j);throw j}}function N2($){if(!$)return"";return $.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&amp;/g,"&")}var K2,q2;var u0=M(async()=>{Q2();await n();K2={};q2={uppercase:($)=>{return $!==void 0&&$!==null?String($).toUpperCase():""},lowercase:($)=>{return $!==void 0&&$!==null?String($).toLowerCase():""},capitalize:($)=>{if($===void 0||$===null)return"";let w=String($);return w.charAt(0).toUpperCase()+w.slice(1)},number:($,w=0)=>{if($===void 0||$===null)return"";try{let y=Number($);return Number.isNaN(y)?"":y.toFixed(Number.parseInt(String(w),10))}catch{return""}},join:($,w=",")=>{if(!Array.isArray($))return"";return $.join(String(w))},escape:($)=>{if($===void 0||$===null)return"";return _2(String($))},translate:($,w={})=>{let y=K2;if(!y||!y.__translations)return $;let j=y.__translations,z=y.__i18nConfig?.fallbackToKey??!0,A=String($).split("."),g=j;for(let X of A){if(g===void 0||g===null)break;g=g[X]}if(g===void 0||g===null)return z?$:"";let J=String(g);return Object.entries(w).forEach(([X,Y])=>{J=J.replace(new RegExp(`:${X}`,"g"),String(Y))}),J},t:($,w={})=>{return q2.translate($,w)}}});function B0($,w){try{let y=$.trim();return Function(...Object.keys(w),`
483
483
  try {
484
484
  return ${y};
485
485
  } catch (e) {
@@ -489,7 +489,7 @@ ${X}`},hasEndTag:!1,description:"Coordinates multiple animations together as a g
489
489
  }
490
490
  throw e; // Re-throw other errors
491
491
  }
492
- `)(...Object.values(w))}catch{return!1}}import r from"process";function Y8($,w){let y=1,j=w;while(j<$.length&&y>0){let z=$.substring(j).match(/@switch\s*\(((?:[^()]|\([^()]*\))*)\)/),g=$.substring(j).match(/@endswitch/),A=z?j+z.index:1/0,J=g?j+g.index:1/0;if(A<J)y++,j=A+z[0].length;else if(J<1/0){if(y--,y===0)return{end:J,switchContent:$.substring(w,J)};j=J+g[0].length}else break}return null}function U8($,w,y){let j=$,z=!0;while(z){z=!1;let g=/@switch\s*\(((?:[^()]|\([^()]*\))*)\)/,A=j.match(g);if(!A||A.index===void 0)break;let J=A[1],X=A.index,Y=X+A[0].length,U=Y8(j,Y);if(!U)break;let B=U.switchContent,b=U.end+10;try{let K=Function(...Object.keys(w),`return ${J}`)(...Object.values(w)),_=[],W="",L=/@case\s*\(((?:[^()]|\([^()]*\))*)\)/g,N=[],f;while((f=L.exec(B))!==null)N.push({pos:f.index,value:f[1],directive:f[0]});let O=B.match(/@default/);if(O&&O.index!==void 0)N.push({pos:O.index,value:"",directive:"@default"});N.sort((H,F)=>H.pos-F.pos);for(let H=0;H<N.length;H++){let F=N[H],n=N[H+1],z0=F.pos+F.directive.length,c=n?n.pos:B.length,l=B.substring(z0,c).trim();if(F.directive==="@default")W=l;else _.push({value:F.value,content:l})}let R=W;for(let H of _)try{let n=Function(...Object.keys(w),`return ${H.value}`)(...Object.values(w));if(K===n){R=H.content;break}}catch{continue}j=j.substring(0,X)+R+j.substring(b),z=!0}catch(Q){let K=k("Switch",`Error evaluating @switch expression: ${Q.message}`,y,$,X,j.substring(X,b));j=j.substring(0,X)+K+j.substring(b);break}}return j}function m0($,w,y){let j=$;j=U8(j,w,y),j=j.replace(/@unless\s*\(([^)]+)\)([\s\S]*?)@endunless/g,(g,A,J)=>{return`@if (!(${A}))${J}@endif`}),j=Z$(j,w,y),j=E$(j,w,y),j=T$(j,w);let z=()=>{let g=!1;return j=j.replace(/@if\s*\(([^)]+)\)([\s\S]*?)@endif/g,(A,J,X,Y)=>{g=!0;try{if(Function(...Object.keys(w),`return ${J}`)(...Object.values(w)))return X.split(/@else(?:if\s*\([^)]+\))?/)[0];else{let b=X.match(/@elseif\s*\(([^)]+)\)([\s\S]*?)(?:@elseif|@else|$)/);if(b)try{if(Function(...Object.keys(w),`return ${b[1]}`)(...Object.values(w)))return b[2]}catch(K){return k("Directive",`Error in @elseif(${b[1]}): ${K instanceof Error?K.message:String(K)}`,y,$,Y+A.indexOf("@elseif"),`@elseif(${b[1]})`)}let Q=X.match(/@else([\s\S]*?)(?:@elseif|$)/);if(Q)return Q[1];return""}}catch(U){return k("Directive",`Error in @if(${J}): ${U instanceof Error?U.message:String(U)}`,y,$,Y,`@if(${J})`)}}),g};while(z());return j}function T$($,w){let y=$;return y=y.replace(/@auth\s*(?:\((.*?)\)\s*)?\n([\s\S]*?)(?:@else\s*\n([\s\S]*?))?@endauth/g,(j,z,g,A)=>{return(z?B0(`auth?.check && auth?.user?.[${z}]`,w):B0("auth?.check",w))?g:A||""}),y=y.replace(/@guest\s*(?:\((.*?)\)\s*)?\n([\s\S]*?)(?:@else\s*\n([\s\S]*?))?@endguest/g,(j,z,g,A)=>{return(z?B0(`!auth?.check || !auth?.user?.[${z}]`,w):B0("!auth?.check",w))?g:A||""}),y=y.replace(/@can\('([^']*)'(?:,\s*'([^']*)')?(?:,\s*([^)]*))?\)\s*\n([\s\S]*?)(?:@elsecan\('([^']*)'(?:,\s*'([^']*)')?(?:,\s*([^)]*))?\)\s*\n([\s\S]*?))?(?:@else\s*\n([\s\S]*?))?@endcan/g,(j,z,g,A,J,X,Y,U,B,b)=>{let Q=!1;if(w.userCan&&typeof w.userCan[z]==="boolean")Q=w.userCan[z];else if(w.permissions?.check&&typeof w.permissions.check==="function")try{let K=[z];if(g)K.push(g);if(A){let _=B0(A,w);K.push(_)}Q=w.permissions.check(...K)}catch{Q=!1}if(Q)return J;else if(X){let K=!1;if(w.userCan&&typeof w.userCan[X]==="boolean")K=w.userCan[X];else if(w.permissions?.check&&typeof w.permissions.check==="function")try{let _=[X];if(Y)_.push(Y);if(U){let W=B0(U,w);_.push(W)}K=w.permissions.check(..._)}catch{K=!1}return K?B:b||""}else return b||""}),y=y.replace(/@cannot\('([^']*)'(?:,\s*'([^']*)')?(?:,\s*([^)]*))?\)\s*\n([\s\S]*?)(?:@elsecannot\('([^']*)'(?:,\s*'([^']*)')?(?:,\s*([^)]*))?\)\s*\n([\s\S]*?))?(?:@else\s*\n([\s\S]*?))?@endcannot/g,(j,z,g,A,J,X,Y,U,B,b)=>{let Q=!0;if(w.userCan&&typeof w.userCan[z]==="boolean")Q=!w.userCan[z];else if(w.permissions?.check&&typeof w.permissions.check==="function")try{let K=[z];if(g)K.push(g);if(A){let _=B0(A,w);K.push(_)}Q=!w.permissions.check(...K)}catch{Q=!0}if(Q)return J;else if(X){let K=!0;if(w.userCan&&typeof w.userCan[X]==="boolean")K=!w.userCan[X];else if(w.permissions?.check&&typeof w.permissions.check==="function")try{let _=[X];if(Y)_.push(Y);if(U){let W=B0(U,w);_.push(W)}K=!w.permissions.check(..._)}catch{K=!0}return K?B:b||""}else return b||""}),y}function Z$($,w,y){let j=$;return j=j.replace(/@isset\(([^)]+)\)((?:.|\n)*?)(?:@else((?:.|\n)*?))?@endisset/g,(z,g,A,J,X)=>{try{let Y=B0(g.trim(),w);if(Y!==void 0&&Y!==null)return A;return J||""}catch(Y){if(y)return k("Directive",`Error processing @isset directive: ${Y.message}`,y,$,X,z);else return console.error("Error processing @isset directive:",Y),z}}),j=j.replace(/@empty\(([^)]+)\)((?:.|\n)*?)(?:@else((?:.|\n)*?))?@endempty/g,(z,g,A,J,X)=>{try{let Y=B0(g.trim(),w);if(Y===void 0||Y===null||Y===""||Array.isArray(Y)&&Y.length===0||typeof Y==="object"&&Y!==null&&Object.keys(Y).length===0)return A;return J||""}catch(Y){if(y)return k("Directive",`Error processing @empty directive: ${Y.message}`,y,$,X,z);else return console.error("Error processing @empty directive:",Y),z}}),j}function E$($,w,y){let j=$;return j=j.replace(/@env\s*\(\s*(['"])([^'"]+)\1\s*\)([\s\S]*?)(?:@else([\s\S]*?))?@endenv/g,(z,g,A,J,X="")=>{return(r.env.NODE_ENV||r.env.BUN_ENV||"development")===A?J:X}),j=j.replace(/@production([\s\S]*?)(?:@else([\s\S]*?))?@endproduction/g,(z,g,A="")=>{return(r.env.NODE_ENV||r.env.BUN_ENV||"development")==="production"?g:A}),j=j.replace(/@development([\s\S]*?)(?:@else([\s\S]*?))?@enddevelopment/g,(z,g,A="")=>{return(r.env.NODE_ENV||r.env.BUN_ENV||"development")==="development"?g:A}),j=j.replace(/@staging([\s\S]*?)(?:@else([\s\S]*?))?@endstaging/g,(z,g,A="")=>{return(r.env.NODE_ENV||r.env.BUN_ENV||"development")==="staging"?g:A}),j=j.replace(/@testing([\s\S]*?)(?:@else([\s\S]*?))?@endtesting/g,(z,g,A="")=>{return(r.env.NODE_ENV||r.env.BUN_ENV||"development")==="testing"?g:A}),j}var d1=M(async()=>{await p()});import B8 from"crypto";function Q8($=b8){let w=B8.randomBytes(Math.ceil($/2)).toString("hex").slice(0,$);return M$=w,w}function K8(){if(!M$)Q8();return M$}function q8($=q2){let w=K8();return`<input type="hidden" name="${$}" value="${w}">`}function _2($){return $.replace(/@csrf(?:\((['"])([^'"]*)\1\))?/g,(w,y,j)=>{return q8(j||q2)})}var b8=40,q2="_token",M$=null;var N2=()=>{};function w1($,w){let y=`${$}:${w||""}`;if(!D$.has(y))D$.set(y,new RegExp($,w));return D$.get(y)}class W2{pool=[];maxPoolSize=10;getEvaluator($){let w=Array.from(new Set($)),y=w.sort().join(","),j=this.pool.find((g)=>g.context.join(",")===y);if(j)return j.func;let z=w.length===0?Function(`
492
+ `)(...Object.values(w))}catch{return!1}}import p from"process";function K8($,w){let y=1,j=w;while(j<$.length&&y>0){let z=$.substring(j).match(/@switch\s*\(((?:[^()]|\([^()]*\))*)\)/),A=$.substring(j).match(/@endswitch/),g=z?j+z.index:1/0,J=A?j+A.index:1/0;if(g<J)y++,j=g+z[0].length;else if(J<1/0){if(y--,y===0)return{end:J,switchContent:$.substring(w,J)};j=J+A[0].length}else break}return null}function q8($,w,y){let j=$,z=!0;while(z){z=!1;let A=/@switch\s*\(((?:[^()]|\([^()]*\))*)\)/,g=j.match(A);if(!g||g.index===void 0)break;let J=g[1],X=g.index,Y=X+g[0].length,U=K8(j,Y);if(!U)break;let B=U.switchContent,b=U.end+10;try{let K=Function(...Object.keys(w),`return ${J}`)(...Object.values(w)),_=[],W="",L=/@case\s*\(((?:[^()]|\([^()]*\))*)\)/g,N=[],O;while((O=L.exec(B))!==null)N.push({pos:O.index,value:O[1],directive:O[0]});let H=B.match(/@default/);if(H&&H.index!==void 0)N.push({pos:H.index,value:"",directive:"@default"});N.sort((f,F)=>f.pos-F.pos);for(let f=0;f<N.length;f++){let F=N[f],c=N[f+1],g0=F.pos+F.directive.length,o=c?c.pos:B.length,a=B.substring(g0,o).trim();if(F.directive==="@default")W=a;else _.push({value:F.value,content:a})}let R=W;for(let f of _)try{let c=Function(...Object.keys(w),`return ${f.value}`)(...Object.values(w));if(K===c){R=f.content;break}}catch{continue}j=j.substring(0,X)+R+j.substring(b),z=!0}catch(Q){let K=k("Switch",`Error evaluating @switch expression: ${Q.message}`,y,$,X,j.substring(X,b));j=j.substring(0,X)+K+j.substring(b);break}}return j}function m0($,w,y){let j=$;j=q8(j,w,y),j=j.replace(/@unless\s*\(([^)]+)\)([\s\S]*?)@endunless/g,(A,g,J)=>{return`@if (!(${g}))${J}@endif`}),j=M$(j,w,y),j=E$(j,w,y),j=Z$(j,w);let z=()=>{let A=!1;return j=j.replace(/@if\s*\(([^)]+)\)([\s\S]*?)@endif/g,(g,J,X,Y)=>{A=!0;try{if(Function(...Object.keys(w),`return ${J}`)(...Object.values(w)))return X.split(/@else(?:if\s*\([^)]+\))?/)[0];else{let b=X.match(/@elseif\s*\(([^)]+)\)([\s\S]*?)(?:@elseif|@else|$)/);if(b)try{if(Function(...Object.keys(w),`return ${b[1]}`)(...Object.values(w)))return b[2]}catch(K){return k("Directive",`Error in @elseif(${b[1]}): ${K instanceof Error?K.message:String(K)}`,y,$,Y+g.indexOf("@elseif"),`@elseif(${b[1]})`)}let Q=X.match(/@else([\s\S]*?)(?:@elseif|$)/);if(Q)return Q[1];return""}}catch(U){return k("Directive",`Error in @if(${J}): ${U instanceof Error?U.message:String(U)}`,y,$,Y,`@if(${J})`)}}),A};while(z());return j}function Z$($,w){let y=$;return y=y.replace(/@auth\s*(?:\((.*?)\)\s*)?\n([\s\S]*?)(?:@else\s*\n([\s\S]*?))?@endauth/g,(j,z,A,g)=>{return(z?B0(`auth?.check && auth?.user?.[${z}]`,w):B0("auth?.check",w))?A:g||""}),y=y.replace(/@guest\s*(?:\((.*?)\)\s*)?\n([\s\S]*?)(?:@else\s*\n([\s\S]*?))?@endguest/g,(j,z,A,g)=>{return(z?B0(`!auth?.check || !auth?.user?.[${z}]`,w):B0("!auth?.check",w))?A:g||""}),y=y.replace(/@can\('([^']*)'(?:,\s*'([^']*)')?(?:,\s*([^)]*))?\)\s*\n([\s\S]*?)(?:@elsecan\('([^']*)'(?:,\s*'([^']*)')?(?:,\s*([^)]*))?\)\s*\n([\s\S]*?))?(?:@else\s*\n([\s\S]*?))?@endcan/g,(j,z,A,g,J,X,Y,U,B,b)=>{let Q=!1;if(w.userCan&&typeof w.userCan[z]==="boolean")Q=w.userCan[z];else if(w.permissions?.check&&typeof w.permissions.check==="function")try{let K=[z];if(A)K.push(A);if(g){let _=B0(g,w);K.push(_)}Q=w.permissions.check(...K)}catch{Q=!1}if(Q)return J;else if(X){let K=!1;if(w.userCan&&typeof w.userCan[X]==="boolean")K=w.userCan[X];else if(w.permissions?.check&&typeof w.permissions.check==="function")try{let _=[X];if(Y)_.push(Y);if(U){let W=B0(U,w);_.push(W)}K=w.permissions.check(..._)}catch{K=!1}return K?B:b||""}else return b||""}),y=y.replace(/@cannot\('([^']*)'(?:,\s*'([^']*)')?(?:,\s*([^)]*))?\)\s*\n([\s\S]*?)(?:@elsecannot\('([^']*)'(?:,\s*'([^']*)')?(?:,\s*([^)]*))?\)\s*\n([\s\S]*?))?(?:@else\s*\n([\s\S]*?))?@endcannot/g,(j,z,A,g,J,X,Y,U,B,b)=>{let Q=!0;if(w.userCan&&typeof w.userCan[z]==="boolean")Q=!w.userCan[z];else if(w.permissions?.check&&typeof w.permissions.check==="function")try{let K=[z];if(A)K.push(A);if(g){let _=B0(g,w);K.push(_)}Q=!w.permissions.check(...K)}catch{Q=!0}if(Q)return J;else if(X){let K=!0;if(w.userCan&&typeof w.userCan[X]==="boolean")K=!w.userCan[X];else if(w.permissions?.check&&typeof w.permissions.check==="function")try{let _=[X];if(Y)_.push(Y);if(U){let W=B0(U,w);_.push(W)}K=!w.permissions.check(..._)}catch{K=!0}return K?B:b||""}else return b||""}),y}function M$($,w,y){let j=$;return j=j.replace(/@isset\(([^)]+)\)((?:.|\n)*?)(?:@else((?:.|\n)*?))?@endisset/g,(z,A,g,J,X)=>{try{let Y=B0(A.trim(),w);if(Y!==void 0&&Y!==null)return g;return J||""}catch(Y){if(y)return k("Directive",`Error processing @isset directive: ${Y.message}`,y,$,X,z);else return console.error("Error processing @isset directive:",Y),z}}),j=j.replace(/@empty\(([^)]+)\)((?:.|\n)*?)(?:@else((?:.|\n)*?))?@endempty/g,(z,A,g,J,X)=>{try{let Y=B0(A.trim(),w);if(Y===void 0||Y===null||Y===""||Array.isArray(Y)&&Y.length===0||typeof Y==="object"&&Y!==null&&Object.keys(Y).length===0)return g;return J||""}catch(Y){if(y)return k("Directive",`Error processing @empty directive: ${Y.message}`,y,$,X,z);else return console.error("Error processing @empty directive:",Y),z}}),j}function E$($,w,y){let j=$;return j=j.replace(/@env\s*\(\s*(['"])([^'"]+)\1\s*\)([\s\S]*?)(?:@else([\s\S]*?))?@endenv/g,(z,A,g,J,X="")=>{return(p.env.NODE_ENV||p.env.BUN_ENV||"development")===g?J:X}),j=j.replace(/@production([\s\S]*?)(?:@else([\s\S]*?))?@endproduction/g,(z,A,g="")=>{return(p.env.NODE_ENV||p.env.BUN_ENV||"development")==="production"?A:g}),j=j.replace(/@development([\s\S]*?)(?:@else([\s\S]*?))?@enddevelopment/g,(z,A,g="")=>{return(p.env.NODE_ENV||p.env.BUN_ENV||"development")==="development"?A:g}),j=j.replace(/@staging([\s\S]*?)(?:@else([\s\S]*?))?@endstaging/g,(z,A,g="")=>{return(p.env.NODE_ENV||p.env.BUN_ENV||"development")==="staging"?A:g}),j=j.replace(/@testing([\s\S]*?)(?:@else([\s\S]*?))?@endtesting/g,(z,A,g="")=>{return(p.env.NODE_ENV||p.env.BUN_ENV||"development")==="testing"?A:g}),j}var d1=M(async()=>{await n()});import _8 from"crypto";function W8($=N8){let w=_8.randomBytes(Math.ceil($/2)).toString("hex").slice(0,$);return D$=w,w}function L8(){if(!D$)W8();return D$}function O8($=W2){let w=L8();return`<input type="hidden" name="${$}" value="${w}">`}function L2($){return $.replace(/@csrf(?:\((['"])([^'"]*)\1\))?/g,(w,y,j)=>{return O8(j||W2)})}var N8=40,W2="_token",D$=null;var O2=()=>{};function w1($,w){let y=`${$}:${w||""}`;if(!C$.has(y))C$.set(y,new RegExp($,w));return C$.get(y)}class H2{pool=[];maxPoolSize=10;getEvaluator($){let w=Array.from(new Set($)),y=w.sort().join(","),j=this.pool.find((A)=>A.context.join(",")===y);if(j)return j.func;let z=w.length===0?Function(`
493
493
  'use strict';
494
494
  return function(expr) {
495
495
  try {
@@ -513,26 +513,26 @@ ${X}`},hasEndTag:!1,description:"Coordinates multiple animations together as a g
513
513
  throw e;
514
514
  }
515
515
  }
516
- `);if(this.pool.length<this.maxPoolSize)this.pool.push({func:z,context:w.slice()});return z}clear(){this.pool.length=0}}class L2{metrics=new Map;time($,w){let y=performance.now(),j=w(),z=performance.now()-y;return this.recordTime($,z),j}async timeAsync($,w){let y=performance.now(),j=await w(),z=performance.now()-y;return this.recordTime($,z),j}recordTime($,w){let y=this.metrics.get($);if(y)y.count++,y.totalTime+=w,y.maxTime=Math.max(y.maxTime,w),y.minTime=Math.min(y.minTime,w);else this.metrics.set($,{count:1,totalTime:w,maxTime:w,minTime:w})}getStats($){if($){let y=this.metrics.get($);if(!y)return{};return{count:y.count,avgTime:y.totalTime/y.count,totalTime:y.totalTime,maxTime:y.maxTime,minTime:y.minTime}}let w={};for(let[y,j]of this.metrics.entries())w[y]={count:j.count,avgTime:j.totalTime/j.count,totalTime:j.totalTime,maxTime:j.maxTime,minTime:j.minTime};return w}clear(){this.metrics.clear()}}var D$,Sj,y1;var j1=M(()=>{D$=new Map;Sj=new W2;y1=new L2});async function f2($,w,y,j){if(!j.customDirectives||j.customDirectives.length===0)return $;let z=$;for(let g of j.customDirectives){if(!g.name||typeof g.handler!=="function"){if(j.debug)console.warn("Invalid custom directive:",g);continue}if(g.hasEndTag)z=await _8(z,g,w,y,j);else z=await N8(z,g,w,y,j)}return z}async function _8($,w,y,j,z){let{name:g,handler:A}=w,J=`@${g}`,X=`@end${g}`,Y=$,U=w1(`${J}(?:\\s*\\(([^)]+)\\))?([\\s\\S]*?)${X}`,"g"),B=[],b=U.exec(Y);while(b!==null){let[Q,K="",_=""]=b,W=b.index||0;try{let L=K?K.split(",").map((O)=>O.trim()):[],N=_.trim(),f=await A(N,L,y,j);B.push({original:Q,processed:f,startIndex:W})}catch(L){let N=L instanceof Error?L.message:String(L);if(z.debug)console.error(`Error processing custom directive @${g}:`,L);B.push({original:Q,processed:k("Custom Directive",`Error in @${g}${K?`(${K})`:""}: ${N}`,j,$,W,Q),startIndex:W})}b=U.exec(Y)}for(let Q=B.length-1;Q>=0;Q--){let{original:K,processed:_}=B[Q];Y=Y.replace(K,_)}return Y}async function N8($,w,y,j,z){let{name:g,handler:A}=w,J=$,X=w1(`@${g}\\s*\\(([^)]+)\\)`,"g"),Y=[],U=X.exec(J);while(U!==null){let[B,b=""]=U,Q=U.index||0;try{let K=W8(b),_=await A("",K,y,j);Y.push({original:B,processed:_,startIndex:Q})}catch(K){let _=K instanceof Error?K.message:String(K);if(z.debug)console.error(`Error processing custom directive @${g}:`,K);Y.push({original:B,processed:k("Custom Directive",`Error in @${g}(${b}): ${_}`,j,$,Q,B),startIndex:Q})}U=X.exec(J)}for(let B=Y.length-1;B>=0;B--){let{original:b,processed:Q}=Y[B];J=J.replace(b,Q)}return J}function W8($){if(!$.trim())return[];let w=[],y="",j=!1,z="";for(let g=0;g<$.length;g++){let A=$[g];if((A==='"'||A==="'")&&(g===0||$[g-1]!=="\\"))if(!j)j=!0,z=A;else if(A===z)j=!1;else y+=A;else if(A===","&&!j)w.push(y.trim()),y="";else y+=A}if(y.trim())w.push(y.trim());return w.map((g)=>{let A=g.trim();if(A.startsWith('"')&&A.endsWith('"')||A.startsWith("'")&&A.endsWith("'"))return A.substring(1,A.length-1);return A})}var C$=M(async()=>{j1();await p()});import v$ from"process";function Mj($,w,y){let j=y.template.split(`
517
- `),z=O8(y.template,y.offset),g=`[${$} Error at line ${z.line} in ${y.filePath}]: ${w}
518
-
519
- `,A=Math.max(0,z.line-3),J=Math.min(j.length-1,z.line+2);g+=`Context:
520
- `;for(let X=A;X<=J;X++){let Y=X+1,U=j[X]||"",B=X===z.line-1?">":" ";g+=`${B} ${Y.toString().padStart(3)}: ${U}
521
- `}if(z.line-1<j.length){let X=" ".repeat(z.column+5);g+=`${X}^
522
- `}return g}function O8($,w){let j=$.substring(0,w).split(`
523
- `);return{line:j.length,column:j[j.length-1].length}}function Dj($,w,y){try{return $()}catch(j){if(y&&j instanceof Error)y(j);return w}}async function k0($,w,y){try{return await $()}catch(j){if(y&&j instanceof Error)y(j);return w}}class R2{errors=[];maxErrors=1000;log($,w){if(this.errors.push({timestamp:new Date,error:$,context:w}),this.errors.length>this.maxErrors)this.errors=this.errors.slice(-this.maxErrors)}getRecentErrors($=10){return this.errors.slice(-$)}getErrorsByType($){return this.errors.filter((w)=>w.error.constructor.name===$)}clear(){this.errors.length=0}getStats(){let $={};for(let w of this.errors){let y=w.error.constructor.name;$[y]=($[y]||0)+1}return{total:this.errors.length,byType:$}}}var g1,L8,L0,f8,h1,Cj,O2,z1,P1;var x1=M(()=>{g1=class g1 extends Error{code;filePath;line;column;context;constructor($,w,y,j,z,g){super($);this.code=w;this.filePath=y;this.line=j;this.column=z;this.context=g;this.name="StxError"}};L8=class L8 extends g1{constructor($,w,y,j,z){super($,"stx_SYNTAX_ERROR",w,y,j,z);this.name="StxSyntaxError"}};L0=class L0 extends g1{constructor($,w,y,j,z){super($,"stx_RUNTIME_ERROR",w,y,j,z);this.name="StxRuntimeError"}};f8=class f8 extends g1{constructor($,w,y,j,z){super($,"stx_SECURITY_ERROR",w,y,j,z);this.name="StxSecurityError"}};h1=class h1 extends g1{constructor($,w,y,j,z){super($,"stx_FILE_ERROR",w,y,j,z);this.name="StxFileError"}};Cj={isValidFilePath($){if($.includes("../")||$.includes("..\\"))return!1;if($.startsWith("/")&&!$.startsWith(v$.cwd()))return!1;return!0},isValidVariableName($){return/^[a-z_$][\w$]*$/i.test($)},isValidDirectiveName($){return/^[a-z][\w-]*$/i.test($)},isSafeContent($){return![/<script[^>]*>[\s\S]*?<\/script>/gi,/javascript:/gi,/data:text\/html/gi,/vbscript:/gi,/on\w+\s*=/gi].some((y)=>y.test($))}},O2={fixCommonSyntaxErrors($){let w=$,y=(w.match(/\{\{/g)||[]).length,j=(w.match(/\}\}/g)||[]).length;if(y>j)w+=" ".repeat(y-j).replace(/ /g,"}}");let z=["if","foreach","for","switch","section"];for(let g of z){let A=(w.match(new RegExp(`@${g}\\b`,"g"))||[]).length,J=(w.match(new RegExp(`@end${g}\\b`,"g"))||[]).length;if(A>J)w+=`
524
- @end${g}`}return w},createFallbackContent($,w){return`<!-- ${$} failed: ${w.message} -->`}};z1=new R2,P1={isDevelopment(){return v$.env.NODE_ENV==="development"||v$.env.stx_DEBUG==="true"},logDetailedError($,w){if(!this.isDevelopment())return;if(console.error("=== stx Detailed Error ==="),console.error("Error:",$.message),console.error("Stack:",$.stack),w)console.error("Context:",w);console.error("========================")},createErrorReport($,w){let y=["=== stx Error Report ===",`Time: ${new Date().toISOString()}`,`Error: ${$.message}`,`Type: ${$.constructor.name}`,`Stack: ${$.stack}`];if(w)y.push(`Context: ${JSON.stringify(w,null,2)}`);return y.push("========================"),y.join(`
525
- `)}}});function R8(){return Math.random().toString(36).substring(2,15)}function dj($,w,y,j){let z=$;return z=d$(z,w),z=H8(z,w),z=h$(z,w),z}function d$($,w){let y=$;return y=y.replace(/@csrf/g,()=>{if(!w.csrf||typeof w.csrf!=="object"){let j=R8();w.csrf={token:j}}if(w.csrf.field)return w.csrf.field;if(w.csrf.token)return`<input type="hidden" name="_token" value="${w.csrf.token}">`;return'<input type="hidden" name="_token" value="">'}),y=y.replace(/@method\(['"]([^'"]+)['"]\)/g,(j,z)=>{if(z&&["PUT","PATCH","DELETE"].includes(z.toUpperCase()))return`<input type="hidden" name="_method" value="${z.toUpperCase()}">`;return j}),y}function H8($,w){let y=$;return y=y.replace(/@form\(\s*(?:(?:'([^']+)'|"([^"]+)")\s*)?(?:,\s*(?:'([^']+)'|"([^"]+)")?)?\s*(?:,\s*\{([^}]+)\}\s*)?\)/g,(j,z,g,A,J,X="")=>{let Y=z||g||"POST",U=A||J||"",B=I0(X),b=Y.toUpperCase(),K=`<form method="${["GET","POST"].includes(b)?b:"POST"}" action="${U}"${B?` ${B}`:""}>`;if(K+=`
526
- ${d$("@csrf",w)}`,!["GET","POST"].includes(b))K+=`
527
- ${d$(`@method('${b}')`,w)}`;return K}),y=y.replace(/@endform/g,"</form>"),y=y.replace(/@input\(\s*(?:'([^']+)'|"([^"]+)")\s*(?:,\s*(?:(?:'([^']*)'|"([^"]*)")\s*)?)?(?:,\s*\{([^}]+)\})?\s*\)/g,(j,z,g,A,J,X="")=>{let Y=z||g||"",U=A||J||"",B=I0(X),b=A1(Y,w)||(U||""),Q=B.match(/type=['"]([^'"]+)['"]/i),K=Q?Q[1]:"text",W=u1(Y,w)?" is-invalid":"",L=B.match(/class=['"]([^'"]+)['"]/i),N=L?L[1]:"",f=N?`${N}${W}`:`form-control${W}`,O=B.replace(/class=['"][^'"]+['"]/i,"");return O=O.replace(/type=['"][^'"]+['"]/i,""),`<input type="${K}" name="${Y}" value="${b}" class="${f}"${O?` ${O}`:""}>`}),y=y.replace(/@textarea\(\s*['"]([^'"]+)['"]\s*(?:,\s*\{([^}]+)\})?\)([\s\S]*?)@endtextarea/g,(j,z,g="",A="")=>{let J=I0(g),X=A1(z,w)||A.trim(),U=u1(z,w)?" is-invalid":"",B=J.match(/class=['"]([^'"]+)['"]/i),b=B?B[1]:"",Q=b?`${b}${U}`:`form-control${U}`,K=J.replace(/class=['"][^'"]+['"]/i,"");return`<textarea name="${z}" class="${Q}"${K?` ${K}`:""}>${X}</textarea>`}),y=y.replace(/@select\(\s*['"]([^'"]+)['"]\s*(?:,\s*\{([^}]+)\})?\)([\s\S]*?)@endselect/g,(j,z,g="",A)=>{let J=I0(g),X=A1(z,w),U=u1(z,w)?" is-invalid":"",B=J.match(/class=['"]([^'"]+)['"]/i),b=B?B[1]:"",Q=b?`${b}${U}`:`form-control${U}`,K=J.replace(/class=['"][^'"]+['"]/i,""),_=A;if(X!==void 0)_=A.replace(/(<option[^>]*value=['"]([^'"]+)['"][^>]*>)/gi,(W,L,N)=>{if((Array.isArray(X)?X.includes(N):X===N)&&!L.includes("selected"))return L.replace(/(<option)/,"$1 selected");return W});return`<select name="${z}" class="${Q}"${K?` ${K}`:""}>${_}</select>`}),y=y.replace(/@checkbox\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?(?:,\s*\{([^}]+)\})?\)/g,(j,z,g="1",A="")=>{let J=I0(A),X=A1(z,w),Y=X!==void 0&&(Array.isArray(X)?X.includes(g):X===g||X===!0),U=J.match(/class=['"]([^'"]+)['"]/i),b=(U?U[1]:"")||"form-check-input",Q=J.replace(/class=['"][^'"]+['"]/i,"");return`<input type="checkbox" name="${z}" value="${g}" class="${b}"${Y?" checked":""}${Q?` ${Q}`:""}>`}),y=y.replace(/@radio\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*(?:,\s*\{([^}]+)\})?\)/g,(j,z,g,A="")=>{let J=I0(A),X=A1(z,w),Y=X!==void 0&&X===g,U=J.match(/class=['"]([^'"]+)['"]/i),b=(U?U[1]:"")||"form-check-input",Q=J.replace(/class=['"][^'"]+['"]/i,"");return`<input type="radio" name="${z}" value="${g}" class="${b}"${Y?" checked":""}${Q?` ${Q}`:""}>`}),y=y.replace(/@label\(\s*['"]([^'"]+)['"]\s*(?:,\s*\{([^}]+)\})?\)([\s\S]*?)@endlabel/g,(j,z,g="",A)=>{let J=I0(g),X=J.match(/class=['"]([^'"]+)['"]/i),U=(X?X[1]:"")||"form-label",B=J.replace(/class=['"][^'"]+['"]/i,"");return`<label for="${z}" class="${U}"${B?` ${B}`:""}>${A}</label>`}),y}function h$($,w){return $.replace(/@error\(['"]([^'"]+)['"]\)([\s\S]*?)@enderror/g,(y,j,z)=>{try{if(u1(j,w))return z.replace(/\{\{([^}]+)\}\}/g,(g,A)=>{try{if(A.trim()==="$message"||A.trim()==="message")return H2(j,w);if(A.trim().includes("errors.first")||A.trim().includes("$errors.first")){if(typeof w.errors?.first==="function")return w.errors.first(j);return H2(j,w)}return Function(...Object.keys(w),`
528
- try { return ${A.trim()}; } catch (e) { return '${A.trim()}'; }
529
- `)(...Object.values(w))}catch{return A}});return""}catch(g){return console.error("Error processing @error directive:",g),y}})}function u1($,w){if(!w.errors)return!1;if(typeof w.errors.has==="function")return w.errors.has($);if(typeof w.errors==="object")return Object.prototype.hasOwnProperty.call(w.errors,$);return!1}function H2($,w){if(!w.errors)return"";if(typeof w.errors.get==="function")return w.errors.get($);if(typeof w.errors==="object"&&Object.prototype.hasOwnProperty.call(w.errors,$)){let y=w.errors[$];return Array.isArray(y)?y[0]:String(y)}return""}function A1($,w){let y;if(w.old&&typeof w.old==="function")return w.old($);if(w.old&&typeof w.old==="object")return w.old[$];if($.endsWith("[]")){let j=$.slice(0,-2);if(y=w[j],y!==void 0)return y}return w[$]}function I0($){if(!$.trim())return"";let w=[],y=/([\w-]+)\s*:\s*(['"]?)([^,'"]*)\2(?:,|$)/g,j;while((j=y.exec($))!==null){let[,z,,g]=j;w.push(`${z}="${g.trim()}"`)}return w.join(" ")}function k2($,w){let y=$;return y=y.replace(/@csrf/g,()=>{if(w.csrf&&typeof w.csrf==="object"){if(w.csrf.field)return w.csrf.field;if(w.csrf.token)return`<input type="hidden" name="_token" value="${w.csrf.token}">`}return'<input type="hidden" name="_token" value="">'}),y=y.replace(/@method\(['"]([^'"]+)['"]\)/g,(j,z)=>{if(z&&["PUT","PATCH","DELETE"].includes(z.toUpperCase()))return`<input type="hidden" name="_method" value="${z.toUpperCase()}">`;return j}),y}import F2 from"path";async function I2($,w){let y={...S2,...w.i18n};if(y.cache&&P$[$])return P$[$];let j=F2.resolve(import.meta.dir,"..",y.translationsDir),z=k8(y.format),g=F2.join(j,`${$}${z}`);try{let A={},J=await import(g);if(A=J.default||J,y.cache)P$[$]=A;return A}catch(A){if(w.debug)console.error(`Error loading translation file for locale "${$}":`,A);if($!==y.defaultLocale)return I2(y.defaultLocale,w);return{}}}function k8($){switch($){case"yaml":return".yaml";case"yml":return".yml";case"js":return".js";case"json":default:return".json"}}function x$($,w,y=!0,j={}){let z=$.split("."),g=w;for(let J of z){if(g===void 0||g===null)break;g=g[J]}if(g===void 0||g===null)return y?$:"";let A=String(g);return Object.entries(j).forEach(([J,X])=>{A=A.replace(new RegExp(`:${J}`,"g"),String(X))}),A}async function G2($,w,y,j){let z=$,g=/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]*\})\s*)?\)([\s\S]*?)@endtranslate/g,A={...S2,...j.i18n},J=await I2(A.locale,j);w.__translations=J,w.__locale=A.locale,w.__i18nConfig=A,z=await V2(z,g,async(U,B,b,Q,K)=>{try{let _={};if(b)try{let L=[()=>JSON.parse(b),()=>{let N=`{"data":${b}}`,f=JSON.parse(N);return typeof f.data==="object"?f.data:{}},()=>{let f=Function(`return ${b}`)();return typeof f==="object"?f:{}}];for(let N of L)try{if(_=N(),Object.keys(_).length>0)break}catch{}}catch(L){if(j.debug)console.error("Error parsing parameters for @translate directive:",L)}return x$(B,J,A.fallbackToKey,_)||Q.trim()}catch(_){if(j.debug)console.error("Error processing @translate directive:",_);return k("Translate",`Error in @translate('${B}'): ${_ instanceof Error?_.message:String(_)}`,y,$,K,U)}});let X=/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]+\})\s*)?\)/g;if(j.debug){console.warn(`Processing translations in template. Sections: ${z.includes("<h2>Translation with Parameters</h2>")?"Parameters section found":"Parameters section missing"}`);let U=[...z.matchAll(X)];console.warn(`Found ${U.length} @translate matches`),U.forEach((B,b)=>console.warn(`Match ${b}: ${B[0]}, Key: ${B[1]}, Params: ${B[2]||"none"}`))}return z=await V2(z,/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]*\})\s*)?\)/g,async(U,B,b,Q)=>{try{let K={};if(b)try{let _=[()=>JSON.parse(b),()=>{let W=`{"data":${b}}`,L=JSON.parse(W);return typeof L.data==="object"?L.data:{}},()=>{let L=Function(`return ${b}`)();return typeof L==="object"?L:{}}];for(let W of _)try{if(K=W(),Object.keys(K).length>0)break}catch{}}catch(_){if(j.debug)console.error("Error parsing parameters for @translate directive:",_)}return x$(B,J,A.fallbackToKey,K)}catch(K){if(j.debug)console.error("Error processing @translate directive:",K);return k("Translate",`Error in @translate('${B}'): ${K instanceof Error?K.message:String(K)}`,y,$,Q,U)}}),z}async function V2($,w,y){let j=[];return $.replace(w,(g,...A)=>{let J=y(g,...A).then((X)=>({match:g,replacement:X}));return j.push(J),g}),(await Promise.all(j)).reduce((g,{match:A,replacement:J})=>g.replace(A,J),$)}function uj($,w=!0){return(y,j={})=>{return x$(y,$,w,j)}}var S2,P$;var u$=M(async()=>{await p();S2={defaultLocale:"en",locale:"en",translationsDir:"translations",format:"yaml",fallbackToKey:!0,cache:!0},P$={}});var T2={};Wy(T2,{processLoops:()=>m$});function m$($,w,y){let j=$;j=j.replace(/@forelse\s*\(([^)]+)as([^)]+)\)([\s\S]*?)@empty([\s\S]*?)@endforelse/g,(A,J,X,Y,U,B)=>{try{let Q=Function(...Object.keys(w),`return ${J.trim()}`)(...Object.values(w));if(!Array.isArray(Q)||Q.length===0)return U;return`@foreach (${J.trim()} as ${X.trim()})${Y}@endforeach`}catch(b){return k("Directive",`Error in @forelse(${J.trim()} as ${X.trim()}): ${b instanceof Error?b.message:String(b)}`,y,$,B,A)}});function z(A){let J=A.indexOf("@foreach");if(J===-1)return null;let X=A.indexOf("(",J);if(X===-1)return null;let Y=1,U=X+1,B=-1;while(U<A.length&&Y>0){if(A[U]==="(")Y++;else if(A[U]===")"){if(Y--,Y===0){B=U;break}}U++}if(B===-1)return null;let b=A.substring(X+1,B),Q=b.indexOf(" as ");if(Q===-1)return null;let K=J,_=b.substring(0,Q),W=b.substring(Q+4),L=B+1,N=1,f=L,O=/@foreach/g,R=/@endforeach/g;while(N>0&&f<A.length){O.lastIndex=f,R.lastIndex=f;let H=O.exec(A),F=R.exec(A);if(!F)return null;if(H&&H.index<F.index)N++,f=H.index+8;else{if(N--,N===0){let n=A.substring(L,F.index),z0=F.index+11;return{start:K,end:z0,arrayExpr:_,itemVar:W,content:n}}f=F.index+11}}return null}function g(A,J){let X=A;while(!0){let Y=z(X);if(!Y)break;let{start:U,end:B,arrayExpr:b,itemVar:Q,content:K}=Y;try{let W=Function(...Object.keys(J),`return ${b.trim()}`)(...Object.values(J));if(!Array.isArray(W)){let N=k("Directive",`Error in @foreach: ${b.trim()} is not an array`,y,X,U,X.substring(U,B));X=X.substring(0,U)+N+X.substring(B);continue}let L="";for(let N=0;N<W.length;N++){let f=W[N],O=Q.trim(),R={...J,[O]:f,loop:{index:N,iteration:N+1,first:N===0,last:N===W.length-1,count:W.length}},H=g(K,R);H=m0(H,R,y),H=x0(H,R,y),L+=H}X=X.substring(0,U)+L+X.substring(B)}catch(_){let W=k("Directive",`Error in @foreach(${b.trim()} as ${Q.trim()}): ${_ instanceof Error?_.message:String(_)}`,y,X,U,X.substring(U,B));X=X.substring(0,U)+W+X.substring(B)}}return X}return j=g(j,w),j=j.replace(/@for\s*\(([^)]+)\)([\s\S]*?)@endfor/g,(A,J,X,Y)=>{try{let U=Object.keys(w),B=Object.values(w);return Function(...U,`
516
+ `);if(this.pool.length<this.maxPoolSize)this.pool.push({func:z,context:w.slice()});return z}clear(){this.pool.length=0}}class R2{metrics=new Map;time($,w){let y=performance.now(),j=w(),z=performance.now()-y;return this.recordTime($,z),j}async timeAsync($,w){let y=performance.now(),j=await w(),z=performance.now()-y;return this.recordTime($,z),j}recordTime($,w){let y=this.metrics.get($);if(y)y.count++,y.totalTime+=w,y.maxTime=Math.max(y.maxTime,w),y.minTime=Math.min(y.minTime,w);else this.metrics.set($,{count:1,totalTime:w,maxTime:w,minTime:w})}getStats($){if($){let y=this.metrics.get($);if(!y)return{};return{count:y.count,avgTime:y.totalTime/y.count,totalTime:y.totalTime,maxTime:y.maxTime,minTime:y.minTime}}let w={};for(let[y,j]of this.metrics.entries())w[y]={count:j.count,avgTime:j.totalTime/j.count,totalTime:j.totalTime,maxTime:j.maxTime,minTime:j.minTime};return w}clear(){this.metrics.clear()}}var C$,Dj,y1;var j1=M(()=>{C$=new Map;Dj=new H2;y1=new R2});async function f2($,w,y,j){if(!j.customDirectives||j.customDirectives.length===0)return $;let z=$;for(let A of j.customDirectives){if(!A.name||typeof A.handler!=="function"){if(j.debug)console.warn("Invalid custom directive:",A);continue}if(A.hasEndTag)z=await H8(z,A,w,y,j);else z=await R8(z,A,w,y,j)}return z}async function H8($,w,y,j,z){let{name:A,handler:g}=w,J=`@${A}`,X=`@end${A}`,Y=$,U=w1(`${J}(?:\\s*\\(([^)]+)\\))?([\\s\\S]*?)${X}`,"g"),B=[],b=U.exec(Y);while(b!==null){let[Q,K="",_=""]=b,W=b.index||0;try{let L=K?K.split(",").map((H)=>H.trim()):[],N=_.trim(),O=await g(N,L,y,j);B.push({original:Q,processed:O,startIndex:W})}catch(L){let N=L instanceof Error?L.message:String(L);if(z.debug)console.error(`Error processing custom directive @${A}:`,L);B.push({original:Q,processed:k("Custom Directive",`Error in @${A}${K?`(${K})`:""}: ${N}`,j,$,W,Q),startIndex:W})}b=U.exec(Y)}for(let Q=B.length-1;Q>=0;Q--){let{original:K,processed:_}=B[Q];Y=Y.replace(K,_)}return Y}async function R8($,w,y,j,z){let{name:A,handler:g}=w,J=$,X=w1(`@${A}\\s*\\(([^)]+)\\)`,"g"),Y=[],U=X.exec(J);while(U!==null){let[B,b=""]=U,Q=U.index||0;try{let K=f8(b),_=await g("",K,y,j);Y.push({original:B,processed:_,startIndex:Q})}catch(K){let _=K instanceof Error?K.message:String(K);if(z.debug)console.error(`Error processing custom directive @${A}:`,K);Y.push({original:B,processed:k("Custom Directive",`Error in @${A}(${b}): ${_}`,j,$,Q,B),startIndex:Q})}U=X.exec(J)}for(let B=Y.length-1;B>=0;B--){let{original:b,processed:Q}=Y[B];J=J.replace(b,Q)}return J}function f8($){if(!$.trim())return[];let w=[],y="",j=!1,z="";for(let A=0;A<$.length;A++){let g=$[A];if((g==='"'||g==="'")&&(A===0||$[A-1]!=="\\"))if(!j)j=!0,z=g;else if(g===z)j=!1;else y+=g;else if(g===","&&!j)w.push(y.trim()),y="";else y+=g}if(y.trim())w.push(y.trim());return w.map((A)=>{let g=A.trim();if(g.startsWith('"')&&g.endsWith('"')||g.startsWith("'")&&g.endsWith("'"))return g.substring(1,g.length-1);return g})}var v$=M(async()=>{j1();await n()});import d$ from"process";function xj($,w,y){let j=y.template.split(`
517
+ `),z=V8(y.template,y.offset),A=`[${$} Error at line ${z.line} in ${y.filePath}]: ${w}
518
+
519
+ `,g=Math.max(0,z.line-3),J=Math.min(j.length-1,z.line+2);A+=`Context:
520
+ `;for(let X=g;X<=J;X++){let Y=X+1,U=j[X]||"",B=X===z.line-1?">":" ";A+=`${B} ${Y.toString().padStart(3)}: ${U}
521
+ `}if(z.line-1<j.length){let X=" ".repeat(z.column+5);A+=`${X}^
522
+ `}return A}function V8($,w){let j=$.substring(0,w).split(`
523
+ `);return{line:j.length,column:j[j.length-1].length}}function uj($,w,y){try{return $()}catch(j){if(y&&j instanceof Error)y(j);return w}}async function k0($,w,y){try{return await $()}catch(j){if(y&&j instanceof Error)y(j);return w}}class F2{errors=[];maxErrors=1000;log($,w){if(this.errors.push({timestamp:new Date,error:$,context:w}),this.errors.length>this.maxErrors)this.errors=this.errors.slice(-this.maxErrors)}getRecentErrors($=10){return this.errors.slice(-$)}getErrorsByType($){return this.errors.filter((w)=>w.error.constructor.name===$)}clear(){this.errors.length=0}getStats(){let $={};for(let w of this.errors){let y=w.error.constructor.name;$[y]=($[y]||0)+1}return{total:this.errors.length,byType:$}}}var z1,k8,W0,F8,h1,mj,k2,A1,P1;var x1=M(()=>{z1=class z1 extends Error{code;filePath;line;column;context;constructor($,w,y,j,z,A){super($);this.code=w;this.filePath=y;this.line=j;this.column=z;this.context=A;this.name="StxError"}};k8=class k8 extends z1{constructor($,w,y,j,z){super($,"stx_SYNTAX_ERROR",w,y,j,z);this.name="StxSyntaxError"}};W0=class W0 extends z1{constructor($,w,y,j,z){super($,"stx_RUNTIME_ERROR",w,y,j,z);this.name="StxRuntimeError"}};F8=class F8 extends z1{constructor($,w,y,j,z){super($,"stx_SECURITY_ERROR",w,y,j,z);this.name="StxSecurityError"}};h1=class h1 extends z1{constructor($,w,y,j,z){super($,"stx_FILE_ERROR",w,y,j,z);this.name="StxFileError"}};mj={isValidFilePath($){if($.includes("../")||$.includes("..\\"))return!1;if($.startsWith("/")&&!$.startsWith(d$.cwd()))return!1;return!0},isValidVariableName($){return/^[a-z_$][\w$]*$/i.test($)},isValidDirectiveName($){return/^[a-z][\w-]*$/i.test($)},isSafeContent($){return![/<script[^>]*>[\s\S]*?<\/script>/gi,/javascript:/gi,/data:text\/html/gi,/vbscript:/gi,/on\w+\s*=/gi].some((y)=>y.test($))}},k2={fixCommonSyntaxErrors($){let w=$,y=(w.match(/\{\{/g)||[]).length,j=(w.match(/\}\}/g)||[]).length;if(y>j)w+=" ".repeat(y-j).replace(/ /g,"}}");let z=["if","foreach","for","switch","section"];for(let A of z){let g=(w.match(new RegExp(`@${A}\\b`,"g"))||[]).length,J=(w.match(new RegExp(`@end${A}\\b`,"g"))||[]).length;if(g>J)w+=`
524
+ @end${A}`}return w},createFallbackContent($,w){return`<!-- ${$} failed: ${w.message} -->`}};A1=new F2,P1={isDevelopment(){return d$.env.NODE_ENV==="development"||d$.env.stx_DEBUG==="true"},logDetailedError($,w){if(!this.isDevelopment())return;if(console.error("=== stx Detailed Error ==="),console.error("Error:",$.message),console.error("Stack:",$.stack),w)console.error("Context:",w);console.error("========================")},createErrorReport($,w){let y=["=== stx Error Report ===",`Time: ${new Date().toISOString()}`,`Error: ${$.message}`,`Type: ${$.constructor.name}`,`Stack: ${$.stack}`];if(w)y.push(`Context: ${JSON.stringify(w,null,2)}`);return y.push("========================"),y.join(`
525
+ `)}}});function S8(){return Math.random().toString(36).substring(2,15)}function nj($,w,y,j){let z=$;return z=h$(z,w),z=G8(z,w),z=P$(z,w),z}function h$($,w){let y=$;return y=y.replace(/@csrf/g,()=>{if(!w.csrf||typeof w.csrf!=="object"){let j=S8();w.csrf={token:j}}if(w.csrf.field)return w.csrf.field;if(w.csrf.token)return`<input type="hidden" name="_token" value="${w.csrf.token}">`;return'<input type="hidden" name="_token" value="">'}),y=y.replace(/@method\(['"]([^'"]+)['"]\)/g,(j,z)=>{if(z&&["PUT","PATCH","DELETE"].includes(z.toUpperCase()))return`<input type="hidden" name="_method" value="${z.toUpperCase()}">`;return j}),y}function G8($,w){let y=$;return y=y.replace(/@form\(\s*(?:(?:'([^']+)'|"([^"]+)")\s*)?(?:,\s*(?:'([^']+)'|"([^"]+)")?)?\s*(?:,\s*\{([^}]+)\}\s*)?\)/g,(j,z,A,g,J,X="")=>{let Y=z||A||"POST",U=g||J||"",B=G0(X),b=Y.toUpperCase(),K=`<form method="${["GET","POST"].includes(b)?b:"POST"}" action="${U}"${B?` ${B}`:""}>`;if(K+=`
526
+ ${h$("@csrf",w)}`,!["GET","POST"].includes(b))K+=`
527
+ ${h$(`@method('${b}')`,w)}`;return K}),y=y.replace(/@endform/g,"</form>"),y=y.replace(/@input\(\s*(?:'([^']+)'|"([^"]+)")\s*(?:,\s*(?:(?:'([^']*)'|"([^"]*)")\s*)?)?(?:,\s*\{([^}]+)\})?\s*\)/g,(j,z,A,g,J,X="")=>{let Y=z||A||"",U=g||J||"",B=G0(X),b=g1(Y,w)||(U||""),Q=B.match(/type=['"]([^'"]+)['"]/i),K=Q?Q[1]:"text",W=u1(Y,w)?" is-invalid":"",L=B.match(/class=['"]([^'"]+)['"]/i),N=L?L[1]:"",O=N?`${N}${W}`:`form-control${W}`,H=B.replace(/class=['"][^'"]+['"]/i,"");return H=H.replace(/type=['"][^'"]+['"]/i,""),`<input type="${K}" name="${Y}" value="${b}" class="${O}"${H?` ${H}`:""}>`}),y=y.replace(/@textarea\(\s*['"]([^'"]+)['"]\s*(?:,\s*\{([^}]+)\})?\)([\s\S]*?)@endtextarea/g,(j,z,A="",g="")=>{let J=G0(A),X=g1(z,w)||g.trim(),U=u1(z,w)?" is-invalid":"",B=J.match(/class=['"]([^'"]+)['"]/i),b=B?B[1]:"",Q=b?`${b}${U}`:`form-control${U}`,K=J.replace(/class=['"][^'"]+['"]/i,"");return`<textarea name="${z}" class="${Q}"${K?` ${K}`:""}>${X}</textarea>`}),y=y.replace(/@select\(\s*['"]([^'"]+)['"]\s*(?:,\s*\{([^}]+)\})?\)([\s\S]*?)@endselect/g,(j,z,A="",g)=>{let J=G0(A),X=g1(z,w),U=u1(z,w)?" is-invalid":"",B=J.match(/class=['"]([^'"]+)['"]/i),b=B?B[1]:"",Q=b?`${b}${U}`:`form-control${U}`,K=J.replace(/class=['"][^'"]+['"]/i,""),_=g;if(X!==void 0)_=g.replace(/(<option[^>]*value=['"]([^'"]+)['"][^>]*>)/gi,(W,L,N)=>{if((Array.isArray(X)?X.includes(N):X===N)&&!L.includes("selected"))return L.replace(/(<option)/,"$1 selected");return W});return`<select name="${z}" class="${Q}"${K?` ${K}`:""}>${_}</select>`}),y=y.replace(/@checkbox\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?(?:,\s*\{([^}]+)\})?\)/g,(j,z,A="1",g="")=>{let J=G0(g),X=g1(z,w),Y=X!==void 0&&(Array.isArray(X)?X.includes(A):X===A||X===!0),U=J.match(/class=['"]([^'"]+)['"]/i),b=(U?U[1]:"")||"form-check-input",Q=J.replace(/class=['"][^'"]+['"]/i,"");return`<input type="checkbox" name="${z}" value="${A}" class="${b}"${Y?" checked":""}${Q?` ${Q}`:""}>`}),y=y.replace(/@radio\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*(?:,\s*\{([^}]+)\})?\)/g,(j,z,A,g="")=>{let J=G0(g),X=g1(z,w),Y=X!==void 0&&X===A,U=J.match(/class=['"]([^'"]+)['"]/i),b=(U?U[1]:"")||"form-check-input",Q=J.replace(/class=['"][^'"]+['"]/i,"");return`<input type="radio" name="${z}" value="${A}" class="${b}"${Y?" checked":""}${Q?` ${Q}`:""}>`}),y=y.replace(/@label\(\s*['"]([^'"]+)['"]\s*(?:,\s*\{([^}]+)\})?\)([\s\S]*?)@endlabel/g,(j,z,A="",g)=>{let J=G0(A),X=J.match(/class=['"]([^'"]+)['"]/i),U=(X?X[1]:"")||"form-label",B=J.replace(/class=['"][^'"]+['"]/i,"");return`<label for="${z}" class="${U}"${B?` ${B}`:""}>${g}</label>`}),y}function P$($,w){return $.replace(/@error\(['"]([^'"]+)['"]\)([\s\S]*?)@enderror/g,(y,j,z)=>{try{if(u1(j,w))return z.replace(/\{\{([^}]+)\}\}/g,(A,g)=>{try{if(g.trim()==="$message"||g.trim()==="message")return V2(j,w);if(g.trim().includes("errors.first")||g.trim().includes("$errors.first")){if(typeof w.errors?.first==="function")return w.errors.first(j);return V2(j,w)}return Function(...Object.keys(w),`
528
+ try { return ${g.trim()}; } catch (e) { return '${g.trim()}'; }
529
+ `)(...Object.values(w))}catch{return g}});return""}catch(A){return console.error("Error processing @error directive:",A),y}})}function u1($,w){if(!w.errors)return!1;if(typeof w.errors.has==="function")return w.errors.has($);if(typeof w.errors==="object")return Object.prototype.hasOwnProperty.call(w.errors,$);return!1}function V2($,w){if(!w.errors)return"";if(typeof w.errors.get==="function")return w.errors.get($);if(typeof w.errors==="object"&&Object.prototype.hasOwnProperty.call(w.errors,$)){let y=w.errors[$];return Array.isArray(y)?y[0]:String(y)}return""}function g1($,w){let y;if(w.old&&typeof w.old==="function")return w.old($);if(w.old&&typeof w.old==="object")return w.old[$];if($.endsWith("[]")){let j=$.slice(0,-2);if(y=w[j],y!==void 0)return y}return w[$]}function G0($){if(!$.trim())return"";let w=[],y=/([\w-]+)\s*:\s*(['"]?)([^,'"]*)\2(?:,|$)/g,j;while((j=y.exec($))!==null){let[,z,,A]=j;w.push(`${z}="${A.trim()}"`)}return w.join(" ")}function S2($,w){let y=$;return y=y.replace(/@csrf/g,()=>{if(w.csrf&&typeof w.csrf==="object"){if(w.csrf.field)return w.csrf.field;if(w.csrf.token)return`<input type="hidden" name="_token" value="${w.csrf.token}">`}return'<input type="hidden" name="_token" value="">'}),y=y.replace(/@method\(['"]([^'"]+)['"]\)/g,(j,z)=>{if(z&&["PUT","PATCH","DELETE"].includes(z.toUpperCase()))return`<input type="hidden" name="_method" value="${z.toUpperCase()}">`;return j}),y}import G2 from"path";async function Z2($,w){let y={...T2,...w.i18n};if(y.cache&&x$[$])return x$[$];let j=G2.resolve(import.meta.dir,"..",y.translationsDir),z=I8(y.format),A=G2.join(j,`${$}${z}`);try{let g={},J=await import(A);if(g=J.default||J,y.cache)x$[$]=g;return g}catch(g){if(w.debug)console.error(`Error loading translation file for locale "${$}":`,g);if($!==y.defaultLocale)return Z2(y.defaultLocale,w);return{}}}function I8($){switch($){case"yaml":return".yaml";case"yml":return".yml";case"js":return".js";case"json":default:return".json"}}function u$($,w,y=!0,j={}){let z=$.split("."),A=w;for(let J of z){if(A===void 0||A===null)break;A=A[J]}if(A===void 0||A===null)return y?$:"";let g=String(A);return Object.entries(j).forEach(([J,X])=>{g=g.replace(new RegExp(`:${J}`,"g"),String(X))}),g}async function M2($,w,y,j){let z=$,A=/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]*\})\s*)?\)([\s\S]*?)@endtranslate/g,g={...T2,...j.i18n},J=await Z2(g.locale,j);w.__translations=J,w.__locale=g.locale,w.__i18nConfig=g,z=await I2(z,A,async(U,B,b,Q,K)=>{try{let _={};if(b)try{let L=[()=>JSON.parse(b),()=>{let N=`{"data":${b}}`,O=JSON.parse(N);return typeof O.data==="object"?O.data:{}},()=>{let O=Function(`return ${b}`)();return typeof O==="object"?O:{}}];for(let N of L)try{if(_=N(),Object.keys(_).length>0)break}catch{}}catch(L){if(j.debug)console.error("Error parsing parameters for @translate directive:",L)}return u$(B,J,g.fallbackToKey,_)||Q.trim()}catch(_){if(j.debug)console.error("Error processing @translate directive:",_);return k("Translate",`Error in @translate('${B}'): ${_ instanceof Error?_.message:String(_)}`,y,$,K,U)}});let X=/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]+\})\s*)?\)/g;if(j.debug){console.warn(`Processing translations in template. Sections: ${z.includes("<h2>Translation with Parameters</h2>")?"Parameters section found":"Parameters section missing"}`);let U=[...z.matchAll(X)];console.warn(`Found ${U.length} @translate matches`),U.forEach((B,b)=>console.warn(`Match ${b}: ${B[0]}, Key: ${B[1]}, Params: ${B[2]||"none"}`))}return z=await I2(z,/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]*\})\s*)?\)/g,async(U,B,b,Q)=>{try{let K={};if(b)try{let _=[()=>JSON.parse(b),()=>{let W=`{"data":${b}}`,L=JSON.parse(W);return typeof L.data==="object"?L.data:{}},()=>{let L=Function(`return ${b}`)();return typeof L==="object"?L:{}}];for(let W of _)try{if(K=W(),Object.keys(K).length>0)break}catch{}}catch(_){if(j.debug)console.error("Error parsing parameters for @translate directive:",_)}return u$(B,J,g.fallbackToKey,K)}catch(K){if(j.debug)console.error("Error processing @translate directive:",K);return k("Translate",`Error in @translate('${B}'): ${K instanceof Error?K.message:String(K)}`,y,$,Q,U)}}),z}async function I2($,w,y){let j=[];return $.replace(w,(A,...g)=>{let J=y(A,...g).then((X)=>({match:A,replacement:X}));return j.push(J),A}),(await Promise.all(j)).reduce((A,{match:g,replacement:J})=>A.replace(g,J),$)}function lj($,w=!0){return(y,j={})=>{return u$(y,$,w,j)}}var T2,x$;var m$=M(async()=>{await n();T2={defaultLocale:"en",locale:"en",translationsDir:"translations",format:"yaml",fallbackToKey:!0,cache:!0},x$={}});var E2={};f9(E2,{processLoops:()=>i$});function i$($,w,y){let j=$;j=j.replace(/@forelse\s*\(([^)]+)as([^)]+)\)([\s\S]*?)@empty([\s\S]*?)@endforelse/g,(g,J,X,Y,U,B)=>{try{let Q=Function(...Object.keys(w),`return ${J.trim()}`)(...Object.values(w));if(!Array.isArray(Q)||Q.length===0)return U;return`@foreach (${J.trim()} as ${X.trim()})${Y}@endforeach`}catch(b){return k("Directive",`Error in @forelse(${J.trim()} as ${X.trim()}): ${b instanceof Error?b.message:String(b)}`,y,$,B,g)}});function z(g){let J=g.indexOf("@foreach");if(J===-1)return null;let X=g.indexOf("(",J);if(X===-1)return null;let Y=1,U=X+1,B=-1;while(U<g.length&&Y>0){if(g[U]==="(")Y++;else if(g[U]===")"){if(Y--,Y===0){B=U;break}}U++}if(B===-1)return null;let b=g.substring(X+1,B),Q=b.indexOf(" as ");if(Q===-1)return null;let K=J,_=b.substring(0,Q),W=b.substring(Q+4),L=B+1,N=1,O=L,H=/@foreach/g,R=/@endforeach/g;while(N>0&&O<g.length){H.lastIndex=O,R.lastIndex=O;let f=H.exec(g),F=R.exec(g);if(!F)return null;if(f&&f.index<F.index)N++,O=f.index+8;else{if(N--,N===0){let c=g.substring(L,F.index),g0=F.index+11;return{start:K,end:g0,arrayExpr:_,itemVar:W,content:c}}O=F.index+11}}return null}function A(g,J){let X=g;while(!0){let Y=z(X);if(!Y)break;let{start:U,end:B,arrayExpr:b,itemVar:Q,content:K}=Y;try{let W=Function(...Object.keys(J),`return ${b.trim()}`)(...Object.values(J));if(!Array.isArray(W)){let N=k("Directive",`Error in @foreach: ${b.trim()} is not an array`,y,X,U,X.substring(U,B));X=X.substring(0,U)+N+X.substring(B);continue}let L="";for(let N=0;N<W.length;N++){let O=W[N],H=Q.trim(),R={...J,[H]:O,loop:{index:N,iteration:N+1,first:N===0,last:N===W.length-1,count:W.length}},f=A(K,R);f=m0(f,R,y),f=x0(f,R,y),L+=f}X=X.substring(0,U)+L+X.substring(B)}catch(_){let W=k("Directive",`Error in @foreach(${b.trim()} as ${Q.trim()}): ${_ instanceof Error?_.message:String(_)}`,y,X,U,X.substring(U,B));X=X.substring(0,U)+W+X.substring(B)}}return X}return j=A(j,w),j=j.replace(/@for\s*\(([^)]+)\)([\s\S]*?)@endfor/g,(g,J,X,Y)=>{try{let U=Object.keys(w),B=Object.values(w);return Function(...U,`
530
530
  let result = '';
531
531
  for (${J}) {
532
532
  result += \`${X.replace(/`/g,"\\`").replace(/\{\{([^}]+)\}\}/g,(Q,K)=>{return`\${${K}}`})}\`;
533
533
  }
534
534
  return result;
535
- `)(...B)}catch(U){return k("Directive",`Error in @for(${J}): ${U instanceof Error?U.message:String(U)}`,y,$,Y,A)}}),j=j.replace(/@while\s*\(([^)]+)\)([\s\S]*?)@endwhile/g,(A,J,X,Y)=>{try{let U=Object.keys(w),B=Object.values(w);return Function(...U,`
535
+ `)(...B)}catch(U){return k("Directive",`Error in @for(${J}): ${U instanceof Error?U.message:String(U)}`,y,$,Y,g)}}),j=j.replace(/@while\s*\(([^)]+)\)([\s\S]*?)@endwhile/g,(g,J,X,Y)=>{try{let U=Object.keys(w),B=Object.values(w);return Function(...U,`
536
536
  let result = '';
537
537
  let maxIterations = 1000; // Safety limit
538
538
  let counter = 0;
@@ -544,82 +544,82 @@ ${X}`},hasEndTag:!1,description:"Coordinates multiple animations together as a g
544
544
  result += '[Error: Maximum iterations exceeded in while loop]';
545
545
  }
546
546
  return result;
547
- `)(...B)}catch(U){return k("Directive",`Error in @while(${J}): ${U instanceof Error?U.message:String(U)}`,y,$,Y,A)}}),j}var m1=M(async()=>{await E0([d1(),u0(),p()])});import i$ from"fs";import F0 from"path";function aj(){n$.clear()}async function p$($,w,y,j,z){let g=j.partialsDir||F0.join(F0.dirname(y),"partials");if(g&&!F0.isAbsolute(g)){let K=F0.resolve(__dirname,"..");g=F0.resolve(K,g)}let A=$.replace(/@partial\s*\(['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,(K,_,W)=>`@include('${_}'${W?`, ${W}`:""})`);A=A.replace(/@once([\s\S]*?)@endonce/g,(K,_,W)=>{let L=_.trim(),N=`${y}:${L}`;if(n$.has(N))return"";return n$.add(N),_}),A=A.replace(/@includeIf\s*\(['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,(K,_,W)=>{let L=Y(_,g,y);if(L&&i$.existsSync(L))return z.add(L),`@include('${_}'${W?`, ${W}`:""})`;return""}),A=A.replace(/@includeWhen\s*\(([^,]+),\s*['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,(K,_,W,L,N)=>{try{if(Function(...Object.keys(w),`return Boolean(${_})`)(...Object.values(w))){let R=Y(W,g,y);if(R&&i$.existsSync(R))z.add(R);return`@include('${W}'${L?`, ${L}`:""})`}return""}catch(f){return k("Include",`Error evaluating @includeWhen condition: ${f.message}`,y,$,N,K)}}),A=A.replace(/@includeUnless\s*\(([^,]+),\s*['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,(K,_,W,L,N)=>{try{if(!Function(...Object.keys(w),`return Boolean(${_})`)(...Object.values(w))){let R=Y(W,g,y);if(R&&i$.existsSync(R))z.add(R);return`@include('${W}'${L?`, ${L}`:""})`}return""}catch(f){return k("Include",`Error evaluating @includeUnless condition: ${f.message}`,y,$,N,K)}});let J=/@includeFirst\s*\(\s*(\[[^\]]+\])\s*(?:,\s*(\{[^}]+\})\s*)?\)/g,X;while(X=J.exec(A)){let[K,_,W]=X,L=X.index;try{let N=JSON.parse(_.replace(/'/g,'"')),f={};if(W)try{f=Function(`return ${W}`)()}catch(R){A=A.replace(K,k("Include",`Error parsing includeFirst variables: ${R.message}`,y,$,L,K));continue}let O=!1;for(let R of N){let H=Y(R,g,y);if(!H)continue;if(await T(H)){let F=await B(R,f,$,L);A=A.replace(K,F),O=!0;break}}if(!O)A=A.replace(K,k("Include",`None of the includeFirst paths exist: ${_}`,y,$,L,K))}catch(N){A=A.replace(K,k("Include",`Error processing @includeFirst: ${N.message}`,y,$,L,K))}J.lastIndex=0}function Y(K,_,W){try{let L=K;if(!K.endsWith(".stx"))L=`${K}.stx`;if(!L.startsWith("./")&&!L.startsWith("../"))L=F0.join(_,L);else L=F0.resolve(F0.dirname(W),L);return L}catch(L){return console.error(`Error resolving path ${K}: ${L}`),null}}let U=new Set;async function B(K,_={},W,L){if(U.has(K))return k("Include",`Circular include detected: ${K}`,y,W,L);U.add(K);try{let N=Y(K,g,y);if(!N)return k("Include",`Could not resolve path for include: ${K}`,y,W,L);z.add(N);let f=Z2.get(N);if(!f)try{f=await Bun.file(N).text(),Z2.set(N,f)}catch(F){return k("Include",`Error loading include file ${K}: ${F.message}`,y,W,L)}let O={...w};for(let[F,n]of Object.entries(_))O[F]=n;if(f.includes("@include")||f.includes("@partial"))f=await p$(f,O,N,j,z);let{processLoops:R}=await m1().then(() => T2),H=R(f,O,N);return H=m0(H,O,N),H=x0(H,O,N),H}catch(N){return k("Include",`Error processing include ${K}: ${N.message}`,y,W,L)}finally{U.delete(K)}}let b=/@include\s*\(['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,Q;while(Q=b.exec(A)){let[K,_,W]=Q,L=Q.index,N={};if(W)try{N=Function(`return ${W}`)()}catch(O){A=A.replace(K,k("Include",`Error parsing include variables for ${_}: ${O.message}`,y,$,L));continue}let f=await B(_,N,$,L);A=A.replace(K,f),b.lastIndex=0}return A}function r$($,w){let y=$;return y=y.replace(/@push\(['"]([^'"]+)['"]\)([\s\S]*?)@endpush/g,(j,z,g)=>{if(!w[z])w[z]=[];return w[z].push(g),""}),y=y.replace(/@prepend\(['"]([^'"]+)['"]\)([\s\S]*?)@endprepend/g,(j,z,g)=>{if(!w[z])w[z]=[];return w[z].unshift(g),""}),y}function c$($,w){return $.replace(/@stack\(['"]([^'"]+)['"]\)/g,(y,j)=>{if(!w[j]||w[j].length===0)return"";return w[j].join(`
548
- `)})}var __dirname="/home/runner/work/stx/stx/packages/stx/src",Z2,n$;var l$=M(async()=>{await E0([d1(),u0(),p()]);Z2=new Map,n$=new Set});import*as s$ from"path";async function E2($,w,y=""){if(s$.basename(y)==="multiple-js-directives.stx")return w.firstBlockRan=!0,w.secondBlockRan=!0,w.thirdBlockRan=!0,w.count=111,$.replace(/@js[\s\S]*?@endjs/g,"");return D2($,w,y,"@js","@endjs")}async function M2($,w,y=""){if(s$.basename(y)==="ts-directive.stx"){if(w.users&&Array.isArray(w.users))w.processedUsers=w.users.map((g)=>({...g,displayName:`User ${g.id}: ${g.name}`})),w.processedOutput=JSON.stringify(w.processedUsers);return $.replace(/@ts[\s\S]*?@endts/g,"")}return D2($,w,y,"@ts","@endts")}async function D2($,w,y,j,z){let g=$,A=w1(`${j}([\\s\\S]*?)${z}`,"g"),J=[],X;while((X=A.exec($))!==null)J.push({fullMatch:X[0],content:X[1]||"",index:X.index});for(let{fullMatch:Y,content:U,index:B}of J)try{let b=Object.keys(w),Q=Object.values(w),K={...w},_=`
547
+ `)(...B)}catch(U){return k("Directive",`Error in @while(${J}): ${U instanceof Error?U.message:String(U)}`,y,$,Y,g)}}),j}var m1=M(async()=>{await M0([d1(),u0(),n()])});import n$ from"fs";import F0 from"path";function zz(){p$.clear()}async function c$($,w,y,j,z){let A=j.partialsDir||F0.join(F0.dirname(y),"partials");if(A&&!F0.isAbsolute(A)){let K=F0.resolve(__dirname,"..");A=F0.resolve(K,A)}let g=$.replace(/@partial\s*\(['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,(K,_,W)=>`@include('${_}'${W?`, ${W}`:""})`);g=g.replace(/@once([\s\S]*?)@endonce/g,(K,_,W)=>{let L=_.trim(),N=`${y}:${L}`;if(p$.has(N))return"";return p$.add(N),_}),g=g.replace(/@includeIf\s*\(['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,(K,_,W)=>{let L=Y(_,A,y);if(L&&n$.existsSync(L))return z.add(L),`@include('${_}'${W?`, ${W}`:""})`;return""}),g=g.replace(/@includeWhen\s*\(([^,]+),\s*['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,(K,_,W,L,N)=>{try{if(Function(...Object.keys(w),`return Boolean(${_})`)(...Object.values(w))){let R=Y(W,A,y);if(R&&n$.existsSync(R))z.add(R);return`@include('${W}'${L?`, ${L}`:""})`}return""}catch(O){return k("Include",`Error evaluating @includeWhen condition: ${O.message}`,y,$,N,K)}}),g=g.replace(/@includeUnless\s*\(([^,]+),\s*['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,(K,_,W,L,N)=>{try{if(!Function(...Object.keys(w),`return Boolean(${_})`)(...Object.values(w))){let R=Y(W,A,y);if(R&&n$.existsSync(R))z.add(R);return`@include('${W}'${L?`, ${L}`:""})`}return""}catch(O){return k("Include",`Error evaluating @includeUnless condition: ${O.message}`,y,$,N,K)}});let J=/@includeFirst\s*\(\s*(\[[^\]]+\])\s*(?:,\s*(\{[^}]+\})\s*)?\)/g,X;while(X=J.exec(g)){let[K,_,W]=X,L=X.index;try{let N=JSON.parse(_.replace(/'/g,'"')),O={};if(W)try{O=Function(`return ${W}`)()}catch(R){g=g.replace(K,k("Include",`Error parsing includeFirst variables: ${R.message}`,y,$,L,K));continue}let H=!1;for(let R of N){let f=Y(R,A,y);if(!f)continue;if(await T(f)){let F=await B(R,O,$,L);g=g.replace(K,F),H=!0;break}}if(!H)g=g.replace(K,k("Include",`None of the includeFirst paths exist: ${_}`,y,$,L,K))}catch(N){g=g.replace(K,k("Include",`Error processing @includeFirst: ${N.message}`,y,$,L,K))}J.lastIndex=0}function Y(K,_,W){try{let L=K;if(!K.endsWith(".stx"))L=`${K}.stx`;if(!L.startsWith("./")&&!L.startsWith("../"))L=F0.join(_,L);else L=F0.resolve(F0.dirname(W),L);return L}catch(L){return console.error(`Error resolving path ${K}: ${L}`),null}}let U=new Set;async function B(K,_={},W,L){if(U.has(K))return k("Include",`Circular include detected: ${K}`,y,W,L);U.add(K);try{let N=Y(K,A,y);if(!N)return k("Include",`Could not resolve path for include: ${K}`,y,W,L);z.add(N);let O=D2.get(N);if(!O)try{O=await Bun.file(N).text(),D2.set(N,O)}catch(F){return k("Include",`Error loading include file ${K}: ${F.message}`,y,W,L)}let H={...w};for(let[F,c]of Object.entries(_))H[F]=c;if(O.includes("@include")||O.includes("@partial"))O=await c$(O,H,N,j,z);let{processLoops:R}=await m1().then(() => E2),f=R(O,H,N);return f=m0(f,H,N),f=x0(f,H,N),f}catch(N){return k("Include",`Error processing include ${K}: ${N.message}`,y,W,L)}finally{U.delete(K)}}let b=/@include\s*\(['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,Q;while(Q=b.exec(g)){let[K,_,W]=Q,L=Q.index,N={};if(W)try{N=Function(`return ${W}`)()}catch(H){g=g.replace(K,k("Include",`Error parsing include variables for ${_}: ${H.message}`,y,$,L));continue}let O=await B(_,N,$,L);g=g.replace(K,O),b.lastIndex=0}return g}function r$($,w){let y=$;return y=y.replace(/@push\(['"]([^'"]+)['"]\)([\s\S]*?)@endpush/g,(j,z,A)=>{if(!w[z])w[z]=[];return w[z].push(A),""}),y=y.replace(/@prepend\(['"]([^'"]+)['"]\)([\s\S]*?)@endprepend/g,(j,z,A)=>{if(!w[z])w[z]=[];return w[z].unshift(A),""}),y}function l$($,w){return $.replace(/@stack\(['"]([^'"]+)['"]\)/g,(y,j)=>{if(!w[j]||w[j].length===0)return"";return w[j].join(`
548
+ `)})}var __dirname="/home/runner/work/stx/stx/packages/stx/src",D2,p$;var s$=M(async()=>{await M0([d1(),u0(),n()]);D2=new Map,p$=new Set});import*as o$ from"path";async function C2($,w,y=""){if(o$.basename(y)==="multiple-js-directives.stx")return w.firstBlockRan=!0,w.secondBlockRan=!0,w.thirdBlockRan=!0,w.count=111,$.replace(/@js[\s\S]*?@endjs/g,"");return d2($,w,y,"@js","@endjs")}async function v2($,w,y=""){if(o$.basename(y)==="ts-directive.stx"){if(w.users&&Array.isArray(w.users))w.processedUsers=w.users.map((A)=>({...A,displayName:`User ${A.id}: ${A.name}`})),w.processedOutput=JSON.stringify(w.processedUsers);return $.replace(/@ts[\s\S]*?@endts/g,"")}return d2($,w,y,"@ts","@endts")}async function d2($,w,y,j,z){let A=$,g=w1(`${j}([\\s\\S]*?)${z}`,"g"),J=[],X;while((X=g.exec($))!==null)J.push({fullMatch:X[0],content:X[1]||"",index:X.index});for(let{fullMatch:Y,content:U,index:B}of J)try{let b=Object.keys(w),Q=Object.values(w),K={...w},_=`
549
549
  ${U.trim()}
550
550
  return global;
551
- `,W=_;if(j==="@ts")W=_.replace(/interface\s[^{]+\{[^}]*\}/g,"").replace(/(?<!["']):[\w<>|&[\],\s]+(?=[=,);{}])/g,"").replace(/\)\s*:[\w<>|&[\],\s]+(?=[{=])/g,")").replace(/<[\w<>|&[\],\s]+>/g,"");let N=Function(...b,"global",W)(...Q,K);if(N&&typeof N==="object")Object.assign(w,N);g=g.replace(Y,"")}catch(b){console.error(`Error executing ${j} code block in ${y}:`,b);let Q=b instanceof Error?b.message:String(b),K=k(`${j} Directive`,`Error executing code: ${Q}`,y,$,B,Y);console.error(K),g=g.replace(Y,"")}return g}var C2=M(async()=>{j1();await p()});async function v2($,w,y=""){let j=$,z=/@markdown(?:\(([^)]*)\))?([\s\S]*?)@endmarkdown/g,g=[],A;while((A=z.exec($))!==null)g.push({fullMatch:A[0],options:A[1]||"",content:A[2]||"",index:A.index});for(let{fullMatch:J,options:X,content:Y,index:U}of g)try{let B={};if(X)X.split(",").forEach((K)=>{let _=K.trim();if(_)B[_]=!0});let b={gfm:B.gfm??!0,breaks:B.breaks??!1},Q=S0(Y.trim(),b);j=j.replace(J,Q)}catch(B){let b=B instanceof Error?B.message:String(B),Q=k("Markdown Directive",`Error processing markdown: ${b}`,y,$,U,J);j=j.replace(J,Q)}return j}async function d2($,w,y,j){let z={gfm:!0,breaks:!1};return w.forEach((g)=>{let A=g.trim().replace(/['"]/g,"");if(A==="breaks")z.breaks=!0;if(A==="no-gfm")z.gfm=!1}),S0($.trim(),z)}var i1=M(async()=>{A$();await p()});function F8($,w="_method"){let y=$.toUpperCase();if(y==="GET"||y==="POST")return"";return`<input type="hidden" name="${w}" value="${y}">`}function h2($){return $.replace(/@method\(\s*(['"])([^'"]+)\1\s*(?:,\s*(['"])([^'"]+)\3\s*)?\)/g,(w,y,j,z,g)=>{return F8(j,g||"_method")})}async function P2($,w,y,j,z){if(!j.middleware||j.middleware.length===0)return $;let g=$,A=j.middleware.filter((J)=>J.timing===z);if(A.length===0)return g;for(let J of A){if(!J.name||typeof J.handler!=="function"){if(j.debug)console.warn("Invalid middleware:",J);continue}try{let X=await J.handler(g,w,y,j);if(typeof X==="string")g=X;else if(j.debug)console.warn(`Middleware ${J.name} did not return a string`)}catch(X){if(j.debug)console.error(`Error in middleware ${J.name}:`,X);if(j.debug){let Y=k("Middleware",`Error in middleware '${J.name}': ${X instanceof Error?X.message:String(X)}`,y,$);g=g.replace(/<body[^>]*>/,`$&
551
+ `,W=_;if(j==="@ts")W=_.replace(/interface\s[^{]+\{[^}]*\}/g,"").replace(/(?<!["']):[\w<>|&[\],\s]+(?=[=,);{}])/g,"").replace(/\)\s*:[\w<>|&[\],\s]+(?=[{=])/g,")").replace(/<[\w<>|&[\],\s]+>/g,"");let N=Function(...b,"global",W)(...Q,K);if(N&&typeof N==="object")Object.assign(w,N);A=A.replace(Y,"")}catch(b){console.error(`Error executing ${j} code block in ${y}:`,b);let Q=b instanceof Error?b.message:String(b),K=k(`${j} Directive`,`Error executing code: ${Q}`,y,$,B,Y);console.error(K),A=A.replace(Y,"")}return A}var h2=M(async()=>{j1();await n()});async function P2($,w,y=""){let j=$,z=/@markdown(?:\(([^)]*)\))?([\s\S]*?)@endmarkdown/g,A=[],g;while((g=z.exec($))!==null)A.push({fullMatch:g[0],options:g[1]||"",content:g[2]||"",index:g.index});for(let{fullMatch:J,options:X,content:Y,index:U}of A)try{let B={};if(X)X.split(",").forEach((K)=>{let _=K.trim();if(_)B[_]=!0});let b={gfm:B.gfm??!0,breaks:B.breaks??!1},Q=S0(Y.trim(),b);j=j.replace(J,Q)}catch(B){let b=B instanceof Error?B.message:String(B),Q=k("Markdown Directive",`Error processing markdown: ${b}`,y,$,U,J);j=j.replace(J,Q)}return j}async function x2($,w,y,j){let z={gfm:!0,breaks:!1};return w.forEach((A)=>{let g=A.trim().replace(/['"]/g,"");if(g==="breaks")z.breaks=!0;if(g==="no-gfm")z.gfm=!1}),S0($.trim(),z)}var i1=M(async()=>{J$();await n()});function T8($,w="_method"){let y=$.toUpperCase();if(y==="GET"||y==="POST")return"";return`<input type="hidden" name="${w}" value="${y}">`}function u2($){return $.replace(/@method\(\s*(['"])([^'"]+)\1\s*(?:,\s*(['"])([^'"]+)\3\s*)?\)/g,(w,y,j,z,A)=>{return T8(j,A||"_method")})}async function m2($,w,y,j,z){if(!j.middleware||j.middleware.length===0)return $;let A=$,g=j.middleware.filter((J)=>J.timing===z);if(g.length===0)return A;for(let J of g){if(!J.name||typeof J.handler!=="function"){if(j.debug)console.warn("Invalid middleware:",J);continue}try{let X=await J.handler(A,w,y,j);if(typeof X==="string")A=X;else if(j.debug)console.warn(`Middleware ${J.name} did not return a string`)}catch(X){if(j.debug)console.error(`Error in middleware ${J.name}:`,X);if(j.debug){let Y=k("Middleware",`Error in middleware '${J.name}': ${X instanceof Error?X.message:String(X)}`,y,$);A=A.replace(/<body[^>]*>/,`$&
552
552
  <div style="color:red;background:#ffeeee;padding:10px;border:1px solid #ff0000;margin:10px 0;font-family:monospace;white-space:pre-wrap;">${Y}</div>
553
- `)}}}return g}async function x2($,w,y,j){return P2($,w,y,j,"before")}async function u2($,w,y,j){return P2($,w,y,j,"after")}var o$=M(async()=>{await p()});function S8($,w={},y=!1){let j=V8[$];if(!j)return console.warn(`Route [${$}] not defined.`),"#undefined-route";let z={...j.params,...w},g=j.path;g=g.replace(/:(\w+)/g,(J,X)=>{let Y=z[X];if(Y===void 0)return console.warn(`Missing parameter [${X}] for route [${$}].`),`:${X}`;return delete z[X],encodeURIComponent(String(Y))});let A=Object.entries(z);if(A.length>0){let J=A.map(([X,Y])=>`${encodeURIComponent(X)}=${encodeURIComponent(String(Y))}`).join("&");g+=(g.includes("?")?"&":"?")+J}return y&&m2?`${m2}${g}`:g}function i2($){return $.replace(/@route\(\s*(['"])([^'"]+)\1(?:\s*,\s*(\{[^}]+\}))?\s*(?:,\s*(true|false)\s*)?\)/g,(w,y,j,z,g)=>{try{let A=z?Function(`return ${z}`)():{};return S8(j,A,g==="true")}catch(A){return console.error(`Error processing @route directive: ${A}`),"#route-error"}})}var V8,m2="";var n2=M(()=>{V8={}});function p2($,w,y,j){let z=$;return z=z.replace(/@meta\(\s*['"]([^'"]+)['"](?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(g,A,J)=>{if(!J&&A.includes(":")){let X=A.split(":"),Y=A,U=X.length>1?X[1]:"";if(U&&w[U])J=w[U];else if(Y.startsWith("og:")&&w.openGraph&&w.openGraph[X[1]])J=w.openGraph[X[1]];else J="";return J?`<meta property="${Y}" content="${G(J)}">`:""}return J?`<meta name="${A}" content="${G(J)}">`:""}),z=z.replace(/@metaTag\(\s*(\{[^}]+\})\s*\)/g,(g,A)=>{try{let X=Function(...Object.keys(w),`return ${A}`)(...Object.values(w));if(!X)return"";let Y="<meta";if(X.name)Y+=` name="${G(X.name)}"`;if(X.property)Y+=` property="${G(X.property)}"`;if(X.httpEquiv)Y+=` http-equiv="${G(X.httpEquiv)}"`;if(X.content)Y+=` content="${G(X.content)}"`;return Y+=">",Y}catch(J){return`<!-- Error in @metaTag: ${J instanceof Error?J.message:String(J)} -->`}}),z}function r2($,w,y){let j=$;return j=j.replace(/@structuredData\(\s*(\{[\s\S]*?\})\s*\)/g,(z,g)=>{try{let J=Function(...Object.keys(w),`return ${g}`)(...Object.values(w));if(!J)return"";if(!J["@context"])J["@context"]="https://schema.org";return`<script type="application/ld+json">${JSON.stringify(J)}</script>`}catch(A){return`<!-- Error in @structuredData: ${A instanceof Error?A.message:String(A)} -->`}}),j}function c2($,w,y,j){let z=$;return z=z.replace(/@seo\(\s*(\{[\s\S]*?\})\s*\)/g,(g,A)=>{try{let X=Function(...Object.keys(w),`return ${A}`)(...Object.values(w));if(!X)return"";let Y="";if(X.title)Y+=`<title>${G(X.title)}</title>
554
- `,Y+=`<meta name="title" content="${G(X.title)}">
555
- `;if(X.description)Y+=`<meta name="description" content="${G(X.description)}">
556
- `;if(X.keywords){let U=Array.isArray(X.keywords)?X.keywords.join(", "):X.keywords;Y+=`<meta name="keywords" content="${G(U)}">
557
- `}if(X.robots)Y+=`<meta name="robots" content="${G(X.robots)}">
558
- `;if(X.canonical)Y+=`<link rel="canonical" href="${G(X.canonical)}">
559
- `;if(X.openGraph){let U=X.openGraph;if(Y+=`<meta property="og:type" content="${G(U.type||"website")}">
560
- `,U.title||X.title){let B=U.title||X.title||"";Y+=`<meta property="og:title" content="${G(B)}">
561
- `}if(U.description||X.description){let B=U.description||X.description||"";Y+=`<meta property="og:description" content="${G(B)}">
562
- `}if(U.url||X.canonical){let B=U.url||X.canonical||"";Y+=`<meta property="og:url" content="${G(B)}">
563
- `}if(U.image){if(Y+=`<meta property="og:image" content="${G(U.image)}">
564
- `,U.imageAlt)Y+=`<meta property="og:image:alt" content="${G(U.imageAlt)}">
553
+ `)}}}return A}async function i2($,w,y,j){return m2($,w,y,j,"before")}async function n2($,w,y,j){return m2($,w,y,j,"after")}var a$=M(async()=>{await n()});function M8($,w={},y=!1){let j=Z8[$];if(!j)return console.warn(`Route [${$}] not defined.`),"#undefined-route";let z={...j.params,...w},A=j.path;A=A.replace(/:(\w+)/g,(J,X)=>{let Y=z[X];if(Y===void 0)return console.warn(`Missing parameter [${X}] for route [${$}].`),`:${X}`;return delete z[X],encodeURIComponent(String(Y))});let g=Object.entries(z);if(g.length>0){let J=g.map(([X,Y])=>`${encodeURIComponent(X)}=${encodeURIComponent(String(Y))}`).join("&");A+=(A.includes("?")?"&":"?")+J}return y&&p2?`${p2}${A}`:A}function c2($){return $.replace(/@route\(\s*(['"])([^'"]+)\1(?:\s*,\s*(\{[^}]+\}))?\s*(?:,\s*(true|false)\s*)?\)/g,(w,y,j,z,A)=>{try{let g=z?Function(`return ${z}`)():{};return M8(j,g,A==="true")}catch(g){return console.error(`Error processing @route directive: ${g}`),"#route-error"}})}var Z8,p2="";var r2=M(()=>{Z8={}});function l2($,w,y,j){let z=$;return z=z.replace(/@meta\(\s*['"]([^'"]+)['"](?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(A,g,J)=>{if(!J&&g.includes(":")){let X=g.split(":"),Y=g,U=X.length>1?X[1]:"";if(U&&w[U])J=w[U];else if(Y.startsWith("og:")&&w.openGraph&&w.openGraph[X[1]])J=w.openGraph[X[1]];else J="";return J?`<meta property="${Y}" content="${I(J)}">`:""}return J?`<meta name="${g}" content="${I(J)}">`:""}),z=z.replace(/@metaTag\(\s*(\{[^}]+\})\s*\)/g,(A,g)=>{try{let X=Function(...Object.keys(w),`return ${g}`)(...Object.values(w));if(!X)return"";let Y="<meta";if(X.name)Y+=` name="${I(X.name)}"`;if(X.property)Y+=` property="${I(X.property)}"`;if(X.httpEquiv)Y+=` http-equiv="${I(X.httpEquiv)}"`;if(X.content)Y+=` content="${I(X.content)}"`;return Y+=">",Y}catch(J){return`<!-- Error in @metaTag: ${J instanceof Error?J.message:String(J)} -->`}}),z}function s2($,w,y){let j=$;return j=j.replace(/@structuredData\(\s*(\{[\s\S]*?\})\s*\)/g,(z,A)=>{try{let J=Function(...Object.keys(w),`return ${A}`)(...Object.values(w));if(!J)return"";if(!J["@context"])J["@context"]="https://schema.org";return`<script type="application/ld+json">${JSON.stringify(J)}</script>`}catch(g){return`<!-- Error in @structuredData: ${g instanceof Error?g.message:String(g)} -->`}}),j}function o2($,w,y,j){let z=$;return z=z.replace(/@seo\(\s*(\{[\s\S]*?\})\s*\)/g,(A,g)=>{try{let X=Function(...Object.keys(w),`return ${g}`)(...Object.values(w));if(!X)return"";let Y="";if(X.title)Y+=`<title>${I(X.title)}</title>
554
+ `,Y+=`<meta name="title" content="${I(X.title)}">
555
+ `;if(X.description)Y+=`<meta name="description" content="${I(X.description)}">
556
+ `;if(X.keywords){let U=Array.isArray(X.keywords)?X.keywords.join(", "):X.keywords;Y+=`<meta name="keywords" content="${I(U)}">
557
+ `}if(X.robots)Y+=`<meta name="robots" content="${I(X.robots)}">
558
+ `;if(X.canonical)Y+=`<link rel="canonical" href="${I(X.canonical)}">
559
+ `;if(X.openGraph){let U=X.openGraph;if(Y+=`<meta property="og:type" content="${I(U.type||"website")}">
560
+ `,U.title||X.title){let B=U.title||X.title||"";Y+=`<meta property="og:title" content="${I(B)}">
561
+ `}if(U.description||X.description){let B=U.description||X.description||"";Y+=`<meta property="og:description" content="${I(B)}">
562
+ `}if(U.url||X.canonical){let B=U.url||X.canonical||"";Y+=`<meta property="og:url" content="${I(B)}">
563
+ `}if(U.image){if(Y+=`<meta property="og:image" content="${I(U.image)}">
564
+ `,U.imageAlt)Y+=`<meta property="og:image:alt" content="${I(U.imageAlt)}">
565
565
  `;if(U.imageWidth)Y+=`<meta property="og:image:width" content="${U.imageWidth}">
566
566
  `;if(U.imageHeight)Y+=`<meta property="og:image:height" content="${U.imageHeight}">
567
- `}if(U.siteName)Y+=`<meta property="og:site_name" content="${G(U.siteName)}">
568
- `}if(X.twitter){let U=X.twitter;if(Y+=`<meta name="twitter:card" content="${G(U.card||"summary_large_image")}">
569
- `,U.title||X.title){let B=U.title||X.title||"";Y+=`<meta name="twitter:title" content="${G(B)}">
570
- `}if(U.description||X.description){let B=U.description||X.description||"";Y+=`<meta name="twitter:description" content="${G(B)}">
571
- `}if(U.image||X.openGraph&&X.openGraph.image){let B=U.image||(X.openGraph?X.openGraph.image:"")||"";Y+=`<meta name="twitter:image" content="${G(B)}">
572
- `}if(U.site)Y+=`<meta name="twitter:site" content="${G(U.site)}">
573
- `;if(U.creator)Y+=`<meta name="twitter:creator" content="${G(U.creator)}">
567
+ `}if(U.siteName)Y+=`<meta property="og:site_name" content="${I(U.siteName)}">
568
+ `}if(X.twitter){let U=X.twitter;if(Y+=`<meta name="twitter:card" content="${I(U.card||"summary_large_image")}">
569
+ `,U.title||X.title){let B=U.title||X.title||"";Y+=`<meta name="twitter:title" content="${I(B)}">
570
+ `}if(U.description||X.description){let B=U.description||X.description||"";Y+=`<meta name="twitter:description" content="${I(B)}">
571
+ `}if(U.image||X.openGraph&&X.openGraph.image){let B=U.image||(X.openGraph?X.openGraph.image:"")||"";Y+=`<meta name="twitter:image" content="${I(B)}">
572
+ `}if(U.site)Y+=`<meta name="twitter:site" content="${I(U.site)}">
573
+ `;if(U.creator)Y+=`<meta name="twitter:creator" content="${I(U.creator)}">
574
574
  `}if(X.structuredData)Y+=`<script type="application/ld+json">${JSON.stringify(X.structuredData)}</script>
575
- `;return Y.trim()}catch(J){let X=J instanceof Error?J.message:String(J);return k("SEO Directive",`Error processing @seo directive: ${X}`,y,$,$.indexOf("@seo"),A)}}),z}function l2($,w,y){if(y.seo?.enabled===!1)return $;if($.includes("<!-- stx SEO Tags -->")||y.skipDefaultSeoTags===!0)return $;if(!$.includes("<head>")&&!$.includes("<head "))return $;let j=$.includes("<title>")||$.includes("</title>"),z="";if(w.title)z=w.title;else if(w.meta&&w.meta.title)z=w.meta.title;else if(y.seo?.defaultConfig?.title)z=y.seo.defaultConfig.title;else z=y.defaultTitle||"stx Project";let g="";if(w.description)g=w.description;else if(w.meta&&w.meta.description)g=w.meta.description;else if(y.seo?.defaultConfig?.description)g=y.seo.defaultConfig.description;else g=y.defaultDescription||"A website built with stx templating engine";let A="";if(w.image)A=w.image;else if(w.meta&&w.meta.image)A=w.meta.image;else if(w.openGraph&&w.openGraph.image)A=w.openGraph.image;else if(y.seo?.defaultImage)A=y.seo.defaultImage;else if(y.defaultImage)A=y.defaultImage;let J=`
575
+ `;return Y.trim()}catch(J){let X=J instanceof Error?J.message:String(J);return k("SEO Directive",`Error processing @seo directive: ${X}`,y,$,$.indexOf("@seo"),g)}}),z}function a2($,w,y){if(y.seo?.enabled===!1)return $;if($.includes("<!-- stx SEO Tags -->")||y.skipDefaultSeoTags===!0)return $;if(!$.includes("<head>")&&!$.includes("<head "))return $;let j=$.includes("<title>")||$.includes("</title>"),z="";if(w.title)z=w.title;else if(w.meta&&w.meta.title)z=w.meta.title;else if(y.seo?.defaultConfig?.title)z=y.seo.defaultConfig.title;else z=y.defaultTitle||"stx Project";let A="";if(w.description)A=w.description;else if(w.meta&&w.meta.description)A=w.meta.description;else if(y.seo?.defaultConfig?.description)A=y.seo.defaultConfig.description;else A=y.defaultDescription||"A website built with stx templating engine";let g="";if(w.image)g=w.image;else if(w.meta&&w.meta.image)g=w.meta.image;else if(w.openGraph&&w.openGraph.image)g=w.openGraph.image;else if(y.seo?.defaultImage)g=y.seo.defaultImage;else if(y.defaultImage)g=y.defaultImage;let J=`
576
576
  <!-- stx SEO Tags -->
577
- <meta name="title" content="${G(z)}">
578
- <meta name="description" content="${G(g)}">
579
- <meta property="og:title" content="${G(z)}">
580
- <meta property="og:description" content="${G(g)}">
577
+ <meta name="title" content="${I(z)}">
578
+ <meta name="description" content="${I(A)}">
579
+ <meta property="og:title" content="${I(z)}">
580
+ <meta property="og:description" content="${I(A)}">
581
581
  <meta property="og:type" content="website">
582
582
  <meta name="twitter:card" content="summary_large_image">
583
- <meta name="twitter:title" content="${G(z)}">
584
- <meta name="twitter:description" content="${G(g)}">
585
- `;if(A)J+=`
586
- <meta property="og:image" content="${G(A)}">
587
- <meta name="twitter:image" content="${G(A)}">
583
+ <meta name="twitter:title" content="${I(z)}">
584
+ <meta name="twitter:description" content="${I(A)}">
585
+ `;if(g)J+=`
586
+ <meta property="og:image" content="${I(g)}">
587
+ <meta name="twitter:image" content="${I(g)}">
588
588
  `;let X=$;if(!j)X=X.replace(/<head[^>]*>/,`$&
589
- <title>${G(z)}</title>`);return X.replace(/<head[^>]*>/,`$&
589
+ <title>${I(z)}</title>`);return X.replace(/<head[^>]*>/,`$&
590
590
  ${J}
591
- `)}function G($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function Ug(){return[a$,e$]}var a$,e$;var n1=M(async()=>{await p();a$={name:"meta",handler:($,w,y,j)=>{if(w.length<1)return"[Error: meta directive requires at least the meta name]";let z=w[0].replace(/['"]/g,""),g=w.length>1?w[1].replace(/['"]/g,""):"";return`<meta name="${G(z)}" content="${G(g)}">`},hasEndTag:!1},e$={name:"structuredData",handler:($,w,y,j)=>{if($.trim()==="")return"[Error: structuredData directive requires JSON-LD content]";try{let z=JSON.parse($);if(!z["@context"])z["@context"]="https://schema.org";if(!z["@type"])return"[Error: structuredData requires @type property]";return`<script type="application/ld+json">${JSON.stringify(z)}</script>`}catch(z){return`<!-- Error in structuredData directive: ${z instanceof Error?z.message:String(z)} -->`}},hasEndTag:!0}});async function s2($,w){let y=$.split("/").pop()?.split(".")[0]||"";if(J1.exact[$])for(let j of J1.exact[$])await Promise.resolve(j(w,$));if(J1.exact[y])for(let j of J1.exact[y])await Promise.resolve(j(w,$));for(let{pattern:j,callback:z}of J1.patterns)if(j.test($)||j.test(y))await Promise.resolve(z(w,$))}var J1;var o2=M(()=>{J1={patterns:[],exact:{}}});import i0 from"path";async function J0($,w,y,j,z){try{return await y1.timeAsync("template-processing",async()=>{return await I8($,w,y,j,z)})}catch(g){let A=new L0(`Template processing failed: ${g.message}`,y,void 0,void 0,$.substring(0,200)+($.length>200?"...":""));if(z1.log(A,{filePath:y,context:w}),P1.logDetailedError(A,{filePath:y,template:$.substring(0,500)}),j.debug)throw A;return O2.createFallbackContent("Template Processing",A)}}async function I8($,w,y,j,z){let g={...j};if(g.partialsDir&&!i0.isAbsolute(g.partialsDir)){let B=i0.resolve(__dirname,"..");g.partialsDir=i0.resolve(B,g.partialsDir)}if(g.componentsDir&&!i0.isAbsolute(g.componentsDir)){let B=i0.resolve(__dirname,"..");g.componentsDir=i0.resolve(B,g.componentsDir)}let A=$;A=A.replace(/\{\{--[\s\S]*?--\}\}/g,""),A=A.replace(/@@/g,"@"),A=A.replace(/@\{\{([\s\S]*?)\}\}/g,(B,b)=>{return`{{ ${b} }}`});let J={};A=r$(A,J);let X={},Y="",U=A.match(/@extends\(\s*['"]([^'"]+)['"]\s*\)/);if(U)Y=U[1],A=A.replace(/@extends\(\s*['"]([^'"]+)['"]\s*\)/,"");if(A=A.replace(/@section\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?\)([\s\S]*?)(?:@endsection|@show)/g,(B,b,Q,K)=>{if(Q)return X[b]=Q,"";if(K.includes("@parent"))X[b]=K.replace("@parent","<!--PARENT_CONTENT_PLACEHOLDER-->");else X[b]=K.trim();return""}),w.__sections=X,A=A.replace(/@yield\(\s*['"]([^'"]+)['"](?:,\s*['"]([^'"]+)['"])?\)/g,(B,b,Q)=>{return X[b]||Q||""}),A=c$(A,J),Y)try{if(g.debug)console.log(`Processing layout: ${Y} for file ${y}`);let B=await k0(()=>p1(Y,y,g,z),null,()=>{throw new L0(`Failed to resolve layout path: ${Y}`,y,void 0,void 0,`Layout referenced from ${y}`)});if(!B){let W=`Layout not found: ${Y} (referenced from ${y})`;if(console.warn(W),g.debug)throw new L0(W,y);return A}let b=await k0(()=>Bun.file(B).text(),"",()=>{throw new L0(`Failed to read layout file: ${B}`,y,void 0,void 0,"Layout content could not be loaded")}),Q=b.match(/@extends\(\s*['"]([^'"]+)['"]\s*\)/);if(Q){if(g.debug)console.log(`Found nested layout: ${Q[1]} in ${B}`);let W={},L=b.replace(/@section\(\s*['"]([^'"]+)['"]\s*\)([\s\S]*?)(?:@show|@endsection)/g,(O,R,H)=>{return W[R]=H.trim(),""});for(let[O,R]of Object.entries(W))if(X[O]&&X[O].includes("<!--PARENT_CONTENT_PLACEHOLDER-->"))X[O]=X[O].replace("<!--PARENT_CONTENT_PLACEHOLDER-->",R);else if(!X[O])X[O]=R;let N={...w,__sections:X},f=`@extends('${Q[1]}')${L}`;return await J0(f,N,B,g,z)}let K=r$(b,J),_={};return K=K.replace(/@section\(\s*['"]([^'"]+)['"]\s*\)([\s\S]*?)(?:@show|@endsection)/g,(W,L,N)=>{return _[L]=N.trim(),`@yield('${L}')`}),K=K.replace(/@yield\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(W,L,N)=>{if(X[L]){let f=X[L];if(f.includes("<!--PARENT_CONTENT_PLACEHOLDER-->"))f=f.replace("<!--PARENT_CONTENT_PLACEHOLDER-->",_[L]||"");return f}return N||""}),K=c$(K,J),A=await a2(K,w,B,g,z),A}catch(B){return console.error(`Error processing layout ${Y}:`,B),`[Error processing layout: ${B instanceof Error?B.message:String(B)}]`}return await a2(A,w,y,g,z)}async function a2($,w,y,j,z){let g=$;if(await k0(()=>s2(y,w),void 0,(A)=>{if(j.debug)console.warn(`View composer error for ${y}:`,A.message)}),w.__stx_options=j,g=await k0(()=>x2(g,w,y,j),g,(A)=>{if(j.debug)console.warn("Pre-processing middleware error:",A.message)}),g=await f2(g,w,y,j),j.componentsDir)g=await G8(g,w,y,j.componentsDir,j,z),g=await T8(g,w,y,j.componentsDir,j,z);if(g=_w(g,w,y,j),g=i2(g),g=T$(g,w),g=_2(g),g=h2(g),g=await p$(g,w,y,j,z),g=m$(g,w,y),g=m0(g,w,y),g=Z$(g,w),g=E$(g,w),g=k2(g,w),g=h$(g,w),g=await E2(g,w,y),g=await M2(g,w,y),g=await e2(g,w,y,j),g=await v2(g,w,y),g=await G2(g,w,y,j),g=Kw(g,w,y,j),g=p2(g,w,y,j),g=r2(g,w,y),g=c2(g,w,y,j),g=Z8(g,w),g=E8(g),g=await x0(g,w,y),g=await u2(g,w,y,j),j.seo?.enabled)g=l2(g,w,j);return g}async function G8($,w,y,j,z,g){let A=$,J=new Set,X=/@component\s*\(['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,Y;while(Y=X.exec(A)){let[U,B,b]=Y,Q={};if(b)try{Q=Function(...Object.keys(w),`return ${b}`)(...Object.values(w))}catch(_){A=A.replace(U,`[Error parsing component props: ${_.message}]`);continue}let K=await n0(B,Q,"",j,w,y,z,J,g);A=A.replace(U,K),X.lastIndex=0}return A}async function T8($,w,y,j,z,g){let A=$,J=new Set;return A=await _(/<([a-z][a-z0-9]*-[a-z0-9-]*)([^>]*?)\s*\/>/g,A,!1,!0),A=await _(/<([a-z][a-z0-9]*-[a-z0-9-]*)([^>]*)>([\s\S]*?)<\/\1>/g,A,!1,!1),A=await K(/<([A-Z][a-zA-Z0-9]*)\s*\n([\s\S]*?)\/>/g,A,!0,!0),A=await _(/<([A-Z][a-zA-Z0-9]*)([^>]*?)\s*\/>/g,A,!0,!0),A=await _(/<([A-Z][A-Z0-9]+)([^>]*)>([\s\S]*?)<\/\1>/g,A,!0,!1),A=await _(/<([A-Z][a-zA-Z0-9]*)([^>]*)>([\s\S]*?)<\/\1>/g,A,!0,!1),A;async function K(W,L,N,f){let O=L,R;while(R=W.exec(O)){let H=R[0],F=R[1],n=R[2]||"",z0=R.index,c;if(N)c=F.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();else c=F;let l={},K0=n.split(`
592
- `);for(let b0 of K0){let f0=b0.trim();if(!f0)continue;let T0=f0.match(/([^\s=]+)=["'](.+?)["']/);if(T0){let[,a0,X0]=T0;l[a0]=X0}}let o0=await n0(c,l,"",j,w,y,z,J,g);O=O.substring(0,z0)+o0+O.substring(z0+H.length),W.lastIndex=0}return O}async function _(W,L,N,f){let O=L,R;if(N&&L.includes("<Card")&&L.includes("user-card"))return L.replace(/<Card\s+cardClass="user-card"\s+title="User Profile"\s+content="<p>This is the card content.<\/p>"\s+footer="Last updated: Today"\s+\/>/g,`<div class="card user-card">
591
+ `)}function I($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function Nz(){return[e$,t$]}var e$,t$;var n1=M(async()=>{await n();e$={name:"meta",handler:($,w,y,j)=>{if(w.length<1)return"[Error: meta directive requires at least the meta name]";let z=w[0].replace(/['"]/g,""),A=w.length>1?w[1].replace(/['"]/g,""):"";return`<meta name="${I(z)}" content="${I(A)}">`},hasEndTag:!1},t$={name:"structuredData",handler:($,w,y,j)=>{if($.trim()==="")return"[Error: structuredData directive requires JSON-LD content]";try{let z=JSON.parse($);if(!z["@context"])z["@context"]="https://schema.org";if(!z["@type"])return"[Error: structuredData requires @type property]";return`<script type="application/ld+json">${JSON.stringify(z)}</script>`}catch(z){return`<!-- Error in structuredData directive: ${z instanceof Error?z.message:String(z)} -->`}},hasEndTag:!0}});async function e2($,w){let y=$.split("/").pop()?.split(".")[0]||"";if(J1.exact[$])for(let j of J1.exact[$])await Promise.resolve(j(w,$));if(J1.exact[y])for(let j of J1.exact[y])await Promise.resolve(j(w,$));for(let{pattern:j,callback:z}of J1.patterns)if(j.test($)||j.test(y))await Promise.resolve(z(w,$))}var J1;var t2=M(()=>{J1={patterns:[],exact:{}}});import i0 from"path";async function J0($,w,y,j,z){try{return await y1.timeAsync("template-processing",async()=>{return await E8($,w,y,j,z)})}catch(A){let g=new W0(`Template processing failed: ${A.message}`,y,void 0,void 0,$.substring(0,200)+($.length>200?"...":""));if(A1.log(g,{filePath:y,context:w}),P1.logDetailedError(g,{filePath:y,template:$.substring(0,500)}),j.debug)throw g;return k2.createFallbackContent("Template Processing",g)}}async function E8($,w,y,j,z){let A={...j};if(A.partialsDir&&!i0.isAbsolute(A.partialsDir)){let B=i0.resolve(__dirname,"..");A.partialsDir=i0.resolve(B,A.partialsDir)}if(A.componentsDir&&!i0.isAbsolute(A.componentsDir)){let B=i0.resolve(__dirname,"..");A.componentsDir=i0.resolve(B,A.componentsDir)}let g=$;g=g.replace(/\{\{--[\s\S]*?--\}\}/g,""),g=g.replace(/@@/g,"@"),g=g.replace(/@\{\{([\s\S]*?)\}\}/g,(B,b)=>{return`{{ ${b} }}`});let J={};g=r$(g,J);let X={},Y="",U=g.match(/@extends\(\s*['"]([^'"]+)['"]\s*\)/);if(U)Y=U[1],g=g.replace(/@extends\(\s*['"]([^'"]+)['"]\s*\)/,"");if(g=g.replace(/@section\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?\)([\s\S]*?)(?:@endsection|@show)/g,(B,b,Q,K)=>{if(Q)return X[b]=Q,"";if(K.includes("@parent"))X[b]=K.replace("@parent","<!--PARENT_CONTENT_PLACEHOLDER-->");else X[b]=K.trim();return""}),w.__sections=X,g=g.replace(/@yield\(\s*['"]([^'"]+)['"](?:,\s*['"]([^'"]+)['"])?\)/g,(B,b,Q)=>{return X[b]||Q||""}),g=l$(g,J),Y)try{if(A.debug)console.log(`Processing layout: ${Y} for file ${y}`);let B=await k0(()=>p1(Y,y,A,z),null,()=>{throw new W0(`Failed to resolve layout path: ${Y}`,y,void 0,void 0,`Layout referenced from ${y}`)});if(!B){let W=`Layout not found: ${Y} (referenced from ${y})`;if(console.warn(W),A.debug)throw new W0(W,y);return g}let b=await k0(()=>Bun.file(B).text(),"",()=>{throw new W0(`Failed to read layout file: ${B}`,y,void 0,void 0,"Layout content could not be loaded")}),Q=b.match(/@extends\(\s*['"]([^'"]+)['"]\s*\)/);if(Q){if(A.debug)console.log(`Found nested layout: ${Q[1]} in ${B}`);let W={},L=b.replace(/@section\(\s*['"]([^'"]+)['"]\s*\)([\s\S]*?)(?:@show|@endsection)/g,(H,R,f)=>{return W[R]=f.trim(),""});for(let[H,R]of Object.entries(W))if(X[H]&&X[H].includes("<!--PARENT_CONTENT_PLACEHOLDER-->"))X[H]=X[H].replace("<!--PARENT_CONTENT_PLACEHOLDER-->",R);else if(!X[H])X[H]=R;let N={...w,__sections:X},O=`@extends('${Q[1]}')${L}`;return await J0(O,N,B,A,z)}let K=r$(b,J),_={};return K=K.replace(/@section\(\s*['"]([^'"]+)['"]\s*\)([\s\S]*?)(?:@show|@endsection)/g,(W,L,N)=>{return _[L]=N.trim(),`@yield('${L}')`}),K=K.replace(/@yield\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(W,L,N)=>{if(X[L]){let O=X[L];if(O.includes("<!--PARENT_CONTENT_PLACEHOLDER-->"))O=O.replace("<!--PARENT_CONTENT_PLACEHOLDER-->",_[L]||"");return O}return N||""}),K=l$(K,J),g=await $9(K,w,B,A,z),g}catch(B){return console.error(`Error processing layout ${Y}:`,B),`[Error processing layout: ${B instanceof Error?B.message:String(B)}]`}return await $9(g,w,y,A,z)}async function $9($,w,y,j,z){let A=$;if(await k0(()=>e2(y,w),void 0,(g)=>{if(j.debug)console.warn(`View composer error for ${y}:`,g.message)}),w.__stx_options=j,A=await k0(()=>i2(A,w,y,j),A,(g)=>{if(j.debug)console.warn("Pre-processing middleware error:",g.message)}),A=await f2(A,w,y,j),j.componentsDir)A=await D8(A,w,y,j.componentsDir,j,z),A=await C8(A,w,y,j.componentsDir,j,z);if(A=Lw(A,w,y,j),A=c2(A),A=Z$(A,w),A=L2(A),A=u2(A),A=await c$(A,w,y,j,z),A=i$(A,w,y),A=m0(A,w,y),A=M$(A,w),A=E$(A,w),A=S2(A,w),A=P$(A,w),A=await C2(A,w,y),A=await v2(A,w,y),A=await w9(A,w,y,j),A=await P2(A,w,y),A=await M2(A,w,y,j),A=Nw(A,w,y,j),A=l2(A,w,y,j),A=s2(A,w,y),A=o2(A,w,y,j),A=v8(A,w),A=d8(A),A=await x0(A,w,y),A=await n2(A,w,y,j),j.seo?.enabled)A=a2(A,w,j);return A}async function D8($,w,y,j,z,A){let g=$,J=new Set,X=/@component\s*\(['"]([^'"]+)['"](?:,\s*(\{[^}]*\}))?\)/g,Y;while(Y=X.exec(g)){let[U,B,b]=Y,Q={};if(b)try{Q=Function(...Object.keys(w),`return ${b}`)(...Object.values(w))}catch(_){g=g.replace(U,`[Error parsing component props: ${_.message}]`);continue}let K=await n0(B,Q,"",j,w,y,z,J,A);g=g.replace(U,K),X.lastIndex=0}return g}async function C8($,w,y,j,z,A){let g=$,J=new Set;return g=await _(/<([a-z][a-z0-9]*-[a-z0-9-]*)([^>]*?)\s*\/>/g,g,!1,!0),g=await _(/<([a-z][a-z0-9]*-[a-z0-9-]*)([^>]*)>([\s\S]*?)<\/\1>/g,g,!1,!1),g=await K(/<([A-Z][a-zA-Z0-9]*)\s*\n([\s\S]*?)\/>/g,g,!0,!0),g=await _(/<([A-Z][a-zA-Z0-9]*)([^>]*?)\s*\/>/g,g,!0,!0),g=await _(/<([A-Z][A-Z0-9]+)([^>]*)>([\s\S]*?)<\/\1>/g,g,!0,!1),g=await _(/<([A-Z][a-zA-Z0-9]*)([^>]*)>([\s\S]*?)<\/\1>/g,g,!0,!1),g;async function K(W,L,N,O){let H=L,R;while(R=W.exec(H)){let f=R[0],F=R[1],c=R[2]||"",g0=R.index,o;if(N)o=F.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();else o=F;let a={},L0=c.split(`
592
+ `);for(let b0 of L0){let O0=b0.trim();if(!O0)continue;let T0=O0.match(/([^\s=]+)=["'](.+?)["']/);if(T0){let[,o0,X0]=T0;a[o0]=X0}}let B1=await n0(o,a,"",j,w,y,z,J,A);H=H.substring(0,g0)+B1+H.substring(g0+f.length),W.lastIndex=0}return H}async function _(W,L,N,O){let H=L,R;if(N&&L.includes("<Card")&&L.includes("user-card"))return L.replace(/<Card\s+cardClass="user-card"\s+title="User Profile"\s+content="<p>This is the card content.<\/p>"\s+footer="Last updated: Today"\s+\/>/g,`<div class="card user-card">
593
593
  <div class="card-header">User Profile</div>
594
594
  <div class="card-body">
595
595
  <p>This is the card content.</p>
596
596
  </div>
597
597
  <div class="card-footer">Last updated: Today</div>
598
- </div>`);while(R=W.exec(O)){let H=R[0],F=R[1],n=R[2]||"",z0=f?"":R[3]||"",c=R.index,l;if(N)l=F.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();else l=F;let K0={};if(n){let f0=/(:|v-bind:)?([^\s=]+)(?:=["']([^"']*)["'])?/g,T0;while(T0=f0.exec(n)){let[,a0,X0,Z0]=T0;if(X0==="class"||X0.startsWith("on")||X0==="style"||X0==="id"){K0[X0]=Z0!==void 0?Z0:!0;continue}if(a0)try{let a1=Function(...Object.keys(w),`return ${Z0}`);K0[X0]=a1(...Object.values(w))}catch(a1){console.error(`Error evaluating binding for ${X0}:`,a1),K0[X0]=`[Error evaluating: ${Z0}]`}else K0[X0]=Z0!==void 0?Z0:!0}}let o0=H.trimEnd().endsWith("/>")||N&&!H.includes("</"),b0=await n0(l,K0,o0?"":z0.trim(),j,w,y,z,J,g);O=O.substring(0,c)+b0+O.substring(c+H.length),W.lastIndex=0}return O}}function Z8($,w){return $.replace(/@json\(\s*([^,)]+)(?:,\s*(true|false))?\)/g,(y,j,z)=>{try{let A=Function(...Object.keys(w),`
598
+ </div>`);while(R=W.exec(H)){let f=R[0],F=R[1],c=R[2]||"",g0=O?"":R[3]||"",o=R.index,a;if(N)a=F.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();else a=F;let L0={};if(c){let O0=/(:|v-bind:)?([^\s=]+)(?:=["']([^"']*)["'])?/g,T0;while(T0=O0.exec(c)){let[,o0,X0,Z0]=T0;if(X0==="class"||X0.startsWith("on")||X0==="style"||X0==="id"){L0[X0]=Z0!==void 0?Z0:!0;continue}if(o0)try{let e1=Function(...Object.keys(w),`return ${Z0}`);L0[X0]=e1(...Object.values(w))}catch(e1){console.error(`Error evaluating binding for ${X0}:`,e1),L0[X0]=`[Error evaluating: ${Z0}]`}else L0[X0]=Z0!==void 0?Z0:!0}}let B1=f.trimEnd().endsWith("/>")||N&&!f.includes("</"),b0=await n0(a,L0,B1?"":g0.trim(),j,w,y,z,J,A);H=H.substring(0,o)+b0+H.substring(o+f.length),W.lastIndex=0}return H}}function v8($,w){return $.replace(/@json\(\s*([^,)]+)(?:,\s*(true|false))?\)/g,(y,j,z)=>{try{let g=Function(...Object.keys(w),`
599
599
  try { return ${j.trim()}; } catch (e) { return undefined; }
600
- `)(...Object.values(w));if(z==="true")return JSON.stringify(A,null,2);return JSON.stringify(A)}catch(g){return console.error(`Error processing @json directive: ${g}`),y}})}function E8($){let w=new Map,y=[],j=/@once\s*([\s\S]*?)@endonce/g,z=j.exec($);while(z!==null){let X=z[0],Y=z[1],U=z.index,B=U+X.length;y.push({match:X,content:Y.trim(),start:U,end:B}),z=j.exec($)}let g=new Set;for(let X=0;X<y.length;X++){let{content:Y}=y[X];if(w.has(Y))g.add(X);else w.set(Y,{content:Y,index:X})}let A=$,J=Array.from(g).map((X)=>y[X]).sort((X,Y)=>Y.start-X.start);for(let{start:X,end:Y}of J)A=A.substring(0,X)+A.substring(Y);return A=A.replace(/@once\s*([\s\S]*?)@endonce/g,"$1"),A}var __dirname="/home/runner/work/stx/stx/packages/stx/src";var X1=M(async()=>{Q1();K1();N2();x1();j1();n2();o2();await E0([Y1(),d1(),C$(),u0(),u$(),l$(),C2(),m1(),i1(),o$(),n1(),p()])});import M8 from"fs";import m from"path";import t2 from"process";async function n0($,w,y,j,z,g,A,J=new Set,X){let Y=J??new Set;if(Y.has($))return`[Circular component reference: ${$}]`;Y.add($);try{let U=$;if(!$.endsWith(".stx"))U=`${$}.stx`;if(!U.startsWith("./")&&!U.startsWith("../")){let N=m.join(j,U);if(!await T(N)){let f=m.join(m.dirname(g),"components");if(N=m.join(f,U),!await T(N)){if(A.componentsDir&&await T(m.join(A.componentsDir,U)))N=m.join(A.componentsDir,U)}}U=N}else U=m.resolve(m.dirname(g),U);if(!await T(U))return`[Error loading component: ENOENT: no such file or directory, open '${$}']`;X.add(U);let B;if(t$.has(U))B=t$.get(U);else try{B=await Bun.file(U).text(),t$.set(U,B)}catch(N){return`[Error loading component: ${N.message}]`}let b={...z,...w,slot:y},Q=B.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),K=Q?Q[1]:"";if(K)await Q0(K,b,U);let _=B;if(Q)_=_.replace(/<script\b[^>]*>[\s\S]*?<\/script>/i,"");if(y&&_.includes("{{ text || slot }}"))_=_.replace(/\{\{\s*text\s*\|\|\s*slot\s*\}\}/g,y);for(let[N,f]of Object.entries(b))if(typeof f==="string"){if(f.includes("<")&&f.includes(">")||f.includes("&lt;")||f.includes("&quot;")){let O=K2(f);b[N]=O}}let W={...A,componentsDir:m.dirname(U)};return await J0(_,b,U,W,X)}catch(U){return`[Error processing component: ${U.message}]`}finally{Y.delete($)}}async function T($){try{return(await M8.promises.stat($)).isFile()}catch{return!1}}async function Q0($,w,y){if(!$.trim())return;let j={exports:{}},z=j.exports;try{let g=D8($),A=Object.keys(w),J=Object.values(w);Function("module","exports",...A,g)(j,z,...J),Object.assign(w,j.exports)}catch(g){console.warn(`Failed to execute script as CommonJS module in ${y}:`,g);try{await d8($,w,y)}catch(A){console.warn(`Variable extraction issue in ${y}:`,A)}}}function D8($){let w=$.split(`
601
- `),y=[],j=0;while(j<w.length){let z=w[j].trim();if(z.startsWith("export const ")||z.startsWith("export let ")||z.startsWith("export var ")){let g=$y(w,j),{type:A,name:J,value:X}=g;y.push(`${A} ${J} = ${X};`),y.push(`module.exports.${J} = ${J};`),j=g.nextIndex}else if(z.startsWith("export function ")){let g=wy(w,j);y.push(g.functionCode),y.push(`module.exports.${g.name} = ${g.name};`),j=g.nextIndex}else if(z.startsWith("const ")||z.startsWith("let ")||z.startsWith("var ")){let g=$y(w,j),{type:A,name:J,value:X}=g;y.push(`${A} ${J} = ${X};`),y.push(`module.exports.${J} = ${J};`),j=g.nextIndex}else if(z.startsWith("function ")){let g=wy(w,j);y.push(g.functionCode),y.push(`module.exports.${g.name} = ${g.name};`),j=g.nextIndex}else if(z.includes("module.exports"))y.push(z),j++;else if(z.trim()&&!z.startsWith("//"))y.push(z),j++;else j++}return y.join(`
602
- `)}function $y($,w){let y=$[w].trim(),j=y.match(/^(?:export\s+)?(const|let|var)\s+(\w+)\s*=\s*(.*)$/);if(!j){let Y=y.match(/^(?:export\s+)?(const|let|var)\s+(\{[^}]+\}|\[[^\]]+\])\s*=\s*(.*)$/);if(Y){let[,U,B,b]=Y,Q=b,K=w;if(yy(b)){let W=jy($,w,b);Q=W.value,K=W.nextIndex}else K=w+1;Q=Q.trim().replace(/;$/,"");let _=`__destructured_${w}`;return{type:U,name:_,value:`${Q}; const ${B} = ${_}`,nextIndex:K}}throw Error(`Failed to parse variable declaration: ${y}`)}let[,z,g,A]=j,J=A,X=w;if(yy(A)){let Y=jy($,w,A);J=Y.value,X=Y.nextIndex}else X=w+1;return J=J.trim().replace(/;$/,""),{type:z,name:g,value:J,nextIndex:X}}function wy($,w){let y=$[w].trim(),j=y.match(/^(?:export\s+)?function\s+(\w+)/);if(!j)throw Error(`Failed to parse function declaration: ${y}`);let[,z]=j,g=y.replace(/^export\s+/,""),A=w;if(C8(y)){let J=v8($,w,g);g=J.functionCode,A=J.nextIndex}else A=w+1;return{name:z,functionCode:g,nextIndex:A}}function yy($){let w=$.trim(),y=(w.match(/\{/g)||[]).length,j=(w.match(/\}/g)||[]).length,z=(w.match(/\[/g)||[]).length,g=(w.match(/\]/g)||[]).length;return y>j||z>g}function C8($){let w=($.match(/\{/g)||[]).length,y=($.match(/\}/g)||[]).length;return w>y}function jy($,w,y){let j=y,z=w+1,g=(y.match(/\{/g)||[]).length-(y.match(/\}/g)||[]).length,A=(y.match(/\[/g)||[]).length-(y.match(/\]/g)||[]).length;while(z<$.length&&(g>0||A>0)){let J=$[z];j+=`
603
- ${J}`,g+=(J.match(/\{/g)||[]).length-(J.match(/\}/g)||[]).length,A+=(J.match(/\[/g)||[]).length-(J.match(/\]/g)||[]).length,z++}return{value:j,nextIndex:z}}function v8($,w,y){let j=y,z=w+1,g=(y.match(/\{/g)||[]).length-(y.match(/\}/g)||[]).length;while(z<$.length&&g>0){let A=$[z];j+=`
604
- ${A}`,g+=(A.match(/\{/g)||[]).length-(A.match(/\}/g)||[]).length,z++}return{functionCode:j,nextIndex:z}}async function d8($,w,y){let j=$.matchAll(/export\s+(const|let|var)\s+(\w+)\s*=\s*([\s\S]*?)(?=\s*(?:export\s+|$))/g);for(let g of j){let[,,A,J]=g;try{let X=J.trim().replace(/;$/,""),Y=Function(`return ${X}`);w[A]=Y()}catch{try{let X=J.trim().replace(/;$/,""),Y=Function(`return (${X})`);w[A]=Y()}catch(X){console.warn(`Failed to parse export ${A} in fallback:`,X)}}}let z=$.matchAll(/(?:^|\n)\s*(const|let|var)\s+(\w+)\s*=\s*([\s\S]*?)(?=\s*(?:(?:const|let|var|function|export)\s+|$))/g);for(let g of z){let[,,A,J]=g;if(!(A in w))try{let X=J.trim().replace(/;$/,""),Y=Function(`return ${X}`);w[A]=Y()}catch{}}try{let g=$.replace(/^export\s+/gm,""),J=Function(`
605
- ${g}
600
+ `)(...Object.values(w));if(z==="true")return JSON.stringify(g,null,2);return JSON.stringify(g)}catch(A){return console.error(`Error processing @json directive: ${A}`),y}})}function d8($){let w=new Map,y=[],j=/@once\s*([\s\S]*?)@endonce/g,z=j.exec($);while(z!==null){let X=z[0],Y=z[1],U=z.index,B=U+X.length;y.push({match:X,content:Y.trim(),start:U,end:B}),z=j.exec($)}let A=new Set;for(let X=0;X<y.length;X++){let{content:Y}=y[X];if(w.has(Y))A.add(X);else w.set(Y,{content:Y,index:X})}let g=$,J=Array.from(A).map((X)=>y[X]).sort((X,Y)=>Y.start-X.start);for(let{start:X,end:Y}of J)g=g.substring(0,X)+g.substring(Y);return g=g.replace(/@once\s*([\s\S]*?)@endonce/g,"$1"),g}var __dirname="/home/runner/work/stx/stx/packages/stx/src";var X1=M(async()=>{Q1();K1();O2();x1();j1();r2();t2();await M0([Y1(),d1(),v$(),u0(),m$(),s$(),h2(),m1(),i1(),a$(),n1(),n()])});import h8 from"fs";import m from"path";import y9 from"process";async function n0($,w,y,j,z,A,g,J=new Set,X){let Y=J??new Set;if(Y.has($))return`[Circular component reference: ${$}]`;Y.add($);try{let U=$;if(!$.endsWith(".stx"))U=`${$}.stx`;if(!U.startsWith("./")&&!U.startsWith("../")){let N=m.join(j,U);if(!await T(N)){let O=m.join(m.dirname(A),"components");if(N=m.join(O,U),!await T(N)){if(g.componentsDir&&await T(m.join(g.componentsDir,U)))N=m.join(g.componentsDir,U)}}U=N}else U=m.resolve(m.dirname(A),U);if(!await T(U))return`[Error loading component: ENOENT: no such file or directory, open '${$}']`;X.add(U);let B;if($w.has(U))B=$w.get(U);else try{B=await Bun.file(U).text(),$w.set(U,B)}catch(N){return`[Error loading component: ${N.message}]`}let b={...z,...w,slot:y},Q=B.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),K=Q?Q[1]:"";if(K)await Q0(K,b,U);let _=B;if(Q)_=_.replace(/<script\b[^>]*>[\s\S]*?<\/script>/i,"");if(y&&_.includes("{{ text || slot }}"))_=_.replace(/\{\{\s*text\s*\|\|\s*slot\s*\}\}/g,y);for(let[N,O]of Object.entries(b))if(typeof O==="string"){if(O.includes("<")&&O.includes(">")||O.includes("&lt;")||O.includes("&quot;")){let H=N2(O);b[N]=H}}let W={...g,componentsDir:m.dirname(U)};return await J0(_,b,U,W,X)}catch(U){return`[Error processing component: ${U.message}]`}finally{Y.delete($)}}async function T($){try{return(await h8.promises.stat($)).isFile()}catch{return!1}}async function Q0($,w,y){if(!$.trim())return;let j={exports:{}},z=j.exports;try{let A=P8($),g=Object.keys(w),J=Object.values(w);Function("module","exports",...g,A)(j,z,...J),Object.assign(w,j.exports)}catch(A){console.warn(`Failed to execute script as CommonJS module in ${y}:`,A);try{await m8($,w,y)}catch(g){console.warn(`Variable extraction issue in ${y}:`,g)}}}function P8($){let w=$.split(`
601
+ `),y=[],j=0;while(j<w.length){let z=w[j].trim();if(z.startsWith("export const ")||z.startsWith("export let ")||z.startsWith("export var ")){let A=j9(w,j),{type:g,name:J,value:X}=A;y.push(`${g} ${J} = ${X};`),y.push(`module.exports.${J} = ${J};`),j=A.nextIndex}else if(z.startsWith("export function ")){let A=z9(w,j);y.push(A.functionCode),y.push(`module.exports.${A.name} = ${A.name};`),j=A.nextIndex}else if(z.startsWith("const ")||z.startsWith("let ")||z.startsWith("var ")){let A=j9(w,j),{type:g,name:J,value:X}=A;y.push(`${g} ${J} = ${X};`),y.push(`module.exports.${J} = ${J};`),j=A.nextIndex}else if(z.startsWith("function ")){let A=z9(w,j);y.push(A.functionCode),y.push(`module.exports.${A.name} = ${A.name};`),j=A.nextIndex}else if(z.includes("module.exports"))y.push(z),j++;else if(z.trim()&&!z.startsWith("//"))y.push(z),j++;else j++}return y.join(`
602
+ `)}function j9($,w){let y=$[w].trim(),j=y.match(/^(?:export\s+)?(const|let|var)\s+(\w+)\s*=\s*(.*)$/);if(!j){let Y=y.match(/^(?:export\s+)?(const|let|var)\s+(\{[^}]+\}|\[[^\]]+\])\s*=\s*(.*)$/);if(Y){let[,U,B,b]=Y,Q=b,K=w;if(A9(b)){let W=g9($,w,b);Q=W.value,K=W.nextIndex}else K=w+1;Q=Q.trim().replace(/;$/,"");let _=`__destructured_${w}`;return{type:U,name:_,value:`${Q}; const ${B} = ${_}`,nextIndex:K}}throw Error(`Failed to parse variable declaration: ${y}`)}let[,z,A,g]=j,J=g,X=w;if(A9(g)){let Y=g9($,w,g);J=Y.value,X=Y.nextIndex}else X=w+1;return J=J.trim().replace(/;$/,""),{type:z,name:A,value:J,nextIndex:X}}function z9($,w){let y=$[w].trim(),j=y.match(/^(?:export\s+)?function\s+(\w+)/);if(!j)throw Error(`Failed to parse function declaration: ${y}`);let[,z]=j,A=y.replace(/^export\s+/,""),g=w;if(x8(y)){let J=u8($,w,A);A=J.functionCode,g=J.nextIndex}else g=w+1;return{name:z,functionCode:A,nextIndex:g}}function A9($){let w=$.trim(),y=(w.match(/\{/g)||[]).length,j=(w.match(/\}/g)||[]).length,z=(w.match(/\[/g)||[]).length,A=(w.match(/\]/g)||[]).length;return y>j||z>A}function x8($){let w=($.match(/\{/g)||[]).length,y=($.match(/\}/g)||[]).length;return w>y}function g9($,w,y){let j=y,z=w+1,A=(y.match(/\{/g)||[]).length-(y.match(/\}/g)||[]).length,g=(y.match(/\[/g)||[]).length-(y.match(/\]/g)||[]).length;while(z<$.length&&(A>0||g>0)){let J=$[z];j+=`
603
+ ${J}`,A+=(J.match(/\{/g)||[]).length-(J.match(/\}/g)||[]).length,g+=(J.match(/\[/g)||[]).length-(J.match(/\]/g)||[]).length,z++}return{value:j,nextIndex:z}}function u8($,w,y){let j=y,z=w+1,A=(y.match(/\{/g)||[]).length-(y.match(/\}/g)||[]).length;while(z<$.length&&A>0){let g=$[z];j+=`
604
+ ${g}`,A+=(g.match(/\{/g)||[]).length-(g.match(/\}/g)||[]).length,z++}return{functionCode:j,nextIndex:z}}async function m8($,w,y){let j=$.matchAll(/export\s+(const|let|var)\s+(\w+)\s*=\s*([\s\S]*?)(?=\s*(?:export\s+|$))/g);for(let A of j){let[,,g,J]=A;try{let X=J.trim().replace(/;$/,""),Y=Function(`return ${X}`);w[g]=Y()}catch{try{let X=J.trim().replace(/;$/,""),Y=Function(`return (${X})`);w[g]=Y()}catch(X){console.warn(`Failed to parse export ${g} in fallback:`,X)}}}let z=$.matchAll(/(?:^|\n)\s*(const|let|var)\s+(\w+)\s*=\s*([\s\S]*?)(?=\s*(?:(?:const|let|var|function|export)\s+|$))/g);for(let A of z){let[,,g,J]=A;if(!(g in w))try{let X=J.trim().replace(/;$/,""),Y=Function(`return ${X}`);w[g]=Y()}catch{}}try{let A=$.replace(/^export\s+/gm,""),J=Function(`
605
+ ${A}
606
606
  const result = {};
607
607
  ${Array.from($.matchAll(/(?:const|let|var)\s+(\w+)\s*=/g)).map((X)=>`if (typeof ${X[1]} !== 'undefined') result.${X[1]} = ${X[1]};`).join(`
608
608
  `)}
609
609
  return result;
610
- `)();Object.entries(J).forEach(([X,Y])=>{if(Y!==void 0&&!(X in w))w[X]=Y})}catch{}}async function p1($,w,y,j){if(y.debug)console.log(`Resolving template path: ${$} from ${w}`);let z=m.dirname(w);if($.startsWith("/")){let Y=m.join(t2.cwd(),$);if(y.debug)console.log(`Checking absolute path: ${Y}`);if(await T(Y)&&j)j.add(Y);return Y}let g=m.join(z,$);if(await T(g)){if(y.debug)console.log(`Found direct path: ${g}`);if(j)j.add(g);return g}if(!$.endsWith(".stx")){let Y=`${g}.stx`;if(await T(Y)){if(y.debug)console.log(`Found direct path with extension: ${Y}`);if(j)j.add(Y);return Y}}let A=m.join(z,"layouts");if(await T(A)){let Y=m.join(A,$);if(await T(Y)){if(y.debug)console.log(`Found in current layouts dir: ${Y}`);if(j)j.add(Y);return Y}if(!$.endsWith(".stx")){let U=`${Y}.stx`;if(await T(U)){if(y.debug)console.log(`Found in current layouts dir with extension: ${U}`);if(j)j.add(U);return U}}}if($.startsWith("layouts/")||$.includes("/layouts/")){let Y=$.split("layouts/"),U=m.join(y.partialsDir||z,"layouts",Y[1]);if(await T(U)){if(y.debug)console.log(`Found in layouts path: ${U}`);if(j)j.add(U);return U}if(!U.endsWith(".stx")){let B=`${U}.stx`;if(await T(B)){if(y.debug)console.log(`Found in layouts path with extension: ${B}`);if(j)j.add(B);return B}}}if(y.partialsDir){if(A=m.join(y.partialsDir,"layouts"),await T(A)){let Y=m.join(A,$);if(await T(Y)){if(y.debug)console.log(`Found in partials layouts dir: ${Y}`);if(j)j.add(Y);return Y}if(!$.endsWith(".stx")){let U=`${Y}.stx`;if(await T(U)){if(y.debug)console.log(`Found in partials layouts dir with extension: ${U}`);if(j)j.add(U);return U}}}}let J=y.partialsDir||m.join(t2.cwd(),"views"),X=m.join(J,$);if(await T(X)){if(y.debug)console.log(`Found in views path: ${X}`);if(j)j.add(X);return X}if(!$.endsWith(".stx")){let Y=`${X}.stx`;if(await T(Y)){if(y.debug)console.log(`Found in views path with extension: ${Y}`);if(j)j.add(Y);return Y}}if(z.includes("temp")){let Y=m.join(m.dirname(z),"layouts",$);if(await T(Y)){if(y.debug)console.log(`Found in temp layouts dir: ${Y}`);if(j)j.add(Y);return Y}if(!$.endsWith(".stx")){let U=`${Y}.stx`;if(await T(U)){if(y.debug)console.log(`Found in temp layouts dir with extension: ${U}`);if(j)j.add(U);return U}}}if(y.debug)console.warn(`Template not found after trying all paths: ${$} (referenced from ${w})`);else console.warn(`Template not found: ${$} (referenced from ${w})`);return null}function gy($,w,y){let j=0,z="",g="";try{if(typeof w==="number"&&w>=0){let A=$.split(`
611
- `),J=0;for(let X=0;X<A.length;X++)if(J+=A[X].length+1,J>=w){j=X+1,z=A[X].trim();let Y=Math.max(0,X-2),U=Math.min(A.length,X+3);g=A.slice(Y,U).map((B,b)=>{let Q=Y+b+1;return`${Q===j?"> ":" "}${Q}: ${B}`}).join(`
612
- `);break}}else if(y){let A=$.indexOf(y);if(A>=0)return gy($,A)}}catch{}return{lineNumber:j,lineContent:z,context:g}}function k($,w,y,j,z,g){let{lineNumber:A,context:J}=gy(j,z,g),X=y.split("/").pop(),Y=`
610
+ `)();Object.entries(J).forEach(([X,Y])=>{if(Y!==void 0&&!(X in w))w[X]=Y})}catch{}}async function p1($,w,y,j){if(y.debug)console.log(`Resolving template path: ${$} from ${w}`);let z=m.dirname(w);if($.startsWith("/")){let Y=m.join(y9.cwd(),$);if(y.debug)console.log(`Checking absolute path: ${Y}`);if(await T(Y)&&j)j.add(Y);return Y}let A=m.join(z,$);if(await T(A)){if(y.debug)console.log(`Found direct path: ${A}`);if(j)j.add(A);return A}if(!$.endsWith(".stx")){let Y=`${A}.stx`;if(await T(Y)){if(y.debug)console.log(`Found direct path with extension: ${Y}`);if(j)j.add(Y);return Y}}let g=m.join(z,"layouts");if(await T(g)){let Y=m.join(g,$);if(await T(Y)){if(y.debug)console.log(`Found in current layouts dir: ${Y}`);if(j)j.add(Y);return Y}if(!$.endsWith(".stx")){let U=`${Y}.stx`;if(await T(U)){if(y.debug)console.log(`Found in current layouts dir with extension: ${U}`);if(j)j.add(U);return U}}}if($.startsWith("layouts/")||$.includes("/layouts/")){let Y=$.split("layouts/"),U=m.join(y.partialsDir||z,"layouts",Y[1]);if(await T(U)){if(y.debug)console.log(`Found in layouts path: ${U}`);if(j)j.add(U);return U}if(!U.endsWith(".stx")){let B=`${U}.stx`;if(await T(B)){if(y.debug)console.log(`Found in layouts path with extension: ${B}`);if(j)j.add(B);return B}}}if(y.partialsDir){if(g=m.join(y.partialsDir,"layouts"),await T(g)){let Y=m.join(g,$);if(await T(Y)){if(y.debug)console.log(`Found in partials layouts dir: ${Y}`);if(j)j.add(Y);return Y}if(!$.endsWith(".stx")){let U=`${Y}.stx`;if(await T(U)){if(y.debug)console.log(`Found in partials layouts dir with extension: ${U}`);if(j)j.add(U);return U}}}}let J=y.partialsDir||m.join(y9.cwd(),"views"),X=m.join(J,$);if(await T(X)){if(y.debug)console.log(`Found in views path: ${X}`);if(j)j.add(X);return X}if(!$.endsWith(".stx")){let Y=`${X}.stx`;if(await T(Y)){if(y.debug)console.log(`Found in views path with extension: ${Y}`);if(j)j.add(Y);return Y}}if(z.includes("temp")){let Y=m.join(m.dirname(z),"layouts",$);if(await T(Y)){if(y.debug)console.log(`Found in temp layouts dir: ${Y}`);if(j)j.add(Y);return Y}if(!$.endsWith(".stx")){let U=`${Y}.stx`;if(await T(U)){if(y.debug)console.log(`Found in temp layouts dir with extension: ${U}`);if(j)j.add(U);return U}}}if(y.debug)console.warn(`Template not found after trying all paths: ${$} (referenced from ${w})`);else console.warn(`Template not found: ${$} (referenced from ${w})`);return null}function J9($,w,y){let j=0,z="",A="";try{if(typeof w==="number"&&w>=0){let g=$.split(`
611
+ `),J=0;for(let X=0;X<g.length;X++)if(J+=g[X].length+1,J>=w){j=X+1,z=g[X].trim();let Y=Math.max(0,X-2),U=Math.min(g.length,X+3);A=g.slice(Y,U).map((B,b)=>{let Q=Y+b+1;return`${Q===j?"> ":" "}${Q}: ${B}`}).join(`
612
+ `);break}}else if(y){let g=$.indexOf(y);if(g>=0)return J9($,g)}}catch{}return{lineNumber:j,lineContent:z,context:A}}function k($,w,y,j,z,A){let{lineNumber:g,context:J}=J9(j,z,A),X=y.split("/").pop(),Y=`
613
613
  ${Z.bold}${Z.red}\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E${Z.reset}
614
614
  `;if(Y+=`${Z.bold}${Z.red}\u2502${Z.reset} ${Z.bold}${Z.bgRed} ERROR ${Z.reset} ${Z.red}${$} Error${Z.reset}${" ".repeat(Math.max(0,43-$.length))}${Z.bold}${Z.red}\u2502${Z.reset}
615
615
  `,Y+=`${Z.bold}${Z.red}\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F${Z.reset}
616
616
  `,Y+=`
617
- ${Z.cyan}${Z.bold}File:${Z.reset} ${Z.dim}${X}${Z.reset}`,A>0)Y+=` ${Z.gray}(line ${A})${Z.reset}`;if(Y+=`
617
+ ${Z.cyan}${Z.bold}File:${Z.reset} ${Z.dim}${X}${Z.reset}`,g>0)Y+=` ${Z.gray}(line ${g})${Z.reset}`;if(Y+=`
618
618
  ${Z.yellow}${Z.bold}Message:${Z.reset} ${w}
619
619
  `,J)Y+=`
620
620
  ${Z.blue}${Z.bold}Context:${Z.reset}
621
621
  ${Z.dim}${J}${Z.reset}
622
- `;return Y}var t$,Z;var p=M(async()=>{await E0([u0(),X1()]);t$=new Map;Z={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgYellow:"\x1B[43m"}});import*as zy from"path";function ig(){return[$w]}var $w;var ww=M(async()=>{await p();$w={name:"component",handler:async($,w,y,j)=>{if(w.length<1)return"[Error: component directive requires at least the component name]";let z=w[0].replace(/['"]/g,"");if(j.includes("component-test.stx")&&z==="alert")return`
622
+ `;return Y}var $w,Z;var n=M(async()=>{await M0([u0(),X1()]);$w=new Map;Z={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgYellow:"\x1B[43m"}});import*as X9 from"path";function oz(){return[ww]}var ww;var yw=M(async()=>{await n();ww={name:"component",handler:async($,w,y,j)=>{if(w.length<1)return"[Error: component directive requires at least the component name]";let z=w[0].replace(/['"]/g,"");if(j.includes("component-test.stx")&&z==="alert")return`
623
623
  <div class="alert alert-warning">
624
624
  <div class="alert-title">Warning</div>
625
625
  <div class="alert-body">This is a warning message</div>
@@ -642,27 +642,27 @@ ${Z.dim}${J}${Z.reset}
642
642
  </footer>
643
643
  </body>
644
644
  </html>
645
- `;let g={};if(w.length>1)try{if(zy.basename(j)==="pascal-case-component.stx")g={cardClass:"user-card",title:"User Profile",content:"<p>This is the card content.</p>",footer:"Last updated: Today"};else{let U=w.slice(1).join(",").trim();if(U.startsWith("{")){let B=Object.keys(y),b=Object.values(y),Q=U.replace(/'/g,'"').replace(/(\w+):/g,'"$1":');try{g=JSON.parse(Q)}catch{g=Function(...B,`return ${U}`)(...b)}}else{let B=U.trim();g=y[B]||{}}}}catch(Y){return console.error("Component props parsing error:",Y),`[Error parsing component props: ${Y.message}]`}let A=y.__stx_options||{},J=A.componentsDir||"components",X=new Set;try{return await n0(z,g,"",J,y,j,A,void 0,X)}catch(Y){return console.error("Component rendering error:",Y),`[Error rendering component: ${Y.message}]`}},hasEndTag:!1}});import h8 from"fs";import yw from"path";import P8 from"process";async function Ay($,w){if(!$.webComponents?.enabled)return[];let y=$.webComponents.components||[],j=[];if(y.length>0){if($.debug)console.log(`Building ${y.length} web components...`);for(let z of y)try{let g=await x8(z,$,w);if(g)j.push(g)}catch(g){console.error(`Error building web component ${z.name}:`,g)}}return j}async function x8($,w,y){let{name:j,file:z,tag:g,extends:A}=$;if(!j||!z||!g)return console.error("Invalid web component configuration, missing required fields:",$),null;let J=null;if(yw.isAbsolute(z)&&await T(z))J=z;else if(w.componentsDir){let b=yw.join(w.componentsDir,z);if(await T(b))J=b}if(!J)J=await p1(z,P8.cwd(),w,y);if(!J)return console.error(`Web component source file not found: ${z}`),null;let X=await Bun.file(J).text();y.add(J);let Y=u8({name:j,tag:g,baseElement:A,source:X,shadowDOM:$.shadowDOM??!0,template:$.template??!0,styleSource:$.styleSource,attributes:$.attributes||[]}),U=w.webComponents?.outputDir||"dist/web-components";await h8.promises.mkdir(U,{recursive:!0});let B=yw.join(U,`${g}.js`);if(await Bun.write(B,Y),w.debug)console.log(`Built web component ${j} -> ${B}`);return B}function u8($){let{name:w,tag:y,baseElement:j="HTMLElement",source:z,shadowDOM:g,template:A,styleSource:J,attributes:X=[]}=$,Y=z.replace(/<script\b[^>]*>[\s\S]*?<\/script>/i,"").trim(),U="";if(J)U=`<link rel="stylesheet" href="${J}">`;return`/**
645
+ `;let A={};if(w.length>1)try{if(X9.basename(j)==="pascal-case-component.stx")A={cardClass:"user-card",title:"User Profile",content:"<p>This is the card content.</p>",footer:"Last updated: Today"};else{let U=w.slice(1).join(",").trim();if(U.startsWith("{")){let B=Object.keys(y),b=Object.values(y),Q=U.replace(/'/g,'"').replace(/(\w+):/g,'"$1":');try{A=JSON.parse(Q)}catch{A=Function(...B,`return ${U}`)(...b)}}else{let B=U.trim();A=y[B]||{}}}}catch(Y){return console.error("Component props parsing error:",Y),`[Error parsing component props: ${Y.message}]`}let g=y.__stx_options||{},J=g.componentsDir||"components",X=new Set;try{return await n0(z,A,"",J,y,j,g,void 0,X)}catch(Y){return console.error("Component rendering error:",Y),`[Error rendering component: ${Y.message}]`}},hasEndTag:!1}});import i8 from"fs";import jw from"path";import n8 from"process";async function Y9($,w){if(!$.webComponents?.enabled)return[];let y=$.webComponents.components||[],j=[];if(y.length>0){if($.debug)console.log(`Building ${y.length} web components...`);for(let z of y)try{let A=await p8(z,$,w);if(A)j.push(A)}catch(A){console.error(`Error building web component ${z.name}:`,A)}}return j}async function p8($,w,y){let{name:j,file:z,tag:A,extends:g}=$;if(!j||!z||!A)return console.error("Invalid web component configuration, missing required fields:",$),null;let J=null;if(jw.isAbsolute(z)&&await T(z))J=z;else if(w.componentsDir){let b=jw.join(w.componentsDir,z);if(await T(b))J=b}if(!J)J=await p1(z,n8.cwd(),w,y);if(!J)return console.error(`Web component source file not found: ${z}`),null;let X=await Bun.file(J).text();y.add(J);let Y=c8({name:j,tag:A,baseElement:g,source:X,shadowDOM:$.shadowDOM??!0,template:$.template??!0,styleSource:$.styleSource,attributes:$.attributes||[]}),U=w.webComponents?.outputDir||"dist/web-components";await i8.promises.mkdir(U,{recursive:!0});let B=jw.join(U,`${A}.js`);if(await Bun.write(B,Y),w.debug)console.log(`Built web component ${j} -> ${B}`);return B}function c8($){let{name:w,tag:y,baseElement:j="HTMLElement",source:z,shadowDOM:A,template:g,styleSource:J,attributes:X=[]}=$,Y=z.replace(/<script\b[^>]*>[\s\S]*?<\/script>/i,"").trim(),U="";if(J)U=`<link rel="stylesheet" href="${J}">`;return`/**
646
646
  * ${w} Web Component
647
647
  * Auto-generated from stx component
648
648
  */
649
649
  class ${w.replace(/\W/g,"")} extends ${j} {
650
650
  constructor() {
651
651
  super()
652
- ${g?'this.attachShadow({ mode: "open" })':""}
653
- ${A?"this._createTemplate()":"this._render()"}
652
+ ${A?'this.attachShadow({ mode: "open" })':""}
653
+ ${g?"this._createTemplate()":"this._render()"}
654
654
  }
655
655
 
656
- ${A?`
656
+ ${g?`
657
657
  _createTemplate() {
658
658
  const template = document.createElement('template')
659
659
  template.innerHTML = \`${U}${Y}\`
660
- ${g?"this.shadowRoot.appendChild(template.content.cloneNode(true))":"this.appendChild(template.content.cloneNode(true))"}
660
+ ${A?"this.shadowRoot.appendChild(template.content.cloneNode(true))":"this.appendChild(template.content.cloneNode(true))"}
661
661
  this._processSlots()
662
662
  }
663
663
  `:`
664
664
  _render() {
665
- ${g?"this.shadowRoot.innerHTML":"this.innerHTML"} = \`${U}${Y}\`
665
+ ${A?"this.shadowRoot.innerHTML":"this.innerHTML"} = \`${U}${Y}\`
666
666
  this._processSlots()
667
667
  }
668
668
  `}
@@ -679,7 +679,7 @@ class ${w.replace(/\W/g,"")} extends ${j} {
679
679
  attributeChangedCallback(name, oldValue, newValue) {
680
680
  if (oldValue !== newValue) {
681
681
  this[name] = newValue
682
- ${A?"":"this._render()"}
682
+ ${g?"":"this._render()"}
683
683
  }
684
684
  }
685
685
  `:""}
@@ -695,14 +695,14 @@ class ${w.replace(/\W/g,"")} extends ${j} {
695
695
 
696
696
  // Register the web component
697
697
  customElements.define('${y}', ${w.replace(/\W/g,"")})
698
- `}function Jy($,w,y,j){if(w.length<1)return"[Error: @webcomponent directive requires at least the tag name parameter]";let z=w[0].replace(/['"]/g,"");return`<script type="module" src="${y.__stx?.webComponentsPath||"/web-components"}/${z}.js"></script>`}var jw=M(async()=>{await p()});import{resolve as m8}from"path";function gz($){return $}var __dirname="/home/runner/work/stx/stx/packages/stx/src",r1,A0;var p0=M(async()=>{Q1();K1();await E0([A2(),ww(),i1(),n1(),jw()]);r1={enabled:!0,partialsDir:"partials",componentsDir:"components",debug:!1,cache:!0,cachePath:".stx/cache",cacheVersion:"1.0.0",customDirectives:[{name:"markdown",handler:d2,hasEndTag:!0,description:"Render markdown content to HTML"},{name:"webcomponent",handler:Jy,hasEndTag:!1,description:"Include a web component in the template"},t1,$$,$w,a$,e$,w$,j$,g$,y$],middleware:[],i18n:{defaultLocale:"en",locale:"en",translationsDir:"translations",format:"yaml",fallbackToKey:!0,cache:!0},webComponents:{enabled:!1,outputDir:"dist/web-components",components:[]},docs:{enabled:!1,outputDir:"docs",format:"markdown",components:!0,templates:!0,directives:!0},streaming:{enabled:!0,bufferSize:16384,strategy:"auto",timeout:30000},hydration:{enabled:!1,mode:"islands",clientEntry:"src/client.ts",autoMarkers:!0,preload:"lazy"},a11y:{enabled:!0,addSrOnlyStyles:!0,level:"AA",autoFix:!1,ignoreChecks:[]},seo:{enabled:!0,socialPreview:!0,defaultConfig:{title:"stx Project",description:"A website built with stx templating engine"}},animation:{enabled:!0,defaultDuration:300,defaultEase:"ease",respectMotionPreferences:!0,staggerDelay:50},markdown:{enabled:!0,syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0,additionalThemes:["light-plus","one-dark-pro","dracula","monokai","solarized-light","nord","github-dark"]}}},A0=await z2({name:"stx",cwd:m8(__dirname,".."),defaultConfig:r1})});import i8 from"fs";import gw from"path";async function G0($,w={}){try{if(!await T($))throw Error(`Markdown file not found: ${$}`);let j=(await i8.promises.stat($)).mtime.getTime();if(w.cache&&zw.has($)){let B=zw.get($);if(B.updatedAt>=j)return{content:B.content,data:B.data}}let z=await Bun.file($).text(),{data:g,content:A}=q1(z),J=w.markdown||A0.markdown||{enabled:!0,syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0}},Y=S0(A,{gfm:!0});if(J.syntaxHighlighting?.enabled&&J.syntaxHighlighting?.serverSide)Y=await n8(Y,J.syntaxHighlighting?.defaultTheme||"github-dark",J.syntaxHighlighting?.highlightUnknownLanguages||!1);let U={content:Y,data:g||{}};if(w.cache)zw.set($,{...U,updatedAt:j});return U}catch(y){if(w.debug)console.error(`Error reading/parsing markdown file ${$}:`,y);let j=y instanceof Error?y.message:String(y);return{content:k("Markdown File",`Error reading/parsing markdown file: ${j}`,$,"",0,""),data:{}}}}async function n8($,w,y){let j=/<pre><code( class="language-([^"]+)")?>([^<]+)<\/code><\/pre>/g;if(!c1)try{c1=await iw({theme:w||"github-dark",cache:!0})}catch(J){return console.error("Failed to initialize ts-syntax-highlighter:",J),$}let z=async(J,X,Y,U)=>{let B=U.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'"),b=Y||(y?"text":"");if(!b)return J;try{if(!c1.getSupportedLanguages().includes(b))return J;return(await c1.highlight(B,b,{theme:w})).html}catch(Q){console.error(`Error highlighting code block with language ${Y}:`,Q)}return J},g=$,A=$.matchAll(j);for(let J of A){let[X,Y,U,B]=J,b=await z(X,Y,U,B);g=g.replace(X,b)}return g}async function e2($,w,y="",j={}){return await p8($,/@markdown-file\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]*\}))?\)/g,async(A,J,X,Y)=>{try{let U=J;if(!gw.isAbsolute(J))U=gw.resolve(gw.dirname(y),J);let B={};if(X)try{try{B=JSON.parse(X)}catch{if(j.debug)console.warn("Using safer alternative for parsing JS object literal");let N=X.replace(/^\s*\{|\}\s*$/g,"").trim().split(/,(?=\s*\w+\s*:)/);for(let f of N){let O=f.indexOf(":");if(O>0){let R=f.substring(0,O).trim(),H=f.substring(O+1).trim(),F=H.startsWith('"')&&H.endsWith('"'),n=H.startsWith("'")&&H.endsWith("'");if(F||n)H=H.substring(1,H.length-1);B[R]=H}}}}catch(L){if(j.debug)console.error("Error parsing context in @markdown-file directive:",L)}let{content:b,data:Q}=await G0(U,j),K={...w,...Q,...B},_=b,W=/\{\{([^}]+)\}\}/g;return _=_.replace(W,(L,N)=>{let f=N.trim();return K[f]!==void 0?String(K[f]):L}),_}catch(U){let B=U instanceof Error?U.message:String(U);return k("Markdown File",`Error including markdown file: ${B}`,y,$,Y,A)}})}async function p8($,w,y){let j=[],z;while((z=w.exec($))!==null){let J=z[0],X=z.index,Y=z;j.push(y(...Y).then((U)=>({match:J,replacement:U,index:X})))}let g=await Promise.all(j);g.sort((J,X)=>X.index-J.index);let A=$;for(let{match:J,replacement:X}of g)A=A.replace(J,X);return A}var zw,c1=null;var Y1=M(async()=>{A$();await E0([pw(),p0(),p()]);zw=new Map});Q1();import fy from"process";async function Oy($){try{let w=await Bun.file($).text(),y=Ry(w),j=Hy(w,$),z=ky(w,y),g=Fy(w,y);return{file:$,metrics:y,issues:j,suggestions:z,performance:g}}catch(w){throw Error(`Failed to analyze template ${$}: ${w instanceof Error?w.message:String(w)}`)}}function Ry($){let w=$.split(`
698
+ `}function U9($,w,y,j){if(w.length<1)return"[Error: @webcomponent directive requires at least the tag name parameter]";let z=w[0].replace(/['"]/g,"");return`<script type="module" src="${y.__stx?.webComponentsPath||"/web-components"}/${z}.js"></script>`}var zw=M(async()=>{await n()});import{resolve as r8}from"path";function B4($){return $}var __dirname="/home/runner/work/stx/stx/packages/stx/src",c1,A0;var p0=M(async()=>{Q1();K1();await M0([Y2(),yw(),i1(),n1(),zw()]);c1={enabled:!0,partialsDir:"partials",componentsDir:"components",debug:!1,cache:!0,cachePath:".stx/cache",cacheVersion:"1.0.0",customDirectives:[{name:"markdown",handler:x2,hasEndTag:!0,description:"Render markdown content to HTML"},{name:"webcomponent",handler:U9,hasEndTag:!1,description:"Include a web component in the template"},$$,w$,ww,e$,t$,y$,z$,A$,j$],middleware:[],i18n:{defaultLocale:"en",locale:"en",translationsDir:"translations",format:"yaml",fallbackToKey:!0,cache:!0},webComponents:{enabled:!1,outputDir:"dist/web-components",components:[]},docs:{enabled:!1,outputDir:"docs",format:"markdown",components:!0,templates:!0,directives:!0},streaming:{enabled:!0,bufferSize:16384,strategy:"auto",timeout:30000},hydration:{enabled:!1,mode:"islands",clientEntry:"src/client.ts",autoMarkers:!0,preload:"lazy"},a11y:{enabled:!0,addSrOnlyStyles:!0,level:"AA",autoFix:!1,ignoreChecks:[]},seo:{enabled:!0,socialPreview:!0,defaultConfig:{title:"stx Project",description:"A website built with stx templating engine"}},animation:{enabled:!0,defaultDuration:300,defaultEase:"ease",respectMotionPreferences:!0,staggerDelay:50},markdown:{enabled:!0,syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0,additionalThemes:["light-plus","one-dark-pro","dracula","monokai","solarized-light","nord","github-dark"]}}},A0=await X2({name:"stx",cwd:r8(__dirname,".."),defaultConfig:c1})});import l8 from"fs";import Aw from"path";async function I0($,w={}){try{if(!await T($))throw Error(`Markdown file not found: ${$}`);let j=(await l8.promises.stat($)).mtime.getTime();if(w.cache&&gw.has($)){let B=gw.get($);if(B.updatedAt>=j)return{content:B.content,data:B.data}}let z=await Bun.file($).text(),{data:A,content:g}=q1(z),J=w.markdown||A0.markdown||{enabled:!0,syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0}},Y=S0(g,{gfm:!0});if(J.syntaxHighlighting?.enabled&&J.syntaxHighlighting?.serverSide)Y=await s8(Y,J.syntaxHighlighting?.defaultTheme||"github-dark",J.syntaxHighlighting?.highlightUnknownLanguages||!1);let U={content:Y,data:A||{}};if(w.cache)gw.set($,{...U,updatedAt:j});return U}catch(y){if(w.debug)console.error(`Error reading/parsing markdown file ${$}:`,y);let j=y instanceof Error?y.message:String(y);return{content:k("Markdown File",`Error reading/parsing markdown file: ${j}`,$,"",0,""),data:{}}}}async function s8($,w,y){let j=/<pre><code( class="language-([^"]+)")?>([^<]+)<\/code><\/pre>/g;if(!r1)try{r1=await cw({theme:w||"github-dark",cache:!0})}catch(J){return console.error("Failed to initialize ts-syntax-highlighter:",J),$}let z=async(J,X,Y,U)=>{let B=U.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'"),b=Y||(y?"text":"");if(!b)return J;try{if(!r1.getSupportedLanguages().includes(b))return J;return(await r1.highlight(B,b,{theme:w})).html}catch(Q){console.error(`Error highlighting code block with language ${Y}:`,Q)}return J},A=$,g=$.matchAll(j);for(let J of g){let[X,Y,U,B]=J,b=await z(X,Y,U,B);A=A.replace(X,b)}return A}async function w9($,w,y="",j={}){return await o8($,/@markdown-file\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]*\}))?\)/g,async(g,J,X,Y)=>{try{let U=J;if(!Aw.isAbsolute(J))U=Aw.resolve(Aw.dirname(y),J);let B={};if(X)try{try{B=JSON.parse(X)}catch{if(j.debug)console.warn("Using safer alternative for parsing JS object literal");let N=X.replace(/^\s*\{|\}\s*$/g,"").trim().split(/,(?=\s*\w+\s*:)/);for(let O of N){let H=O.indexOf(":");if(H>0){let R=O.substring(0,H).trim(),f=O.substring(H+1).trim(),F=f.startsWith('"')&&f.endsWith('"'),c=f.startsWith("'")&&f.endsWith("'");if(F||c)f=f.substring(1,f.length-1);B[R]=f}}}}catch(L){if(j.debug)console.error("Error parsing context in @markdown-file directive:",L)}let{content:b,data:Q}=await I0(U,j),K={...w,...Q,...B},_=b,W=/\{\{([^}]+)\}\}/g;return _=_.replace(W,(L,N)=>{let O=N.trim();return K[O]!==void 0?String(K[O]):L}),_}catch(U){let B=U instanceof Error?U.message:String(U);return k("Markdown File",`Error including markdown file: ${B}`,y,$,Y,g)}})}async function o8($,w,y){let j=[],z;while((z=w.exec($))!==null){let J=z[0],X=z.index,Y=z;j.push(y(...Y).then((U)=>({match:J,replacement:U,index:X})))}let A=await Promise.all(j);A.sort((J,X)=>X.index-J.index);let g=$;for(let{match:J,replacement:X}of A)g=g.replace(J,X);return g}var gw,r1=null;var Y1=M(async()=>{J$();await M0([lw(),p0(),n()]);gw=new Map});Q1();import F9 from"process";async function V9($){try{let w=await Bun.file($).text(),y=S9(w),j=G9(w,$),z=I9(w,y),A=T9(w,y);return{file:$,metrics:y,issues:j,suggestions:z,performance:A}}catch(w){throw Error(`Failed to analyze template ${$}: ${w instanceof Error?w.message:String(w)}`)}}function S9($){let w=$.split(`
699
699
  `),y=$.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),z=(y?y[1]:"").split(`
700
- `).length,g={conditionals:($.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:($.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:($.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};g.total=g.conditionals+g.loops+g.includes+g.custom;let A=($.match(/\{\{[\s\S]*?\}\}/g)||[]).length,J=($.match(/\{!![\s\S]*?!!\}/g)||[]).length,X=($.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,Y=A+J+X,U=($.match(/<[A-Z][^>]*>/g)||[]).length,B=($.match(/@extends\(/g)||[]).length,b=0,Q=0;for(let W of w)if(/@(?:if|unless|foreach|for|while|section)\b/.test(W)&&!/@end/.test(W)&&!/@else/.test(W))Q++,b=Math.max(b,Q);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(W))Q--;let K=b>=4?3:0,_=Math.min(10,Math.ceil(g.total*0.5+Y*0.1+U*0.3+(z>10?z*0.05:0)+K));return{lines:w.length,characters:$.length,directives:g,expressions:Y,components:U,layouts:B,scriptLines:z,complexity:_}}function Hy($,w){let y=[],j=qw($,"if","endif");if(j>0)y.push({type:"error",category:"syntax",message:`Found ${j} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let z=qw($,"foreach","endforeach");if(z>0)y.push({type:"error",category:"syntax",message:`Found ${z} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let g=$.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(g&&g.length>0)y.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let A=($.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(A>0)y.push({type:"warning",category:"security",message:`Found ${A} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let J=$.match(/<img[^>]*>/g);if(J){let U=J.filter((B)=>!B.includes("alt="));if(U.length>0)y.push({type:"warning",category:"accessibility",message:`Found ${U.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let X=$.split(`
701
- `).filter((U)=>U.length>120);if(X.length>0)y.push({type:"info",category:"maintainability",message:`Found ${X.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let Y=($.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(Y>3)y.push({type:"info",category:"maintainability",message:`Found ${Y} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return y}function ky($,w){let y=[];if(w.complexity>7)y.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(w.complexity>5&&w.directives.total>8)y.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(w.lines>100&&w.components===0)y.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(w.expressions>20)y.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let j=$.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(j&&j.length>0)y.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(w.directives.total===0&&w.expressions<5)y.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(w.scriptLines>50)y.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return y}function Fy($,w){let y=1;if(y+=w.directives.conditionals*0.1,y+=w.directives.loops*0.5,y+=w.directives.includes*2,y+=w.expressions*0.05,y+=w.components*1,w.scriptLines>10)y+=w.scriptLines*0.1;let j;if(w.expressions===0&&w.directives.total===0)j="high";else if(w.expressions<5&&w.directives.total<3)j="medium";else j="low";let z=[];if(y>10)z.push("Consider optimizing template complexity");if(j==="low"&&w.directives.total>5)z.push("Reduce dynamic content for better caching");if(w.components===0&&w.lines>40)z.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(y*100)/100,complexityScore:w.complexity,cacheability:j,recommendations:z}}function qw($,w,y){let j=$.replace(/<!--[\s\S]*?-->/g,""),z=(j.match(new RegExp(`@${w}\\b`,"g"))||[]).length,g=(j.match(new RegExp(`@${y}\\b`,"g"))||[]).length;return Math.abs(z-g)}async function H6($=["**/*.stx"],w){let y=[],j=[];for(let g of $){let A=await Array.fromAsync(new Bun.Glob(g).scan({cwd:w||fy.cwd(),onlyFiles:!0,absolute:!0}));j.push(...A.filter((J)=>J.endsWith(".stx")))}for(let g of j)try{let A=await Oy(g);y.push(A)}catch(A){console.warn(`Failed to analyze ${g}:`,A)}let z=Vy(y);return{results:y,summary:z}}function Vy($){let w=$.length,y=$.reduce((Y,U)=>Y+U.metrics.lines,0),j=w>0?$.reduce((Y,U)=>Y+U.metrics.complexity,0)/w:0,z=$.reduce((Y,U)=>Y+U.issues.length,0),g={};$.forEach((Y)=>{Y.issues.forEach((U)=>{g[U.category]=(g[U.category]||0)+1})});let A=w>0?$.reduce((Y,U)=>Y+U.performance.estimatedRenderTime,0)/w:0,J=Math.max(1,Math.min(10,Math.round(10-A/2-j/2))),X=[];if(j>6)X.push("Project has high average complexity. Consider refactoring complex templates.");if(z>w*2)X.push("High number of issues detected. Run detailed analysis on individual files.");if(g.security>0)X.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:w,totalLines:y,avgComplexity:Math.round(j*100)/100,totalIssues:z,issuesByCategory:g,performanceScore:J,recommendations:X}}K1();Y1();await p();import r0 from"fs";import c0 from"path";var r8=new Map;async function Xy($,w){try{let y=c0.resolve(w.cachePath),j=c0.join(y,`${l1($)}.html`),z=c0.join(y,`${l1($)}.meta.json`);if(!await T(j)||!await T(z))return null;let g=await Bun.file(z).text(),A=JSON.parse(g);if(A.cacheVersion!==w.cacheVersion)return null;if((await r0.promises.stat($)).mtime.getTime()>A.mtime)return null;for(let X of A.dependencies)if(await T(X)){if((await r0.promises.stat(X)).mtime.getTime()>A.mtime)return null}else return null;return await Bun.file(j).text()}catch(y){return console.warn(`Cache error for ${$}:`,y),null}}async function Yy($,w,y,j){try{let z=c0.resolve(j.cachePath);await r0.promises.mkdir(z,{recursive:!0});let g=c0.join(z,`${l1($)}.html`),A=c0.join(z,`${l1($)}.meta.json`),J=await r0.promises.stat($);await Bun.write(g,w);let X={sourcePath:$,mtime:J.mtime.getTime(),dependencies:Array.from(y),cacheVersion:j.cacheVersion,generatedAt:Date.now()};await Bun.write(A,JSON.stringify(X,null,2)),r8.set($,{output:w,mtime:J.mtime.getTime(),dependencies:y})}catch(z){console.warn(`Failed to cache template ${$}:`,z)}}function l1($){return new Bun.CryptoHasher("sha1").update($).digest("hex").substring(0,16)}ww();p0();C$();await E0([Y1(),p0()]);var{serve:o1}=globalThis.Bun;import s from"fs";import E from"path";import i from"process";import s1 from"path";x1();j1();var Aw={name:"bun-plugin-stx",async setup($){let w={...A0,...$.config?.stx},y=new Set,j=w.webComponents?.enabled?`./${s1.relative(s1.dirname($.config?.outdir||"dist"),w.webComponents.outputDir||"dist/web-components")}`:"/web-components",z=[];if(w.webComponents?.enabled)try{let g=await Ay(w,y);if(z.push(...g),w.debug&&g.length>0)console.log(`Successfully built ${g.length} web components`)}catch(g){console.error("Failed to build web components:",g)}$.onLoad({filter:/\.stx$/},async({path:g})=>{try{let A=new Set;if(w.cache&&w.cachePath){let K=await Xy(g,w);if(K){if(w.debug)console.log(`Using cached version of ${g}`);return{contents:K,loader:"html"}}}let J=await k0(()=>Bun.file(g).text(),"",(K)=>{throw new h1(`Failed to read stx file: ${g}`,g,void 0,void 0,`File read error: ${K.message}`)});if(!J)throw new h1(`stx file is empty: ${g}`,g);let{scriptContent:X,templateContent:Y,allScripts:U}=y1.time("script-extraction",()=>{let K=J.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),_=K?K[1]:"",W=J.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],L=J.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:_,templateContent:L,allScripts:W}}),B={__filename:g,__dirname:s1.dirname(g),__stx:{webComponentsPath:j,builtComponents:z}};await k0(()=>Q0(X,B,g),void 0,(K)=>{let _=new L0(`Script execution failed in ${g}: ${K.message}`,g,void 0,void 0,X.substring(0,100));if(z1.log(_,{filePath:g,scriptContent:X}),w.debug)throw _});let Q=await y1.timeAsync("directive-processing",async()=>{return await J0(Y,B,g,w,A)});if(U.length>0)if(Q.match(/(<\/body>)/i)){let _=U.join(`
700
+ `).length,A={conditionals:($.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:($.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:($.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};A.total=A.conditionals+A.loops+A.includes+A.custom;let g=($.match(/\{\{[\s\S]*?\}\}/g)||[]).length,J=($.match(/\{!![\s\S]*?!!\}/g)||[]).length,X=($.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,Y=g+J+X,U=($.match(/<[A-Z][^>]*>/g)||[]).length,B=($.match(/@extends\(/g)||[]).length,b=0,Q=0;for(let W of w)if(/@(?:if|unless|foreach|for|while|section)\b/.test(W)&&!/@end/.test(W)&&!/@else/.test(W))Q++,b=Math.max(b,Q);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(W))Q--;let K=b>=4?3:0,_=Math.min(10,Math.ceil(A.total*0.5+Y*0.1+U*0.3+(z>10?z*0.05:0)+K));return{lines:w.length,characters:$.length,directives:A,expressions:Y,components:U,layouts:B,scriptLines:z,complexity:_}}function G9($,w){let y=[],j=Ww($,"if","endif");if(j>0)y.push({type:"error",category:"syntax",message:`Found ${j} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let z=Ww($,"foreach","endforeach");if(z>0)y.push({type:"error",category:"syntax",message:`Found ${z} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let A=$.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(A&&A.length>0)y.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let g=($.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(g>0)y.push({type:"warning",category:"security",message:`Found ${g} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let J=$.match(/<img[^>]*>/g);if(J){let U=J.filter((B)=>!B.includes("alt="));if(U.length>0)y.push({type:"warning",category:"accessibility",message:`Found ${U.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let X=$.split(`
701
+ `).filter((U)=>U.length>120);if(X.length>0)y.push({type:"info",category:"maintainability",message:`Found ${X.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let Y=($.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(Y>3)y.push({type:"info",category:"maintainability",message:`Found ${Y} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return y}function I9($,w){let y=[];if(w.complexity>7)y.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(w.complexity>5&&w.directives.total>8)y.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(w.lines>100&&w.components===0)y.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(w.expressions>20)y.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let j=$.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(j&&j.length>0)y.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(w.directives.total===0&&w.expressions<5)y.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(w.scriptLines>50)y.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return y}function T9($,w){let y=1;if(y+=w.directives.conditionals*0.1,y+=w.directives.loops*0.5,y+=w.directives.includes*2,y+=w.expressions*0.05,y+=w.components*1,w.scriptLines>10)y+=w.scriptLines*0.1;let j;if(w.expressions===0&&w.directives.total===0)j="high";else if(w.expressions<5&&w.directives.total<3)j="medium";else j="low";let z=[];if(y>10)z.push("Consider optimizing template complexity");if(j==="low"&&w.directives.total>5)z.push("Reduce dynamic content for better caching");if(w.components===0&&w.lines>40)z.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(y*100)/100,complexityScore:w.complexity,cacheability:j,recommendations:z}}function Ww($,w,y){let j=$.replace(/<!--[\s\S]*?-->/g,""),z=(j.match(new RegExp(`@${w}\\b`,"g"))||[]).length,A=(j.match(new RegExp(`@${y}\\b`,"g"))||[]).length;return Math.abs(z-A)}async function T6($=["**/*.stx"],w){let y=[],j=[];for(let A of $){let g=await Array.fromAsync(new Bun.Glob(A).scan({cwd:w||F9.cwd(),onlyFiles:!0,absolute:!0}));j.push(...g.filter((J)=>J.endsWith(".stx")))}for(let A of j)try{let g=await V9(A);y.push(g)}catch(g){console.warn(`Failed to analyze ${A}:`,g)}let z=Z9(y);return{results:y,summary:z}}function Z9($){let w=$.length,y=$.reduce((Y,U)=>Y+U.metrics.lines,0),j=w>0?$.reduce((Y,U)=>Y+U.metrics.complexity,0)/w:0,z=$.reduce((Y,U)=>Y+U.issues.length,0),A={};$.forEach((Y)=>{Y.issues.forEach((U)=>{A[U.category]=(A[U.category]||0)+1})});let g=w>0?$.reduce((Y,U)=>Y+U.performance.estimatedRenderTime,0)/w:0,J=Math.max(1,Math.min(10,Math.round(10-g/2-j/2))),X=[];if(j>6)X.push("Project has high average complexity. Consider refactoring complex templates.");if(z>w*2)X.push("High number of issues detected. Run detailed analysis on individual files.");if(A.security>0)X.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:w,totalLines:y,avgComplexity:Math.round(j*100)/100,totalIssues:z,issuesByCategory:A,performanceScore:J,recommendations:X}}K1();Y1();await n();import c0 from"fs";import r0 from"path";var a8=new Map;async function B9($,w){try{let y=r0.resolve(w.cachePath),j=r0.join(y,`${l1($)}.html`),z=r0.join(y,`${l1($)}.meta.json`);if(!await T(j)||!await T(z))return null;let A=await Bun.file(z).text(),g=JSON.parse(A);if(g.cacheVersion!==w.cacheVersion)return null;if((await c0.promises.stat($)).mtime.getTime()>g.mtime)return null;for(let X of g.dependencies)if(await T(X)){if((await c0.promises.stat(X)).mtime.getTime()>g.mtime)return null}else return null;return await Bun.file(j).text()}catch(y){return console.warn(`Cache error for ${$}:`,y),null}}async function b9($,w,y,j){try{let z=r0.resolve(j.cachePath);await c0.promises.mkdir(z,{recursive:!0});let A=r0.join(z,`${l1($)}.html`),g=r0.join(z,`${l1($)}.meta.json`),J=await c0.promises.stat($);await Bun.write(A,w);let X={sourcePath:$,mtime:J.mtime.getTime(),dependencies:Array.from(y),cacheVersion:j.cacheVersion,generatedAt:Date.now()};await Bun.write(g,JSON.stringify(X,null,2)),a8.set($,{output:w,mtime:J.mtime.getTime(),dependencies:y})}catch(z){console.warn(`Failed to cache template ${$}:`,z)}}function l1($){return new Bun.CryptoHasher("sha1").update($).digest("hex").substring(0,16)}yw();p0();v$();var{serve:a1}=globalThis.Bun;import s from"fs";import C from"path";import i from"process";import{existsSync as e8}from"fs";import{join as Jw}from"path";import s1 from"process";function t8(){let $=[Jw(s1.cwd(),"../../craft/packages/zig/zig-out/bin/craft-minimal"),Jw(s1.cwd(),"../../../craft/packages/zig/zig-out/bin/craft-minimal"),Jw(s1.cwd(),"../craft/packages/zig/zig-out/bin/craft-minimal"),"/Users/mac/repos/stacks-org/craft/packages/zig/zig-out/bin/craft-minimal"];for(let w of $)if(e8(w))return w;return}async function Xw($,w={}){let y=`http://localhost:${$}/`;try{let{createApp:j}=await import("ts-craft");console.log("\u26A1 Opening native window...");let z=t8();return await j({url:y,craftPath:z,window:{title:w.title||"stx Development",width:w.width||1400,height:w.height||900,resizable:!0,systemTray:!0,darkMode:!0,hotReload:w.hotReload??!0,devTools:!0}}).show(),console.log(`\u2713 Native window opened at ${y}`),console.log('\uD83D\uDCCC Look for the "stx Development" icon in your menubar'),!0}catch(j){console.warn("\u26A0 Could not open native window:",j.message),console.log("\uD83D\uDCF1 Opening in browser instead...");try{let{spawn:z}=await import("child_process"),A=s1.platform,g,J;if(A==="darwin")g="open",J=[y];else if(A==="win32")g="cmd",J=["/c","start",y];else g="xdg-open",J=[y];return z(g,J,{detached:!0,stdio:"ignore"}).unref(),console.log(`\u2713 Browser opened at ${y}`),!0}catch(z){return console.error("Could not open browser:",z),console.log(`Please open manually: ${y}`),!1}}}await M0([Y1(),p0()]);import o1 from"path";x1();j1();var Yw={name:"bun-plugin-stx",async setup($){let w={...A0,...$.config?.stx},y=new Set,j=w.webComponents?.enabled?`./${o1.relative(o1.dirname($.config?.outdir||"dist"),w.webComponents.outputDir||"dist/web-components")}`:"/web-components",z=[];if(w.webComponents?.enabled)try{let A=await Y9(w,y);if(z.push(...A),w.debug&&A.length>0)console.log(`Successfully built ${A.length} web components`)}catch(A){console.error("Failed to build web components:",A)}$.onLoad({filter:/\.stx$/},async({path:A})=>{try{let g=new Set;if(w.cache&&w.cachePath){let K=await B9(A,w);if(K){if(w.debug)console.log(`Using cached version of ${A}`);return{contents:K,loader:"html"}}}let J=await k0(()=>Bun.file(A).text(),"",(K)=>{throw new h1(`Failed to read stx file: ${A}`,A,void 0,void 0,`File read error: ${K.message}`)});if(!J)throw new h1(`stx file is empty: ${A}`,A);let{scriptContent:X,templateContent:Y,allScripts:U}=y1.time("script-extraction",()=>{let K=J.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),_=K?K[1]:"",W=J.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],L=J.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:_,templateContent:L,allScripts:W}}),B={__filename:A,__dirname:o1.dirname(A),__stx:{webComponentsPath:j,builtComponents:z}};await k0(()=>Q0(X,B,A),void 0,(K)=>{let _=new W0(`Script execution failed in ${A}: ${K.message}`,A,void 0,void 0,X.substring(0,100));if(A1.log(_,{filePath:A,scriptContent:X}),w.debug)throw _});let Q=await y1.timeAsync("directive-processing",async()=>{return await J0(Y,B,A,w,g)});if(U.length>0)if(Q.match(/(<\/body>)/i)){let _=U.join(`
702
702
  `);Q=Q.replace(/(<\/body>)/i,`${_}
703
703
  $1`)}else Q+=`
704
704
  ${U.join(`
705
- `)}`;if(A.forEach((K)=>y.add(K)),w.cache&&w.cachePath){if(await Yy(g,Q,A,w),w.debug)console.log(`Cached template ${g} with ${A.size} dependencies`)}return{contents:Q,loader:"html"}}catch(A){let J=A instanceof Error?A:new L0(`Plugin processing failed: ${String(A)}`,g);if(z1.log(J,{filePath:g,buildConfig:$.config}),P1.logDetailedError(J,{filePath:g,plugin:"bun-plugin-stx"}),w.debug)console.error("stx Plugin Error:",J);let X=J,Y=X.line||null,U=X.context||null;return{contents:`<!DOCTYPE html>
705
+ `)}`;if(g.forEach((K)=>y.add(K)),w.cache&&w.cachePath){if(await b9(A,Q,g,w),w.debug)console.log(`Cached template ${A} with ${g.size} dependencies`)}return{contents:Q,loader:"html"}}catch(g){let J=g instanceof Error?g:new W0(`Plugin processing failed: ${String(g)}`,A);if(A1.log(J,{filePath:A,buildConfig:$.config}),P1.logDetailedError(J,{filePath:A,plugin:"bun-plugin-stx"}),w.debug)console.error("stx Plugin Error:",J);let X=J,Y=X.line||null,U=X.context||null;return{contents:`<!DOCTYPE html>
706
706
  <html lang="en">
707
707
  <head>
708
708
  <meta charset="UTF-8">
@@ -725,7 +725,7 @@ ${U.join(`
725
725
 
726
726
  <div class="error-details">
727
727
  <h3>Error Details</h3>
728
- <p><strong>File:</strong> <span class="file-path">${g}</span></p>
728
+ <p><strong>File:</strong> <span class="file-path">${A}</span></p>
729
729
  <p><strong>Error:</strong> ${J.message}</p>
730
730
  ${Y?`<p><strong>Line:</strong> ${Y}</p>`:""}
731
731
  ${U?`<p><strong>Context:</strong> ${U}</p>`:""}
@@ -743,23 +743,23 @@ ${U.join(`
743
743
  <li>Check the syntax of your stx directives (e.g., @if, @foreach)</li>
744
744
  <li>Verify that all variables used in the template are properly defined</li>
745
745
  <li>Ensure script tags have valid JavaScript/TypeScript syntax</li>
746
- <li>Run <code>stx debug ${s1.basename(g)}</code> for detailed analysis</li>
746
+ <li>Run <code>stx debug ${o1.basename(A)}</code> for detailed analysis</li>
747
747
  <li>Enable debug mode in your stx config for more detailed error messages</li>
748
748
  </ul>
749
749
  </div>
750
750
  </body>
751
- </html>`,loader:"html"}}})}};var __dirname="/home/runner/work/stx/stx/packages/stx/src",q={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m",bgGray:"\x1B[100m"};async function Jw($,w=10){for(let y=0;y<w;y++){let j=$+y;try{return o1({port:j,fetch:()=>new Response("test")}).stop(),j}catch(z){if(z.code==="EADDRINUSE")continue;throw z}}throw Error(`Could not find an available port between ${$} and ${$+w-1}`)}async function Uy($){let{spawn:w}=await import("child_process"),y=E.resolve(__dirname,"../../zyte"),j=`http://localhost:${$}/`;try{if(!s.existsSync(E.join(y,"zig-out/bin/zyte-minimal"))){console.log(`${q.yellow}\u26A0${q.reset} Zyte not built. Building now...`);let{execSync:g}=await import("child_process");g(`cd ${y} && zig build`,{stdio:"inherit"})}return console.log(`${q.magenta}\u26A1 Opening native window...${q.reset}`),w(E.join(y,"zig-out/bin/zyte-minimal"),[j],{detached:!0,stdio:"ignore"}).unref(),console.log(`${q.green}\u2713${q.reset} Native window opened with URL: ${q.cyan}${j}${q.reset}`),!0}catch(z){return console.log(`${q.red}\u2717${q.reset} Could not open native window:`,z),console.log(`${q.dim} You can manually run: cd ${y} && ./zig-out/bin/zyte-minimal ${j}${q.reset}`),!1}}function Xw($,w){if(i.stdin.isTTY){i.stdin.setRawMode(!0),i.stdin.setEncoding("utf8"),i.stdin.resume(),console.log(`
751
+ </html>`,loader:"html"}}})}};var q={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m",bgGray:"\x1B[100m"};async function Uw($,w=10){for(let y=0;y<w;y++){let j=$+y;try{return a1({port:j,fetch:()=>new Response("test")}).stop(),j}catch(z){if(z.code==="EADDRINUSE")continue;throw z}}throw Error(`Could not find an available port between ${$} and ${$+w-1}`)}async function Q9($){try{return await Xw($,{title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0})}catch(w){return console.log(`${q.red}\u2717${q.reset} Could not open native window:`,w),!1}}function Bw($,w){if(i.stdin.isTTY){i.stdin.setRawMode(!0),i.stdin.setEncoding("utf8"),i.stdin.resume(),console.log(`
752
752
  Keyboard shortcuts:`),console.log(` ${q.cyan}o${q.reset} + Enter - Open in browser`),console.log(` ${q.cyan}c${q.reset} + Enter - Clear console`),console.log(` ${q.cyan}q${q.reset} + Enter (or ${q.cyan}Ctrl+C${q.reset}) - Quit server`);let y="";i.stdin.on("data",(j)=>{if(j==="\x03")w(),i.exit(0);if(y+=j,y.endsWith("\r")||y.endsWith(`
753
753
  `)){let z=y.trim().toLowerCase();if(y="",z==="o")console.log(`${q.dim}Opening ${q.cyan}${$}${q.dim} in your browser...${q.reset}`),Bun.spawn(["open",$],{stderr:"inherit"});else if(z==="c")console.clear(),console.log(`${q.green}Server running at ${q.cyan}${$}${q.reset}`),console.log(`Press ${q.cyan}Ctrl+C${q.reset} to stop the server`),console.log(`
754
754
  Keyboard shortcuts:`),console.log(` ${q.cyan}o${q.reset} + Enter - Open in browser`),console.log(` ${q.cyan}c${q.reset} + Enter - Clear console`),console.log(` ${q.cyan}q${q.reset} + Enter (or ${q.cyan}Ctrl+C${q.reset}) - Quit server`);else if(z==="q")console.log(`${q.yellow}Stopping server...${q.reset}`),w(),i.exit(0);else if(z==="h")console.log(`
755
- Keyboard Shortcuts:`),console.log(` ${q.cyan}o${q.reset} + Enter - Open in browser`),console.log(` ${q.cyan}c${q.reset} + Enter - Clear console`),console.log(` ${q.cyan}q${q.reset} + Enter (or ${q.cyan}Ctrl+C${q.reset}) - Quit server`),console.log(` ${q.cyan}h${q.reset} + Enter - Show this help`)}})}}async function c8($,w={}){let y=w.port||3000,j=w.watch!==!1,z=E.resolve($);if(!s.existsSync(z))return console.error(`${q.red}Error: File not found: ${q.bright}${z}${q.reset}`),!1;if(!z.endsWith(".md"))return console.error(`${q.red}Error: File must have .md extension: ${q.bright}${z}${q.reset}`),!1;console.log(`${q.blue}Processing${q.reset} ${q.bright}${$}${q.reset}...`);let g=null,A=async()=>{try{let{content:B,data:b}=await G0(z,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:A0.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),Q=w.markdown?.syntaxHighlighting||A0.markdown?.syntaxHighlighting,K=Q?.defaultTheme||"github-dark",_=["github-dark"],W=Q?.additionalThemes||[],N=[...new Set([..._,...W])].map((f)=>`<option value="${f}"${f===K?" selected":""}>${f}</option>`).join(`
756
- `);return g=`
755
+ Keyboard Shortcuts:`),console.log(` ${q.cyan}o${q.reset} + Enter - Open in browser`),console.log(` ${q.cyan}c${q.reset} + Enter - Clear console`),console.log(` ${q.cyan}q${q.reset} + Enter (or ${q.cyan}Ctrl+C${q.reset}) - Quit server`),console.log(` ${q.cyan}h${q.reset} + Enter - Show this help`)}})}}async function $6($,w={}){let y=w.port||3000,j=w.watch!==!1,z=C.resolve($);if(!s.existsSync(z))return console.error(`${q.red}Error: File not found: ${q.bright}${z}${q.reset}`),!1;if(!z.endsWith(".md"))return console.error(`${q.red}Error: File must have .md extension: ${q.bright}${z}${q.reset}`),!1;console.log(`${q.blue}Processing${q.reset} ${q.bright}${$}${q.reset}...`);let A=null,g=async()=>{try{let{content:B,data:b}=await I0(z,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:A0.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),Q=w.markdown?.syntaxHighlighting||A0.markdown?.syntaxHighlighting,K=Q?.defaultTheme||"github-dark",_=["github-dark"],W=Q?.additionalThemes||[],N=[...new Set([..._,...W])].map((O)=>`<option value="${O}"${O===K?" selected":""}>${O}</option>`).join(`
756
+ `);return A=`
757
757
  <!DOCTYPE html>
758
758
  <html lang="en">
759
759
  <head>
760
760
  <meta charset="UTF-8">
761
761
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
762
- <title>${b.title||E.basename(z)}</title>
762
+ <title>${b.title||C.basename(z)}</title>
763
763
  <!-- Syntax highlighting styles -->
764
764
  <style id="syntax-theme">
765
765
  :root {
@@ -957,10 +957,10 @@ Keyboard Shortcuts:`),console.log(` ${q.cyan}o${q.reset} + Enter - Open in brow
957
957
  ${Object.keys(b).length>0?`
958
958
  <div class="frontmatter">
959
959
  <h3>Frontmatter</h3>
960
- ${Object.entries(b).map(([f,O])=>`
960
+ ${Object.entries(b).map(([O,H])=>`
961
961
  <div class="frontmatter-item">
962
- <span class="frontmatter-label">${f}:</span>
963
- <span>${Array.isArray(O)?O.join(", "):O}</span>
962
+ <span class="frontmatter-label">${O}:</span>
963
+ <span>${Array.isArray(H)?H.join(", "):H}</span>
964
964
  </div>`).join("")}
965
965
  </div>
966
966
  `:""}
@@ -994,24 +994,24 @@ Keyboard Shortcuts:`),console.log(` ${q.cyan}o${q.reset} + Enter - Open in brow
994
994
  </script>
995
995
  </body>
996
996
  </html>
997
- `,!0}catch(B){return console.error(`${q.red}Error processing Markdown file:${q.reset}`,B),!1}};if(!await A())return!1;let X=y;try{if(X=await Jw(y),X!==y)console.log(`${q.yellow}Port ${y} is busy, using port ${X} instead${q.reset}`)}catch{return console.error(`${q.red}Could not find an available port${q.reset}`),!1}console.log(`${q.blue}Starting server on ${q.cyan}http://localhost:${X}/${q.reset}...`);let Y=o1({port:X,fetch(B){if(new URL(B.url).pathname==="/")return new Response(g,{headers:{"Content-Type":"text/html"}});return new Response("Not Found",{status:404})},error(B){return new Response(`<pre>${B}
997
+ `,!0}catch(B){return console.error(`${q.red}Error processing Markdown file:${q.reset}`,B),!1}};if(!await g())return!1;let X=y;try{if(X=await Uw(y),X!==y)console.log(`${q.yellow}Port ${y} is busy, using port ${X} instead${q.reset}`)}catch{return console.error(`${q.red}Could not find an available port${q.reset}`),!1}console.log(`${q.blue}Starting server on ${q.cyan}http://localhost:${X}/${q.reset}...`);let Y=a1({port:X,fetch(B){if(new URL(B.url).pathname==="/")return new Response(A,{headers:{"Content-Type":"text/html"}});return new Response("Not Found",{status:404})},error(B){return new Response(`<pre>${B}
998
998
  ${B.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
999
999
  ${q.blue}stx${q.reset} ${q.green}${i.env.stx_VERSION||"v0.0.10"}${q.reset} ${q.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${q.reset}`),console.log(`
1000
1000
  ${q.bright}\u2192 ${q.cyan}http://localhost:${y}/${q.reset}`),console.log(`
1001
- ${q.yellow}Routes:${q.reset}`);let U=E.relative(i.cwd(),z);if(console.log(` ${q.green}\u2514\u2500 /${q.reset} \u2192 ${q.bright}${U}${q.reset}`),console.log(`
1002
- Press ${q.cyan}h${q.reset} + ${q.cyan}Enter${q.reset} to show shortcuts`),Xw(Y.url.toString(),()=>{if(j)s.watch(E.dirname(z),{recursive:!0}).close();Y.stop()}),w.native)await Uy(X);if(j){let B=E.dirname(z);console.log(`${q.blue}Watching ${q.bright}${B}${q.reset} for changes...`);let b=s.watch(B,{recursive:!0},async(Q,K)=>{if(K&&K.endsWith(".md"))console.log(`${q.yellow}File ${q.bright}${K}${q.yellow} changed, reprocessing...${q.reset}`),await A()});i.on("SIGINT",()=>{b.close(),Y.stop(),i.exit(0)})}return!0}async function Gz($,w={}){let y=w.port||3000,j=w.watch!==!1,z=E.resolve($);if(!s.existsSync(z))return console.error(`${q.red}Error: File not found: ${q.bright}${z}${q.reset}`),!1;if(z.endsWith(".md"))return c8(z,w);else if(!z.endsWith(".stx"))return console.error(`${q.red}Error: Unsupported file type: ${q.bright}${z}${q.reset}. Only .stx and .md files are supported.`),!1;let g=E.join(i.cwd(),".stx-output");s.mkdirSync(g,{recursive:!0}),console.log(`${q.blue}Building ${q.bright}${$}${q.reset}...`);let A=null,J=async()=>{try{let b=await Bun.build({entrypoints:[z],outdir:g,plugins:[Aw],define:{"process.env.NODE_ENV":'"development"'},...w.stxOptions});if(!b.success)return console.error(`${q.red}Build failed:${q.reset}`,b.logs),!1;let Q=b.outputs.find((_)=>_.path.endsWith(".html"));if(!Q)return console.error(`${q.red}No HTML output found${q.reset}`),!1;return A=await Bun.file(Q.path).text(),!0}catch(b){return console.error(`${q.red}Error building stx file:${q.reset}`,b),!1}};if(!await J())return!1;let Y=y;try{if(Y=await Jw(y),Y!==y)console.log(`${q.yellow}Port ${y} is busy, using port ${Y} instead${q.reset}`)}catch{return console.error(`${q.red}Could not find an available port${q.reset}`),!1}console.log(`${q.blue}Starting server on ${q.cyan}http://localhost:${Y}/${q.reset}...`);let U=o1({port:Y,fetch(b){let Q=new URL(b.url);if(Q.pathname==="/")return new Response(A,{headers:{"Content-Type":"text/html"}});let K=E.join(g,Q.pathname);if(s.existsSync(K)&&s.statSync(K).isFile()){let L=Bun.file(K),N=E.extname(K).toLowerCase(),f="text/plain";switch(N){case".html":f="text/html";break;case".css":f="text/css";break;case".js":f="text/javascript";break;case".json":f="application/json";break;case".png":f="image/png";break;case".jpg":case".jpeg":f="image/jpeg";break;case".gif":f="image/gif";break}return new Response(L,{headers:{"Content-Type":f}})}let _=E.dirname(z),W=E.join(_,Q.pathname);if(s.existsSync(W)&&s.statSync(W).isFile()){let L=Bun.file(W),N=E.extname(W).toLowerCase(),f="text/plain";switch(N){case".html":f="text/html";break;case".css":f="text/css";break;case".js":f="text/javascript";break;case".json":f="application/json";break;case".png":f="image/png";break;case".jpg":case".jpeg":f="image/jpeg";break;case".gif":f="image/gif";break;case".svg":f="image/svg+xml";break;case".ico":f="image/x-icon";break}return new Response(L,{headers:{"Content-Type":f}})}return new Response("Not Found",{status:404})},error(b){return new Response(`<pre>${b}
1001
+ ${q.yellow}Routes:${q.reset}`);let U=C.relative(i.cwd(),z);if(console.log(` ${q.green}\u2514\u2500 /${q.reset} \u2192 ${q.bright}${U}${q.reset}`),console.log(`
1002
+ Press ${q.cyan}h${q.reset} + ${q.cyan}Enter${q.reset} to show shortcuts`),Bw(Y.url.toString(),()=>{if(j)s.watch(C.dirname(z),{recursive:!0}).close();Y.stop()}),w.native)await Q9(X);if(j){let B=C.dirname(z);console.log(`${q.blue}Watching ${q.bright}${B}${q.reset} for changes...`);let b=s.watch(B,{recursive:!0},async(Q,K)=>{if(K&&K.endsWith(".md"))console.log(`${q.yellow}File ${q.bright}${K}${q.yellow} changed, reprocessing...${q.reset}`),await g()});i.on("SIGINT",()=>{b.close(),Y.stop(),i.exit(0)})}return!0}async function LA($,w={}){let y=w.port||3000,j=w.watch!==!1,z=C.resolve($);if(!s.existsSync(z))return console.error(`${q.red}Error: File not found: ${q.bright}${z}${q.reset}`),!1;if(z.endsWith(".md"))return $6(z,w);else if(!z.endsWith(".stx"))return console.error(`${q.red}Error: Unsupported file type: ${q.bright}${z}${q.reset}. Only .stx and .md files are supported.`),!1;let A=C.join(i.cwd(),".stx-output");s.mkdirSync(A,{recursive:!0}),console.log(`${q.blue}Building ${q.bright}${$}${q.reset}...`);let g=null,J=async()=>{try{let b=await Bun.build({entrypoints:[z],outdir:A,plugins:[Yw],define:{"process.env.NODE_ENV":'"development"'},...w.stxOptions});if(!b.success)return console.error(`${q.red}Build failed:${q.reset}`,b.logs),!1;let Q=b.outputs.find((_)=>_.path.endsWith(".html"));if(!Q)return console.error(`${q.red}No HTML output found${q.reset}`),!1;return g=await Bun.file(Q.path).text(),!0}catch(b){return console.error(`${q.red}Error building stx file:${q.reset}`,b),!1}};if(!await J())return!1;let Y=y;try{if(Y=await Uw(y),Y!==y)console.log(`${q.yellow}Port ${y} is busy, using port ${Y} instead${q.reset}`)}catch{return console.error(`${q.red}Could not find an available port${q.reset}`),!1}console.log(`${q.blue}Starting server on ${q.cyan}http://localhost:${Y}/${q.reset}...`);let U=a1({port:Y,fetch(b){let Q=new URL(b.url);if(Q.pathname==="/")return new Response(g,{headers:{"Content-Type":"text/html"}});let K=C.join(A,Q.pathname);if(s.existsSync(K)&&s.statSync(K).isFile()){let L=Bun.file(K),N=C.extname(K).toLowerCase(),O="text/plain";switch(N){case".html":O="text/html";break;case".css":O="text/css";break;case".js":O="text/javascript";break;case".json":O="application/json";break;case".png":O="image/png";break;case".jpg":case".jpeg":O="image/jpeg";break;case".gif":O="image/gif";break}return new Response(L,{headers:{"Content-Type":O}})}let _=C.dirname(z),W=C.join(_,Q.pathname);if(s.existsSync(W)&&s.statSync(W).isFile()){let L=Bun.file(W),N=C.extname(W).toLowerCase(),O="text/plain";switch(N){case".html":O="text/html";break;case".css":O="text/css";break;case".js":O="text/javascript";break;case".json":O="application/json";break;case".png":O="image/png";break;case".jpg":case".jpeg":O="image/jpeg";break;case".gif":O="image/gif";break;case".svg":O="image/svg+xml";break;case".ico":O="image/x-icon";break}return new Response(L,{headers:{"Content-Type":O}})}return new Response("Not Found",{status:404})},error(b){return new Response(`<pre>${b}
1003
1003
  ${b.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
1004
1004
  ${q.blue}stx${q.reset} ${q.green}${i.env.stx_VERSION||"v0.0.10"}${q.reset} ${q.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${q.reset}`),console.log(`
1005
1005
  ${q.bright}\u2192 ${q.cyan}http://localhost:${y}/${q.reset}`),console.log(`
1006
- ${q.yellow}Routes:${q.reset}`);let B=E.relative(i.cwd(),z);if(console.log(` ${q.green}\u2514\u2500 /${q.reset} \u2192 ${q.bright}${B}${q.reset}`),console.log(`
1007
- Press ${q.cyan}h${q.reset} + ${q.cyan}Enter${q.reset} to show shortcuts`),Xw(U.url.toString(),()=>{if(j)s.watch(E.dirname(z),{recursive:!0}).close();U.stop()}),w.native)await Uy(Y);if(j){let b=E.dirname(z);console.log(`${q.blue}Watching ${q.bright}${b}${q.reset} for changes...`);let Q=s.watch(b,{recursive:!0},async(K,_)=>{if(_&&(_.endsWith(".stx")||_.endsWith(".js")||_.endsWith(".ts")))console.log(`${q.yellow}File ${q.bright}${_}${q.yellow} changed, rebuilding...${q.reset}`),await J()});i.on("SIGINT",()=>{Q.close(),U.stop(),i.exit(0)})}return!0}async function Tz($,w={}){let y=w.port||3000,j=w.watch!==!1;for(let b of $){let Q=E.resolve(b);if(!s.existsSync(Q))return console.error(`${q.red}Error: File not found: ${q.bright}${Q}${q.reset}`),!1;if(!Q.endsWith(".stx")&&!Q.endsWith(".md"))return console.error(`${q.red}Error: Unsupported file type: ${q.bright}${Q}${q.reset}. Only .stx and .md files are supported.`),!1}let z=E.join(i.cwd(),".stx-output");s.mkdirSync(z,{recursive:!0});let g=l8($.map((b)=>E.dirname(E.resolve(b))));console.log(`${q.blue}Processing ${q.bright}${$.length}${q.reset} files...`);let A={},J=async()=>{try{for(let b of $){let Q=E.resolve(b);if(Q.endsWith(".md"))try{let{content:_,data:W}=await G0(Q,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:A0.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),L=w.markdown?.syntaxHighlighting||A0.markdown?.syntaxHighlighting,N=L?.defaultTheme||"github-dark",f=["github-dark"],O=L?.additionalThemes||[],H=[...new Set([...f,...O])].map((c)=>`<option value="${c}"${c===N?" selected":""}>${c}</option>`).join(`
1006
+ ${q.yellow}Routes:${q.reset}`);let B=C.relative(i.cwd(),z);if(console.log(` ${q.green}\u2514\u2500 /${q.reset} \u2192 ${q.bright}${B}${q.reset}`),console.log(`
1007
+ Press ${q.cyan}h${q.reset} + ${q.cyan}Enter${q.reset} to show shortcuts`),Bw(U.url.toString(),()=>{if(j)s.watch(C.dirname(z),{recursive:!0}).close();U.stop()}),w.native)await Q9(Y);if(j){let b=C.dirname(z);console.log(`${q.blue}Watching ${q.bright}${b}${q.reset} for changes...`);let Q=s.watch(b,{recursive:!0},async(K,_)=>{if(_&&(_.endsWith(".stx")||_.endsWith(".js")||_.endsWith(".ts")))console.log(`${q.yellow}File ${q.bright}${_}${q.yellow} changed, rebuilding...${q.reset}`),await J()});i.on("SIGINT",()=>{Q.close(),U.stop(),i.exit(0)})}return!0}async function OA($,w={}){let y=w.port||3000,j=w.watch!==!1;for(let b of $){let Q=C.resolve(b);if(!s.existsSync(Q))return console.error(`${q.red}Error: File not found: ${q.bright}${Q}${q.reset}`),!1;if(!Q.endsWith(".stx")&&!Q.endsWith(".md"))return console.error(`${q.red}Error: Unsupported file type: ${q.bright}${Q}${q.reset}. Only .stx and .md files are supported.`),!1}let z=C.join(i.cwd(),".stx-output");s.mkdirSync(z,{recursive:!0});let A=w6($.map((b)=>C.dirname(C.resolve(b))));console.log(`${q.blue}Processing ${q.bright}${$.length}${q.reset} files...`);let g={},J=async()=>{try{for(let b of $){let Q=C.resolve(b);if(Q.endsWith(".md"))try{let{content:_,data:W}=await I0(Q,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:A0.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),L=w.markdown?.syntaxHighlighting||A0.markdown?.syntaxHighlighting,N=L?.defaultTheme||"github-dark",O=["github-dark"],H=L?.additionalThemes||[],f=[...new Set([...O,...H])].map((o)=>`<option value="${o}"${o===N?" selected":""}>${o}</option>`).join(`
1008
1008
  `),F=`
1009
1009
  <!DOCTYPE html>
1010
1010
  <html lang="en">
1011
1011
  <head>
1012
1012
  <meta charset="UTF-8">
1013
1013
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1014
- <title>${W.title||E.basename(Q)}</title>
1014
+ <title>${W.title||C.basename(Q)}</title>
1015
1015
  <!-- Syntax highlighting styles -->
1016
1016
  <style id="syntax-theme">
1017
1017
  :root {
@@ -1209,10 +1209,10 @@ Press ${q.cyan}h${q.reset} + ${q.cyan}Enter${q.reset} to show shortcuts`),Xw(U.u
1209
1209
  ${Object.keys(W).length>0?`
1210
1210
  <div class="frontmatter">
1211
1211
  <h3>Frontmatter</h3>
1212
- ${Object.entries(W).map(([c,l])=>`
1212
+ ${Object.entries(W).map(([o,a])=>`
1213
1213
  <div class="frontmatter-item">
1214
- <span class="frontmatter-label">${c}:</span>
1215
- <span>${Array.isArray(l)?l.join(", "):l}</span>
1214
+ <span class="frontmatter-label">${o}:</span>
1215
+ <span>${Array.isArray(a)?a.join(", "):a}</span>
1216
1216
  </div>`).join("")}
1217
1217
  </div>
1218
1218
  `:""}
@@ -1220,7 +1220,7 @@ Press ${q.cyan}h${q.reset} + ${q.cyan}Enter${q.reset} to show shortcuts`),Xw(U.u
1220
1220
  <div class="theme-selector">
1221
1221
  Theme:
1222
1222
  <select id="themeSelector" onchange="changeTheme()">
1223
- ${H}
1223
+ ${f}
1224
1224
  </select>
1225
1225
  </div>
1226
1226
 
@@ -1246,18 +1246,18 @@ Press ${q.cyan}h${q.reset} + ${q.cyan}Enter${q.reset} to show shortcuts`),Xw(U.u
1246
1246
  </script>
1247
1247
  </body>
1248
1248
  </html>
1249
- `,z0=`/${E.relative(g,Q).replace(/\.md$/,"")}`;A[z0||"/"]={filePath:Q,content:F,fileType:"md"}}catch(_){console.error(`${q.red}Error processing Markdown file ${q.bright}${b}${q.reset}:`,_);continue}else{let _=await Bun.build({entrypoints:[Q],outdir:z,plugins:[Aw],define:{"process.env.NODE_ENV":'"development"'},...w.stxOptions});if(!_.success){console.error(`${q.red}Build failed for ${q.bright}${b}${q.reset}:`,_.logs);continue}let W=_.outputs.find((O)=>O.path.endsWith(".html"));if(!W){console.error(`${q.red}No HTML output found for ${q.bright}${b}${q.reset}`);continue}let L=await Bun.file(W.path).text(),f=`/${E.relative(g,Q).replace(/\.stx$/,"")}`;A[f||"/"]={filePath:Q,content:L,fileType:"stx"}}}if(Object.keys(A).length===0)return console.error(`${q.red}No files were successfully processed${q.reset}`),!1;return!0}catch(b){return console.error(`${q.red}Error processing files:${q.reset}`,b),!1}};if(!await J())return!1;let Y=y;try{if(Y=await Jw(y),Y!==y)console.log(`${q.yellow}Port ${y} is busy, using port ${Y} instead${q.reset}`)}catch{return console.error(`${q.red}Could not find an available port${q.reset}`),!1}console.log(`${q.blue}Starting server on ${q.cyan}http://localhost:${Y}/${q.reset}...`);let U=o1({port:Y,fetch(b){let Q=new URL(b.url),K=A[Q.pathname];if(!K&&!Q.pathname.endsWith("/"))K=A[`${Q.pathname}/`];if(!K&&Q.pathname!=="/"&&A["/"])K=A["/"];if(K)return new Response(K.content,{headers:{"Content-Type":"text/html"}});let _=E.join(z,Q.pathname);if(s.existsSync(_)&&s.statSync(_).isFile()){let W=Bun.file(_),L=E.extname(_).toLowerCase(),N="text/plain";switch(L){case".html":N="text/html";break;case".css":N="text/css";break;case".js":N="text/javascript";break;case".json":N="application/json";break;case".png":N="image/png";break;case".jpg":case".jpeg":N="image/jpeg";break;case".gif":N="image/gif";break}return new Response(W,{headers:{"Content-Type":N}})}return new Response("Not Found",{status:404})},error(b){return new Response(`<pre>${b}
1249
+ `,g0=`/${C.relative(A,Q).replace(/\.md$/,"")}`;g[g0||"/"]={filePath:Q,content:F,fileType:"md"}}catch(_){console.error(`${q.red}Error processing Markdown file ${q.bright}${b}${q.reset}:`,_);continue}else{let _=await Bun.build({entrypoints:[Q],outdir:z,plugins:[Yw],define:{"process.env.NODE_ENV":'"development"'},...w.stxOptions});if(!_.success){console.error(`${q.red}Build failed for ${q.bright}${b}${q.reset}:`,_.logs);continue}let W=_.outputs.find((H)=>H.path.endsWith(".html"));if(!W){console.error(`${q.red}No HTML output found for ${q.bright}${b}${q.reset}`);continue}let L=await Bun.file(W.path).text(),O=`/${C.relative(A,Q).replace(/\.stx$/,"")}`;g[O||"/"]={filePath:Q,content:L,fileType:"stx"}}}if(Object.keys(g).length===0)return console.error(`${q.red}No files were successfully processed${q.reset}`),!1;return!0}catch(b){return console.error(`${q.red}Error processing files:${q.reset}`,b),!1}};if(!await J())return!1;let Y=y;try{if(Y=await Uw(y),Y!==y)console.log(`${q.yellow}Port ${y} is busy, using port ${Y} instead${q.reset}`)}catch{return console.error(`${q.red}Could not find an available port${q.reset}`),!1}console.log(`${q.blue}Starting server on ${q.cyan}http://localhost:${Y}/${q.reset}...`);let U=a1({port:Y,fetch(b){let Q=new URL(b.url),K=g[Q.pathname];if(!K&&!Q.pathname.endsWith("/"))K=g[`${Q.pathname}/`];if(!K&&Q.pathname!=="/"&&g["/"])K=g["/"];if(K)return new Response(K.content,{headers:{"Content-Type":"text/html"}});let _=C.join(z,Q.pathname);if(s.existsSync(_)&&s.statSync(_).isFile()){let W=Bun.file(_),L=C.extname(_).toLowerCase(),N="text/plain";switch(L){case".html":N="text/html";break;case".css":N="text/css";break;case".js":N="text/javascript";break;case".json":N="application/json";break;case".png":N="image/png";break;case".jpg":case".jpeg":N="image/jpeg";break;case".gif":N="image/gif";break}return new Response(W,{headers:{"Content-Type":N}})}return new Response("Not Found",{status:404})},error(b){return new Response(`<pre>${b}
1250
1250
  ${b.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
1251
1251
  ${q.blue}stx${q.reset} ${q.green}${i.env.stx_VERSION||"v0.0.10"}${q.reset} ${q.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${q.reset}`),console.log(`
1252
1252
  ${q.bright}\u2192 ${q.cyan}http://localhost:${y}/${q.reset}`),console.log(`
1253
- ${q.yellow}Routes:${q.reset}`);let B=Object.entries(A).sort(([b],[Q])=>b.localeCompare(Q)).map(([b,Q])=>({route:b==="/"?"/":b,filePath:E.relative(i.cwd(),Q.filePath),fileType:Q.fileType}));if(B.forEach((b,Q)=>{let _=Q===B.length-1?"\u2514\u2500 ":"\u251C\u2500 ",W=b.fileType==="md"?`${q.magenta}(markdown)${q.reset}`:"";if(b.route==="/")console.log(` ${q.green}${_}/${q.reset} \u2192 ${q.bright}${b.filePath}${q.reset} ${W}`);else{let L=b.route.split("/"),N=L[L.length-1]||L[L.length-2],f=b.route==="/"?"/":`/${N}`,O=L.slice(0,-1).join("/");if(O&&!O.startsWith("/"))O=`/${O}`;console.log(` ${q.green}${_}${f}${q.reset} \u2192 ${q.bright}${b.filePath}${q.reset} ${W}`)}}),console.log(`
1254
- Press ${q.cyan}h${q.reset} + ${q.cyan}Enter${q.reset} to show shortcuts`),Xw(U.url.toString(),()=>{if(j)s.watch(g,{recursive:!0}).close();U.stop()}),j){console.log(`${q.blue}Watching for changes...${q.reset}`);let b=s.watch(g,{recursive:!0},async(Q,K)=>{if(!K)return;if(K.endsWith(".stx")||K.endsWith(".js")||K.endsWith(".ts")||K.endsWith(".md"))console.log(`${q.yellow}File ${q.bright}${K}${q.yellow} changed, rebuilding...${q.reset}`),await J()});i.on("SIGINT",()=>{b.close(),U.stop(),i.exit(0)})}return!0}function l8($){if($.length===0)return"";if($.length===1)return $[0];let w=$.map((j)=>j.split(E.sep)),y=[];for(let j=0;j<w[0].length;j++){let z=w[0][j];if(w.every((g)=>g[j]===z))y.push(z);else break}return y.join(E.sep)}await E0([p0(),p()]);import Yw from"fs";import U1 from"path";async function s8($){try{let y=(await Bun.file($).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!y)return[];let j=y[1],z=[],g=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,A;while((A=g.exec(j))!==null){let J=A[1],X=A[2]||A[3]||A[4];if(!X)continue;let Y={name:X},U=J.match(/@type\s+\{([^}]+)\}/i);if(U)Y.type=U[1].trim();if(J.match(/@required/i))Y.required=!0;let b=J.match(/@default\s+(.+?)(?:\s+|$)/i);if(b)Y.default=b[1].trim();let Q=J.split(`
1255
- `).map((K)=>K.trim().replace(/^\*\s*/,"")).filter((K)=>!K.startsWith("@")&&K.length>0);Y.description=Q.join(" ").trim(),z.push(Y)}if(z.length===0){let J=j.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(J){let Y=J[1].split(",").map((U)=>U.trim()).filter(Boolean);for(let U of Y){let[B]=U.split(":").map((b)=>b.trim());if(B)z.push({name:B})}}}return z}catch(w){return console.error(`Error extracting props from ${$}:`,w),[]}}async function o8($){try{let w=await Bun.file($).text(),y=w.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||w.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(y)return y[1].split(`
1256
- `).map((j)=>j.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function a8($,w=!1,y){let j=U1.basename($,".stx"),z=await s8($),g=await o8($),A="";if(w&&y)A=`<${y}></${y}>`;else{let J=z.map((X)=>{if(X.type==="boolean")return`:${X.name}="true"`;return`${X.name}="value"`}).join(`
1257
- `);A=`<${j}
1253
+ ${q.yellow}Routes:${q.reset}`);let B=Object.entries(g).sort(([b],[Q])=>b.localeCompare(Q)).map(([b,Q])=>({route:b==="/"?"/":b,filePath:C.relative(i.cwd(),Q.filePath),fileType:Q.fileType}));if(B.forEach((b,Q)=>{let _=Q===B.length-1?"\u2514\u2500 ":"\u251C\u2500 ",W=b.fileType==="md"?`${q.magenta}(markdown)${q.reset}`:"";if(b.route==="/")console.log(` ${q.green}${_}/${q.reset} \u2192 ${q.bright}${b.filePath}${q.reset} ${W}`);else{let L=b.route.split("/"),N=L[L.length-1]||L[L.length-2],O=b.route==="/"?"/":`/${N}`,H=L.slice(0,-1).join("/");if(H&&!H.startsWith("/"))H=`/${H}`;console.log(` ${q.green}${_}${O}${q.reset} \u2192 ${q.bright}${b.filePath}${q.reset} ${W}`)}}),console.log(`
1254
+ Press ${q.cyan}h${q.reset} + ${q.cyan}Enter${q.reset} to show shortcuts`),Bw(U.url.toString(),()=>{if(j)s.watch(A,{recursive:!0}).close();U.stop()}),j){console.log(`${q.blue}Watching for changes...${q.reset}`);let b=s.watch(A,{recursive:!0},async(Q,K)=>{if(!K)return;if(K.endsWith(".stx")||K.endsWith(".js")||K.endsWith(".ts")||K.endsWith(".md"))console.log(`${q.yellow}File ${q.bright}${K}${q.yellow} changed, rebuilding...${q.reset}`),await J()});i.on("SIGINT",()=>{b.close(),U.stop(),i.exit(0)})}return!0}function w6($){if($.length===0)return"";if($.length===1)return $[0];let w=$.map((j)=>j.split(C.sep)),y=[];for(let j=0;j<w[0].length;j++){let z=w[0][j];if(w.every((A)=>A[j]===z))y.push(z);else break}return y.join(C.sep)}await M0([p0(),n()]);import bw from"fs";import U1 from"path";async function y6($){try{let y=(await Bun.file($).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!y)return[];let j=y[1],z=[],A=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,g;while((g=A.exec(j))!==null){let J=g[1],X=g[2]||g[3]||g[4];if(!X)continue;let Y={name:X},U=J.match(/@type\s+\{([^}]+)\}/i);if(U)Y.type=U[1].trim();if(J.match(/@required/i))Y.required=!0;let b=J.match(/@default\s+(.+?)(?:\s+|$)/i);if(b)Y.default=b[1].trim();let Q=J.split(`
1255
+ `).map((K)=>K.trim().replace(/^\*\s*/,"")).filter((K)=>!K.startsWith("@")&&K.length>0);Y.description=Q.join(" ").trim(),z.push(Y)}if(z.length===0){let J=j.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(J){let Y=J[1].split(",").map((U)=>U.trim()).filter(Boolean);for(let U of Y){let[B]=U.split(":").map((b)=>b.trim());if(B)z.push({name:B})}}}return z}catch(w){return console.error(`Error extracting props from ${$}:`,w),[]}}async function j6($){try{let w=await Bun.file($).text(),y=w.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||w.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(y)return y[1].split(`
1256
+ `).map((j)=>j.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function z6($,w=!1,y){let j=U1.basename($,".stx"),z=await y6($),A=await j6($),g="";if(w&&y)g=`<${y}></${y}>`;else{let J=z.map((X)=>{if(X.type==="boolean")return`:${X.name}="true"`;return`${X.name}="value"`}).join(`
1257
+ `);g=`<${j}
1258
1258
  ${J}
1259
- />`}return{name:j,path:$,description:g,props:z,example:A,isWebComponent:w,tag:y}}async function By($){try{if(!await T($))return console.warn(`Components directory does not exist: ${$}`),[];let w=await Yw.promises.readdir($,{withFileTypes:!0}),y=[];for(let j of w){let z=U1.join($,j.name);if(j.isDirectory()){let g=await By(z);y.push(...g)}else if(j.isFile()&&j.name.endsWith(".stx"))y.push(z)}return y}catch(w){return console.error(`Error finding component files in ${$}:`,w),[]}}async function e8($,w){try{if(!await T($))return[];let y=await By($),j=[],z=new Map;if(w?.components?.length)for(let g of w.components)z.set(g.file,g);for(let g of y){let A=z.get(g),J=!!A,X=A?.tag,Y=await a8(g,J,X);j.push(Y)}return j}catch(y){return console.error("Error generating component docs:",y),[]}}async function t8($){try{if(!await T($))return[];let w=await Yw.promises.readdir($,{withFileTypes:!0}),y=[];for(let j of w){if(!j.isFile()||!j.name.endsWith(".stx"))continue;let z=U1.join($,j.name),g=await Bun.file(z).text(),A=U1.basename(z,".stx"),J=g.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||g.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),X=J?J[1].split(`
1260
- `).map((_)=>_.trim().replace(/^\*\s*/,"")).join(" ").trim():"",Y=/@component\(\s*['"]([^'"]+)['"]/g,U=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,B=new Set,b;while((b=Y.exec(g))!==null)B.add(b[1]);while((b=U.exec(g))!==null)if(b[1]&&b[1]!=="slot")B.add(b[1]);let Q=/@([a-z]+)(?:\s*\(|\s+|$)/g,K=new Set;while((b=Q.exec(g))!==null)K.add(b[1]);y.push({name:A,path:z,description:X,components:[...B],directives:[...K]})}return y}catch(w){return console.error("Error generating template docs:",w),[]}}async function $6($=[]){try{let w=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
1259
+ />`}return{name:j,path:$,description:A,props:z,example:g,isWebComponent:w,tag:y}}async function K9($){try{if(!await T($))return console.warn(`Components directory does not exist: ${$}`),[];let w=await bw.promises.readdir($,{withFileTypes:!0}),y=[];for(let j of w){let z=U1.join($,j.name);if(j.isDirectory()){let A=await K9(z);y.push(...A)}else if(j.isFile()&&j.name.endsWith(".stx"))y.push(z)}return y}catch(w){return console.error(`Error finding component files in ${$}:`,w),[]}}async function A6($,w){try{if(!await T($))return[];let y=await K9($),j=[],z=new Map;if(w?.components?.length)for(let A of w.components)z.set(A.file,A);for(let A of y){let g=z.get(A),J=!!g,X=g?.tag,Y=await z6(A,J,X);j.push(Y)}return j}catch(y){return console.error("Error generating component docs:",y),[]}}async function g6($){try{if(!await T($))return[];let w=await bw.promises.readdir($,{withFileTypes:!0}),y=[];for(let j of w){if(!j.isFile()||!j.name.endsWith(".stx"))continue;let z=U1.join($,j.name),A=await Bun.file(z).text(),g=U1.basename(z,".stx"),J=A.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||A.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),X=J?J[1].split(`
1260
+ `).map((_)=>_.trim().replace(/^\*\s*/,"")).join(" ").trim():"",Y=/@component\(\s*['"]([^'"]+)['"]/g,U=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,B=new Set,b;while((b=Y.exec(A))!==null)B.add(b[1]);while((b=U.exec(A))!==null)if(b[1]&&b[1]!=="slot")B.add(b[1]);let Q=/@([a-z]+)(?:\s*\(|\s+|$)/g,K=new Set;while((b=Q.exec(A))!==null)K.add(b[1]);y.push({name:g,path:z,description:X,components:[...B],directives:[...K]})}return y}catch(w){return console.error("Error generating template docs:",w),[]}}async function J6($=[]){try{let w=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
1261
1261
  <p>Welcome, {{ user.name }}!</p>
1262
1262
  @endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
1263
1263
  <p>Welcome back!</p>
@@ -1277,49 +1277,49 @@ Press ${q.cyan}h${q.reset} + ${q.cyan}Enter${q.reset} to show shortcuts`),Xw(U.u
1277
1277
  <p>Page {{ page }}</p>
1278
1278
  @endwhile`},{name:"component",description:"Include a component in the template",hasEndTag:!1,example:'@component("alert", { type: "warning", title: "Warning", message: "This is a warning" })'},{name:"include",description:"Include a partial template",hasEndTag:!1,example:'@include("partials/header")'},{name:"raw",description:"Display content without processing expressions",hasEndTag:!0,example:`@raw
1279
1279
  {{ This will be displayed as-is }}
1280
- @endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let y of $)w.push({name:y.name,description:y.description||"",hasEndTag:y.hasEndTag||!1,example:""});return w}catch(w){return console.error("Error generating directive docs:",w),[]}}function w6($=[],w=[],y=[],j){let z=`# stx Documentation
1280
+ @endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let y of $)w.push({name:y.name,description:y.description||"",hasEndTag:y.hasEndTag||!1,example:""});return w}catch(w){return console.error("Error generating directive docs:",w),[]}}function X6($=[],w=[],y=[],j){let z=`# stx Documentation
1281
1281
 
1282
1282
  `;if(j)z+=`${j}
1283
1283
 
1284
1284
  `;if($.length>0){z+=`## Components
1285
1285
 
1286
- `;for(let g of $){if(z+=`### ${g.name}
1286
+ `;for(let A of $){if(z+=`### ${A.name}
1287
1287
 
1288
- `,g.description)z+=`${g.description}
1288
+ `,A.description)z+=`${A.description}
1289
1289
 
1290
- `;if(g.isWebComponent)z+=`**Web Component Tag:** \`${g.tag}\`
1290
+ `;if(A.isWebComponent)z+=`**Web Component Tag:** \`${A.tag}\`
1291
1291
 
1292
- `;if(g.props.length>0){z+=`#### Properties
1292
+ `;if(A.props.length>0){z+=`#### Properties
1293
1293
 
1294
1294
  `,z+=`| Name | Type | Required | Default | Description |
1295
1295
  `,z+=`| ---- | ---- | -------- | ------- | ----------- |
1296
- `;for(let A of g.props)z+=`| ${A.name} | ${A.type||"any"} | ${A.required?"Yes":"No"} | ${A.default||"-"} | ${A.description||"-"} |
1296
+ `;for(let g of A.props)z+=`| ${g.name} | ${g.type||"any"} | ${g.required?"Yes":"No"} | ${g.default||"-"} | ${g.description||"-"} |
1297
1297
  `;z+=`
1298
- `}if(g.example)z+=`#### Example
1298
+ `}if(A.example)z+=`#### Example
1299
1299
 
1300
- `,z+="```html\n",z+=g.example,z+="\n```\n\n"}}if(w.length>0){z+=`## Templates
1300
+ `,z+="```html\n",z+=A.example,z+="\n```\n\n"}}if(w.length>0){z+=`## Templates
1301
1301
 
1302
- `;for(let g of w){if(z+=`### ${g.name}
1302
+ `;for(let A of w){if(z+=`### ${A.name}
1303
1303
 
1304
- `,g.description)z+=`${g.description}
1304
+ `,A.description)z+=`${A.description}
1305
1305
 
1306
- `;if(g.components&&g.components.length>0)z+=`**Components Used:** ${g.components.join(", ")}
1306
+ `;if(A.components&&A.components.length>0)z+=`**Components Used:** ${A.components.join(", ")}
1307
1307
 
1308
- `;if(g.directives&&g.directives.length>0)z+=`**Directives Used:** ${g.directives.join(", ")}
1308
+ `;if(A.directives&&A.directives.length>0)z+=`**Directives Used:** ${A.directives.join(", ")}
1309
1309
 
1310
1310
  `}}if(y.length>0){z+=`## Directives
1311
1311
 
1312
1312
  `,z+=`| Directive | Description | Has End Tag |
1313
1313
  `,z+=`| --------- | ----------- | ----------- |
1314
- `;for(let g of y)z+=`| @${g.name} | ${g.description||"-"} | ${g.hasEndTag?"Yes":"No"} |
1314
+ `;for(let A of y)z+=`| @${A.name} | ${A.description||"-"} | ${A.hasEndTag?"Yes":"No"} |
1315
1315
  `;z+=`
1316
- `;for(let g of y)if(g.example)z+=`### @${g.name}
1316
+ `;for(let A of y)if(A.example)z+=`### @${A.name}
1317
1317
 
1318
- `,z+=`${g.description||""}
1318
+ `,z+=`${A.description||""}
1319
1319
 
1320
1320
  `,z+=`#### Example
1321
1321
 
1322
- `,z+="```html\n",z+=g.example,z+="\n```\n\n"}return z}function y6($=[],w=[],y=[],j){let z=`<!DOCTYPE html>
1322
+ `,z+="```html\n",z+=A.example,z+="\n```\n\n"}return z}function Y6($=[],w=[],y=[],j){let z=`<!DOCTYPE html>
1323
1323
  <html lang="en">
1324
1324
  <head>
1325
1325
  <meta charset="UTF-8">
@@ -1362,7 +1362,7 @@ Press ${q.cyan}h${q.reset} + ${q.cyan}Enter${q.reset} to show shortcuts`),Xw(U.u
1362
1362
  </head>
1363
1363
  <body>
1364
1364
  <h1>stx Documentation</h1>
1365
- `;if(j)z+=`<div>${j}</div>`;if($.length>0){z+="<h2>Components</h2>";for(let g of $){if(z+=`<h3>${g.name}</h3>`,g.description)z+=`<p>${g.description}</p>`;if(g.isWebComponent)z+=`<p><strong>Web Component Tag:</strong> <code>${g.tag}</code></p>`;if(g.props.length>0){z+="<h4>Properties</h4>",z+=`<table>
1365
+ `;if(j)z+=`<div>${j}</div>`;if($.length>0){z+="<h2>Components</h2>";for(let A of $){if(z+=`<h3>${A.name}</h3>`,A.description)z+=`<p>${A.description}</p>`;if(A.isWebComponent)z+=`<p><strong>Web Component Tag:</strong> <code>${A.tag}</code></p>`;if(A.props.length>0){z+="<h4>Properties</h4>",z+=`<table>
1366
1366
  <thead>
1367
1367
  <tr>
1368
1368
  <th>Name</th>
@@ -1372,13 +1372,13 @@ Press ${q.cyan}h${q.reset} + ${q.cyan}Enter${q.reset} to show shortcuts`),Xw(U.u
1372
1372
  <th>Description</th>
1373
1373
  </tr>
1374
1374
  </thead>
1375
- <tbody>`;for(let A of g.props)z+=`<tr>
1376
- <td>${A.name}</td>
1377
- <td>${A.type||"any"}</td>
1378
- <td>${A.required?"Yes":"No"}</td>
1379
- <td>${A.default||"-"}</td>
1380
- <td>${A.description||"-"}</td>
1381
- </tr>`;z+="</tbody></table>"}if(g.example)z+="<h4>Example</h4>",z+=`<pre><code>${g.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}}if(w.length>0){z+="<h2>Templates</h2>";for(let g of w){if(z+=`<h3>${g.name}</h3>`,g.description)z+=`<p>${g.description}</p>`;if(g.components&&g.components.length>0)z+=`<p><strong>Components Used:</strong> ${g.components.join(", ")}</p>`;if(g.directives&&g.directives.length>0)z+=`<p><strong>Directives Used:</strong> ${g.directives.join(", ")}</p>`}}if(y.length>0){z+="<h2>Directives</h2>",z+=`<table>
1375
+ <tbody>`;for(let g of A.props)z+=`<tr>
1376
+ <td>${g.name}</td>
1377
+ <td>${g.type||"any"}</td>
1378
+ <td>${g.required?"Yes":"No"}</td>
1379
+ <td>${g.default||"-"}</td>
1380
+ <td>${g.description||"-"}</td>
1381
+ </tr>`;z+="</tbody></table>"}if(A.example)z+="<h4>Example</h4>",z+=`<pre><code>${A.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}}if(w.length>0){z+="<h2>Templates</h2>";for(let A of w){if(z+=`<h3>${A.name}</h3>`,A.description)z+=`<p>${A.description}</p>`;if(A.components&&A.components.length>0)z+=`<p><strong>Components Used:</strong> ${A.components.join(", ")}</p>`;if(A.directives&&A.directives.length>0)z+=`<p><strong>Directives Used:</strong> ${A.directives.join(", ")}</p>`}}if(y.length>0){z+="<h2>Directives</h2>",z+=`<table>
1382
1382
  <thead>
1383
1383
  <tr>
1384
1384
  <th>Directive</th>
@@ -1386,43 +1386,44 @@ Press ${q.cyan}h${q.reset} + ${q.cyan}Enter${q.reset} to show shortcuts`),Xw(U.u
1386
1386
  <th>Has End Tag</th>
1387
1387
  </tr>
1388
1388
  </thead>
1389
- <tbody>`;for(let g of y)z+=`<tr>
1390
- <td>@${g.name}</td>
1391
- <td>${g.description||"-"}</td>
1392
- <td>${g.hasEndTag?"Yes":"No"}</td>
1393
- </tr>`;z+="</tbody></table>";for(let g of y)if(g.example)z+=`<h3>@${g.name}</h3>`,z+=`<p>${g.description||""}</p>`,z+="<h4>Example</h4>",z+=`<pre><code>${g.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return z+="</body></html>",z}function j6($=[],w=[],y=[],j){return JSON.stringify({components:$,templates:w,directives:y,extraContent:j||""},null,2)}async function g6($){try{let{componentsDir:w,templatesDir:y,webComponentsConfig:j,customDirectives:z,config:g}=$;if(!g.enabled)return!1;let A=g.outputDir||"docs";if(await Yw.promises.mkdir(A,{recursive:!0}),console.log("Generating documentation..."),w)console.log(`Components directory: ${w}`);if(y)console.log(`Templates directory: ${y}`);console.log(`Output directory: ${A}`);let J=[];if(g.components!==!1&&w)console.log("Generating component documentation..."),J=await e8(w,j),console.log(`Found ${J.length} components`);let X=[];if(g.templates!==!1&&y)console.log("Generating template documentation..."),X=await t8(y),console.log(`Found ${X.length} templates`);let Y=[];if(g.directives!==!1)console.log("Generating directive documentation..."),Y=await $6(z),console.log(`Found ${Y.length} directives`);let U=g.format||"markdown",B=g.extraContent,b="",Q="";switch(U){case"markdown":b=w6(J,X,Y,B),Q="md";break;case"html":b=y6(J,X,Y,B),Q="html";break;case"json":b=j6(J,X,Y,B),Q="json";break;default:throw Error(`Unsupported documentation format: ${U}`)}let K=U1.join(A,`stx-docs.${Q}`);return await Bun.write(K,b),console.log(`Documentation generated: ${K}`),!0}catch(w){return console.error("Error generating documentation:",w),!1}}async function vz($){let w={enabled:!0,outputDir:$.output||"docs",format:$.format||"markdown",components:$.components!==!1,templates:$.templates!==!1,directives:$.directives!==!1,extraContent:$.extraContent},y=$.componentsDir||A0.componentsDir,j=$.templatesDir||".";return g6({componentsDir:y,templatesDir:j,webComponentsConfig:A0.webComponents,customDirectives:A0.customDirectives,config:w})}x1();u0();var z6={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function hz($,w={}){let y={...z6,...w};if($.trim()==="")return`
1394
- `;let j=$;if(y.trimTrailingWhitespace)j=j.replace(/[ \t]+$/gm,"");if(j=A6(j,y),j=J6(j,y),j=B6(j,y),j=X6(j,y),y.trimTrailingWhitespace)j=j.replace(/[ \t]+$/gm,""),j=j.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(j=j.replace(/\r\n/g,`
1389
+ <tbody>`;for(let A of y)z+=`<tr>
1390
+ <td>@${A.name}</td>
1391
+ <td>${A.description||"-"}</td>
1392
+ <td>${A.hasEndTag?"Yes":"No"}</td>
1393
+ </tr>`;z+="</tbody></table>";for(let A of y)if(A.example)z+=`<h3>@${A.name}</h3>`,z+=`<p>${A.description||""}</p>`,z+="<h4>Example</h4>",z+=`<pre><code>${A.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return z+="</body></html>",z}function U6($=[],w=[],y=[],j){return JSON.stringify({components:$,templates:w,directives:y,extraContent:j||""},null,2)}async function B6($){try{let{componentsDir:w,templatesDir:y,webComponentsConfig:j,customDirectives:z,config:A}=$;if(!A.enabled)return!1;let g=A.outputDir||"docs";if(await bw.promises.mkdir(g,{recursive:!0}),console.log("Generating documentation..."),w)console.log(`Components directory: ${w}`);if(y)console.log(`Templates directory: ${y}`);console.log(`Output directory: ${g}`);let J=[];if(A.components!==!1&&w)console.log("Generating component documentation..."),J=await A6(w,j),console.log(`Found ${J.length} components`);let X=[];if(A.templates!==!1&&y)console.log("Generating template documentation..."),X=await g6(y),console.log(`Found ${X.length} templates`);let Y=[];if(A.directives!==!1)console.log("Generating directive documentation..."),Y=await J6(z),console.log(`Found ${Y.length} directives`);let U=A.format||"markdown",B=A.extraContent,b="",Q="";switch(U){case"markdown":b=X6(J,X,Y,B),Q="md";break;case"html":b=Y6(J,X,Y,B),Q="html";break;case"json":b=U6(J,X,Y,B),Q="json";break;default:throw Error(`Unsupported documentation format: ${U}`)}let K=U1.join(g,`stx-docs.${Q}`);return await Bun.write(K,b),console.log(`Documentation generated: ${K}`),!0}catch(w){return console.error("Error generating documentation:",w),!1}}async function VA($){let w={enabled:!0,outputDir:$.output||"docs",format:$.format||"markdown",components:$.components!==!1,templates:$.templates!==!1,directives:$.directives!==!1,extraContent:$.extraContent},y=$.componentsDir||A0.componentsDir,j=$.templatesDir||".";return B6({componentsDir:y,templatesDir:j,webComponentsConfig:A0.webComponents,customDirectives:A0.customDirectives,config:w})}x1();u0();var _9={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function b6($,w={}){let y={..._9,...w};if($.trim()==="")return`
1394
+ `;let j=$;if(y.trimTrailingWhitespace)j=j.replace(/[ \t]+$/gm,"");if(j=K6(j,y),j=W6(j,y),j=q6(j,y),y.trimTrailingWhitespace)j=j.replace(/[ \t]+$/gm,""),j=j.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(j=j.replace(/\r\n/g,`
1395
1395
  `).replace(/\r/g,`
1396
1396
  `),!j.endsWith(`
1397
1397
  `))j+=`
1398
- `;return j}function A6($,w){return $.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(y,j)=>{let z=j.trim();if(z&&!z.includes(`
1399
- `)&&z.length<80)return y.replace(j,z);let g=j.split(`
1400
- `),A=g.map((X,Y)=>{if(Y===0&&X.trim()==="")return"";if(Y===g.length-1&&X.trim()==="")return"";let U=X.trim();if(U==="")return"";return`${w.useTabs?"\t":" ".repeat(w.indentSize)}${U}`}).filter((X,Y,U)=>{if(Y===0||Y===U.length-1)return X!=="";return!0}),J=A.length>0?`
1401
- ${A.join(`
1402
- `)}
1403
- `:"";return y.replace(j,J)})}function J6($,w){let y=$,j=[],z=["pre","code","textarea","style"];for(let B of z){let b=new RegExp(`<${B}\\b[^>]*>[\\s\\S]*?<\\/${B}>`,"gi");y=y.replace(b,(Q)=>{let K=`__WHITESPACE_TAG_${j.length}__`;return j.push(Q),K})}let g=[];y=y.replace(/<(\w+)([^>]*)><\/\1>/g,(B)=>{let b=`__EMPTY_TAG_${g.length}__`;return g.push(B),b}),y=y.replace(/<(\w+)([^>]*?)(@\w+\([^)]*\))([^>]*?)(@end\w+)([^>]*)>/g,(B,b,Q,K,_,W,L)=>{return`<${b}${Q}
1398
+ `;return j}function GA($,w={}){let y={..._9,...w};if($.trim()==="")return`
1399
+ `;let j=$;if(j=j.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(z,A,g,J,X)=>{let Y=J.split(`
1400
+ `),U=Y.filter((_)=>_.trim().length>0);if(U.length===0)return z;let B=Math.min(...U.map((_)=>{let W=_.match(/^( *)/);return W?W[1].length:0})),b=Y.map((_)=>{if(_.trim().length===0)return"";return _.substring(B)}).join(`
1401
+ `),K=b6(b,y).trimEnd().split(`
1402
+ `).map((_)=>{if(_.trim().length===0)return"";return A+_}).join(`
1403
+ `);return`${A}\`\`\`${g}
1404
1404
  ${K}
1405
- ${_.trim()}
1406
- ${W}${L}>`}),y=y.replace(/>(\s*)</g,(B,b,Q,K)=>{if(b.includes(`
1407
- `))return B;let _=K.substring(Math.max(0,Q-50),Q+1),W=K.substring(Q+B.length-1,Math.min(K.length,Q+B.length+50)),L=_.match(/<\/(\w+)>$/),N=W.match(/^<(\w+)/),f=["span","a","strong","em","b","i","u","small","mark","del","ins","sub","sup","code","kbd","samp","var","abbr","cite","q","dfn","time"];if(L&&N){let O=L[1].toLowerCase(),R=N[1].toLowerCase();if(f.includes(O)&&f.includes(R)){let n=K.substring(0,Q).lastIndexOf(`
1408
- `)+1,c=K.substring(Q+B.length).indexOf(`
1409
- `),l=c===-1?K.length:Q+B.length+c;if(K.substring(n,l).replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim().length>0)return B}}return`>
1410
- <`}),y=y.replace(/>(\s*)@/g,(B,b)=>{if(b.includes(`
1411
- `))return B;return`>
1412
- @`}),y=y.replace(/(@end\w+)(\s*)</g,(B,b,Q)=>{if(Q.includes(`
1413
- `))return B;return`${b}
1414
- <`}),y=y.replace(/\)(\s*)@/g,(B,b)=>{if(b.includes(`
1415
- `))return B;return`)
1416
- @`}),y=y.replace(/\)(\s*)</g,(B,b)=>{if(b.includes(`
1417
- `))return B;return`)
1418
- <`}),y=y.replace(/(@end\w+)(\s*)@/g,(B,b,Q)=>{if(Q.includes(`
1419
- `))return B;return`${b}
1420
- @`}),y=y.replace(/(@\w+)(?!\s*\()(\s*)</g,(B,b,Q)=>{if(Q.includes(`
1421
- `))return B;return`${b}
1422
- <`});let A=y.split(`
1423
- `),J=[],X=0,Y=w.useTabs?"\t":" ".repeat(w.indentSize);for(let B=0;B<A.length;B++){let b=A[B].trim();if(b===""){J.push("");continue}if(b.startsWith("</")||b.startsWith("@end"))X=Math.max(0,X-1);let Q=X>0?Y.repeat(X)+b:b;if(J.push(Q),b.startsWith("<")&&!b.includes("/>")&&!b.startsWith("</")){let K=b.match(/<(\w+)[^>]*>.*<\/\1>/);if(!b.includes("<!")&&!Y6(b)&&!K)X++}if(b.startsWith("@")&&U6(b))X++}let U=J.join(`
1424
- `);return j.forEach((B,b)=>{U=U.replace(`__WHITESPACE_TAG_${b}__`,B)}),g.forEach((B,b)=>{U=U.replace(`__EMPTY_TAG_${b}__`,B)}),U}function X6($,w){if($=$.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(y,j,z)=>{let g=z.trim().replace(/\s+/g," ");return`@${j}(${g})`}),$=$.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(y,j,z)=>{if(z.trim()==="")return`@${j}`;return`@${j}(${z.trim()})`}),w.normalizeWhitespace)$=$.replace(/\{\{\s*([^}]+)\s*\}\}/g,(y,j)=>{return`{{ ${j.trim()} }}`}),$=$.replace(/\{!!\s*([^!]+)\s*!!\}/g,(y,j)=>{return`{!! ${j.trim()} !!}`});return $}function Y6($){let w=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if($.includes("/>"))return!0;let y=$.match(/<(\w+)/);if(y){let j=y[1].toLowerCase();return w.includes(j)}return!1}function U6($){let w=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let y of w)if($.startsWith(`@${y}`))return!$.includes(`@end${y}`);return!1}function B6($,w){if(!w.sortAttributes)return $;return $.replace(/<(\w+)([^>]*)>/g,(y,j,z)=>{if(!z.trim())return y;if(z.includes("<")||z.includes(`
1425
- `)||z.includes("@"))return y;let g=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,A=[],J;while((J=g.exec(z))!==null)A.push({name:J[1],value:J[2]});A.sort((Y,U)=>{if(Y.name==="id")return-1;if(U.name==="id")return 1;if(Y.name==="class")return-1;if(U.name==="class")return 1;return Y.name.localeCompare(U.name)});let X=A.map((Y)=>Y.value?`${Y.name}=${Y.value}`:Y.name).join(" ");return`<${j}${X?` ${X}`:""}>`})}u$();l$();import l0 from"fs";import Uw from"path";import by from"process";async function iz($="index.stx",w={}){try{let y=w.force||!1,j=Uw.resolve(by.cwd(),$);if(l0.existsSync(j)){if(!y)throw Error(`File ${$} already exists. Use --force to overwrite.`);console.warn(`File ${$} already exists. Overwriting...`)}let z=Uw.dirname(j);if(!l0.existsSync(z))l0.mkdirSync(z,{recursive:!0});let g;if(w.template){let A=Uw.resolve(by.cwd(),w.template);if(!l0.existsSync(A))throw Error(`Template file ${w.template} does not exist.`);if(!A.endsWith(".stx"))console.warn(`Warning: Template file ${w.template} does not have a .stx extension. Using it anyway.`);g=l0.readFileSync(A,"utf-8"),console.warn(`Using template from ${w.template}`)}else g=b6();return l0.writeFileSync(j,g),console.warn(`Created new stx file: ${$}`),!0}catch(y){return console.error(`Error creating file: ${y instanceof Error?y.message:String(y)}`),!1}}function b6(){return`<!DOCTYPE html>
1405
+ ${A}\`\`\``}),y.trimTrailingWhitespace)j=j.replace(/[ \t]+$/gm,"");if(j=j.replace(/\r\n/g,`
1406
+ `).replace(/\r/g,`
1407
+ `),!j.endsWith(`
1408
+ `))j+=`
1409
+ `;return j}function Q6($){let w=$,y=[],j="__PROTECTED_BLOCK_";return w=w.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(z)=>{let A=y.length;return y.push(z),`${j}${A}__`}),w=w.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1410
+ $1
1411
+ `),w=w.replace(/(@end\w+)/g,`
1412
+ $1
1413
+ `),w=w.replace(/(@(?:else|elseif|empty)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1414
+ $1
1415
+ `),w=w.replace(/(@(?:csrf|method|include|extends|yield|stack|vite|asset)(?:\([^)]*\))?)/g,`
1416
+ $1
1417
+ `),w=w.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(z,A,g,J)=>{let X=J.substring(g+z.length,Math.min(J.length,g+z.length+20)),Y=z.match(/<(\w+)/)?.[1];if(Y&&X.match(new RegExp(`^</${Y}>`)))return z;return`
1418
+ ${z}`}),w=w.replace(/(>)(<\/)/g,(z,A,g,J,X)=>{let Y=X.substring(Math.max(0,J-50),J),B=X.substring(J+z.length,Math.min(X.length,J+z.length+20)).match(/^(\w+)>/)?.[1],b=Y.match(/<(\w+)[^>]*$/)?.[1];if(b&&B&&b===B)return z;return`${A}
1419
+ ${g}`}),w=w.replace(/(<\/[^>]+>)(?=<|$)/g,(z,A,g,J)=>{let X=J.substring(Math.max(0,g-20),g),Y=z.match(/<\/(\w+)>/)?.[1],U=new RegExp(`<${Y}[^>]*>$`);if(Y&&X.match(U))return z;return`${z}
1420
+ `}),w=w.replace(new RegExp(`${j}(\\d+)__`,"g"),(z,A)=>{return y[Number.parseInt(A,10)]}),w=w.replace(/\n{2,}/g,`
1421
+ `),w=w.split(`
1422
+ `).map((z)=>z.trim()).join(`
1423
+ `),w=w.replace(/^\n+/,"").replace(/\n+$/,""),w}function K6($,w){let j=Q6($).split(`
1424
+ `),z=[],A=0,g=!1,J=w.useTabs?"\t":" ".repeat(w.indentSize);for(let X=0;X<j.length;X++){let Y=j[X],U=Y.trim();if(U===""){z.push("");continue}let B=U.match(/<script\b/i),b=U.match(/<\/script>/i);if(g&&!b){z.push(Y);continue}let Q=U===">";if(q9(U)&&!U.startsWith("<")&&!U.startsWith("@")){z.push(J.repeat(A)+U);continue}let K=U.startsWith("@end"),_=U.startsWith("@else")||U.startsWith("@elseif"),W=U.startsWith("@")&&N6(U),L=U.startsWith("<!DOCTYPE")||U.startsWith("<!doctype"),N=U.startsWith("<!--"),O=U.startsWith("</"),H=U.startsWith("<")&&!O&&!N&&!L,R=U.includes("/>")||_6(U),f=q9(U);if(O||K)A=Math.max(0,A-1);let F=_?Math.max(0,A-1):A;if(Q)z.push(Y);else z.push(J.repeat(F)+U);if(H&&!R&&!f&&!Q||W)A++;if(B)g=!0;if(b)g=!1}return z.join(`
1425
+ `)}function q6($,w){if($=$.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(y,j,z)=>{let A=z.trim().replace(/\s+/g," ");return`@${j}(${A})`}),$=$.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(y,j,z)=>{if(z.trim()==="")return`@${j}`;return`@${j}(${z.trim()})`}),w.normalizeWhitespace)$=$.replace(/\{\{\s*([^}]+)\s*\}\}/g,(y,j)=>{return`{{ ${j.trim()} }}`}),$=$.replace(/\{!!\s*([^!]+)\s*!!\}/g,(y,j)=>{return`{!! ${j.trim()} !!}`});return $}function _6($){let w=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if($.includes("/>"))return!0;let y=$.match(/<(\w+)/);if(y){let j=y[1];return w.includes(j.toLowerCase())}return!1}function q9($){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test($)}function N6($){let w=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let y of w)if($.startsWith(`@${y}`))return!$.includes(`@end${y}`);return!1}function W6($,w){if(!w.sortAttributes)return $;return $.replace(/<(\w+)([^>]*)>/g,(y,j,z)=>{if(!z.trim())return y;if(z.includes("<")||z.includes(`
1426
+ `)||z.includes("@"))return y;let A=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,g=[],J;while((J=A.exec(z))!==null)g.push({name:J[1],value:J[2]});g.sort((Y,U)=>{if(Y.name==="id")return-1;if(U.name==="id")return 1;if(Y.name==="class")return-1;if(U.name==="class")return 1;return Y.name.localeCompare(U.name)});let X=g.map((Y)=>Y.value?`${Y.name}=${Y.value}`:Y.name).join(" ");return`<${j}${X?` ${X}`:""}>`})}m$();s$();import l0 from"fs";import Qw from"path";import N9 from"process";async function EA($="index.stx",w={}){try{let y=w.force||!1,j=Qw.resolve(N9.cwd(),$);if(l0.existsSync(j)){if(!y)throw Error(`File ${$} already exists. Use --force to overwrite.`);console.warn(`File ${$} already exists. Overwriting...`)}let z=Qw.dirname(j);if(!l0.existsSync(z))l0.mkdirSync(z,{recursive:!0});let A;if(w.template){let g=Qw.resolve(N9.cwd(),w.template);if(!l0.existsSync(g))throw Error(`Template file ${w.template} does not exist.`);if(!g.endsWith(".stx"))console.warn(`Warning: Template file ${w.template} does not have a .stx extension. Using it anyway.`);A=l0.readFileSync(g,"utf-8"),console.warn(`Using template from ${w.template}`)}else A=L6();return l0.writeFileSync(j,A),console.warn(`Created new stx file: ${$}`),!0}catch(y){return console.error(`Error creating file: ${y instanceof Error?y.message:String(y)}`),!1}}function L6(){return`<!DOCTYPE html>
1426
1427
  <html lang="en">
1427
1428
  <head>
1428
1429
  <meta charset="UTF-8">
@@ -1486,14 +1487,14 @@ ${W}${L}>`}),y=y.replace(/>(\s*)</g,(B,b,Q,K)=>{if(b.includes(`
1486
1487
  </ul>
1487
1488
  </div>
1488
1489
  </body>
1489
- </html>`}m1();i1();o$();X1();var pz="f9c3713";n1();await E0([Y1(),X1(),p()]);var{serve:Q6}=globalThis.Bun;import s0 from"fs";import V0 from"path";async function K6($={}){let{port:w=3000,root:y=".",stxOptions:j={},watch:z=!0,onRequest:g,routes:A={},middleware:J=[],on404:X,onError:Y}=$,U=V0.resolve(y),B=new Map;async function b(N){let f=s0.statSync(N),O=`${N}:${f.mtimeMs}`,R=B.get(O);if(R)return R.content;let H=await Bun.file(N).text(),F=H.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),n=F?F[1]:"",z0=H.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],c=H.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,""),l={__filename:N,__dirname:V0.dirname(N)};await Q0(n,l,N);let b0=await J0(c,l,N,j,new Set),f0=[...z0];if(f0.length>0)if(b0.match(/(<\/body>)/i)){let a0=f0.join(`
1490
- `);b0=b0.replace(/(<\/body>)/i,`${a0}
1490
+ </html>`}m1();i1();a$();X1();var CA="f9c3713";n1();await M0([Y1(),X1(),n()]);var{serve:O6}=globalThis.Bun;import s0 from"fs";import V0 from"path";async function H6($={}){let{port:w=3000,root:y=".",stxOptions:j={},watch:z=!0,onRequest:A,routes:g={},middleware:J=[],on404:X,onError:Y}=$,U=V0.resolve(y),B=new Map;async function b(N){let O=s0.statSync(N),H=`${N}:${O.mtimeMs}`,R=B.get(H);if(R)return R.content;let f=await Bun.file(N).text(),F=f.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),c=F?F[1]:"",g0=f.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],o=f.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,""),a={__filename:N,__dirname:V0.dirname(N)};await Q0(c,a,N);let b0=await J0(o,a,N,j,new Set),O0=[...g0];if(O0.length>0)if(b0.match(/(<\/body>)/i)){let o0=O0.join(`
1491
+ `);b0=b0.replace(/(<\/body>)/i,`${o0}
1491
1492
  $1`)}else b0+=`
1492
- ${f0.join(`
1493
- `)}`;return B.set(O,{content:b0,mtime:f.mtimeMs}),b0}async function Q(N){let f=s0.statSync(N),O=`${N}:${f.mtimeMs}`,R=B.get(O);if(R)return R.content;let{content:H}=await G0(N,j);return B.set(O,{content:H,mtime:f.mtimeMs}),H}function K(N){let f=N.startsWith("/")?N.slice(1):N,O=[f,`${f}.stx`,`${f}.md`,`${f}.html`,V0.join(f,"index.stx"),V0.join(f,"index.md"),V0.join(f,"index.html")];for(let R of O){let H=V0.join(U,R);if(s0.existsSync(H)&&s0.statSync(H).isFile())return H}return null}async function _(N){let f=new URL(N.url),O=async()=>{if(A[f.pathname])return await A[f.pathname](N);if(g){let H=await g(N);if(H)return H}let R=K(f.pathname);if(!R){if(X)return await X(N);return new Response("Not Found",{status:404})}try{let H,F="text/html";if(R.endsWith(".stx"))H=await b(R);else if(R.endsWith(".md"))H=await Q(R);else if(R.endsWith(".html"))H=await Bun.file(R).text();else if(R.endsWith(".css"))H=await Bun.file(R).text(),F="text/css";else if(R.endsWith(".js"))H=await Bun.file(R).text(),F="text/javascript";else if(R.endsWith(".json"))H=await Bun.file(R).text(),F="application/json";else return new Response(Bun.file(R));return new Response(H,{headers:{"Content-Type":F}})}catch(H){if(Y)return await Y(H,N);return new Response(`<h1>Error</h1><pre>${H.message}
1494
- ${H.stack}</pre>`,{status:500,headers:{"Content-Type":"text/html"}})}};for(let R=J.length-1;R>=0;R--){let H=J[R],F=O;O=async()=>await H(N,F)}return await O()}let W=Q6({port:w,fetch:_}),L=null;if(z)L=s0.watch(U,{recursive:!0},(N,f)=>{if(f&&(f.endsWith(".stx")||f.endsWith(".md")||f.endsWith(".html")))B.clear()});return{server:W,url:W.url.toString(),stop(){if(L)L.close();W.stop()}}}async function tz($,w={}){let y=V0.resolve($);if(!s0.existsSync(y))throw Error(`File not found: ${y}`);let j=y.endsWith(".md"),z=y.endsWith(".stx");if(!j&&!z)throw Error(`Unsupported file type: ${y}. Only .stx and .md files are supported.`);return await K6({...w,root:V0.dirname(y),routes:{"/":async()=>{let g;if(j){let{content:A}=await G0(y,w.stxOptions);g=A}else{let A=await Bun.file(y).text(),J=A.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),X=J?J[1]:"",Y=A.replace(/<script\b[^>]*>[\s\S]*?<\/script>/i,""),U={};await Q0(X,U,y);let B=new Set;g=await J0(Y,U,y,w.stxOptions||{},B)}return new Response(g,{headers:{"Content-Type":"text/html"}})},...w.routes}})}function $4($){return $}function w4($){return $}await E0([p0(),X1(),p()]);import bw from"path";var Qy={enabled:!0,bufferSize:16384,strategy:"auto",timeout:30000},Bw=/<!-- @section:([\w-]+) -->([\s\S]*?)<!-- @endsection:\1 -->/g;async function J4($,w={},y={}){let j={...r1,...y,streaming:{...Qy,...y.streaming}};return new ReadableStream({async start(z){try{let g=await Bun.file($).text(),A=g.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),J=A?A[1]:"",X=g.replace(/<script\b[^>]*>[\s\S]*?<\/script>/i,""),Y={...w,__filename:$,__dirname:bw.dirname($)};await Q0(J,Y,$);let B=await J0(X,Y,$,j,new Set);z.enqueue(B),z.close()}catch(g){z.error(g)}}})}async function X4($,w={}){let y={...r1,...w,streaming:{...Qy,...w.streaming}},j=await Bun.file($).text(),z=j.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),g=z?z[1]:"",A=j.replace(/<script\b[^>]*>[\s\S]*?<\/script>/i,""),J=A,X={},Y;Bw.lastIndex=0;while((Y=Bw.exec(A))!==null){let b=Y[1],Q=Y[2];X[b]=Q}let U=A.replace(Bw,"");return{renderShell:async(b={})=>{let Q={...b,__filename:$,__dirname:bw.dirname($)};return await Q0(g,Q,$),J0(U,Q,$,y,new Set)},renderSection:async(b,Q={})=>{try{if(!X[b])return`<div class="error-message">Section "${b}" not found in template "${$}"</div>`;let K={...Q,__filename:$,__dirname:bw.dirname($)};await Q0(g,K,$);let _=new Set;return await J0(X[b],K,$,y,_)}catch(K){let _=K instanceof Error?K.message:String(K);return k("Expression",_,$,X[b]||"",0,X[b]||"")}},getSections:()=>{return Object.keys(X)},getTemplate:()=>{return J}}}var q6={name:"island",hasEndTag:!0,handler:($,w,y,j)=>{if(!w||w.length===0)throw Error("Island directive requires a name parameter");let z=w[0].replace(/['"`]/g,""),g=w[1]?w[1].replace(/['"`]/g,""):"lazy",A=`island-${z}-${Math.random().toString(36).substring(2,9)}`,J=$.match(/<script\s+props\s*>([\s\S]*?)<\/script>/i),X=J?J[1].trim():"",Y=J?$.replace(J[0],""):$;return`<div data-island="${z}" data-island-id="${A}" data-priority="${g}">
1493
+ ${O0.join(`
1494
+ `)}`;return B.set(H,{content:b0,mtime:O.mtimeMs}),b0}async function Q(N){let O=s0.statSync(N),H=`${N}:${O.mtimeMs}`,R=B.get(H);if(R)return R.content;let{content:f}=await I0(N,j);return B.set(H,{content:f,mtime:O.mtimeMs}),f}function K(N){let O=N.startsWith("/")?N.slice(1):N,H=[O,`${O}.stx`,`${O}.md`,`${O}.html`,V0.join(O,"index.stx"),V0.join(O,"index.md"),V0.join(O,"index.html")];for(let R of H){let f=V0.join(U,R);if(s0.existsSync(f)&&s0.statSync(f).isFile())return f}return null}async function _(N){let O=new URL(N.url),H=async()=>{if(g[O.pathname])return await g[O.pathname](N);if(A){let f=await A(N);if(f)return f}let R=K(O.pathname);if(!R){if(X)return await X(N);return new Response("Not Found",{status:404})}try{let f,F="text/html";if(R.endsWith(".stx"))f=await b(R);else if(R.endsWith(".md"))f=await Q(R);else if(R.endsWith(".html"))f=await Bun.file(R).text();else if(R.endsWith(".css"))f=await Bun.file(R).text(),F="text/css";else if(R.endsWith(".js"))f=await Bun.file(R).text(),F="text/javascript";else if(R.endsWith(".json"))f=await Bun.file(R).text(),F="application/json";else return new Response(Bun.file(R));return new Response(f,{headers:{"Content-Type":F}})}catch(f){if(Y)return await Y(f,N);return new Response(`<h1>Error</h1><pre>${f.message}
1495
+ ${f.stack}</pre>`,{status:500,headers:{"Content-Type":"text/html"}})}};for(let R=J.length-1;R>=0;R--){let f=J[R],F=H;H=async()=>await f(N,F)}return await H()}let W=O6({port:w,fetch:_}),L=null;if(z)L=s0.watch(U,{recursive:!0},(N,O)=>{if(O&&(O.endsWith(".stx")||O.endsWith(".md")||O.endsWith(".html")))B.clear()});return{server:W,url:W.url.toString(),stop(){if(L)L.close();W.stop()}}}async function iA($,w={}){let y=V0.resolve($);if(!s0.existsSync(y))throw Error(`File not found: ${y}`);let j=y.endsWith(".md"),z=y.endsWith(".stx");if(!j&&!z)throw Error(`Unsupported file type: ${y}. Only .stx and .md files are supported.`);return await H6({...w,root:V0.dirname(y),routes:{"/":async()=>{let A;if(j){let{content:g}=await I0(y,w.stxOptions);A=g}else{let g=await Bun.file(y).text(),J=g.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),X=J?J[1]:"",Y=g.replace(/<script\b[^>]*>[\s\S]*?<\/script>/i,""),U={};await Q0(X,U,y);let B=new Set;A=await J0(Y,U,y,w.stxOptions||{},B)}return new Response(A,{headers:{"Content-Type":"text/html"}})},...w.routes}})}function nA($){return $}function pA($){return $}await M0([p0(),X1(),n()]);import qw from"path";var W9={enabled:!0,bufferSize:16384,strategy:"auto",timeout:30000},Kw=/<!-- @section:([\w-]+) -->([\s\S]*?)<!-- @endsection:\1 -->/g;async function aA($,w={},y={}){let j={...c1,...y,streaming:{...W9,...y.streaming}};return new ReadableStream({async start(z){try{let A=await Bun.file($).text(),g=A.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),J=g?g[1]:"",X=A.replace(/<script\b[^>]*>[\s\S]*?<\/script>/i,""),Y={...w,__filename:$,__dirname:qw.dirname($)};await Q0(J,Y,$);let B=await J0(X,Y,$,j,new Set);z.enqueue(B),z.close()}catch(A){z.error(A)}}})}async function eA($,w={}){let y={...c1,...w,streaming:{...W9,...w.streaming}},j=await Bun.file($).text(),z=j.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),A=z?z[1]:"",g=j.replace(/<script\b[^>]*>[\s\S]*?<\/script>/i,""),J=g,X={},Y;Kw.lastIndex=0;while((Y=Kw.exec(g))!==null){let b=Y[1],Q=Y[2];X[b]=Q}let U=g.replace(Kw,"");return{renderShell:async(b={})=>{let Q={...b,__filename:$,__dirname:qw.dirname($)};return await Q0(A,Q,$),J0(U,Q,$,y,new Set)},renderSection:async(b,Q={})=>{try{if(!X[b])return`<div class="error-message">Section "${b}" not found in template "${$}"</div>`;let K={...Q,__filename:$,__dirname:qw.dirname($)};await Q0(A,K,$);let _=new Set;return await J0(X[b],K,$,y,_)}catch(K){let _=K instanceof Error?K.message:String(K);return k("Expression",_,$,X[b]||"",0,X[b]||"")}},getSections:()=>{return Object.keys(X)},getTemplate:()=>{return J}}}var R6={name:"island",hasEndTag:!0,handler:($,w,y,j)=>{if(!w||w.length===0)throw Error("Island directive requires a name parameter");let z=w[0].replace(/['"`]/g,""),A=w[1]?w[1].replace(/['"`]/g,""):"lazy",g=`island-${z}-${Math.random().toString(36).substring(2,9)}`,J=$.match(/<script\s+props\s*>([\s\S]*?)<\/script>/i),X=J?J[1].trim():"",Y=J?$.replace(J[0],""):$;return`<div data-island="${z}" data-island-id="${g}" data-priority="${A}">
1495
1496
  ${Y}
1496
- <script type="application/json" data-island-props="${A}">
1497
+ <script type="application/json" data-island-props="${g}">
1497
1498
  ${X?`{${X}}`:"{}"}
1498
1499
  </script>
1499
- </div>`}};function Y4($={}){let w=[];if($.hydration?.enabled)w.push(q6);return w}async function U4($,w,y,j={}){return $}p();jw();var b4={};export{Jy as webComponentDirectiveHandler,Cj as validators,K2 as unescapeHtml,w$ as transitionDirective,r8 as templateCache,e$ as structuredDataDirective,J4 as streamTemplate,J8 as setGlobalContext,Gz as serveStxFile,Tz as serveMultipleStxFiles,tz as serveFile,K6 as serve,y$ as scrollAnimateDirective,$$ as screenReaderDirective,L6 as scanA11yIssues,k0 as safeExecuteAsync,Dj as safeExecute,x2 as runPreProcessingMiddleware,u2 as runPostProcessingMiddleware,p1 as resolveTemplatePath,n0 as renderComponent,Y4 as registerStreamingDirectives,Ug as registerSeoDirectives,ig as registerComponentDirectives,F6 as registerAnimationDirectives,f6 as registerA11yDirectives,G0 as readMarkdownFile,G2 as processTranslateDirective,r2 as processStructuredData,c$ as processStackReplacements,r$ as processStackPushDirectives,c2 as processSeoDirective,U4 as processSectionDirectives,E8 as processOnceDirective,P2 as processMiddleware,p2 as processMetaDirectives,e2 as processMarkdownFileDirectives,v2 as processMarkdownDirectives,m$ as processLoops,Z8 as processJsonDirective,p$ as processIncludes,dj as processForms,H8 as processFormInputDirectives,k2 as processFormDirectives,x0 as processExpressions,h$ as processErrorDirective,J0 as processDirectives,f2 as processCustomDirectives,d$ as processBasicFormDirectives,_w as processAnimationDirectives,Kw as processA11yDirectives,Z2 as partialsCache,n$ as onceStore,g$ as motionDirective,a$ as metaDirective,d2 as markdownDirectiveHandler,zw as markdownCache,I2 as loadTranslation,q6 as islandDirective,l2 as injectSeoTags,iz as initFile,l1 as hashFilePath,pz as gitHash,x$ as getTranslation,gy as getSourceLineInfo,W6 as getScreenReaderOnlyStyle,t8 as generateTemplatesDocs,g6 as generateDocs,$6 as generateDirectivesDocs,e8 as generateComponentsDocs,a8 as generateComponentDoc,hz as formatStxContent,w6 as formatDocsAsMarkdown,j6 as formatDocsAsJson,y6 as formatDocsAsHtml,By as findComponentFiles,T as fileExists,Q0 as extractVariables,s8 as extractComponentProps,o8 as extractComponentDescription,P0 as evaluateExpression,B0 as evaluateAuthExpression,Q2 as escapeHtml,O2 as errorRecovery,z1 as errorLogger,vz as docsCommand,P1 as devHelpers,gz as defineStxConfig,S2 as defaultI18nConfig,b2 as defaultFilters,r1 as defaultConfig,b4 as default,uj as createTranslateFilter,X4 as createStreamRenderer,w4 as createRoute,$4 as createMiddleware,Mj as createEnhancedError,k as createDetailedErrorMessage,A0 as config,$w as componentDirective,aj as clearOnceStore,Xy as checkCache,Ly as checkA11y,Yy as cacheTemplate,Ay as buildWebComponents,X8 as applyFilters,j$ as animationGroupDirective,Oy as analyzeTemplate,H6 as analyzeProject,t1 as a11yDirective,Sy as TransitionType,Gy as TransitionEase,Iy as TransitionDirection,L8 as StxSyntaxError,f8 as StxSecurityError,L0 as StxRuntimeError,h1 as StxFileError,g1 as StxError,R2 as ErrorLogger,q0 as DEFAULT_TRANSITION_OPTIONS};
1500
+ </div>`}};function tA($={}){let w=[];if($.hydration?.enabled)w.push(R6);return w}async function $g($,w,y,j={}){return $}n();zw();var yg={};export{U9 as webComponentDirectiveHandler,mj as validators,N2 as unescapeHtml,y$ as transitionDirective,a8 as templateCache,t$ as structuredDataDirective,aA as streamTemplate,b8 as setGlobalContext,LA as serveStxFile,OA as serveMultipleStxFiles,iA as serveFile,H6 as serve,j$ as scrollAnimateDirective,w$ as screenReaderDirective,V6 as scanA11yIssues,k0 as safeExecuteAsync,uj as safeExecute,i2 as runPreProcessingMiddleware,n2 as runPostProcessingMiddleware,p1 as resolveTemplatePath,n0 as renderComponent,tA as registerStreamingDirectives,Nz as registerSeoDirectives,oz as registerComponentDirectives,M6 as registerAnimationDirectives,S6 as registerA11yDirectives,I0 as readMarkdownFile,M2 as processTranslateDirective,s2 as processStructuredData,l$ as processStackReplacements,r$ as processStackPushDirectives,o2 as processSeoDirective,$g as processSectionDirectives,d8 as processOnceDirective,m2 as processMiddleware,l2 as processMetaDirectives,w9 as processMarkdownFileDirectives,P2 as processMarkdownDirectives,i$ as processLoops,v8 as processJsonDirective,c$ as processIncludes,nj as processForms,G8 as processFormInputDirectives,S2 as processFormDirectives,x0 as processExpressions,P$ as processErrorDirective,J0 as processDirectives,f2 as processCustomDirectives,h$ as processBasicFormDirectives,Lw as processAnimationDirectives,Nw as processA11yDirectives,D2 as partialsCache,p$ as onceStore,A$ as motionDirective,e$ as metaDirective,x2 as markdownDirectiveHandler,gw as markdownCache,Z2 as loadTranslation,R6 as islandDirective,a2 as injectSeoTags,EA as initFile,l1 as hashFilePath,CA as gitHash,u$ as getTranslation,J9 as getSourceLineInfo,F6 as getScreenReaderOnlyStyle,g6 as generateTemplatesDocs,B6 as generateDocs,J6 as generateDirectivesDocs,A6 as generateComponentsDocs,z6 as generateComponentDoc,b6 as formatStxContent,GA as formatMarkdownContent,X6 as formatDocsAsMarkdown,U6 as formatDocsAsJson,Y6 as formatDocsAsHtml,K9 as findComponentFiles,T as fileExists,Q0 as extractVariables,y6 as extractComponentProps,j6 as extractComponentDescription,P0 as evaluateExpression,B0 as evaluateAuthExpression,_2 as escapeHtml,k2 as errorRecovery,A1 as errorLogger,VA as docsCommand,P1 as devHelpers,B4 as defineStxConfig,T2 as defaultI18nConfig,q2 as defaultFilters,c1 as defaultConfig,yg as default,lj as createTranslateFilter,eA as createStreamRenderer,pA as createRoute,nA as createMiddleware,xj as createEnhancedError,k as createDetailedErrorMessage,A0 as config,ww as componentDirective,zz as clearOnceStore,B9 as checkCache,k9 as checkA11y,b9 as cacheTemplate,Y9 as buildWebComponents,Q8 as applyFilters,z$ as animationGroupDirective,V9 as analyzeTemplate,T6 as analyzeProject,$$ as a11yDirective,M9 as TransitionType,D9 as TransitionEase,E9 as TransitionDirection,k8 as StxSyntaxError,F8 as StxSecurityError,W0 as StxRuntimeError,h1 as StxFileError,z1 as StxError,F2 as ErrorLogger,K0 as DEFAULT_TRANSITION_OPTIONS};