// @bun
var{defineProperty:f,getOwnPropertyNames:NJ,getOwnPropertyDescriptor:RJ}=Object,KJ=Object.prototype.hasOwnProperty;function AJ(J){return this[J]}var FQ=(J)=>{var Q=(i??=new WeakMap).get(J),W;if(Q)return Q;if(Q=f({},"__esModule",{value:!0}),J&&typeof J==="object"||typeof J==="function"){for(var Z of NJ(J))if(!KJ.call(Q,Z))f(Q,Z,{get:AJ.bind(J,Z),enumerable:!(W=RJ(J,Z))||W.enumerable})}return i.set(J,Q),Q},i;var kJ=(J)=>J;function DJ(J,Q){this[J]=kJ.bind(null,Q)}var GQ=(J,Q)=>{for(var W in Q)f(J,W,{get:Q[W],enumerable:!0,configurable:!0,set:DJ.bind(Q,W)})};var j=(J,Q)=>()=>(J&&(Q=J(J=0)),Q);var b=import.meta.require;function BQ(J){H={...H,...J}}function UQ(){H={...o}}function IQ(){return{...H}}function zJ(J){let Q="",W=null,Z=!1;for(let $=0;$<J.length;$++){let q=J[$];if(Z){Z=!1;continue}if(q==="\\"&&W){Z=!0;continue}if(W){if(W==="`"&&q==="$"&&$+1<J.length&&J[$+1]==="{"){let F=1;$+=2;while($<J.length&&F>0){if(J[$]==="{")F++;else if(J[$]==="}")F--;if(F>0)Q+=J[$],$++}continue}if(q===W)W=null;continue}if(q==='"'||q==="'"||q==="`"){W=q;continue}Q+=q}return Q}function LJ(J,Q){let W=/[$A-Z_a-z][$\w]*/g,Z;while((Z=W.exec(J))!==null){let $=Z[0],q=J[Z.index-1];if(jJ.has($))throw Error(`Potentially unsafe expression (matched /\\b${$}\\b/; identifier ${$}): ${Q}`);if(q==="."&&a.has($))throw Error(`Potentially unsafe expression (matched /.${$}/; property ${$}): ${Q}`)}}function HJ(J){let Q=/\[\s*(['"])(.*?)\1\s*\]/g,W;while((W=Q.exec(J))!==null){let Z=W[2];if(!a.has(Z))continue;let $=J.slice(0,W.index).match(/\S(?=\s*$)/)?.[0],q=J.slice(W.index+W[0].length).match(/^\s*(\S)/)?.[1];if(!(($==="{"||$===",")&&q===":"))throw Error(`Potentially unsafe expression (bracket key ${W[2]}): ${J}`)}}function d(J){let Q=J.trim(),W=zJ(Q);LJ(W,Q),HJ(Q);for(let Z of u)if(Z.test(W))throw Error(`Potentially unsafe expression (matched /${Z.source}/): ${Q}`);if(!H.allowBracketNotation&&wJ.test(Q))throw Error(`Bracket notation with strings not allowed: ${Q}. Enable with configureSafeEvaluator({ allowBracketNotation: true })`);return Q}function t(J){let Q={};Q.Math=Math,Q.JSON=JSON,Q.Date=Date,Q.String=String,Q.Number=Number,Q.Boolean=Boolean,Q.Array=Array,Q.parseInt=Number.parseInt,Q.parseFloat=Number.parseFloat,Q.isNaN=Number.isNaN,Q.isFinite=Number.isFinite,Q.encodeURIComponent=encodeURIComponent,Q.decodeURIComponent=decodeURIComponent;for(let[W,Z]of Object.entries(J)){if(W.startsWith("__")||u.some(($)=>$.test(W)))continue;if(Z&&typeof Z==="object"&&!Array.isArray(Z))Q[W]=x(Z);else Q[W]=Z}return Q}function x(J,Q=0){if(Q>=H.maxSanitizeDepth)return"[Object too deep]";if(J===null||typeof J!=="object")return J;if(Array.isArray(J))return J.map((Z)=>x(Z,Q+1));if(J instanceof Date||J instanceof RegExp||J instanceof Map||J instanceof Set||J instanceof Error)return J;let W={};for(let[Z,$]of Object.entries(J)){if(Z.startsWith("__")||Z==="constructor"||Z==="prototype")continue;if($&&typeof $==="object")W[Z]=x($,Q+1);else W[Z]=$}return W}function m(J,Q){try{let W=t(Q),Z=Object.keys(W),$=Object.values(W);return bJ(J,Z)(...$)}catch{return}}function OQ(J){try{return d(J),!0}catch{return!1}}function _Q(J){try{return d(J),null}catch(Q){return Q instanceof Error?Q.message:String(Q)}}function MQ(J,Q){try{let W=m(J,Q);return Boolean(W)}catch{return!1}}function NQ(J,Q){try{let W=m(J,Q);if(Array.isArray(W))return W;if(W&&typeof W==="object"&&"length"in W){let Z=W.length;if(typeof Z==="number"&&Number.isFinite(Z)&&Z>=0&&Number.isInteger(Z))return Array.from(W)}return[]}catch{return[]}}function E(J,Q){try{let W=m(J,Q);if(W&&typeof W==="object"&&!Array.isArray(W))return W;return{}}catch{return{}}}function bJ(J,Q){let W=d(J),Z=/^[A-Za-z_$][\w$]*$/,$=[],q=[];for(let V=0;V<Q.length;V++){let G=Q[V];if(!Z.test(G))continue;if(TJ.has(G))continue;$.push(V),q.push(G)}let F=Function(...q,`
    'use strict';
    try {
      return ${W};
    }
catch (e) {
      if (e instanceof ReferenceError || e instanceof TypeError) {
        return undefined;
      }
      throw e;
    }
  `);if(q.length===Q.length)return F;return(...V)=>{let G=Array($.length);for(let Y=0;Y<$.length;Y++)G[Y]=V[$[Y]];return F(...G)}}function RQ(J,Q){try{if(typeof J!=="string")return;if(J.length>n)throw Error(`safeEvaluateCode: input exceeds ${n} chars`);for(let F of u)if(F.test(J))throw Error("Potentially unsafe code detected");let W=t(Q),Z=Object.keys(W),$=Object.values(W);return Function(...Z,`
      'use strict';
      ${J}
    `)(...$)}catch{return}}function SJ(J){let Q=J.trim(),W=[/\beval\s*\(/i,/\bFunction\s*\(/i,/\bimport\s*\(/i,/\brequire\s*\(/i,/\bprocess\b/i,/\b__proto__\b/i,/\bconstructor\s*[.(]/i,/\bglobalThis\b/i,/\bwindow\b/i,/\bdocument\b/i,/\bfetch\s*\(/i,/\bBun\b/i,/\bDeno\b/i,/\bconsole\b/i,/\bthis\b/i,/\bReflect\b/i,/\bProxy\b/i,/\bprototype\b/i,/\.(bind|call|apply)\s*\(/i];for(let Z of W)if(Z.test(Q))return!1;return!0}function KQ(J,Q,W,Z,$=1000){if(!SJ(Q))throw Error(`Unsafe expression in @${J}: ${Q}`);let q=W.replace(/`/g,"\\`").replace(/\$\{/g,"\\${").replace(/\{\{([^}]+)\}\}/g,(F,V)=>{return`\${${V}}`});if(J==="for")return Function(...Z,`
      'use strict';
      let result = '';
      for (${Q}) {
        result += \`${q}\`;
      }
      return result;
    // eslint-disable-next-line pickier/no-unused-vars
    `);else return Function(...Z,`
      'use strict';
      let result = '';
      let __safeCounter = 0;
      const __maxIterations = ${$};
      while (${Q} && __safeCounter < __maxIterations) {
        __safeCounter++;
        result += \`${q}\`;
      }
      // Surface the truncation both inline (for end users) and via
      // console.warn (for developers running \`stx dev\`). A silent cut-off
      // made pages render half a list with no breadcrumb.
      if (__safeCounter >= __maxIterations) {
        result += '<!-- [Loop Error]: Maximum iterations exceeded -->';
        if (typeof console !== 'undefined' && typeof console.warn === 'function') {
          console.warn('[stx] @while loop hit max iterations (' + __maxIterations + '); template output was truncated. Raise via createSafeForLoop(..., maxIterations) if intentional.');
        }
      }
      return result;
    // eslint-disable-next-line pickier/no-unused-vars
    `)}var o,H,u,jJ,a,wJ,TJ,n=65536;var e=j(()=>{o={maxSanitizeDepth:10,allowBracketNotation:!1},H={...o};u=[/\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/,/\b(Reflect|Proxy)\b/,/\bSymbol\b/,/\b(WeakMap|WeakSet|WeakRef|FinalizationRegistry)\b/,/\b(Generator|AsyncGenerator)\b/,/__\w+__/,/\.(bind|call|apply)\s*\(/,/\bnew\s+/,/\bdelete\s+/,/\bthis\b/],jJ=new Set(["eval","Function","setTimeout","setInterval","setImmediate","process","require","import","exports","module","window","document","global","globalThis","constructor","prototype","Reflect","Proxy","Symbol","WeakMap","WeakSet","WeakRef","FinalizationRegistry","Generator","AsyncGenerator","delete","this"]),a=new Set(["__proto__","constructor","prototype"]),wJ=/[\w)\]]\s*\[\s*['"]/;TJ=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with","yield","let","static","implements","interface","package","private","protected","public","arguments","eval","await"])});function CJ(J){JJ=J}function PJ(){return JJ}function vJ(J){C={...C,...J}}function yJ(){C={}}function QJ(J,Q={}){let W=C[J]||EJ[J]||{message:`Unknown error (code: ${J})`},Z=W.message,$=W.help;for(let[q,F]of Object.entries(Q)){let V=`{{${q}}}`;if(Z=Z.replace(new RegExp(V,"g"),F),$)$=$.replace(new RegExp(V,"g"),F)}return{message:Z,help:$}}function hJ(J,Q={}){let{message:W,help:Z}=QJ(J,Q);return Z?`${W}
  Help: ${Z}`:W}function c(J){for(let[Q,W]of Object.entries(K))if(W===J)return Q;return}var EJ,C,JJ="en",K;var P=j(()=>{EJ={1001:{message:"Unclosed directive: {{directive}}",help:"Make sure to close the directive with the appropriate end tag"},1002:{message:"Unclosed expression at position {{position}}",help:"Check for missing closing braces }}"},1003:{message:"Invalid directive syntax: {{directive}}",help:"Review the directive documentation for correct syntax"},1004:{message:"Malformed expression: {{expression}}",help:"Check for syntax errors in your expression"},1005:{message:"Unexpected token: {{token}}",help:"Remove or fix the unexpected token"},1101:{message:"Undefined variable: {{variable}}",help:"Make sure the variable is defined in the template context"},1102:{message:"Type error: {{details}}",help:"Check that you are using the correct types"},1103:{message:"Evaluation error: {{details}}",help:"Review the expression for errors"},1104:{message:"Infinite loop detected in {{location}}",help:"Check your loop conditions"},1105:{message:"Circular reference detected: {{path}}",help:"Remove the circular dependency"},1201:{message:"Unsafe expression blocked: {{expression}}",help:"This expression contains potentially dangerous code"},1202:{message:"Path traversal attempt blocked: {{path}}",help:"Use only relative paths within allowed directories"},1203:{message:"Potential XSS attempt blocked",help:"Sanitize user input before rendering"},1204:{message:"Code injection attempt blocked: {{code}}",help:"Avoid executing dynamic code"},1205:{message:"Prohibited DOM API usage: {{api}}",help:"Use STX.useRefs(), STX.useRef(), STX.el() and other STX helpers instead of direct DOM manipulation"},1301:{message:"File not found: {{path}}",help:"Check that the file exists and the path is correct"},1302:{message:"Error reading file: {{path}}",help:"Check file permissions and encoding"},1303:{message:"Invalid file path: {{path}}",help:"Use a valid file path"},1304:{message:"Permission denied: {{path}}",help:"Check file permissions"},1401:{message:"Invalid configuration: {{details}}",help:"Review your stx.config.ts file"},1402:{message:"Missing required configuration: {{key}}",help:"Add the required configuration option"},1403:{message:"Deprecated configuration: {{key}}",help:"Update to the new configuration format"},1501:{message:"Component not found: {{name}}",help:"Check that the component exists in your components directory"},1502:{message:"Invalid props for component {{name}}: {{details}}",help:"Check the component prop requirements"},1503:{message:"Error rendering component {{name}}: {{details}}",help:"Check the component template for errors"},1601:{message:"Filter not found: {{filter}}",help:"Register the filter or check the filter name"},1602:{message:"Invalid arguments for filter {{filter}}: {{details}}",help:"Check the filter documentation for correct arguments"},1603:{message:"Expression evaluation timed out",help:"Simplify the expression or increase the timeout"}},C={};K={UNCLOSED_DIRECTIVE:1001,UNCLOSED_EXPRESSION:1002,INVALID_DIRECTIVE_SYNTAX:1003,MALFORMED_EXPRESSION:1004,UNEXPECTED_TOKEN:1005,UNDEFINED_VARIABLE:1101,TYPE_ERROR:1102,EVALUATION_ERROR:1103,INFINITE_LOOP:1104,CIRCULAR_REFERENCE:1105,UNSAFE_EXPRESSION:1201,PATH_TRAVERSAL:1202,XSS_ATTEMPT:1203,CODE_INJECTION:1204,DOM_API_VIOLATION:1205,FILE_NOT_FOUND:1301,FILE_READ_ERROR:1302,INVALID_FILE_PATH:1303,PERMISSION_DENIED:1304,INVALID_CONFIG:1401,MISSING_REQUIRED_CONFIG:1402,DEPRECATED_CONFIG:1403,COMPONENT_NOT_FOUND:1501,INVALID_PROPS:1502,COMPONENT_RENDER_ERROR:1503,FILTER_NOT_FOUND:1601,INVALID_FILTER_ARGS:1602,EXPRESSION_TIMEOUT:1603}});function fJ(){return!1}function S(){return!fJ()||process.env.STX_DEBUG==="true"}function DQ(){return!1}import xJ from"path";function uJ(J){T={...T,...J}}function v(){return{...T}}function dJ(){T={...WJ}}function y(J){if(!T.showRelativePaths||!J)return J;let Q=T.baseDir||process.cwd();try{let W=xJ.relative(Q,J);return W.startsWith("..")?J:W}catch{return J}}var WJ,T,L,ZJ,$J,qJ,VJ,YJ;var h=j(()=>{P();WJ={showRelativePaths:!1,enableAutoRecovery:S(),logRecoveryWarnings:!0},T={...WJ};L=class L extends Error{code;filePath;line;column;context;numericCode;constructor(J,Q,W,Z,$,q,F){super(J);this.code=Q;this.filePath=W;this.line=Z;this.column=$;this.context=q;if(this.name="StxError",this.numericCode=F||K.EVALUATION_ERROR,this.filePath)this.filePath=y(this.filePath)}};ZJ=class ZJ extends L{constructor(J,Q,W,Z,$,q){super(J,"stx_SYNTAX_ERROR",Q,W,Z,$,q||K.INVALID_DIRECTIVE_SYNTAX);this.name="StxSyntaxError"}};$J=class $J extends L{constructor(J,Q,W,Z,$,q){super(J,"stx_RUNTIME_ERROR",Q,W,Z,$,q||K.EVALUATION_ERROR);this.name="StxRuntimeError"}};qJ=class qJ extends L{constructor(J,Q,W,Z,$,q){super(J,"stx_SECURITY_ERROR",Q,W,Z,$,q||K.UNSAFE_EXPRESSION);this.name="StxSecurityError"}};VJ=class VJ extends L{constructor(J,Q,W,Z,$,q){super(J,"stx_FILE_ERROR",Q,W,Z,$,q||K.FILE_NOT_FOUND);this.name="StxFileError"}};YJ=class YJ extends L{isFatal=!0;constructor(J,Q,W,Z,$,q){super(J,"stx_VALIDATION_ERROR",Q,W,Z,$,q||K.DOM_API_VIOLATION);this.name="StxValidationError"}}});function p(J){let{type:Q,message:W,code:Z,filePath:$,line:q,column:F,template:V,offset:G,snippet:Y,suggestion:X,format:U="text"}=J,_=q,N=F;if(!_&&V&&G!==void 0){let B=GJ(V,G);_=B.line,N=B.column}let R=$?y($):void 0,k=Z?c(Z):void 0,z={type:Q,code:Z,codeName:k,message:W,filePath:R,line:_,column:N,snippet:Y,suggestion:X,timestamp:new Date().toISOString()},A;switch(U){case"html":A=cJ(z);break;case"json":A=JSON.stringify(z,null,2);break;case"console":A=pJ(z,V,G);break;case"text":default:A=mJ(z,V,G);break}return{formatted:A,data:z}}function mJ(J,Q,W){let Z=[],$=J.code?` [${J.codeName||J.code}]`:"";if(Z.push(`[${J.type} Error${$}]`),J.filePath){let q=J.filePath;if(J.line){if(q+=`:${J.line}`,J.column)q+=`:${J.column}`}Z.push(`at ${q}`)}if(Z.push(`
${J.message}`),Q&&J.line){let q=lJ(Q,J.line,2);if(q)Z.push(`
${q}`)}if(J.snippet)Z.push(`
Snippet: ${J.snippet}`);if(J.suggestion)Z.push(`
Suggestion: ${J.suggestion}`);return Z.join(" ")}function cJ(J){let Q=J.code?` [${J.code}]`:"",W=J.filePath?` in ${J.filePath}${J.line?`:${J.line}`:""}`:"",Z=`<!-- [${J.type} Error${Q}]${W}: ${FJ(J.message)}`;if(J.suggestion)Z+=` | Suggestion: ${FJ(J.suggestion)}`;return Z+=" -->",Z}function pJ(J,Q,W){let Y=[],X=J.code?` [${J.codeName||J.code}]`:"";if(Y.push(`\x1B[1m${"\x1B[31m"}\u2501\u2501\u2501 ${J.type} Error${X} \u2501\u2501\u2501${"\x1B[0m"}`),J.filePath){let U=`\x1B[36m${J.filePath}\x1B[0m`;if(J.line){if(U+=`\x1B[90m:${J.line}\x1B[0m`,J.column)U+=`\x1B[90m:${J.column}\x1B[0m`}Y.push(`
\x1B[90mat\x1B[0m ${U}`)}if(Y.push(`

${J.message}`),Q&&J.line){let U=sJ(Q,J.line,2);if(U)Y.push(`

\x1B[90mContext:\x1B[0m
${U}`)}if(J.suggestion)Y.push(`

\x1B[33mSuggestion:\x1B[0m ${J.suggestion}`);return Y.push(`
${"\x1B[31m"}\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${"\x1B[0m"}`),Y.join("")}function lJ(J,Q,W){let Z=J.split(`
`),$=Math.max(0,Q-W-1),q=Math.min(Z.length-1,Q+W-1),F=[];for(let V=$;V<=q;V++){let G=(V+1).toString().padStart(4),Y=V===Q-1?">":" ";F.push(`${Y}${G} | ${Z[V]}`)}return F.join(`
`)}function sJ(J,Q,W){let Z=J.split(`
`),$=Math.max(0,Q-W-1),q=Math.min(Z.length-1,Q+W-1),F="\x1B[90m",V="\x1B[31m",G="\x1B[0m",Y=[];for(let X=$;X<=q;X++){let U=(X+1).toString().padStart(4),_=X===Q-1,N=_?"\x1B[31m>\x1B[0m":" ",R=_?`\x1B[31m${Z[X]}\x1B[0m`:`\x1B[90m${Z[X]}\x1B[0m`;Y.push(`${N}\x1B[90m${U}\x1B[0m | ${R}`)}return Y.join(`
`)}function FJ(J){return J.replace(/--/g,"- -").replace(/>/g,"&gt;")}function GJ(J,Q){let Z=J.substring(0,Q).split(`
`);return{line:Z.length,column:Z[Z.length-1].length}}function w(J,Q,W){return p({type:J,message:Q,code:W,format:"html"}).formatted}function rJ(J,Q,W,Z,$){return p({type:J,message:Q,code:$,filePath:W,line:Z,format:"console"}).formatted}function iJ(J,Q,W){let Z=W.template.split(`
`),$=GJ(W.template,W.offset),q=`[${J} Error at line ${$.line} in ${W.filePath}]: ${Q}

`,F=Math.max(0,$.line-3),V=Math.min(Z.length-1,$.line+2);q+=`Context:
`;for(let G=F;G<=V;G++){let Y=G+1,X=Z[G]||"",U=G===$.line-1?">":" ";q+=`${U} ${Y.toString().padStart(3)}: ${X}
`}if($.line-1<Z.length){let G=" ".repeat($.column+5);q+=`${G}^
`}return q}function nJ(J,Q,W){try{return J()}catch(Z){if(W&&Z instanceof Error)W(Z);return Q}}async function oJ(J,Q,W){try{return await J()}catch(Z){if(W&&Z instanceof Error)W(Z);return Q}}var XJ=j(()=>{P();h()});class l{errors=[];maxErrors;enableFileLogging;logFilePath;logFormat;maxFileSize;maxLogFiles;minLevel;writeQueue=Promise.resolve();constructor(J={}){this.maxErrors=J.maxErrors??1000,this.enableFileLogging=J.enableFileLogging??!1,this.logFilePath=J.logFilePath??".stx/errors.log",this.logFormat=J.logFormat??"json",this.maxFileSize=J.maxFileSize??10485760,this.maxLogFiles=J.maxLogFiles??5,this.minLevel=J.minLevel??"all"}configure(J){if(J.maxErrors!==void 0)this.maxErrors=J.maxErrors;if(J.enableFileLogging!==void 0)this.enableFileLogging=J.enableFileLogging;if(J.logFilePath!==void 0)this.logFilePath=J.logFilePath;if(J.logFormat!==void 0)this.logFormat=J.logFormat;if(J.maxFileSize!==void 0)this.maxFileSize=J.maxFileSize;if(J.maxLogFiles!==void 0)this.maxLogFiles=J.maxLogFiles;if(J.minLevel!==void 0)this.minLevel=J.minLevel}log(J,Q,W="error"){let Z={timestamp:new Date,error:J,context:Q,level:W};if(this.errors.push(Z),this.errors.length>this.maxErrors)this.errors=this.errors.slice(-this.maxErrors);if(this.enableFileLogging&&this.shouldLog(W))this.writeToFile(Z)}shouldLog(J){if(this.minLevel==="all")return!0;if(this.minLevel==="warning")return J==="error"||J==="warning";if(this.minLevel==="error")return J==="error";return!0}formatEntry(J){if(this.logFormat==="json")return JSON.stringify({timestamp:J.timestamp.toISOString(),level:J.level||"error",type:J.error.constructor.name,message:J.error.message,stack:J.error.stack,context:J.context});let Q=[`[${J.timestamp.toISOString()}] [${(J.level||"error").toUpperCase()}] ${J.error.constructor.name}: ${J.error.message}`];if(J.error.stack)Q.push(`  Stack: ${J.error.stack.split(`
`).slice(1).join(`
  `)}`);if(J.context)Q.push(`  Context: ${JSON.stringify(J.context)}`);return Q.join(`
`)}writeToFile(J){this.writeQueue=this.writeQueue.then(async()=>{try{let Q=await import("fs"),Z=(await import("path")).dirname(this.logFilePath);if(!Q.existsSync(Z))Q.mkdirSync(Z,{recursive:!0});await this.rotateIfNeeded(Q);let $=`${this.formatEntry(J)}
`;Q.appendFileSync(this.logFilePath,$,"utf-8")}catch(Q){if(process.env.STX_DEBUG==="true")console.error("Failed to write to error log:",Q)}})}async rotateIfNeeded(J){try{if(!J.existsSync(this.logFilePath))return;if(J.statSync(this.logFilePath).size<this.maxFileSize)return;for(let W=this.maxLogFiles-1;W>=1;W--){let Z=`${this.logFilePath}.${W}`,$=`${this.logFilePath}.${W+1}`;if(J.existsSync(Z))if(W>=this.maxLogFiles-1)J.unlinkSync(Z);else J.renameSync(Z,$)}if(this.maxLogFiles<=1)J.writeFileSync(this.logFilePath,"");else J.renameSync(this.logFilePath,`${this.logFilePath}.1`)}catch(Q){if(process.env.STX_DEBUG==="true")console.error("Failed to rotate error logs:",Q)}}getRecentErrors(J=10){return this.errors.slice(-J)}getErrorsByType(J){return this.errors.filter((Q)=>Q.error.constructor.name===J)}getErrorsByLevel(J){return this.errors.filter((Q)=>Q.level===J)}clear(){this.errors.length=0}async clearLogFile(){try{let J=await import("fs");if(J.existsSync(this.logFilePath))J.writeFileSync(this.logFilePath,"","utf-8")}catch(J){if(process.env.STX_DEBUG==="true")console.error("Failed to clear error log:",J)}}getStats(){let J={},Q={error:0,warning:0,info:0};for(let W of this.errors){let Z=W.error.constructor.name;J[Z]=(J[Z]||0)+1;let $=W.level||"error";Q[$]=(Q[$]||0)+1}return{total:this.errors.length,byType:J,byLevel:Q}}async exportToFile(J,Q="json"){let W=await import("fs"),$=(await import("path")).dirname(J);if(!W.existsSync($))W.mkdirSync($,{recursive:!0});if(Q==="json"){let q=this.errors.map((F)=>({timestamp:F.timestamp.toISOString(),level:F.level||"error",type:F.error.constructor.name,message:F.error.message,stack:F.error.stack,context:F.context}));W.writeFileSync(J,JSON.stringify(q,null,2),"utf-8")}else{let q=this.errors.map((F)=>this.formatEntry(F));W.writeFileSync(J,q.join(`

`),"utf-8")}}async flush(){await this.writeQueue}}var aJ,tJ,eJ;var BJ=j(()=>{h();aJ={isEnabled(){return v().enableAutoRecovery},fixCommonSyntaxErrors(J){let Q=v();if(!Q.enableAutoRecovery)return{fixed:J,fixes:[]};let W=J,Z=[],$=(W.match(/\{\{/g)||[]).length,q=(W.match(/\}\}/g)||[]).length;if($>q){let V=$-q;W+="}}".repeat(V),Z.push(`Added ${V} missing closing braces '}}'`)}let F=["if","foreach","for","switch","section"];for(let V of F){let G=(W.match(new RegExp(`@${V}\\b`,"g"))||[]).length,Y=(W.match(new RegExp(`@end${V}\\b`,"g"))||[]).length;if(G>Y){let X=G-Y;for(let U=0;U<X;U++)W+=`
@end${V}`;Z.push(`Added ${X} missing @end${V}`)}}if(Z.length>0&&Q.logRecoveryWarnings)console.warn("[stx] Auto-recovery applied fixes:"),Z.forEach((V)=>console.warn(`  - ${V}`)),console.warn("  Consider fixing these issues in your template.");return{fixed:W,fixes:Z}},createFallbackContent(J,Q){if(S())return`<!-- ${J} failed: ${Q.message} -->`;return"<!-- stx rendering error -->"}};tJ=new l,eJ={isDevelopment(){return S()},logDetailedError(J,Q){if(!this.isDevelopment())return;if(console.error("=== stx Detailed Error ==="),console.error("Error:",J.message),console.error("Stack:",J.stack),Q)console.error("Context:",Q);console.error("========================")},createErrorReport(J,Q){let W=["=== stx Error Report ===",`Time: ${new Date().toISOString()}`,`Error: ${J.message}`,`Type: ${J.constructor.name}`,`Stack: ${J.stack}`];if(Q)W.push(`Context: ${JSON.stringify(Q,null,2)}`);return W.push("========================"),W.join(`
`)}}});import s from"path";function JQ(J){let Q={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};return J.replace(/[&<>"']/g,(W)=>Q[W]||W)}function g(J,Q={}){let{allowHtml:W=!1,maxLength:Z=1e4,allowSpecialChars:$=!0,customSanitizer:q}=Q,F=[],V=J,G=!1;if(q){let X=q(V);if(X!==V)V=X,G=!0}if(V.includes("\x00"))V=V.replace(/\0/g,""),G=!0,F.push("Null bytes removed from parameter");if(V.length>Z)V=V.substring(0,Z),G=!0,F.push(`Parameter truncated to ${Z} characters`);if(!W&&/<[^>]+>/.test(V))V=JQ(V),G=!0,F.push("HTML content was escaped");let Y=[{pattern:/javascript:/gi,replacement:"",name:"javascript: URI"},{pattern:/vbscript:/gi,replacement:"",name:"vbscript: URI"},{pattern:/data:text\/html/gi,replacement:"",name:"data:text/html URI"}];for(let{pattern:X,replacement:U,name:_}of Y)if(X.test(V))V=V.replace(X,U),G=!0,F.push(`Removed ${_} from parameter`);if(!$){let X=V;if(V=V.split("").filter((U)=>{let _=U.charCodeAt(0);return _>=32&&_!==127}).join(""),V!==X)G=!0,F.push("Control characters removed")}return{value:V,modified:G,warnings:F}}function QQ(J,Q){let W=J.replace(/\0/g,"");W=W.replace(/\\/g,"/"),W=W.replace(/^[a-z][a-z0-9+.-]*:/i,"");while(W.includes("../")||W.includes("./"))W=W.replace(/\.\.\//g,"").replace(/\.\//g,"");if(!r.isValidFilePath(W,Q))return null;return W}function WQ(J){let Q=[],W=J.trim(),Z=W!==J,$=[{pattern:/\beval\s*\(/gi,name:"eval()"},{pattern:/\bFunction\s*\(/gi,name:"Function()"},{pattern:/\bsetTimeout\s*\(/gi,name:"setTimeout()"},{pattern:/\bsetInterval\s*\(/gi,name:"setInterval()"},{pattern:/\bimport\s*\(/gi,name:"dynamic import()"},{pattern:/\brequire\s*\(/gi,name:"require()"},{pattern:/\b__proto__\b/gi,name:"__proto__"},{pattern:/\bconstructor\b/gi,name:"constructor"},{pattern:/\bprototype\b/gi,name:"prototype"}];for(let{pattern:q,name:F}of $)if(q.test(W))Q.push(`Potentially dangerous pattern detected: ${F}`);if(W.includes("\x00"))W=W.replace(/\0/g,""),Z=!0,Q.push("Null bytes removed from expression");return{value:W,modified:Z,warnings:Q}}function ZQ(J,Q={}){return J.map((W)=>g(W,Q))}function UJ(J){let Q={};for(let[W,Z]of Object.entries(J)){if(!r.isValidVariableName(W))continue;if(typeof Z==="string"){let $=g(Z);Q[W]=$.value}else if(Array.isArray(Z))Q[W]=Z.map(($)=>typeof $==="string"?g($).value:$);else if(typeof Z==="object"&&Z!==null)Q[W]=UJ(Z);else Q[W]=Z}return Q}var r;var IJ=j(()=>{r={isValidFilePath(J,Q){let W=J.replace(/\\/g,"/");if(W.includes("\x00"))return!1;if(W.includes("../")||W.includes("..\\")||W===".."||W.startsWith("../")||W.endsWith("/..")||W.includes("/..\\")||W.includes("\\../"))return!1;if(/^[a-z][a-z0-9+.-]*:/i.test(W))return!1;if(W.startsWith("/")){if(["/etc/","/root/","/var/","/usr/","/bin/","/sbin/","/proc/","/sys/","/dev/","/boot/","/home/","/private/","/Library/","/System/"].some((q)=>W===q.slice(0,-1)||W.startsWith(q)))return!1}if(/^[a-z]:/i.test(W)){if(["Windows/","Windows\\","System32/","System32\\","Program Files/","Program Files\\"].some((q)=>W.includes(q)))return!1}if(Q){let $=s.resolve(Q,J),q=s.resolve(Q);if(!$.startsWith(q+s.sep)&&$!==q)return!1}return!0},isValidVariableName(J){return/^[a-z_$]\w*$/i.test(J)},isValidDirectiveName(J){return/^[a-z][\w-]*$/i.test(J)},isSafeContent(J){return![/<script[^>]*>[\s\S]*?<\/script>/i,/javascript:/i,/data:text\/html/i,/vbscript:/i,/on\w+\s*=/i].some((W)=>W.test(J))}}});var OJ=j(()=>{P();XJ();BJ();IJ();h()});var _J=j(()=>{OJ()});function sQ(J,Q,W,Z){let $=J;$=$.replace(/@meta\(\s*['"]([^'"]+)['"](?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(V,G,Y)=>{if(!Y&&G.includes(":")){let X=G.split(":"),U=G,_=X.length>1?X[1]:"";if(_&&Q[_])Y=Q[_];else if(U.startsWith("og:")&&Q.openGraph&&Q.openGraph[X[1]])Y=Q.openGraph[X[1]];else Y="";return Y?`<meta property="${I(U)}" content="${I(Y)}">`:""}return Y?`<meta name="${I(G)}" content="${I(Y)}">`:""});let q=/@metaTag\s*\(/g,F;while((F=q.exec($))!==null){let V=F.index,G=V+F[0].length-1,Y=1,X=G+1;while(X<$.length&&Y>0){if($[X]==="(")Y++;else if($[X]===")"){if(Y--,Y===0)break}X++}if(Y!==0)break;let U=$.substring(G+1,X).trim(),_=X+1,N=(()=>{try{let R=E(U,Q);if(!R)return"";let k="<meta";if(R.name)k+=` name="${I(String(R.name))}"`;if(R.property)k+=` property="${I(String(R.property))}"`;if(R.httpEquiv)k+=` http-equiv="${I(String(R.httpEquiv))}"`;if(R.content)k+=` content="${I(String(R.content))}"`;return k+=">",k}catch(R){let k=R instanceof Error?R.message:String(R);return w("MetaTag",k,K.EVALUATION_ERROR)}})();$=$.substring(0,V)+N+$.substring(_),q.lastIndex=0}return $}function rQ(J,Q,W){let Z=J,$=/@structuredData\s*\(/g,q;while((q=$.exec(Z))!==null){let F=q.index,V=F+q[0].length-1,G=1,Y=V+1;while(Y<Z.length&&G>0){if(Z[Y]==="(")G++;else if(Z[Y]===")"){if(G--,G===0)break}Y++}if(G!==0)break;let X=Z.substring(V+1,Y).trim(),U=Y+1,_=(()=>{try{let N=E(X,Q);if(!N)return"";if(!N["@context"])N["@context"]="https://schema.org";return`<script type="application/ld+json">${JSON.stringify(N).replace(/<\//g,"<\\/")}</script>`}catch(N){let R=N instanceof Error?N.message:String(N);return w("StructuredData",R,K.EVALUATION_ERROR)}})();Z=Z.substring(0,F)+_+Z.substring(U),$.lastIndex=0}return Z}function iQ(J,Q,W,Z){let $=J,q=/@seo\s*\(\s*\{/g,F;while((F=q.exec($))!==null){let V=$.indexOf("{",F.index+4),G=1,Y=V+1,X=null,U=!1;while(Y<$.length&&G>0){let A=$[Y];if(U){U=!1,Y++;continue}if(A==="\\"&&X){U=!0,Y++;continue}if(X){if(A===X)X=null;Y++;continue}if(A==='"'||A==="'"||A==="`"){X=A,Y++;continue}if(A==="{")G++;else if(A==="}")G--;Y++}if(G!==0)break;let _=$.substring(Y).match(/^\s*\)/);if(!_)break;let N=Y+_[0].length,R=$.substring(V,Y),k=$.substring(F.index,N),z=((A)=>{try{let B=E(A,Q);if(!B)return"";let M="";if(B.title)M+=`<title>${I(B.title)}</title>
`,M+=`<meta name="title" content="${I(B.title)}">
`;if(B.description)M+=`<meta name="description" content="${I(B.description)}">
`;if(B.keywords){let O=Array.isArray(B.keywords)?B.keywords.join(", "):B.keywords;M+=`<meta name="keywords" content="${I(O)}">
`}if(B.robots)M+=`<meta name="robots" content="${I(B.robots)}">
`;if(B.canonical)M+=`<link rel="canonical" href="${I(B.canonical)}">
`;if(B.openGraph){let O=B.openGraph;if(M+=`<meta property="og:type" content="${I(O.type||"website")}">
`,O.title||B.title){let D=O.title||B.title||"";M+=`<meta property="og:title" content="${I(D)}">
`}if(O.description||B.description){let D=O.description||B.description||"";M+=`<meta property="og:description" content="${I(D)}">
`}if(O.url||B.canonical){let D=O.url||B.canonical||"";M+=`<meta property="og:url" content="${I(D)}">
`}if(O.image){if(M+=`<meta property="og:image" content="${I(O.image)}">
`,O.imageAlt)M+=`<meta property="og:image:alt" content="${I(O.imageAlt)}">
`;if(O.imageWidth)M+=`<meta property="og:image:width" content="${I(String(O.imageWidth))}">
`;if(O.imageHeight)M+=`<meta property="og:image:height" content="${I(String(O.imageHeight))}">
`}if(O.siteName)M+=`<meta property="og:site_name" content="${I(O.siteName)}">
`}if(B.twitter){let O=B.twitter;if(M+=`<meta name="twitter:card" content="${I(O.card||"summary_large_image")}">
`,O.title||B.title){let D=O.title||B.title||"";M+=`<meta name="twitter:title" content="${I(D)}">
`}if(O.description||B.description){let D=O.description||B.description||"";M+=`<meta name="twitter:description" content="${I(D)}">
`}if(O.image||B.openGraph&&B.openGraph.image){let D=O.image||(B.openGraph?B.openGraph.image:"")||"";M+=`<meta name="twitter:image" content="${I(D)}">
`}if(O.site)M+=`<meta name="twitter:site" content="${I(O.site)}">
`;if(O.creator)M+=`<meta name="twitter:creator" content="${I(O.creator)}">
`}if(B.structuredData){let O=JSON.stringify(B.structuredData).replace(/<\//g,"<\\/");M+=`<script type="application/ld+json">${O}</script>
`}return M.trim()}catch(B){let M=B instanceof Error?B.message:String(B);return w("SEO",`Error processing @seo directive: ${M}`,K.EVALUATION_ERROR)}})(R);$=$.substring(0,F.index)+z+$.substring(N),q.lastIndex=F.index+z.length}return $}function nQ(J,Q,W){if(W.seo?.enabled===!1)return J;if(J.includes("<!-- stx SEO Tags -->")||W.skipDefaultSeoTags===!0)return J;let Z=Q.__stx_runtime_head;if(!!(Z?.title||Z?.meta?.some((U)=>U.property==="og:title"||U.name==="og:title"||U.name==="twitter:title"||U.name==="description")))return J;if(/<meta\s+(?:[^>]*\s)?property=["']og:title["']/i.test(J)||/<meta\s+(?:[^>]*\s)?name=["']og:title["']/i.test(J)||/<meta\s+(?:[^>]*\s)?name=["']twitter:title["']/i.test(J))return J;if(!J.includes("<head>")&&!J.includes("<head "))return J;let q=J.includes("<title>")||J.includes("</title>"),F="";if(Q.title)F=Q.title;else if(Q.meta&&Q.meta.title)F=Q.meta.title;else if(W.seo?.defaultConfig?.title)F=W.seo.defaultConfig.title;else F=W.defaultTitle||"stx Project";let V="";if(Q.description)V=Q.description;else if(Q.meta&&Q.meta.description)V=Q.meta.description;else if(W.seo?.defaultConfig?.description)V=W.seo.defaultConfig.description;else V=W.defaultDescription||"A website built with stx templating engine";let G="";if(Q.image)G=Q.image;else if(Q.meta&&Q.meta.image)G=Q.meta.image;else if(Q.openGraph&&Q.openGraph.image)G=Q.openGraph.image;else if(W.seo?.defaultImage)G=W.seo.defaultImage;else if(W.defaultImage)G=W.defaultImage;let Y=`
<!-- stx SEO Tags -->
<meta name="title" content="${I(F)}">
<meta name="description" content="${I(V)}">
<meta property="og:title" content="${I(F)}">
<meta property="og:description" content="${I(V)}">
<meta property="og:type" content="website">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="${I(F)}">
<meta name="twitter:description" content="${I(V)}">
`;if(G)Y+=`
<meta property="og:image" content="${I(G)}">
<meta name="twitter:image" content="${I(G)}">
`;let X=J;if(!q)X=X.replace(/<head[^>]*>/,`$&
<title>${I(F)}</title>`);return X.replace(/<head[^>]*>/,`$&
${Y}
`)}function I(J){return J.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function oQ(){return[$Q,qQ]}function aQ(J,Q){let{baseUrl:W,defaultChangefreq:Z="weekly",defaultPriority:$=0.5,includeLastmod:q=!0}=Q,F=W.replace(/\/$/,"");return`<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${J.map((G)=>{let Y=G.loc.startsWith("http")?G.loc:`${F}${G.loc.startsWith("/")?"":"/"}${G.loc}`,X=G.lastmod||(q?new Date().toISOString().split("T")[0]:void 0),U=G.changefreq||Z,_=G.priority??$,N=`  <url>
    <loc>${MJ(Y)}</loc>`;if(X)N+=`
    <lastmod>${X}</lastmod>`;return N+=`
    <changefreq>${U}</changefreq>`,N+=`
    <priority>${_.toFixed(1)}</priority>`,N+=`
  </url>`,N}).join(`
`)}
</urlset>`}function tQ(J,Q){let W=Q.replace(/\/$/,""),Z=new Date().toISOString().split("T")[0];return`<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${J.map((q)=>{let F=q.startsWith("http")?q:`${W}${q.startsWith("/")?"":"/"}${q}`;return`  <sitemap>
    <loc>${MJ(F)}</loc>
    <lastmod>${Z}</lastmod>
  </sitemap>`}).join(`
`)}
</sitemapindex>`}async function eQ(J,Q){let{extensions:W=[".stx",".html",".htm"],ignore:Z=["_*",".*","node_modules","components","partials","layouts"]}=Q,$=[],q=W.length===1?`*${W[0]}`:`*{${W.join(",")}}`,F=new Bun.Glob(`**/${q}`);for await(let V of F.scan(J)){if(Z.some((_)=>{if(_.startsWith("*"))return V.includes(_.slice(1));return V.startsWith(_)||V.includes(`/${_}`)}))continue;let Y=V.replace(/\\/g,"/").replace(/index\.(stx|html|htm)$/,"").replace(/\.(stx|html|htm)$/,"");if(!Y.startsWith("/"))Y=`/${Y}`;if(Y!=="/"&&Y.endsWith("/"))Y=Y.slice(0,-1);let X=`${J}/${V}`,U;try{let _=await Bun.file(X).stat();if(_)U=new Date(_.mtime).toISOString().split("T")[0]}catch{}$.push({loc:Y||"/",lastmod:U,priority:Y==="/"?1:0.5})}return $.sort((V,G)=>V.loc.localeCompare(G.loc)),$}function VQ(J){let Q=[];for(let W of J.rules){if(Q.push(`User-agent: ${W.userAgent}`),W.allow)for(let Z of W.allow)Q.push(`Allow: ${Z}`);if(W.disallow)for(let Z of W.disallow)Q.push(`Disallow: ${Z}`);if(W.crawlDelay!==void 0)Q.push(`Crawl-delay: ${W.crawlDelay}`);Q.push("")}if(J.sitemap){let W=Array.isArray(J.sitemap)?J.sitemap:[J.sitemap];for(let Z of W)Q.push(`Sitemap: ${Z}`)}if(J.host)Q.push(`Host: ${J.host}`);return Q.join(`
`).trim()}function JW(J){return VQ({rules:[{userAgent:"*",allow:["/"]}],sitemap:J})}function MJ(J){return J.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var $Q,qQ;var YQ=j(()=>{_J();e();$Q={name:"meta",handler:(J,Q,W,Z)=>{if(Q.length<1)return w("Meta","meta directive requires at least the meta name",K.INVALID_DIRECTIVE_SYNTAX);let $=Q[0].replace(/['"]/g,""),q=Q.length>1?Q[1].replace(/['"]/g,""):"";return`<meta name="${I($)}" content="${I(q)}">`},hasEndTag:!1},qQ={name:"structuredData",handler:(J,Q,W,Z)=>{if(J.trim()==="")return w("StructuredData","structuredData directive requires JSON-LD content",K.INVALID_DIRECTIVE_SYNTAX);try{let $=JSON.parse(J);if(!$["@context"])$["@context"]="https://schema.org";if(!$["@type"])return w("StructuredData","structuredData requires @type property",K.INVALID_DIRECTIVE_SYNTAX);return`<script type="application/ld+json">${JSON.stringify($)}</script>`}catch($){let q=$ instanceof Error?$.message:String($);return w("StructuredData",q,K.EVALUATION_ERROR)}},hasEndTag:!0}});YQ();export{qQ as structuredDataDirective,eQ as scanForSitemapEntries,oQ as registerSeoDirectives,rQ as processStructuredData,iQ as processSeoDirective,sQ as processMetaDirectives,$Q as metaDirective,nQ as injectSeoTags,tQ as generateSitemapIndex,aQ as generateSitemap,VQ as generateRobotsTxt,JW as generateDefaultRobotsTxt};
