@stacksjs/stx 0.2.341 → 0.2.342
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/build-views.js +12 -1
- package/dist/{chunk-3tjqjpwb.js → chunk-4ecv1e3w.js} +1 -1
- package/dist/{chunk-vfggb00k.js → chunk-4vcyf1kh.js} +1 -1
- package/dist/{chunk-0abjpkv7.js → chunk-567g1ttv.js} +1 -1
- package/dist/{chunk-ejj7qbzd.js → chunk-exhbc57n.js} +1 -1
- package/dist/{chunk-d8cng4x9.js → chunk-k9ep24bd.js} +1 -1
- package/dist/{chunk-m3b6kx1j.js → chunk-ks4j8fjz.js} +1 -1
- package/dist/{chunk-5qr420a9.js → chunk-ntm1761b.js} +47 -47
- package/dist/{chunk-v3yh931q.js → chunk-zv4gb3wb.js} +1 -1
- package/dist/{chunk-trfx00jf.js → chunk-zx2krbqf.js} +1 -1
- package/dist/cli.js +3 -3
- package/package.json +5 -5
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Xe as F$}from"./chunk-
|
|
2
|
+
import{Xe as F$}from"./chunk-567g1ttv.js";import{Yf as u7,ag as z$,bg as h6,cg as E6,eg as B1,fg as d6,gg as J5,hg as H$,ig as O$,jg as u6,kg as m6,og as B5}from"./chunk-4vcyf1kh.js";import{aj as f5}from"./chunk-saqbtgqr.js";import{qj as l1,rj as I1,sj as R1,tj as i$,uj as a$,vj as a5,xj as r5}from"./chunk-e4g8wz6t.js";import{Uj as K$,Vj as _$}from"./chunk-czvzaa42.js";import{wk as m5,xk as p5}from"./chunk-byjy9far.js";import{Dk as o7,Ek as t7}from"./chunk-c0n802j1.js";import{Yk as U1}from"./chunk-4wpxbkbe.js";import{rl as A5,sl as U8}from"./chunk-gbkq5qnw.js";import{Am as n0,Ar as T0,Lo as M0,Np as V0,Sm as y6,Vl as O8,Vo as o0,Wm as G5,Zm as T1,_m as C1,bo as W$,gr as U$,jp as p7,kq as G6,lq as x1,mm as d7,mo as j$,oo as v6,po as A6,pq as t0,qp as g6,rp as f6,tr as T$,vr as s0,wr as w0}from"./chunk-j82hfkcf.js";import{$s as B,Hs as Z5,gt as B$,ht as L$,lt as J0}from"./chunk-xe93ae3r.js";import{qt as u0}from"./chunk-1spzqjve.js";import{Au as G$,Bu as O6,Mu as J6,du as r1,gu as H6,ou as e$,qu as $5,tu as s1,xu as X5}from"./chunk-bt8w146r.js";import{Iv as Y5,Jv as M6,Nv as D6,Ov as w6,bw as T6,cw as C6,dw as k6,ew as x6,fw as S6,gw as P6,iw as b6,nw as V6}from"./chunk-beextc84.js";import{xw as r}from"./chunk-p5d8sb50.js";var s5={read:($)=>{try{return JSON.parse($)}catch{return $}},write:($)=>{return JSON.stringify($)}};function J3($,X,Z={}){let{storage:Q="local",serializer:Y=s5,mergeDefaults:J=!1,listenToStorageChanges:G=!0}=Z,W=new Set,K=typeof window<"u",_=()=>{if(!K)return null;return Q==="session"?sessionStorage:localStorage},U=()=>{let L=_();if(!L)return X;try{let O=L.getItem($);if(O===null)return X;let A=Y.read(O);if(J&&typeof X==="object"&&X!==null)return{...X,...A};return A}catch{return X}},F=(L)=>{let O=_();if(!O)return;try{if(L===null||L===void 0)O.removeItem($);else O.setItem($,Y.write(L))}catch(A){console.warn(`[useStorage] Failed to write key "${$}":`,A)}},z=U(),j=(L,O)=>{for(let A of W)try{A(L,O)}catch(V){console.error("[useStorage] Subscriber error:",V)}};if(K&&G){let L=(A)=>{if(A.key===$&&A.storageArea===_()){let V=z;try{z=A.newValue?Y.read(A.newValue):X}catch(E){console.warn(`[useStorage] Failed to read key "${$}" from a cross-tab update:`,E);return}j(z,V)}};window.addEventListener("storage",L);let O=globalThis.onDestroy;if(typeof O==="function")O(()=>window.removeEventListener("storage",L))}let H={get value(){return z},set value(L){let O=z;z=L,F(L),j(L,O)},get:()=>z,set:(L)=>{H.value=L},remove:()=>{let L=_();if(L){L.removeItem($);let O=z;z=X,j(X,O)}},subscribe:(L)=>{return W.add(L),L(z,void 0),()=>W.delete(L)}};return H}function n5($,X,Z,Q,Y={}){let{serializer:J=s5,mergeDefaults:G=!1,listenToStorageChanges:W=!0}=Y,K=typeof window<"u",_=()=>{if(!K)return null;return $==="session"?sessionStorage:localStorage},U=(j)=>{if(j===null||j===void 0)return Q;try{let H=J.read(j);if(G&&typeof Q==="object"&&Q!==null)return{...Q,...H};return H}catch(H){return console.warn(`[${X}] Failed to read key "${Z}":`,H),Q}},z=a5((()=>{let j=_();if(!j)return Q;try{return U(j.getItem(Z))}catch(H){return console.warn(`[${X}] Cannot read "${Z}":`,H),Q}})());if(r5(()=>{let j=z(),H=_();if(!H)return;try{if(j===null||j===void 0)H.removeItem(Z);else H.setItem(Z,J.write(j))}catch(L){console.warn(`[${X}] Cannot persist "${Z}":`,L)}}),K&&W){let j=(L)=>{if(L.key!==Z)return;if(L.storageArea&&L.storageArea!==_())return;z.set(U(L.newValue))};window.addEventListener("storage",j);let H=globalThis.onDestroy;if(typeof H==="function")H(()=>window.removeEventListener("storage",j))}return z}function G3($,X,Z){return n5("local","useLocalStorage",$,X,Z)}function W3($,X,Z){return n5("session","useSessionStorage",$,X,Z)}function K3($="local"){if(typeof window>"u")return;($==="session"?sessionStorage:localStorage).clear()}function _3($="local"){if(typeof window>"u")return[];let X=$==="session"?sessionStorage:localStorage;return Object.keys(X)}function U3($="local"){if(typeof window>"u")return 0;let X=$==="session"?sessionStorage:localStorage,Z=0;for(let Q in X)if(Object.prototype.hasOwnProperty.call(X,Q))Z+=(Q.length+(X.getItem(Q)?.length||0))*2;return Z}var t=null;function c1($,X,Z=new WeakSet){if(Object.is($,X))return!0;if(typeof $!=="object"||typeof X!=="object"||$===null||X===null)return!1;if(Z.has($))return!0;if(Z.add($),$ instanceof Date&&X instanceof Date)return $.getTime()===X.getTime();if($ instanceof RegExp&&X instanceof RegExp)return $.source===X.source&&$.flags===X.flags;if(Array.isArray($)){if(!Array.isArray(X)||$.length!==X.length)return!1;for(let J=0;J<$.length;J++)if(!c1($[J],X[J],Z))return!1;return!0}if(Array.isArray(X))return!1;if($ instanceof Map){if(!(X instanceof Map)||$.size!==X.size)return!1;for(let[J,G]of $)if(!X.has(J)||!c1(G,X.get(J),Z))return!1;return!0}if(X instanceof Map)return!1;if($ instanceof Set){if(!(X instanceof Set)||$.size!==X.size)return!1;for(let J of $)if(!X.has(J))return!1;return!0}if(X instanceof Set)return!1;let Q=Object.keys($),Y=Object.keys(X);if(Q.length!==Y.length)return!1;for(let J of Q){if(!Object.prototype.hasOwnProperty.call(X,J))return!1;if(!c1($[J],X[J],Z))return!1}return!0}function YJ($){t=$}function JJ(){return t}function GJ(){return{isMounted:!1,isUnmounted:!1,hooks:{beforeMount:[],mounted:[],beforeUpdate:[],updated:[],beforeUnmount:[],unmounted:[]},effects:[],scope:B3()}}function B3(){return{refs:new Map,effects:new Set,cleanups:[]}}function WJ($){let X=new Set,Z=new Set,Q=$,Y=Symbol("ref"),J={get value(){let G=l1();if(G)Z.add(G);return Q},set value(G){if(!Object.is(G,Q)){let W=Q;Q=G;for(let K of X)K(G,W);for(let K of Z)if(i$())a$(K);else K()}},subscribe(G){return X.add(G),()=>{X.delete(G)}}};if(t)t.scope.refs.set(Y,J);return J}var o5=new WeakMap;function L3($){let X=o5.get($);if(X)return X;let Z=new Map,Q=(G)=>{let W=Z.get(G);if(!W)return;for(let K of[...W])if(i$())a$(K);else K()},Y=(G,W)=>{if(!Z.has(G))Z.set(G,new Set);return Z.get(G).add(W),()=>{Z.get(G)?.delete(W)}},J=new Proxy($,{get(G,W,K){let _=Reflect.get(G,W,K),U=l1();if(U)Y(W,U);if(_!==null&&typeof _==="object"&&!Array.isArray(_)){let F=Object.getPrototypeOf(_);if(F===Object.prototype||F===null)return L3(_)}return _},set(G,W,K,_){let U=Reflect.get(G,W,_),F=Reflect.set(G,W,K,_);if(!Object.is(K,U))Q(W);return F},deleteProperty(G,W){let K=Reflect.deleteProperty(G,W);return Q(W),K}});return o5.set($,J),J}function KJ($){let X,Z=!0,Q=new Set,Y=new Set,J=()=>{Z=!0,G()},G=()=>{if(Z){let K=X,_=I1(J);if(X=$(),R1(_),Z=!1,!Object.is(X,K)){for(let U of Q)U(X,K);for(let U of Y)U()}}},W=I1(J);return X=$(),Z=!1,R1(W),{get value(){let K=l1();if(K)Y.add(K);return G(),X},set value(K){console.warn("[stx] Computed properties are readonly")},subscribe(K){return Q.add(K),()=>{Q.delete(K)}}}}function F3($){if(typeof requestAnimationFrame==="function"){requestAnimationFrame(()=>{requestAnimationFrame($)});return}setTimeout($,0)}function _J($,X,Z={}){let{immediate:Q=!1,deep:Y=!1,flush:J="post"}=Z,G,W,K=!1,_=()=>{if(K)return;let H=j();if((Y?!c1(H,G):!Object.is(H,G))||Q)if(X(H,G),Y&&H!==null&&typeof H==="object")try{G=structuredClone(H)}catch{G=H}else G=H},U=(H)=>{if(J==="sync")H();else if(J==="pre")Promise.resolve().then(H);else F3(H)},F=!1,z=()=>{if(K||F)return;F=!0,U(()=>{F=!1,_()})},j=()=>{if(typeof $==="function"){let H=I1(z);try{return $()}finally{R1(H)}}return $.value};if(typeof $!=="function"){let H=$.subscribe(()=>{U(_)});W=()=>{K=!0,H()}}else W=()=>{K=!0};if(G=j(),Q)U(_);if(t)t.scope.cleanups.push(()=>W?.());return()=>W?.()}function UJ($,X,Z={}){let Q=[],Y=$.map((J)=>J.value);for(let J of $){let G=J.subscribe(()=>{let W=$.map((K)=>K.value);X(W,Y),Y=[...W]});Q.push(G)}if(Z.immediate){let J=$.map((G)=>G.value);X(J,Y)}return()=>{for(let J of Q)J()}}function BJ($){let X,Z=!1,Q=()=>{if(Z)return;if(X)X();let Y=I1(Q);X=$(),R1(Y)};if(Q(),t)t.scope.cleanups.push(()=>{if(Z=!0,X)X()});return()=>{if(Z=!0,X)X()}}function LJ($){if(t)t.hooks.beforeMount.push($);else console.warn("[stx] onBeforeMount called outside of component setup")}function FJ($){if(t)t.hooks.mounted.push($);else console.warn("[stx] onMounted called outside of component setup")}function zJ($){if(t)t.hooks.beforeUpdate.push($);else console.warn("[stx] onBeforeUpdate called outside of component setup")}function jJ($){if(t)t.hooks.updated.push($);else console.warn("[stx] onUpdated called outside of component setup")}function HJ($){if(t)t.hooks.beforeUnmount.push($);else console.warn("[stx] onBeforeUnmount called outside of component setup")}function OJ($){if(t)t.hooks.unmounted.push($);else console.warn("[stx] onUnmounted called outside of component setup")}async function Y1($,X){let Z=$.hooks[X];for(let Q of Z)await Q()}async function AJ($){await Y1($,"beforeMount"),$.isMounted=!0,await Y1($,"mounted")}async function qJ($){if(!$.isMounted||$.isUnmounted)return;await Y1($,"beforeUpdate"),await Y1($,"updated")}async function NJ($){if($.isUnmounted)return;await Y1($,"beforeUnmount");for(let X of $.scope.cleanups)X();$.isUnmounted=!0,await Y1($,"unmounted")}function MJ(){return`
|
|
3
3
|
<script data-stx-client-runtime>
|
|
4
4
|
(function() {
|
|
5
5
|
'use strict';
|
|
@@ -178,10 +178,10 @@ import{Xe as F$}from"./chunk-0abjpkv7.js";import{Yf as u7,ag as z$,bg as h6,cg a
|
|
|
178
178
|
});
|
|
179
179
|
window.provide = provide;
|
|
180
180
|
})();
|
|
181
|
-
</script>`}function J1($,X){if(typeof window>"u")return X;return window[$]??X}function i1($,X){if(typeof window>"u")return;window[$]=X}function t5($){let Z=J1("__STX_STORES__",{})[$];if(!Z)throw Error(`Store "${$}" not found. Make sure it's defined with defineStore().`);return Z}function
|
|
181
|
+
</script>`}function J1($,X){if(typeof window>"u")return X;return window[$]??X}function i1($,X){if(typeof window>"u")return;window[$]=X}function t5($){let Z=J1("__STX_STORES__",{})[$];if(!Z)throw Error(`Store "${$}" not found. Make sure it's defined with defineStore().`);return Z}function EJ($){return t5($)}function IJ($,X=5000){return new Promise((Z,Q)=>{let Y=Date.now(),J=()=>{let G=t5($);if(G)Z(G);else if(Date.now()-Y>X)Q(Error(`Timeout waiting for store "${$}"`));else requestAnimationFrame(J)};J()})}function z3(){return J1("__STX_ROUTE_PARAMS__",{})}function j3($){return z3()[$]}function RJ($){let X=j3($);if(X===void 0)throw Error(`Route parameter "${$}" not found`);return X}function H3(){return J1("__STX_MIDDLEWARE_STATE__",{})}function DJ($){return H3()[$]}function wJ(){if(typeof window>"u")return;if(!J1("__STX_STORES__",null))i1("__STX_STORES__",{})}function TJ($,X){let Z=J1("__STX_STORES__",{});Z[$]=X,i1("__STX_STORES__",Z)}function CJ(){return J1("__STX_STORE_STATE__",null)}function kJ($){i1("__STX_ROUTE_PARAMS__",$)}function xJ($){i1("__STX_MIDDLEWARE_STATE__",$)}function O3(){return typeof window>"u"}function A3(){return typeof window<"u"}function SJ($){if(A3())$()}function PJ($){if(O3())$()}async function q3($){try{let X=await Bun.file($).text(),Z=N3(X),Q=M3(X,$),Y=V3(X,Z),J=E3(X,Z);return{file:$,metrics:Z,issues:Q,suggestions:Y,performance:J}}catch(X){throw Error(`Failed to analyze template ${$}: ${X instanceof Error?X.message:String(X)}`)}}function N3($){let X=$.split(`
|
|
182
182
|
`),Z=$.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),Y=(Z?Z[1]:"").split(`
|
|
183
183
|
`).length,J={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};J.total=J.conditionals+J.loops+J.includes+J.custom;let G=($.match(/\{\{[\s\S]*?\}\}/g)||[]).length,W=($.match(/\{!![\s\S]*?!!\}/g)||[]).length,K=($.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,_=G+W+K,U=($.match(/<[A-Z][^>]*>/g)||[]).length,F=($.match(/@(?:layout|extends)\(/g)||[]).length,z=0,j=0;for(let O of X)if(/@(?:if|unless|foreach|for|while|section)\b/.test(O)&&!/@end/.test(O)&&!/@else/.test(O))j++,z=Math.max(z,j);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(O))j--;let H=z>=4?3:0,L=Math.min(10,Math.ceil(J.total*0.5+_*0.1+U*0.3+(Y>10?Y*0.05:0)+H));return{lines:X.length,characters:$.length,directives:J,expressions:_,components:U,layouts:F,scriptLines:Y,complexity:L}}function M3($,X){let Z=[],Q=e5($,"if","endif");if(Q>0)Z.push({type:"error",category:"syntax",message:`Found ${Q} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let Y=e5($,"foreach","endforeach");if(Y>0)Z.push({type:"error",category:"syntax",message:`Found ${Y} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let J=$.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(J&&J.length>0)Z.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)Z.push({type:"warning",category:"security",message:`Found ${G} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let W=$.match(/<img[^>]*>/g);if(W){let U=W.filter((F)=>!F.includes("alt="));if(U.length>0)Z.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 K=$.split(`
|
|
184
|
-
`).filter((U)=>U.length>120);if(K.length>0)Z.push({type:"info",category:"maintainability",message:`Found ${K.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let _=($.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(_>3)Z.push({type:"info",category:"maintainability",message:`Found ${_} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return Z}function V3($,X){let Z=[];if(X.complexity>7)Z.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(X.complexity>5&&X.directives.total>8)Z.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(X.lines>100&&X.components===0)Z.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(X.expressions>20)Z.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let Q=$.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(Q&&Q.length>0)Z.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(X.directives.total===0&&X.expressions<5)Z.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(X.scriptLines>50)Z.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return Z}function E3($,X){let Z=1;if(Z+=X.directives.conditionals*0.1,Z+=X.directives.loops*0.5,Z+=X.directives.includes*2,Z+=X.expressions*0.05,Z+=X.components*1,X.scriptLines>10)Z+=X.scriptLines*0.1;let Q;if(X.expressions===0&&X.directives.total===0)Q="high";else if(X.expressions<5&&X.directives.total<3)Q="medium";else Q="low";let Y=[];if(Z>10)Y.push("Consider optimizing template complexity");if(Q==="low"&&X.directives.total>5)Y.push("Reduce dynamic content for better caching");if(X.components===0&&X.lines>40)Y.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(Z*100)/100,complexityScore:X.complexity,cacheability:Q,recommendations:Y}}function e5($,X,Z){let Q=$.replace(/<!--[\s\S]*?-->/g,""),Y=(Q.match(new RegExp(`@${X}\\b`,"g"))||[]).length,J=(Q.match(new RegExp(`@${Z}\\b`,"g"))||[]).length;return Math.abs(Y-J)}async function
|
|
184
|
+
`).filter((U)=>U.length>120);if(K.length>0)Z.push({type:"info",category:"maintainability",message:`Found ${K.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let _=($.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(_>3)Z.push({type:"info",category:"maintainability",message:`Found ${_} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return Z}function V3($,X){let Z=[];if(X.complexity>7)Z.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(X.complexity>5&&X.directives.total>8)Z.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(X.lines>100&&X.components===0)Z.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(X.expressions>20)Z.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let Q=$.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(Q&&Q.length>0)Z.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(X.directives.total===0&&X.expressions<5)Z.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(X.scriptLines>50)Z.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return Z}function E3($,X){let Z=1;if(Z+=X.directives.conditionals*0.1,Z+=X.directives.loops*0.5,Z+=X.directives.includes*2,Z+=X.expressions*0.05,Z+=X.components*1,X.scriptLines>10)Z+=X.scriptLines*0.1;let Q;if(X.expressions===0&&X.directives.total===0)Q="high";else if(X.expressions<5&&X.directives.total<3)Q="medium";else Q="low";let Y=[];if(Z>10)Y.push("Consider optimizing template complexity");if(Q==="low"&&X.directives.total>5)Y.push("Reduce dynamic content for better caching");if(X.components===0&&X.lines>40)Y.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(Z*100)/100,complexityScore:X.complexity,cacheability:Q,recommendations:Y}}function e5($,X,Z){let Q=$.replace(/<!--[\s\S]*?-->/g,""),Y=(Q.match(new RegExp(`@${X}\\b`,"g"))||[]).length,J=(Q.match(new RegExp(`@${Z}\\b`,"g"))||[]).length;return Math.abs(Y-J)}async function yJ($=["**/*.stx"],X){let Z=[],Q=[];for(let J of $){let G=await Array.fromAsync(new Bun.Glob(J).scan({cwd:X||process.cwd(),onlyFiles:!0,absolute:!0}));Q.push(...G.filter((W)=>W.endsWith(".stx")))}for(let J of Q)try{let G=await q3(J);Z.push(G)}catch(G){console.warn(`Failed to analyze ${J}:`,G)}let Y=I3(Z);return{results:Z,summary:Y}}function I3($){let X=$.length,Z=$.reduce((_,U)=>_+U.metrics.lines,0),Q=X>0?$.reduce((_,U)=>_+U.metrics.complexity,0)/X:0,Y=$.reduce((_,U)=>_+U.issues.length,0),J={};$.forEach((_)=>{_.issues.forEach((U)=>{J[U.category]=(J[U.category]||0)+1})});let G=X>0?$.reduce((_,U)=>_+U.performance.estimatedRenderTime,0)/X:0,W=Math.max(1,Math.min(10,Math.round(10-G/2-Q/2))),K=[];if(Q>6)K.push("Project has high average complexity. Consider refactoring complex templates.");if(Y>X*2)K.push("High number of issues detected. Run detailed analysis on individual files.");if(J.security>0)K.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:X,totalLines:Z,avgComplexity:Math.round(Q*100)/100,totalIssues:Y,issuesByCategory:J,performanceScore:W,recommendations:K}}import a1 from"path";var $6=/<script\b[^>]*\bserver\b/i,R3=/<script\b[^>]*\bclient\b/i;async function hJ($){let X=performance.now(),Z=await s0($),Q=$||Z.root||process.cwd(),Y=[Z.build?.pagesDir||Z.pagesDir||"pages",Z.componentsDir||"components",Z.layoutsDir||"layouts",Z.partialsDir||"partials"].map((W)=>a1.resolve(Q,W)),J=[],G=0;for(let W of Y){let K=await X6(W);for(let _ of K){G++;let U=await Bun.file(_).text();if($6.test(U))J.push(a1.relative(Q,_))}}return{mode:J.length>0?"ssr":"ssg",serverScriptFiles:J,totalFilesScanned:G,scanDurationMs:Math.round(performance.now()-X)}}async function dJ($){let X=await s0($),Z=$||X.root||process.cwd(),Q=a1.resolve(Z,X.componentsDir||"components"),Y=[],J=await X6(Q);for(let G of J){let W=await Bun.file(G).text(),K=$6.test(W),_=R3.test(W)||/<script\b(?![^>]*\bserver\b)[^>]*>/i.test(W)&&!K;if(K&&_){let U=a1.relative(Z,G);Y.push({file:U,message:`Component "${U}" has both <script server> and <script client>. `+"Components should be server OR client \u2014 compose them via props/slots."})}}return Y}async function X6($){let X=[];try{let Z=new Bun.Glob("**/*.stx");for await(let Q of Z.scan({cwd:$,absolute:!0}))X.push(Q)}catch{}return X}var Z6={treeShake:!0,deadCodeElimination:!0,constantFolding:!0,stringPooling:!1,minifyHtml:!0,removeDevCode:!0,constants:{},preserveDirectives:[],target:"production"},Q6=["if","else","elseif","endif","unless","endunless","switch","case","default","endswitch","for","endfor","foreach","endforeach","forelse","endforelse","while","endwhile","break","continue","empty","extends","section","endsection","yield","parent","include","includeIf","includeWhen","includeFirst","once","endonce","push","endpush","prepend","endprepend","stack","component","endcomponent","slot","endslot","props","auth","endauth","guest","endguest","can","endcan","cannot","endcannot","role","endrole","hasRole","endhasRole","hasAnyRole","endhasAnyRole","csrf","method","error","enderror","old","input","textarea","select","checkbox","radio","file","translate","lang","choice","meta","title","seo","jsonld","canonical","robots","sitemap","ts","endts","js","endjs","css","endcss","markdown","endmarkdown","verbatim","endverbatim","env","production","debug","isset","endisset","empty","endempty"];function Y6($){let X=new Map,Z=/@(\w+)/g,Q,Y=1,J=0;while((Q=Z.exec($))!==null){let G=Q[1],W=$.slice(J,Q.index);Y+=(W.match(/\n/g)||[]).length,J=Q.index;let K=Q.index-$.lastIndexOf(`
|
|
185
185
|
`,Q.index-1);if(Q6.includes(G)){let _=X.get(G);if(_)_.count++,_.locations.push({line:Y,column:K});else X.set(G,{name:G,count:1,locations:[{line:Y,column:K}]})}}return Array.from(X.values())}function D3($,X=[]){let Z=Y6($),Q=new Set(Z.map((Y)=>Y.name));for(let Y of X)Q.add(Y);for(let Y of Array.from(Q))if(!Y.startsWith("end"))Q.add(`end${Y}`);return Q6.filter((Y)=>!Q.has(Y))}function w3($){let X=[],Z={conditionals:["if","else","elseif","endif","unless","endunless","switch","case","default","endswitch","isset","endisset"],loops:["for","endfor","foreach","endforeach","forelse","endforelse","while","endwhile","break","continue","empty"],includes:["include","includeIf","includeWhen","includeFirst","once","endonce","extends","section","endsection","yield","parent","push","endpush","prepend","endprepend","stack"],components:["component","endcomponent","slot","endslot","props"],auth:["auth","endauth","guest","endguest","can","endcan","cannot","endcannot","role","endrole","hasRole","endhasRole","hasAnyRole","endhasAnyRole"],forms:["csrf","method","error","enderror","old","input","textarea","select","checkbox","radio","file"],i18n:["translate","lang","choice"],seo:["meta","title","seo","jsonld","canonical","robots","sitemap"]},Q=new Set;for(let J of $)for(let[G,W]of Object.entries(Z))if(W.includes(J)){Q.add(G);break}for(let J of Q)X.push(`import { process${b3(J)} } from './${J}'`);let Y=$.filter((J)=>!J.startsWith("end")).map((J)=>` '${J}': true`).join(`,
|
|
186
186
|
`);return`// Tree-shaken directive bundle
|
|
187
187
|
// Only includes: ${$.join(", ")}
|
|
@@ -195,7 +195,7 @@ ${Y}
|
|
|
195
195
|
export function isDirectiveActive(name: string): boolean {
|
|
196
196
|
return name in activeDirectives
|
|
197
197
|
}
|
|
198
|
-
`}function T3($,X={}){let Z=[],Q=/@if\(([^)]+)\)[\s\S]*?@endif/g,Y=$.matchAll(Q);for(let _ of Y){let U=_[1].trim();if(r$(U,X)===!1)Z.push({start:_.index,end:_.index+_[0].length,reason:`@if condition always false: ${U}`})}let J=/@unless\(([^)]+)\)[\s\S]*?@endunless/g,G=$.matchAll(J);for(let _ of G){let U=_[1].trim();if(r$(U,X)===!0)Z.push({start:_.index,end:_.index+_[0].length,reason:`@unless condition always true: ${U}`})}let W=/@env\(['"]development['"]\)[\s\S]*?@endenv/g;if(X.__ENV__==="production"){let _=$.matchAll(W);for(let U of _)Z.push({start:U.index,end:U.index+U[0].length,reason:"Development-only code in production build"})}let K=/@debug[\s\S]*?@enddebug/g;if(X.__ENV__==="production"){let _=$.matchAll(K);for(let U of _)Z.push({start:U.index,end:U.index+U[0].length,reason:"Debug code in production build"})}return Z}function C3($,X={}){let Z=T3($,X),Q=[];Z.sort((J,G)=>G.start-J.start);let Y=$;for(let J of Z)Y=Y.slice(0,J.start)+Y.slice(J.end),Q.push(J.reason);return{content:Y,removed:Q}}function r$($,X){if($==="true")return!0;if($==="false")return!1;if($==="null")return null;if(/^\d+$/.test($))return Number.parseInt($,10);if(/^\d+\.\d+$/.test($))return Number.parseFloat($);if(/^['"].*['"]$/.test($))return $.slice(1,-1);if($ in X)return X[$];let Z=$.match(/^(\w+)\s*(===|!==|==|!=|>=|<=|>|<)\s*(.+)$/);if(Z){let[,Q,Y,J]=Z,G=Q in X?X[Q]:void 0,W=r$(J,X);if(G!==void 0&&W!==void 0)switch(Y){case"==":case"===":return G===W;case"!=":case"!==":return G!==W;case">":return G>W;case"<":return G<W;case">=":return G>=W;case"<=":return G<=W}}return}function k3($,X){let Z=[],Q=$;return Q=Q.replace(/\{\{\s*(\w+)\s*\}\}/g,(Y,J)=>{if(J in X)return Z.push(`{{ ${J} }} -> ${X[J]}`),String(X[J]);return Y}),Q=Q.replace(/\{\{\s*(\d+)\s*([+\-*])\s*(\d+)\s*\}\}/g,(Y,J,G,W)=>{let K=Number.parseInt(J,10),_=Number.parseInt(W,10),U;switch(G){case"+":U=K+_;break;case"-":U=K-_;break;case"*":U=K*_;break;default:return Y}return Z.push(`{{ ${J} ${G} ${W} }} -> ${U}`),String(U)}),{content:Q,folded:Z}}function x3($){let X=$,Z=[],Q=0;X=X.replace(/<(pre|code|script|style)([^>]*)>([\s\S]*?)<\/\1>/gi,(Y)=>{let J=`__PRESERVE_${Q++}__`;return Z.push({marker:J,content:Y}),J}),X=X.replace(/\{\{([\s\S]*?)\}\}/g,(Y)=>{let J=`__PRESERVE_${Q++}__`;return Z.push({marker:J,content:Y}),J}),X=X.replace(/\{\{--([\s\S]*?)--\}\}/g,""),X=X.replace(/<!--[\s\S]*?-->/g,""),X=X.replace(/>\s+</g,"><"),X=X.replace(/^\s+/gm,""),X=X.replace(/\s+$/gm,""),X=X.replace(/\s{2,}/g," ");for(let{marker:Y,content:J}of Z){let G=X.indexOf(Y);if(G!==-1)X=X.slice(0,G)+J+X.slice(G+Y.length)}return X.trim()}function S3($){let X=new Map,Z=new Map,Q=/(['"])([^'"]{10,})\1/g,Y;while((Y=Q.exec($))!==null){let W=Y[2];Z.set(W,(Z.get(W)||0)+1)}let J=0,G=$;for(let[W,K]of Z)if(K>1){let _=`__STR_${J++}__`;X.set(_,W);let U=W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),F=new RegExp(`(['"])${U}\\1`,"g");G=G.replace(F,_)}return{content:G,pool:X,count:X.size}}function P3($,X={}){let Z={...Z6,...X},Q=new Blob([$]).size,Y=$,J=[],G=[],W=[],K=[],_=0;if(Z.target==="production")Z.constants={...Z.constants,__ENV__:"production"};if(Z.deadCodeElimination){let z=C3(Y,Z.constants);if(Y=z.content,z.removed.length>0)J.push("Dead code elimination"),G.push(...z.removed.map((j)=>`Removed: ${j}`))}if(Z.constantFolding&&Object.keys(Z.constants).length>0){let z=k3(Y,Z.constants);if(Y=z.content,K=z.folded,K.length>0)J.push("Constant folding")}if(Z.treeShake){if(W=D3(Y,Z.preserveDirectives),W.length>0)J.push("Tree shaking")}if(Z.stringPooling){let z=S3(Y);if(Y=z.content,_=z.count,_>0)J.push("String pooling")}if(Z.minifyHtml){let z=x3(Y);if(z.length<Y.length)Y=z,J.push("HTML minification")}let U=new Blob([Y]).size,F=Q>0?Math.round((1-U/Q)*100):0;return{content:Y,originalSize:Q,optimizedSize:U,reduction:F,appliedOptimizations:J,removedDirectives:W,foldedConstants:K,pooledStrings:_,warnings:G}}async function uJ($,X={}){let Z={...Z6,...X},Q=new Map,Y=[],J=0,G=0,W=new Set;for(let[F,z]of $){let j=P3(z,Z);Q.set(F,j),J+=j.originalSize,G+=j.optimizedSize,Y.push(...j.warnings.map((L)=>`${F}: ${L}`));let H=Y6(z);for(let L of H)W.add(L.name)}let K;if(Z.treeShake)K=w3(Array.from(W));let _;if(Z.stringPooling)_=new Map;let U=J>0?Math.round((1-G/J)*100):0;return{templates:Q,directiveBundle:K,stringPool:_,totalOriginalSize:J,totalOptimizedSize:G,overallReduction:U,warnings:Y}}function b3($){return $.charAt(0).toUpperCase()+$.slice(1)}function W6($,X){let Z={},Q=$.trim();if(Q.startsWith("{"))Q=Q.slice(1);if(Q.endsWith("}"))Q=Q.slice(0,-1);if(Q=Q.trim(),!Q)return Z;let Y=0;while(Y<Q.length){while(Y<Q.length&&/\s/.test(Q[Y]))Y++;if(Y>=Q.length)break;let J="";if(Q[Y]==='"'||Q[Y]==="'"){let K=Q[Y];Y++;while(Y<Q.length&&Q[Y]!==K)if(Q[Y]==="\\"&&Y+1<Q.length)J+=Q[Y+1],Y+=2;else J+=Q[Y],Y++;Y++}else while(Y<Q.length&&/[\w$]/.test(Q[Y]))J+=Q[Y],Y++;while(Y<Q.length&&/\s/.test(Q[Y]))Y++;if(Q[Y]===":")Y++;while(Y<Q.length&&/\s/.test(Q[Y]))Y++;let G,W=Y;if(Q[Y]==='"'||Q[Y]==="'"){let K=Q[Y];Y++;let _="";while(Y<Q.length&&Q[Y]!==K)if(Q[Y]==="\\"&&Y+1<Q.length)_+=Q[Y+1],Y+=2;else _+=Q[Y],Y++;Y++,G=_}else if(Q[Y]==="{"){let K=1;Y++;while(Y<Q.length&&K>0){if(Q[Y]==="{")K++;else if(Q[Y]==="}")K--;else if(Q[Y]==='"'||Q[Y]==="'"){let U=Q[Y];Y++;while(Y<Q.length&&Q[Y]!==U){if(Q[Y]==="\\")Y++;Y++}}Y++}let _=Q.slice(W,Y);G=W6(_,X)}else if(Q[Y]==="["){let K=1;Y++;while(Y<Q.length&&K>0){if(Q[Y]==="[")K++;else if(Q[Y]==="]")K--;else if(Q[Y]==='"'||Q[Y]==="'"){let U=Q[Y];Y++;while(Y<Q.length&&Q[Y]!==U){if(Q[Y]==="\\")Y++;Y++}}Y++}let _=Q.slice(W,Y);try{G=JSON.parse(_.replace(/'/g,'"'))}catch{G=_}}else{let K="";while(Y<Q.length&&Q[Y]!==","&&!/\s/.test(Q[Y]))K+=Q[Y],Y++;if(K=K.trim(),K==="true")G=!0;else if(K==="false")G=!1;else if(K==="null")G=null;else if(K==="undefined")G=void 0;else if(/^-?\d+(\.\d+)?$/.test(K))G=Number(K);else if(K in X)G=X[K];else G=K}if(J)Z[J]=G;while(Y<Q.length&&/\s/.test(Q[Y]))Y++;if(Q[Y]===",")Y++}return Z}function iJ($,X,Z){let Q=[];for(let[Y,J]of Object.entries(X)){let G=$[Y];if(J.required&&(G===void 0||G===null)){Q.push(`Component "${Z}": Missing required prop "${Y}"`);continue}if(G===void 0||G===null)continue;let W=Array.isArray(J.type)?J.type:[J.type];if(!W.includes("any")){let K=y3(G);if(!W.includes(K))Q.push(`Component "${Z}": Prop "${Y}" expected ${W.join(" | ")}, got ${K}`)}if(J.validator&&!J.validator(G))Q.push(`Component "${Z}": Prop "${Y}" failed custom validation`)}return Q}function aJ($,X){let Z={...$};for(let[Q,Y]of Object.entries(X))if(Z[Q]===void 0&&Y.default!==void 0)Z[Q]=typeof Y.default==="function"?Y.default():Y.default;return Z}function y3($){if(Array.isArray($))return"array";if($===null)return"null";return typeof $}var v3={name:"component",handler:async($,X,Z,Q)=>{if(X.length<1)return s1("Component","component directive requires at least the component name",r1.INVALID_DIRECTIVE_SYNTAX);let Y=X[0].replace(/['"]/g,""),J={};if(X.length>1)try{let U=X.slice(1).join(",").trim();if(U.startsWith("{")){if(J=J6(U,Z),Object.keys(J).length===0)J=W6(U,Z)}else{let F=U.trim(),z=Z[F];if(z&&typeof z==="object"&&!Array.isArray(z))J=z}}catch(U){let F=U instanceof Error?U.message:String(U);return console.error("Component props parsing error:",F),s1("Component",`Error parsing component props: ${F}`,r1.EVALUATION_ERROR)}let G=Z.__stx_options||{},W=G.componentsDir||"components",K=new Set;if(!Z.__processedComponents)Z.__processedComponents=new Set;let _=Z.__processedComponents;try{return await G6(Y,J,"",W,Z,Q,G,_,K)}catch(U){console.error("Component rendering error:",U);let F=U instanceof Error?U.message:String(U);return s1("Component",`Error rendering component: ${F}`,r1.COMPONENT_RENDER_ERROR)}},hasEndTag:!1};function rJ(){return[v3]}import{mkdir as g3,readFile as f3,readdir as h3,stat as K6,writeFile as d3}from"fs/promises";import U0 from"path";var F6=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function u3($){return $.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((X)=>X.charAt(0).toUpperCase()+X.slice(1)).join("")}function s$($){return $.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function m3($){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test($)&&!$.startsWith("xml")&&!/[A-Z]/.test($)}function p3($){if($===!0)return"open";if($==="open"||$==="closed")return $;return!1}async function c3($){let X=[];async function Z(Q){let Y=await h3(Q,{withFileTypes:!0});Y.sort((J,G)=>J.name.localeCompare(G.name));for(let J of Y){let G=U0.join(Q,J.name);if(J.isDirectory()){if(!J.name.startsWith(".")&&J.name!=="node_modules")await Z(G)}else if(J.isFile()&&J.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(J.name))X.push(G)}}return await Z($),X}function l3($,X){let Z=$.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!Z)return{};let Q=Z[1].trim();if(!Q)return{};try{return JSON.parse(Q)}catch(Y){throw Error(`${X}: <script component> must contain JSON metadata (${Y.message})`)}}function i3($,X){let Z={},Q=[...$.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let Y of Q){if(!/\bclient\b/i.test(Y[1])||/\bcomponent\b|\bstx:component\b/i.test(Y[1]))continue;let J;try{J=new Bun.Transpiler({loader:"ts"}).transformSync(Y[2])}catch(K){throw Error(`${X}: failed to transpile <script client> (${K.message})`)}let G=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,W;while(W=G.exec(J)){let K=W[1];if(F6.has(K))throw Error(`${X}: client method "${K}" is reserved`);let _=G.lastIndex,U=1,F="",z=!1,j=_;for(;j<J.length&&U>0;j++){let L=J[j];if(z){z=!1;continue}if(F){if(L==="\\")z=!0;else if(L===F)F="";continue}if(L==='"'||L==="'"||L==="`")F=L;else if(L==="{")U++;else if(L==="}")U--}if(U!==0)throw Error(`${X}: unterminated client function "${K}"`);let H=W[0].includes("async")?"async ":"";Z[K]=`${H}${K}(${W[2]}) {${J.slice(_,j-1)}}`,G.lastIndex=j}}return Z}function a3($){let X=$.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(X?X[1]:$).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function _6($){return[...$.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((X)=>X[1].trim()).filter(Boolean).join(`
|
|
198
|
+
`}function T3($,X={}){let Z=[],Q=/@if\(([^)]+)\)[\s\S]*?@endif/g,Y=$.matchAll(Q);for(let _ of Y){let U=_[1].trim();if(r$(U,X)===!1)Z.push({start:_.index,end:_.index+_[0].length,reason:`@if condition always false: ${U}`})}let J=/@unless\(([^)]+)\)[\s\S]*?@endunless/g,G=$.matchAll(J);for(let _ of G){let U=_[1].trim();if(r$(U,X)===!0)Z.push({start:_.index,end:_.index+_[0].length,reason:`@unless condition always true: ${U}`})}let W=/@env\(['"]development['"]\)[\s\S]*?@endenv/g;if(X.__ENV__==="production"){let _=$.matchAll(W);for(let U of _)Z.push({start:U.index,end:U.index+U[0].length,reason:"Development-only code in production build"})}let K=/@debug[\s\S]*?@enddebug/g;if(X.__ENV__==="production"){let _=$.matchAll(K);for(let U of _)Z.push({start:U.index,end:U.index+U[0].length,reason:"Debug code in production build"})}return Z}function C3($,X={}){let Z=T3($,X),Q=[];Z.sort((J,G)=>G.start-J.start);let Y=$;for(let J of Z)Y=Y.slice(0,J.start)+Y.slice(J.end),Q.push(J.reason);return{content:Y,removed:Q}}function r$($,X){if($==="true")return!0;if($==="false")return!1;if($==="null")return null;if(/^\d+$/.test($))return Number.parseInt($,10);if(/^\d+\.\d+$/.test($))return Number.parseFloat($);if(/^['"].*['"]$/.test($))return $.slice(1,-1);if($ in X)return X[$];let Z=$.match(/^(\w+)\s*(===|!==|==|!=|>=|<=|>|<)\s*(.+)$/);if(Z){let[,Q,Y,J]=Z,G=Q in X?X[Q]:void 0,W=r$(J,X);if(G!==void 0&&W!==void 0)switch(Y){case"==":case"===":return G===W;case"!=":case"!==":return G!==W;case">":return G>W;case"<":return G<W;case">=":return G>=W;case"<=":return G<=W}}return}function k3($,X){let Z=[],Q=$;return Q=Q.replace(/\{\{\s*(\w+)\s*\}\}/g,(Y,J)=>{if(J in X)return Z.push(`{{ ${J} }} -> ${X[J]}`),String(X[J]);return Y}),Q=Q.replace(/\{\{\s*(\d+)\s*([+\-*])\s*(\d+)\s*\}\}/g,(Y,J,G,W)=>{let K=Number.parseInt(J,10),_=Number.parseInt(W,10),U;switch(G){case"+":U=K+_;break;case"-":U=K-_;break;case"*":U=K*_;break;default:return Y}return Z.push(`{{ ${J} ${G} ${W} }} -> ${U}`),String(U)}),{content:Q,folded:Z}}function x3($){let X=$,Z=[],Q=0;X=X.replace(/<(pre|code|script|style)([^>]*)>([\s\S]*?)<\/\1>/gi,(Y)=>{let J=`__PRESERVE_${Q++}__`;return Z.push({marker:J,content:Y}),J}),X=X.replace(/\{\{([\s\S]*?)\}\}/g,(Y)=>{let J=`__PRESERVE_${Q++}__`;return Z.push({marker:J,content:Y}),J}),X=X.replace(/\{\{--([\s\S]*?)--\}\}/g,""),X=X.replace(/<!--[\s\S]*?-->/g,""),X=X.replace(/>\s+</g,"><"),X=X.replace(/^\s+/gm,""),X=X.replace(/\s+$/gm,""),X=X.replace(/\s{2,}/g," ");for(let{marker:Y,content:J}of Z){let G=X.indexOf(Y);if(G!==-1)X=X.slice(0,G)+J+X.slice(G+Y.length)}return X.trim()}function S3($){let X=new Map,Z=new Map,Q=/(['"])([^'"]{10,})\1/g,Y;while((Y=Q.exec($))!==null){let W=Y[2];Z.set(W,(Z.get(W)||0)+1)}let J=0,G=$;for(let[W,K]of Z)if(K>1){let _=`__STR_${J++}__`;X.set(_,W);let U=W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),F=new RegExp(`(['"])${U}\\1`,"g");G=G.replace(F,_)}return{content:G,pool:X,count:X.size}}function P3($,X={}){let Z={...Z6,...X},Q=new Blob([$]).size,Y=$,J=[],G=[],W=[],K=[],_=0;if(Z.target==="production")Z.constants={...Z.constants,__ENV__:"production"};if(Z.deadCodeElimination){let z=C3(Y,Z.constants);if(Y=z.content,z.removed.length>0)J.push("Dead code elimination"),G.push(...z.removed.map((j)=>`Removed: ${j}`))}if(Z.constantFolding&&Object.keys(Z.constants).length>0){let z=k3(Y,Z.constants);if(Y=z.content,K=z.folded,K.length>0)J.push("Constant folding")}if(Z.treeShake){if(W=D3(Y,Z.preserveDirectives),W.length>0)J.push("Tree shaking")}if(Z.stringPooling){let z=S3(Y);if(Y=z.content,_=z.count,_>0)J.push("String pooling")}if(Z.minifyHtml){let z=x3(Y);if(z.length<Y.length)Y=z,J.push("HTML minification")}let U=new Blob([Y]).size,F=Q>0?Math.round((1-U/Q)*100):0;return{content:Y,originalSize:Q,optimizedSize:U,reduction:F,appliedOptimizations:J,removedDirectives:W,foldedConstants:K,pooledStrings:_,warnings:G}}async function mJ($,X={}){let Z={...Z6,...X},Q=new Map,Y=[],J=0,G=0,W=new Set;for(let[F,z]of $){let j=P3(z,Z);Q.set(F,j),J+=j.originalSize,G+=j.optimizedSize,Y.push(...j.warnings.map((L)=>`${F}: ${L}`));let H=Y6(z);for(let L of H)W.add(L.name)}let K;if(Z.treeShake)K=w3(Array.from(W));let _;if(Z.stringPooling)_=new Map;let U=J>0?Math.round((1-G/J)*100):0;return{templates:Q,directiveBundle:K,stringPool:_,totalOriginalSize:J,totalOptimizedSize:G,overallReduction:U,warnings:Y}}function b3($){return $.charAt(0).toUpperCase()+$.slice(1)}function W6($,X){let Z={},Q=$.trim();if(Q.startsWith("{"))Q=Q.slice(1);if(Q.endsWith("}"))Q=Q.slice(0,-1);if(Q=Q.trim(),!Q)return Z;let Y=0;while(Y<Q.length){while(Y<Q.length&&/\s/.test(Q[Y]))Y++;if(Y>=Q.length)break;let J="";if(Q[Y]==='"'||Q[Y]==="'"){let K=Q[Y];Y++;while(Y<Q.length&&Q[Y]!==K)if(Q[Y]==="\\"&&Y+1<Q.length)J+=Q[Y+1],Y+=2;else J+=Q[Y],Y++;Y++}else while(Y<Q.length&&/[\w$]/.test(Q[Y]))J+=Q[Y],Y++;while(Y<Q.length&&/\s/.test(Q[Y]))Y++;if(Q[Y]===":")Y++;while(Y<Q.length&&/\s/.test(Q[Y]))Y++;let G,W=Y;if(Q[Y]==='"'||Q[Y]==="'"){let K=Q[Y];Y++;let _="";while(Y<Q.length&&Q[Y]!==K)if(Q[Y]==="\\"&&Y+1<Q.length)_+=Q[Y+1],Y+=2;else _+=Q[Y],Y++;Y++,G=_}else if(Q[Y]==="{"){let K=1;Y++;while(Y<Q.length&&K>0){if(Q[Y]==="{")K++;else if(Q[Y]==="}")K--;else if(Q[Y]==='"'||Q[Y]==="'"){let U=Q[Y];Y++;while(Y<Q.length&&Q[Y]!==U){if(Q[Y]==="\\")Y++;Y++}}Y++}let _=Q.slice(W,Y);G=W6(_,X)}else if(Q[Y]==="["){let K=1;Y++;while(Y<Q.length&&K>0){if(Q[Y]==="[")K++;else if(Q[Y]==="]")K--;else if(Q[Y]==='"'||Q[Y]==="'"){let U=Q[Y];Y++;while(Y<Q.length&&Q[Y]!==U){if(Q[Y]==="\\")Y++;Y++}}Y++}let _=Q.slice(W,Y);try{G=JSON.parse(_.replace(/'/g,'"'))}catch{G=_}}else{let K="";while(Y<Q.length&&Q[Y]!==","&&!/\s/.test(Q[Y]))K+=Q[Y],Y++;if(K=K.trim(),K==="true")G=!0;else if(K==="false")G=!1;else if(K==="null")G=null;else if(K==="undefined")G=void 0;else if(/^-?\d+(\.\d+)?$/.test(K))G=Number(K);else if(K in X)G=X[K];else G=K}if(J)Z[J]=G;while(Y<Q.length&&/\s/.test(Q[Y]))Y++;if(Q[Y]===",")Y++}return Z}function aJ($,X,Z){let Q=[];for(let[Y,J]of Object.entries(X)){let G=$[Y];if(J.required&&(G===void 0||G===null)){Q.push(`Component "${Z}": Missing required prop "${Y}"`);continue}if(G===void 0||G===null)continue;let W=Array.isArray(J.type)?J.type:[J.type];if(!W.includes("any")){let K=y3(G);if(!W.includes(K))Q.push(`Component "${Z}": Prop "${Y}" expected ${W.join(" | ")}, got ${K}`)}if(J.validator&&!J.validator(G))Q.push(`Component "${Z}": Prop "${Y}" failed custom validation`)}return Q}function rJ($,X){let Z={...$};for(let[Q,Y]of Object.entries(X))if(Z[Q]===void 0&&Y.default!==void 0)Z[Q]=typeof Y.default==="function"?Y.default():Y.default;return Z}function y3($){if(Array.isArray($))return"array";if($===null)return"null";return typeof $}var v3={name:"component",handler:async($,X,Z,Q)=>{if(X.length<1)return s1("Component","component directive requires at least the component name",r1.INVALID_DIRECTIVE_SYNTAX);let Y=X[0].replace(/['"]/g,""),J={};if(X.length>1)try{let U=X.slice(1).join(",").trim();if(U.startsWith("{")){if(J=J6(U,Z),Object.keys(J).length===0)J=W6(U,Z)}else{let F=U.trim(),z=Z[F];if(z&&typeof z==="object"&&!Array.isArray(z))J=z}}catch(U){let F=U instanceof Error?U.message:String(U);return console.error("Component props parsing error:",F),s1("Component",`Error parsing component props: ${F}`,r1.EVALUATION_ERROR)}let G=Z.__stx_options||{},W=G.componentsDir||"components",K=new Set;if(!Z.__processedComponents)Z.__processedComponents=new Set;let _=Z.__processedComponents;try{return await G6(Y,J,"",W,Z,Q,G,_,K)}catch(U){console.error("Component rendering error:",U);let F=U instanceof Error?U.message:String(U);return s1("Component",`Error rendering component: ${F}`,r1.COMPONENT_RENDER_ERROR)}},hasEndTag:!1};function sJ(){return[v3]}import{mkdir as g3,readFile as f3,readdir as h3,stat as K6,writeFile as d3}from"fs/promises";import U0 from"path";var F6=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function u3($){return $.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((X)=>X.charAt(0).toUpperCase()+X.slice(1)).join("")}function s$($){return $.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function m3($){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test($)&&!$.startsWith("xml")&&!/[A-Z]/.test($)}function p3($){if($===!0)return"open";if($==="open"||$==="closed")return $;return!1}async function c3($){let X=[];async function Z(Q){let Y=await h3(Q,{withFileTypes:!0});Y.sort((J,G)=>J.name.localeCompare(G.name));for(let J of Y){let G=U0.join(Q,J.name);if(J.isDirectory()){if(!J.name.startsWith(".")&&J.name!=="node_modules")await Z(G)}else if(J.isFile()&&J.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(J.name))X.push(G)}}return await Z($),X}function l3($,X){let Z=$.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!Z)return{};let Q=Z[1].trim();if(!Q)return{};try{return JSON.parse(Q)}catch(Y){throw Error(`${X}: <script component> must contain JSON metadata (${Y.message})`)}}function i3($,X){let Z={},Q=[...$.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let Y of Q){if(!/\bclient\b/i.test(Y[1])||/\bcomponent\b|\bstx:component\b/i.test(Y[1]))continue;let J;try{J=new Bun.Transpiler({loader:"ts"}).transformSync(Y[2])}catch(K){throw Error(`${X}: failed to transpile <script client> (${K.message})`)}let G=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,W;while(W=G.exec(J)){let K=W[1];if(F6.has(K))throw Error(`${X}: client method "${K}" is reserved`);let _=G.lastIndex,U=1,F="",z=!1,j=_;for(;j<J.length&&U>0;j++){let L=J[j];if(z){z=!1;continue}if(F){if(L==="\\")z=!0;else if(L===F)F="";continue}if(L==='"'||L==="'"||L==="`")F=L;else if(L==="{")U++;else if(L==="}")U--}if(U!==0)throw Error(`${X}: unterminated client function "${K}"`);let H=W[0].includes("async")?"async ":"";Z[K]=`${H}${K}(${W[2]}) {${J.slice(_,j-1)}}`,G.lastIndex=j}}return Z}function a3($){let X=$.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(X?X[1]:$).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function _6($){return[...$.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((X)=>X[1].trim()).filter(Boolean).join(`
|
|
199
199
|
|
|
200
200
|
`)}function r3($){if(!$)return null;let X=$.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(X))return"string";if(/^number$/.test(X))return"number";if(/^boolean$/.test(X))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(X))return"string";return"object"}function s3($){if($===void 0)return"object";if($==="true"||$==="false")return"boolean";if(/^-?\d+(?:\.\d+)?$/.test($))return"number";if(/^['"`]/.test($))return"string";return"object"}function n3($){if($==="true")return!0;if($==="false")return!1;if(/^-?\d+(?:\.\d+)?$/.test($))return Number($);if(/^['"`]/.test($))return $.slice(1,-1);try{return JSON.parse($)}catch{return}}function o3($){let X=[],Z=0,Q=$.replace(/\{\{--[\s\S]*?--\}\}/g,""),Y=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,J,G=(K)=>{if(Q[K]!=="(")return null;let _=0,U="";for(let F=K;F<Q.length;F++){let z=Q[F];if(U!==""){if(z==="\\")F++;else if(z===U)U="";continue}if(z==="'"||z==='"'||z==="`"){U=z;continue}if(z==="(")_++;else if(z===")"){if(_--,_===0)return{expression:Q.slice(K+1,F),end:F+1}}}return null},W=(K)=>{if(K==="")return;let _=0,U=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,F;while(F=U.exec(K)){if(F.index>_)X.push(`out += ${JSON.stringify(K.slice(_,F.index))};`);X.push(F[1]!==void 0?`out += __raw(${F[1]});`:`out += __escape(${F[2]});`),_=F.index+F[0].length}if(_<K.length)X.push(`out += ${JSON.stringify(K.slice(_))};`)};while(J=Y.exec(Q)){W(Q.slice(Z,J.index)),Z=J.index+J[0].length;let _=J[1]==="if"||J[1]==="elseif"||J[1]==="foreach"?G(Z):null;if(_)Z=_.end,Y.lastIndex=_.end;let U=_?.expression;switch(J[1]){case"if":X.push(`if (${U}) {`);break;case"elseif":X.push(`} else if (${U}) {`);break;case"else":X.push("} else {");break;case"endif":case"endforeach":X.push("}");break;case"foreach":{let F=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((U||"").trim());if(!F){X.push(`out += ${JSON.stringify(J[0]+(_?`(${U})`:""))};`);break}let[,z,j,H]=F;X.push(j?`for (const [${j}, ${H}] of __entries(${z})) {`:`for (const ${H} of __values(${z})) {`);break}}}return W(Q.slice(Z)),X.join(`
|
|
201
201
|
`)}function t3($){let X=$.trim().replace(/^\{/,"").replace(/\}$/,""),Z=[],Q=0;while(Q<X.length){let Y=/\s*([A-Za-z_$][\w$]*)\s*:/y;Y.lastIndex=Q;let J=Y.exec(X);if(!J)break;Q=Y.lastIndex;let G=0,W="",K=Q;while(Q<X.length){let U=X[Q];if(W){if(U==="\\")Q++;else if(U===W)W=""}else if(U==="'"||U==='"'||U==="`")W=U;else if(U==="{"||U==="["||U==="(")G++;else if(U==="}"||U==="]"||U===")")G--;else if(U===","&&G===0)break;Q++}let _=X.slice(K,Q).trim();if(_)Z.push([J[1],_]);Q++}return Z}function e3($,X,Z){let Y=[...$.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((z)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(z[1]));if(!Y)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let J=Y[2],G=[],W=[],K={},_={};J=J.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(z)=>{if(/from\s*['"]stx['"]/.test(z))return"";return G.push(z.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(j,H,L,O)=>{let A=U0.resolve(U0.dirname(X),L),V=U0.relative(Z,A);return`${H}${V.startsWith(".")?V:`./${V}`}${O}`})),""});let F=/const\s*\{([^}]*)\}\s*=\s*(?:withDefaults\s*\(\s*)?defineProps\s*<[^>]*>\s*\(\s*\)\s*(?:,\s*(\{[\s\S]*?\})\s*,?\s*\))?/.exec(J);if(F){for(let z of F[1].split(",")){let j=z.split(":")[0].trim();if(j)W.push(j)}for(let[z,j]of t3(F[2]||""))K[z]=j;J=J.replace(F[0],"")}for(let z of J.matchAll(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{([\s\S]*?)\n\}/g))for(let j of z[1].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))_[j[1]]=j[2].trim();return J=J.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:G,body:J.trim(),propNames:W,defaults:K,declared:_}}function $4($){let X=new Set;return{template:$.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(Q,Y,J,G,W)=>{let K=Y.toLowerCase();X.add(K);let _=(J||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${K}="${W}"${_?` data-stx-mod-${K}="${_}"`:""}`}),eventTypes:[...X].sort()}}function X4($){let X=[];return{template:$.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(Q,Y,J,G)=>{let W=X.length;return X.push({id:W,name:Y,expression:G}),` data-stx-bind-${W}=""`}),bindings:X}}function Z4($){let X=new Set;for(let Z of $.matchAll(/<slot\b([^>]*)>/gi))X.add(Z[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...X].map((Z)=>({name:Z}))}function Q4($){return[...new Set([...$.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((X)=>X[1]))].sort().map((X)=>({name:X}))}function U6($,X){if(!X||!new Set(["string","number","boolean","object","array"]).has(X.type))throw Error(`Property "${$}" must declare one of: string, number, boolean, object, array`);return{...X,reflect:X.reflect??X.attribute!==!1}}async function Y4($,X,Z){let Q=U0.isAbsolute(X.file)?X.file:U0.resolve($,X.file),Y=await f3(Q,"utf8"),J=l3(Y,Q),G=U0.basename(Q,".stx"),W=X.name||J.name||u3(G),K=`${s$(Z.prefix||"stx")}-${s$(G)}`,_=X.tag||J.tag||K;if(!W||!/^[A-Za-z_$][\w$]*$/.test(W))throw Error(`${Q}: invalid component class name "${W}"`);if(!m3(_))throw Error(`${Q}: invalid custom-element tag "${_}"; tags must be lowercase and contain a hyphen`);let U=X.properties||J.properties||J.props||{},F=Object.fromEntries(Object.entries(U).map(([E,q])=>[E,U6(E,q)])),z=$4(a3(Y)),j=X4(z.template),H=e3(Y,Q,U0.resolve(Z.outputDir)),L=o3(j.template);for(let E of H.propNames){if(F[E])continue;let q=H.defaults[E];F[E]=U6(E,{type:r3(H.declared[E])??s3(q),...q===void 0?{}:{default:n3(q)}})}let O=J.methods||{},A=X.methods||{},V=i3(Y,Q);return{file:U0.relative($,Q),sourcePath:Q,name:W,tag:_,description:X.description||J.description||"",template:j.template,styles:_6(Y),shadowMode:p3(X.shadowDOM??J.shadowDOM??Z.shadowDOM),progressive:X.progressive??J.progressive??Z.progressive??!0,properties:F,events:X.events||J.events||{},methods:{...O,...A,...V},eventTypes:z.eventTypes,bindings:j.bindings,slots:Z4(j.template),cssProperties:Q4(_6(Y)),scope:H,render:L}}function J4(){let $=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),X=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
|
|
@@ -591,7 +591,7 @@ export function renderComponent(tag, props = {}, slots = {}) {
|
|
|
591
591
|
}
|
|
592
592
|
|
|
593
593
|
${J}
|
|
594
|
-
`}async function
|
|
594
|
+
`}async function eJ($){let X=U0.resolve($.inputDir),Z=U0.resolve($.outputDir);if(!(await K6(X).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${X}`);let Y=$.components?.length?$.components:(await c3(X)).map((L)=>({file:L}));if(!Y.length)throw Error(`No .stx components found in ${X}`);let J=await Promise.all(Y.map((L)=>Y4(X,L,$)));J.sort((L,O)=>L.tag.localeCompare(O.tag));let G=J.filter((L,O)=>J.findIndex((A)=>A.tag===L.tag)!==O);if(G.length)throw Error(`Duplicate custom-element tag: ${G[0].tag}`);let W=J.filter((L,O)=>J.findIndex((A)=>A.name===L.name)!==O);if(W.length)throw Error(`Duplicate component class name: ${W[0].name}`);await g3(Z,{recursive:!0});let K=[],_=async(L,O)=>{let A=U0.join(Z,L);return await d3(A,O.endsWith(`
|
|
595
595
|
`)?O:`${O}
|
|
596
596
|
`,"utf8"),K.push(A),A};await _("runtime.js",J4());for(let L of J){if(await _(`${L.tag}.js`,G4(L)),$.declarations!==!1)await _(`${L.tag}.d.ts`,W4(L));if($.css!==!1&&L.styles){let O=L.shadowMode?L.styles:B6(L);await _(`${L.tag}.css`,$.minify?L6(O):O)}}let U=J.map((L)=>`export { ${L.name}, default as ${L.name}Element } from './${L.tag}.js';`).join(`
|
|
597
597
|
`);if(await _("index.js",U),await _("ssr.js",U4(J)),$.declarations!==!1)await _("index.d.ts",J.map((L)=>`export * from './${L.tag}.js'`).join(`
|
|
@@ -1120,7 +1120,7 @@ ${O}`}if(H=await A6(H),W.forEach((L)=>Q.add(L)),Z.cache&&Z.cachePath){if(await _
|
|
|
1120
1120
|
<h1>Something went wrong</h1>
|
|
1121
1121
|
<p>An internal error occurred. Please try again later.</p>
|
|
1122
1122
|
</body>
|
|
1123
|
-
</html>`,loader:"html"}}})}};async function E4($,X={}){let Z=X.port||3000,Q=X.watch!==!1,Y=X.hotReload!==!1&&Q,J=null,G=X.hmrPort||Z+1,W=Q0.resolve($);if(!E0.existsSync(W))return console.error(`${B.red}Error: File not found: ${B.bright}${W}${B.reset}`),!1;if(W.endsWith(".md"))return t$(W,X);else if(!W.endsWith(".stx"))return console.error(`${B.red}Error: Unsupported file type: ${B.bright}${W}${B.reset}. Only .stx and .md files are supported.`),!1;let K=u0(process.cwd(),"output");E0.mkdirSync(K,{recursive:!0}),console.log(`${B.blue}Building ${B.bright}${$}${B.reset}...`);let _=null,U=async()=>{try{let I={name:"public-assets",setup(T){T.onResolve({filter:/^\/(images|fonts|assets|public)\//},(f)=>{return{path:f.path,external:!0}})}},M=await Bun.build({entrypoints:[W],outdir:K,plugins:[I,_1],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...X.stxOptions});if(!M.success)return console.error(`${B.red}Build failed:${B.reset}`,M.logs),!1;let w=M.outputs.find((T)=>T.path.endsWith(".html"));if(!w)return console.error(`${B.red}No HTML output found${B.reset}`),!1;return _=await Bun.file(w.path).text(),!0}catch(I){return console.error(`${B.red}Error building stx file:${B.reset}`,I),!1}};if(!await U())return!1;let z=Q0.dirname(W);await B$(z);let j=Z;try{if(j=await h0(Z),j!==Z)console.log(`${B.yellow}Port ${Z} is busy, using port ${j} instead${B.reset}`)}catch{return console.error(`${B.red}Could not find an available port${B.reset}`),!1}if(Y){let I=X.hmrPort||j+1;J=J$({wsPort:I,verbose:!1}),G=J.start(I)}let H={},L=null,O;try{let{loadStxConfig:I}=await import("./chunk-
|
|
1123
|
+
</html>`,loader:"html"}}})}};async function E4($,X={}){let Z=X.port||3000,Q=X.watch!==!1,Y=X.hotReload!==!1&&Q,J=null,G=X.hmrPort||Z+1,W=Q0.resolve($);if(!E0.existsSync(W))return console.error(`${B.red}Error: File not found: ${B.bright}${W}${B.reset}`),!1;if(W.endsWith(".md"))return t$(W,X);else if(!W.endsWith(".stx"))return console.error(`${B.red}Error: Unsupported file type: ${B.bright}${W}${B.reset}. Only .stx and .md files are supported.`),!1;let K=u0(process.cwd(),"output");E0.mkdirSync(K,{recursive:!0}),console.log(`${B.blue}Building ${B.bright}${$}${B.reset}...`);let _=null,U=async()=>{try{let I={name:"public-assets",setup(T){T.onResolve({filter:/^\/(images|fonts|assets|public)\//},(f)=>{return{path:f.path,external:!0}})}},M=await Bun.build({entrypoints:[W],outdir:K,plugins:[I,_1],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...X.stxOptions});if(!M.success)return console.error(`${B.red}Build failed:${B.reset}`,M.logs),!1;let w=M.outputs.find((T)=>T.path.endsWith(".html"));if(!w)return console.error(`${B.red}No HTML output found${B.reset}`),!1;return _=await Bun.file(w.path).text(),!0}catch(I){return console.error(`${B.red}Error building stx file:${B.reset}`,I),!1}};if(!await U())return!1;let z=Q0.dirname(W);await B$(z);let j=Z;try{if(j=await h0(Z),j!==Z)console.log(`${B.yellow}Port ${Z} is busy, using port ${j} instead${B.reset}`)}catch{return console.error(`${B.red}Could not find an available port${B.reset}`),!1}if(Y){let I=X.hmrPort||j+1;J=J$({wsPort:I,verbose:!1}),G=J.start(I)}let H={},L=null,O;try{let{loadStxConfig:I}=await import("./chunk-zv4gb3wb.js"),M=await I();if(O=X.stxOptions?.serverApi??M.serverApi,M?.apiRouter)L=M?.apiRouter,console.log(`${B.blue}Using custom router for API handling${B.reset}`);if(M?.apiRoutes){H=M.apiRoutes;let w=Object.keys(H).length;if(w>0)console.log(`${B.blue}Loaded ${B.bright}${w} API route${w>1?"s":""}${B.reset}`)}if(M?.broadcasting?.enabled)try{let{startBroadcasting:w,loadChannels:D}=await import("./chunk-reskzmsb.js"),T=M.broadcasting;await w(T);let f=T.port??6001;console.log(`${B.magenta}Broadcasting on ${B.cyan}ws://localhost:${f}/ws${B.reset}`);let c=Q0.join(process.cwd(),"channels.ts");if(E0.existsSync(c))try{let v=await D(c);console.log(`${B.blue}Loaded ${B.bright}${v} broadcast channel${v!==1?"s":""}${B.blue} from channels.ts${B.reset}`)}catch(v){console.warn(`${B.yellow}Failed to load channels.ts: ${v.message}${B.reset}`)}}catch(w){console.warn(`${B.yellow}Broadcasting failed to start: ${w.message}${B.reset}`)}}catch{}let{createServerApi:A,isServerApiSource:V}=await import("./chunk-jcbj3xp4.js"),E=await A(process.cwd(),O);if(console.log(`${B.blue}Starting server on ${B.cyan}http://localhost:${j}/${B.reset}...`),Y)console.log(`${B.magenta}Hot reload enabled on ws://localhost:${G}${B.reset}`);let q=V4({port:j,async fetch(I){return F$(I,await(async()=>{let M=new URL(I.url);if([K,Q0.dirname(W),Q0.join(process.cwd(),"public")].some((v)=>V(Q0.join(v,M.pathname),process.cwd(),O)))return new Response("Not Found",{status:404});if(L)try{let v=await L.handleRequest(I);if(v.status!==404)return v}catch{}if(H[M.pathname])try{return await H[M.pathname](I)}catch(v){return new Response(JSON.stringify({error:v.message}),{status:500,headers:{"Content-Type":"application/json"}})}let w=await E(I);if(w)return w;if(M.pathname==="/")return(async()=>{let S=await J0(_||"");if(Y)S=P0(S,G);if(X.native)if(S.includes("<head>"))S=S.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(S.includes("<html"))S=S.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else S="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+S;if(X.titlebarHidden)if(S.includes("<head>"))S=S.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(S.includes("<html"))S=S.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else S=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${S}`;return S})().then((S)=>new Response(S,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let D=Q0.join(K,M.pathname);if(E0.existsSync(D)&&E0.statSync(D).isFile()){let v=Bun.file(D),S=Q0.extname(D).toLowerCase(),k="text/plain";if(S===".ts"||S===".tsx"){let H0=new Bun.Transpiler({loader:S===".tsx"?"tsx":"ts"}),G0=await v.text(),r0=H0.transformSync(G0);return new Response(r0,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(S){case".html":k="text/html";break;case".css":k="text/css";break;case".js":k="text/javascript";break;case".json":k="application/json";break;case".png":k="image/png";break;case".jpg":case".jpeg":k="image/jpeg";break;case".gif":k="image/gif";break;case".woff":k="font/woff";break;case".woff2":k="font/woff2";break;case".ttf":k="font/ttf";break;case".otf":k="font/otf";break;case".eot":k="application/vnd.ms-fontobject";break}return new Response(v,{headers:{"Content-Type":k}})}let T=Q0.dirname(W),f=Q0.join(T,M.pathname);if(E0.existsSync(f)&&E0.statSync(f).isFile()){let v=Bun.file(f),S=Q0.extname(f).toLowerCase(),k="text/plain";if(S===".ts"||S===".tsx"){let H0=new Bun.Transpiler({loader:S===".tsx"?"tsx":"ts"}),G0=await v.text(),r0=H0.transformSync(G0);return new Response(r0,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(S){case".html":k="text/html";break;case".css":k="text/css";break;case".js":k="text/javascript";break;case".json":k="application/json";break;case".png":k="image/png";break;case".jpg":case".jpeg":k="image/jpeg";break;case".gif":k="image/gif";break;case".svg":k="image/svg+xml";break;case".ico":k="image/x-icon";break;case".woff":k="font/woff";break;case".woff2":k="font/woff2";break;case".ttf":k="font/ttf";break;case".otf":k="font/otf";break;case".eot":k="application/vnd.ms-fontobject";break}return new Response(v,{headers:{"Content-Type":k}})}let c=Q0.join(process.cwd(),"public",M.pathname);if(E0.existsSync(c)&&E0.statSync(c).isFile()){let v=Bun.file(c),S=Q0.extname(c).toLowerCase(),k="application/octet-stream";if(S===".ts"||S===".tsx"){let H0=new Bun.Transpiler({loader:S===".tsx"?"tsx":"ts"}),G0=await v.text(),r0=H0.transformSync(G0);return new Response(r0,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(S){case".html":k="text/html";break;case".css":k="text/css";break;case".js":k="text/javascript";break;case".json":k="application/json";break;case".png":k="image/png";break;case".jpg":case".jpeg":k="image/jpeg";break;case".gif":k="image/gif";break;case".svg":k="image/svg+xml";break;case".ico":k="image/x-icon";break;case".woff":k="font/woff";break;case".woff2":k="font/woff2";break;case".ttf":k="font/ttf";break;case".otf":k="font/otf";break;case".eot":k="application/vnd.ms-fontobject";break}return new Response(v,{headers:{"Content-Type":k}})}return new Response("Not Found",{status:404})})())},error(I){return new Response(`<pre>${I}
|
|
1124
1124
|
${I.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
1125
1125
|
${B.blue}stx${B.reset} ${B.green}${process.env.stx_VERSION||"v0.0.10"}${B.reset} ${B.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${B.reset}`),console.log(`
|
|
1126
1126
|
${B.bright}\u2192 ${B.cyan}http://localhost:${j}/${B.reset}`),console.log(`
|
|
@@ -1607,7 +1607,7 @@ ${H.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
|
|
|
1607
1607
|
${B.blue}stx${B.reset} ${B.green}${process.env.stx_VERSION||"v0.0.10"}${B.reset} ${B.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${B.reset}`),console.log(`
|
|
1608
1608
|
${B.bright}\u2192 ${B.cyan}http://localhost:${U}/${B.reset}`),console.log(`
|
|
1609
1609
|
${B.yellow}Routes:${B.reset}`);let z=new Set(W.map((H)=>H.routeTemplate)),j=Object.entries(G).filter(([H])=>!z.has(H)).sort(([H],[L])=>H.localeCompare(L)).map(([H,L])=>({route:H==="/"?"/":H,filePath:B0.relative(process.cwd(),L.filePath),fileType:L.fileType}));for(let H of W){let L=H.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");j.push({route:L,filePath:B0.relative(process.cwd(),H.filePath),fileType:"stx"})}if(j.sort((H,L)=>H.route.localeCompare(L.route)),j.forEach((H,L)=>{let A=L===j.length-1?"\u2514\u2500 ":"\u251C\u2500 ",V=H.fileType==="md"?`${B.magenta}(markdown)${B.reset}`:"";console.log(` ${B.green}${A}${H.route}${B.reset} \u2192 ${B.bright}${H.filePath}${B.reset} ${V}`)}),console.log(`
|
|
1610
|
-
Press ${B.cyan}h${B.reset} + ${B.cyan}Enter${B.reset} to show shortcuts`),d0(F.url.toString(),()=>{if(Q)m0.watch(J,{recursive:!0}).close();F.stop()}),Q){console.log(`${B.blue}Watching for changes...${B.reset}`);let H=m0.watch(J,{recursive:!0},async(L,O)=>{if(!O)return;if(O.endsWith(".stx")||O.endsWith(".js")||O.endsWith(".ts")||O.endsWith(".md"))console.log(`${B.yellow}File ${B.bright}${O}${B.yellow} changed, rebuilding...${B.reset}`),o0.clear(),t0(),await K()});process.on("SIGINT",()=>{H.close(),F.stop(),process.exit(0)})}return!0}function N6($){return String($??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:D4}=globalThis.Bun;import e from"fs";import m from"path";async function R6($){try{return G5(await Bun.file($).text())}catch{return}}function Q5($){let X=Bun.file($),Z=m.extname($).toLowerCase(),Q={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},J=[".js",".css",".json"].includes(Z)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(X,{headers:{"Content-Type":Q[Z]||"application/octet-stream",...J}})}async function w4($=".",X={}){let Z=X.port||3000,Q=X.watch!==!1,Y=X.hotReload!==!1&&Q,J=null,G=X.hmrPort||Z+1,W=m.resolve($),{loadStxConfig:K}=await import("./chunk-v3yh931q.js"),_=await K(W),{createServerApi:U,isServerApiSource:F}=await import("./chunk-jcbj3xp4.js"),z=X.stxOptions?.serverApi??_.serverApi,j=await U(W,z),H=_.root&&_.root!=="."?m.join(W,_.root):W,L=X.pagesDir||_.pagesDir||"pages",O=m.join(H,L);if(!e.existsSync(O)&&!_._layerPageDirs?.some((R)=>e.existsSync(R)))return console.error(`${B.red}Error: No '${L}' directory found${B.reset}`),console.log(`${B.dim}Looked in: ${B.bright}${O}${B.reset}`),console.log(`${B.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${B.reset}`),console.log(`${B.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${B.reset}`),console.log(`${B.dim}Starting fresh? Create ${L}/index.stx for the homepage.${B.reset}`),!1;let A=j$(H,{pagesDir:L,pagesDirs:_._layerPageDirs?[O,..._._layerPageDirs.slice(1)]:void 0});if(A.length===0)return console.error(`${B.red}Error: No page files found in ${B.bright}${O}${B.reset}`),!1;console.log(`${B.blue}Found ${B.bright}${A.length}${B.blue} routes${B.reset}`);let V=_?._pluginPageDirs||[],E=[];for(let{dir:R,prefix:x}of V)if(e.existsSync(R)){let P=j$(m.dirname(R),{pagesDir:m.basename(R)});for(let y of P){let Z0=x==="/"?y.pattern:`${x}${y.pattern==="/"?"":y.pattern}`;E.push({route:{...y,pattern:Z0},prefix:x})}if(P.length>0)console.log(`${B.blue}Plugin pages: ${B.bright}${P.length}${B.blue} routes at ${B.cyan}${x}${B.reset}`)}let q=new Map,N=null,I=null;if(X.stxOptions?.shell!==!1){if(I=await d6(W,X.stxOptions?.shell),I){if(N=await J5(I,X.stxOptions||{}),N)console.log(`${B.blue}Using app shell: ${B.bright}${m.relative(W,I)}${B.reset} ${B.dim}(deprecated: use layouts/default.stx instead)${B.reset}`)}}T6(),await k6(W);let M=C6();if(M.length>0)console.log(`${B.blue}Loaded ${B.bright}${M.length}${B.blue} middleware: ${B.dim}${M.join(", ")}${B.reset}`);let w={},D=null;try{let{loadStxConfig:R}=await import("./chunk-v3yh931q.js"),x=await R(W);if(x?.apiRouter)D=x?.apiRouter,console.log(`${B.blue}Using custom router for API handling${B.reset}`);if(x?.apiRoutes){w=x.apiRoutes;let P=Object.keys(w).length;if(P>0)console.log(`${B.blue}Loaded ${B.bright}${P} API route${P>1?"s":""}${B.reset}`)}if(x?.broadcasting?.enabled)try{let{startBroadcasting:P,loadChannels:y}=await import("./chunk-reskzmsb.js"),Z0=x.broadcasting;await P(Z0);let R0=Z0.port??6001;console.log(`${B.magenta}Broadcasting on ${B.cyan}ws://localhost:${R0}/ws${B.reset}`);let g0=m.join(process.cwd(),"channels.ts");if(e.existsSync(g0))try{let p=await y(g0);console.log(`${B.blue}Loaded ${B.bright}${p} broadcast channel${p!==1?"s":""}${B.blue} from channels.ts${B.reset}`)}catch(p){console.warn(`${B.yellow}Failed to load channels.ts: ${p.message}${B.reset}`)}}catch(P){console.warn(`${B.yellow}Broadcasting failed to start: ${P.message}${B.reset}`)}}catch{}let T=u0(W,"output");e.mkdirSync(T,{recursive:!0});let f=new Map,c=new Set,v=async(R)=>{let x=D6(O,R);if(!x)return null;try{let P=await Bun.build({entrypoints:[x],outdir:T,plugins:[_1],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...X.stxOptions});if(!P.success)return null;let y=P.outputs.find((Z0)=>Z0.path.endsWith(".html"));if(!y)return null;return await Bun.file(y.path).text()}catch{return null}},S=new Map,k=async(R,x)=>{try{let{processDirectives:P,extractVariables:y,defaultConfig:Z0,loadStxConfig:R0,injectRouterScript:g0}=await import("./chunk-v3yh931q.js"),{checkCache:p,cacheTemplate:u,readFileCached:g,templateCache:h}=await import("./chunk-a1rt1fms.js"),Y0=await R0(W),f0=(i)=>{if(!i)return i;if(m.isAbsolute(i))return i;return m.resolve(W,i)},C={...Z0,...Y0,...X.stxOptions,autoShell:!0};if(X.debugDirectives)C.debug=!0;C.partialsDir=f0(C.partialsDir),C.componentsDir=f0(C.componentsDir),C.layoutsDir=f0(C.layoutsDir),C.storesDir=f0(C.storesDir||"stores"),C.cachePath=f0(C.cachePath)??u0(W,"cache");let X0=!x&&!X.profile,a=C.cache!==!1;if(a&&X0){let i=h.get(R.filePath);if(i)try{if((await e.promises.stat(R.filePath)).mtime.getTime()<=i.mtime){let N0=!0;for(let _0 of i.dependencies){if(!e.existsSync(_0)){N0=!1;break}if((await e.promises.stat(_0)).mtime.getTime()>i.mtime){N0=!1;break}}if(N0){let _0=i.output;if(N)_0=O$(_0,{preserveHead:!0});let E1=S.get(R.filePath);return{route:R,content:_0,status:E1?.status??await R6(R.filePath),headers:E1?.headers}}}}catch{}let A0=await p(R.filePath,C);if(A0){let q0=A0;if(N)q0=O$(q0,{preserveHead:!0});let N0=S.get(R.filePath);return{route:R,content:q0,status:N0?.status??await R6(R.filePath),headers:N0?.headers}}}let o=a?await g(R.filePath):await Bun.file(R.filePath).text(),K0=G5(o),{classifyAllScripts:d}=await import("./chunk-v3yh931q.js"),O0=d(o),D0=O0.server.map((i)=>i.content),s=o;for(let i of O0.server)s=s.replace(i.fullTag,"");let n={__filename:R.filePath,__dirname:m.dirname(R.filePath),__stx_options:C,params:x??{},__stx_runtime_head:{}};for(let i of D0)try{await y(i,n,R.filePath)}catch(A0){if(X.stxOptions?.debug)console.error("[stx] variable extraction error",R.filePath,A0?.message||A0)}let S0=new Set,j0;if(X.profile){let i=performance.now();j0=await P(s,n,R.filePath,C,S0);let A0=performance.now()-i,q0=m.relative(W,R.filePath)||R.filePath;console.log(`[stx:profile] ${q0} \u2192 ${A0.toFixed(2)}ms`)}else j0=await P(s,n,R.filePath,C,S0);if(!N)j0=await g0(j0,{router:C.router});{let{interpolateScriptExpressions:i}=await import("./chunk-da0tfpa2.js");j0=j0.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(A0,q0,N0)=>{if(!/function\s+__stx_setup_/.test(N0))return A0;return`<script${q0}>${i(N0,n)}</script>`})}if(N)j0=O$(j0,{preserveHead:!0});if(a&&X0)await u(R.filePath,j0,S0,C);let{extractStreamBoundaries:Y3}=await import("./chunk-wa3ks5zv.js"),Q1=Y3(n),V1=n.__streamTemplates;if(V1&&typeof V1==="object"&&Object.keys(V1).length>0){let i=n.streamBoundaries||{},A0={...C,autoShell:!1},q0=Object.keys(V1).map((_0)=>({id:_0,render:async()=>{let E1=typeof i[_0]==="function"?await i[_0]():void 0;return P(V1[_0],{...n,$boundary:E1},R.filePath,A0,new Set)}})),N0=new Set(q0.map((_0)=>_0.id));Q1=[...(Q1||[]).filter((_0)=>!N0.has(_0.id)),...q0]}if(Q1&&Q1.length>0)c.add(R.pattern);else Q1=void 0;let l5=T1(n),i5=C1(n);if(X0)S.set(R.filePath,{status:l5,headers:i5});return{route:R,content:j0,status:l5??K0,headers:i5,boundaries:Q1}}catch(P){return console.error(`${B.red}Error building ${B.bright}${R.pattern}${B.reset}:`,P),null}},H0=8,G0=async()=>{f.clear(),q.clear();for(let R=0;R<A.length;R+=H0){let x=A.slice(R,R+H0),P=await Promise.all(x.map((y)=>k(y)));for(let y of P)if(y)f.set(y.route.pattern,y)}for(let R=0;R<E.length;R+=H0){let x=E.slice(R,R+H0),P=await Promise.all(x.map(({route:y})=>k(y)));for(let y of P)if(y)q.set(y.route.pattern,y)}return f.size>0};if(console.log(`${B.blue}Building pages...${B.reset}`),!await G0())return console.error(`${B.red}No pages were successfully built${B.reset}`),!1;await B$(W);let v0=Z;try{if(v0=await h0(Z),v0!==Z)console.log(`${B.yellow}Port ${Z} is busy, using port ${v0} instead${B.reset}`)}catch{return console.error(`${B.red}Could not find an available port${B.reset}`),!1}if(Y){let R=X.hmrPort||v0+1;J=J$({wsPort:R,verbose:!1}),G=J.start(R)}let z0=(R,x)=>{let y=`<script data-stx-route-params>(function(){var p=${JSON.stringify(x).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(R.includes("</head>"))return R.replace("</head>",`${y}</head>`);if(R.includes("<body"))return R.replace(/<body([^>]*)>/,`<body$1>${y}`);return y+R};console.log(`${B.blue}Starting server...${B.reset}`);let Z1=D4({port:v0,async fetch(R){let x=new URL(R.url),P=_?.publicDir||"public",y=m.join(W,P,x.pathname),Z0=m.join(W,x.pathname),R0=m.join(T,x.pathname);if([y,Z0,R0].some((C)=>F(C,W,z)))return new Response("Not Found",{status:404});let[g0,p,u]=await Promise.all([e.promises.stat(y).catch(()=>null),e.promises.stat(Z0).catch(()=>null),e.promises.stat(R0).catch(()=>null)]);if(g0?.isFile()&&!F(y,W,z))return Q5(y);if(p?.isFile()&&!F(Z0,W,z))return Q5(Z0);if(u?.isFile()&&!F(R0,W,z))return Q5(R0);if(x.pathname.startsWith("/_stx/component/")){let C=decodeURIComponent(x.pathname.slice(16));if(C)try{let X0=`<${C} />`,a={...buildConfig,autoShell:!1},o=await processDirectives(X0,{},m.join(W,"components",`${C}.stx`),a,new Set);return new Response(o,{headers:{"Content-Type":"text/html"}})}catch(X0){return new Response(`<div class="stx-async-error">${X0.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(x.pathname==="/_stx/img"){let{handleImageRequest:C}=await import("./chunk-pbct6nxk.js"),X0=await C(R,{publicDir:m.join(W,P),cacheDir:u0(W,"cache","img")});if(X0)return X0}if(D)try{let C=await D.handleRequest(R);if(C.status!==404)return C}catch{}if(w[x.pathname])try{return await w[x.pathname](R)}catch(C){return new Response(JSON.stringify({error:C.message}),{status:500,headers:{"Content-Type":"application/json"}})}let g=await j(R);if(g)return g;let h=Y5(x.pathname,A);if(h){let C=f.get(h.route.pattern),X0=c.has(h.route.pattern);if(h.route.isDynamic&&Object.keys(h.params).length>0||X0){let a=await k(h.route,h.params);if(a)C=a}if(C){let a=C.status??200,o=C.headers??{},K0=(h.route.filePath?y6(await Bun.file(h.route.filePath).text().catch(()=>"")):null)??{};if(K0.validate){if(!await K0.validate({params:h.params})){let D0=await v(404);if(D0){let s=D0;if(s=await J0(s,W),Y)s=P0(s,G);return new Response(s,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(K0.middleware){let O0=x6(x.pathname,h.params,K0,x.search),D0=S6(O0,null,R,{isServer:!0}),s=await P6(K0.middleware,D0);if(s.redirect){let n=s.redirect.path,S0=s.redirect.options.redirectCode||302,j0=new Headers(s.responseHeaders);return j0.set("Location",n),new Response(null,{status:S0,headers:j0})}if(s.abort){let{statusCode:n,message:S0}=s.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${n}</title></head><body><h1>Error ${n}</h1><p>${S0}</p></body></html>`,{status:n,headers:{"Content-Type":"text/html"}})}if(Object.keys(s.state).length>0){let n=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(s.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;C.content=C.content.replace("</head>",`${n}</head>`)}}let d=C.content;if(N&&u6(R)){let O0=b6(d),D0=v6(d),s=d.match(/<title[^>]*>([\s\S]*?)<\/title>/i),n=s?h6(s[1].trim()):"";if(Object.keys(h.params).length>0)d=z0(d,h.params);d=await J0(d,W);let S0=_?.router?.container||"main";return d=m6(d,S0),new Response(d,{status:a,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":O0.layout,"X-STX-Layout-Group":O0.group,"X-STX-Runtime":D0?"true":"false",...n&&{"X-STX-Title":encodeURIComponent(n)},[g6]:f6(),...B1(),"Cache-Control":z$}})}if(N)d=H$(N,d);if(Object.keys(h.params).length>0)d=z0(d,h.params);if(d=await J0(d,W),Y)d=P0(d,G);if(X.native)if(d.includes("<head>"))d=d.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else d="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+d;if(X.titlebarHidden)if(d.includes("<head>"))d=d.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else d=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${d}`;if(C.boundaries&&C.boundaries.length>0){let{renderStreamingPage:O0,streamToResponse:D0}=await import("./chunk-wa3ks5zv.js");return D0(O0(d,C.boundaries,{timeoutMs:30000}),{status:a,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(d,{status:a,headers:{"Content-Type":"text/html",...B1(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...o}})}}if(E.length>0){let C=E.map((a)=>a.route),X0=Y5(x.pathname,C);if(X0){let a=q.get(X0.route.pattern);if(a){let o=a.content;if(N)o=H$(N,o);if(Object.keys(X0.params).length>0)o=z0(o,X0.params);if(o=await J0(o,W),Y)o=P0(o,G);return new Response(o,{status:a.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:a}of V)if(a!=="/"&&x.pathname.startsWith(a)){let o=q.get(a)||q.get(a+"/");if(o){let K0=o.content;if(N)K0=H$(N,K0);if(K0=await J0(K0,W),Y)K0=P0(K0,G);return new Response(K0,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}let Y0=f.get("/");if(Y0){let C=Y0.content;if(C=await J0(C,W),Y)C=P0(C,G);if(X.native)if(C.includes("<head>"))C=C.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else C="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+C;return new Response(C,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let f0=await v(404);if(f0){let C=f0;if(C=await J0(C,W),Y)C=P0(C,G);return new Response(C,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(R){let x=await v(500);if(x)return new Response(x,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${R}
|
|
1610
|
+
Press ${B.cyan}h${B.reset} + ${B.cyan}Enter${B.reset} to show shortcuts`),d0(F.url.toString(),()=>{if(Q)m0.watch(J,{recursive:!0}).close();F.stop()}),Q){console.log(`${B.blue}Watching for changes...${B.reset}`);let H=m0.watch(J,{recursive:!0},async(L,O)=>{if(!O)return;if(O.endsWith(".stx")||O.endsWith(".js")||O.endsWith(".ts")||O.endsWith(".md"))console.log(`${B.yellow}File ${B.bright}${O}${B.yellow} changed, rebuilding...${B.reset}`),o0.clear(),t0(),await K()});process.on("SIGINT",()=>{H.close(),F.stop(),process.exit(0)})}return!0}function N6($){return String($??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:D4}=globalThis.Bun;import e from"fs";import m from"path";async function R6($){try{return G5(await Bun.file($).text())}catch{return}}function Q5($){let X=Bun.file($),Z=m.extname($).toLowerCase(),Q={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},J=[".js",".css",".json"].includes(Z)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(X,{headers:{"Content-Type":Q[Z]||"application/octet-stream",...J}})}async function w4($=".",X={}){let Z=X.port||3000,Q=X.watch!==!1,Y=X.hotReload!==!1&&Q,J=null,G=X.hmrPort||Z+1,W=m.resolve($),{loadStxConfig:K}=await import("./chunk-zv4gb3wb.js"),_=await K(W),{createServerApi:U,isServerApiSource:F}=await import("./chunk-jcbj3xp4.js"),z=X.stxOptions?.serverApi??_.serverApi,j=await U(W,z),H=_.root&&_.root!=="."?m.join(W,_.root):W,L=X.pagesDir||_.pagesDir||"pages",O=m.join(H,L);if(!e.existsSync(O)&&!_._layerPageDirs?.some((R)=>e.existsSync(R)))return console.error(`${B.red}Error: No '${L}' directory found${B.reset}`),console.log(`${B.dim}Looked in: ${B.bright}${O}${B.reset}`),console.log(`${B.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${B.reset}`),console.log(`${B.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${B.reset}`),console.log(`${B.dim}Starting fresh? Create ${L}/index.stx for the homepage.${B.reset}`),!1;let A=j$(H,{pagesDir:L,pagesDirs:_._layerPageDirs?[O,..._._layerPageDirs.slice(1)]:void 0});if(A.length===0)return console.error(`${B.red}Error: No page files found in ${B.bright}${O}${B.reset}`),!1;console.log(`${B.blue}Found ${B.bright}${A.length}${B.blue} routes${B.reset}`);let V=_?._pluginPageDirs||[],E=[];for(let{dir:R,prefix:x}of V)if(e.existsSync(R)){let P=j$(m.dirname(R),{pagesDir:m.basename(R)});for(let y of P){let Z0=x==="/"?y.pattern:`${x}${y.pattern==="/"?"":y.pattern}`;E.push({route:{...y,pattern:Z0},prefix:x})}if(P.length>0)console.log(`${B.blue}Plugin pages: ${B.bright}${P.length}${B.blue} routes at ${B.cyan}${x}${B.reset}`)}let q=new Map,N=null,I=null;if(X.stxOptions?.shell!==!1){if(I=await d6(W,X.stxOptions?.shell),I){if(N=await J5(I,X.stxOptions||{}),N)console.log(`${B.blue}Using app shell: ${B.bright}${m.relative(W,I)}${B.reset} ${B.dim}(deprecated: use layouts/default.stx instead)${B.reset}`)}}T6(),await k6(W);let M=C6();if(M.length>0)console.log(`${B.blue}Loaded ${B.bright}${M.length}${B.blue} middleware: ${B.dim}${M.join(", ")}${B.reset}`);let w={},D=null;try{let{loadStxConfig:R}=await import("./chunk-zv4gb3wb.js"),x=await R(W);if(x?.apiRouter)D=x?.apiRouter,console.log(`${B.blue}Using custom router for API handling${B.reset}`);if(x?.apiRoutes){w=x.apiRoutes;let P=Object.keys(w).length;if(P>0)console.log(`${B.blue}Loaded ${B.bright}${P} API route${P>1?"s":""}${B.reset}`)}if(x?.broadcasting?.enabled)try{let{startBroadcasting:P,loadChannels:y}=await import("./chunk-reskzmsb.js"),Z0=x.broadcasting;await P(Z0);let R0=Z0.port??6001;console.log(`${B.magenta}Broadcasting on ${B.cyan}ws://localhost:${R0}/ws${B.reset}`);let g0=m.join(process.cwd(),"channels.ts");if(e.existsSync(g0))try{let p=await y(g0);console.log(`${B.blue}Loaded ${B.bright}${p} broadcast channel${p!==1?"s":""}${B.blue} from channels.ts${B.reset}`)}catch(p){console.warn(`${B.yellow}Failed to load channels.ts: ${p.message}${B.reset}`)}}catch(P){console.warn(`${B.yellow}Broadcasting failed to start: ${P.message}${B.reset}`)}}catch{}let T=u0(W,"output");e.mkdirSync(T,{recursive:!0});let f=new Map,c=new Set,v=async(R)=>{let x=D6(O,R);if(!x)return null;try{let P=await Bun.build({entrypoints:[x],outdir:T,plugins:[_1],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...X.stxOptions});if(!P.success)return null;let y=P.outputs.find((Z0)=>Z0.path.endsWith(".html"));if(!y)return null;return await Bun.file(y.path).text()}catch{return null}},S=new Map,k=async(R,x)=>{try{let{processDirectives:P,extractVariables:y,defaultConfig:Z0,loadStxConfig:R0,injectRouterScript:g0}=await import("./chunk-zv4gb3wb.js"),{checkCache:p,cacheTemplate:u,readFileCached:g,templateCache:h}=await import("./chunk-a1rt1fms.js"),Y0=await R0(W),f0=(i)=>{if(!i)return i;if(m.isAbsolute(i))return i;return m.resolve(W,i)},C={...Z0,...Y0,...X.stxOptions,autoShell:!0};if(X.debugDirectives)C.debug=!0;C.partialsDir=f0(C.partialsDir),C.componentsDir=f0(C.componentsDir),C.layoutsDir=f0(C.layoutsDir),C.storesDir=f0(C.storesDir||"stores"),C.cachePath=f0(C.cachePath)??u0(W,"cache");let X0=!x&&!X.profile,a=C.cache!==!1;if(a&&X0){let i=h.get(R.filePath);if(i)try{if((await e.promises.stat(R.filePath)).mtime.getTime()<=i.mtime){let N0=!0;for(let _0 of i.dependencies){if(!e.existsSync(_0)){N0=!1;break}if((await e.promises.stat(_0)).mtime.getTime()>i.mtime){N0=!1;break}}if(N0){let _0=i.output;if(N)_0=O$(_0,{preserveHead:!0});let E1=S.get(R.filePath);return{route:R,content:_0,status:E1?.status??await R6(R.filePath),headers:E1?.headers}}}}catch{}let A0=await p(R.filePath,C);if(A0){let q0=A0;if(N)q0=O$(q0,{preserveHead:!0});let N0=S.get(R.filePath);return{route:R,content:q0,status:N0?.status??await R6(R.filePath),headers:N0?.headers}}}let o=a?await g(R.filePath):await Bun.file(R.filePath).text(),K0=G5(o),{classifyAllScripts:d}=await import("./chunk-zv4gb3wb.js"),O0=d(o),D0=O0.server.map((i)=>i.content),s=o;for(let i of O0.server)s=s.replace(i.fullTag,"");let n={__filename:R.filePath,__dirname:m.dirname(R.filePath),__stx_options:C,params:x??{},__stx_runtime_head:{}};for(let i of D0)try{await y(i,n,R.filePath)}catch(A0){if(X.stxOptions?.debug)console.error("[stx] variable extraction error",R.filePath,A0?.message||A0)}let S0=new Set,j0;if(X.profile){let i=performance.now();j0=await P(s,n,R.filePath,C,S0);let A0=performance.now()-i,q0=m.relative(W,R.filePath)||R.filePath;console.log(`[stx:profile] ${q0} \u2192 ${A0.toFixed(2)}ms`)}else j0=await P(s,n,R.filePath,C,S0);if(!N)j0=await g0(j0,{router:C.router});{let{interpolateScriptExpressions:i}=await import("./chunk-da0tfpa2.js");j0=j0.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(A0,q0,N0)=>{if(!/function\s+__stx_setup_/.test(N0))return A0;return`<script${q0}>${i(N0,n)}</script>`})}if(N)j0=O$(j0,{preserveHead:!0});if(a&&X0)await u(R.filePath,j0,S0,C);let{extractStreamBoundaries:Y3}=await import("./chunk-wa3ks5zv.js"),Q1=Y3(n),V1=n.__streamTemplates;if(V1&&typeof V1==="object"&&Object.keys(V1).length>0){let i=n.streamBoundaries||{},A0={...C,autoShell:!1},q0=Object.keys(V1).map((_0)=>({id:_0,render:async()=>{let E1=typeof i[_0]==="function"?await i[_0]():void 0;return P(V1[_0],{...n,$boundary:E1},R.filePath,A0,new Set)}})),N0=new Set(q0.map((_0)=>_0.id));Q1=[...(Q1||[]).filter((_0)=>!N0.has(_0.id)),...q0]}if(Q1&&Q1.length>0)c.add(R.pattern);else Q1=void 0;let l5=T1(n),i5=C1(n);if(X0)S.set(R.filePath,{status:l5,headers:i5});return{route:R,content:j0,status:l5??K0,headers:i5,boundaries:Q1}}catch(P){return console.error(`${B.red}Error building ${B.bright}${R.pattern}${B.reset}:`,P),null}},H0=8,G0=async()=>{f.clear(),q.clear();for(let R=0;R<A.length;R+=H0){let x=A.slice(R,R+H0),P=await Promise.all(x.map((y)=>k(y)));for(let y of P)if(y)f.set(y.route.pattern,y)}for(let R=0;R<E.length;R+=H0){let x=E.slice(R,R+H0),P=await Promise.all(x.map(({route:y})=>k(y)));for(let y of P)if(y)q.set(y.route.pattern,y)}return f.size>0};if(console.log(`${B.blue}Building pages...${B.reset}`),!await G0())return console.error(`${B.red}No pages were successfully built${B.reset}`),!1;await B$(W);let v0=Z;try{if(v0=await h0(Z),v0!==Z)console.log(`${B.yellow}Port ${Z} is busy, using port ${v0} instead${B.reset}`)}catch{return console.error(`${B.red}Could not find an available port${B.reset}`),!1}if(Y){let R=X.hmrPort||v0+1;J=J$({wsPort:R,verbose:!1}),G=J.start(R)}let z0=(R,x)=>{let y=`<script data-stx-route-params>(function(){var p=${JSON.stringify(x).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(R.includes("</head>"))return R.replace("</head>",`${y}</head>`);if(R.includes("<body"))return R.replace(/<body([^>]*)>/,`<body$1>${y}`);return y+R};console.log(`${B.blue}Starting server...${B.reset}`);let Z1=D4({port:v0,async fetch(R){let x=new URL(R.url),P=_?.publicDir||"public",y=m.join(W,P,x.pathname),Z0=m.join(W,x.pathname),R0=m.join(T,x.pathname);if([y,Z0,R0].some((C)=>F(C,W,z)))return new Response("Not Found",{status:404});let[g0,p,u]=await Promise.all([e.promises.stat(y).catch(()=>null),e.promises.stat(Z0).catch(()=>null),e.promises.stat(R0).catch(()=>null)]);if(g0?.isFile()&&!F(y,W,z))return Q5(y);if(p?.isFile()&&!F(Z0,W,z))return Q5(Z0);if(u?.isFile()&&!F(R0,W,z))return Q5(R0);if(x.pathname.startsWith("/_stx/component/")){let C=decodeURIComponent(x.pathname.slice(16));if(C)try{let X0=`<${C} />`,a={...buildConfig,autoShell:!1},o=await processDirectives(X0,{},m.join(W,"components",`${C}.stx`),a,new Set);return new Response(o,{headers:{"Content-Type":"text/html"}})}catch(X0){return new Response(`<div class="stx-async-error">${X0.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(x.pathname==="/_stx/img"){let{handleImageRequest:C}=await import("./chunk-pbct6nxk.js"),X0=await C(R,{publicDir:m.join(W,P),cacheDir:u0(W,"cache","img")});if(X0)return X0}if(D)try{let C=await D.handleRequest(R);if(C.status!==404)return C}catch{}if(w[x.pathname])try{return await w[x.pathname](R)}catch(C){return new Response(JSON.stringify({error:C.message}),{status:500,headers:{"Content-Type":"application/json"}})}let g=await j(R);if(g)return g;let h=Y5(x.pathname,A);if(h){let C=f.get(h.route.pattern),X0=c.has(h.route.pattern);if(h.route.isDynamic&&Object.keys(h.params).length>0||X0){let a=await k(h.route,h.params);if(a)C=a}if(C){let a=C.status??200,o=C.headers??{},K0=(h.route.filePath?y6(await Bun.file(h.route.filePath).text().catch(()=>"")):null)??{};if(K0.validate){if(!await K0.validate({params:h.params})){let D0=await v(404);if(D0){let s=D0;if(s=await J0(s,W),Y)s=P0(s,G);return new Response(s,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(K0.middleware){let O0=x6(x.pathname,h.params,K0,x.search),D0=S6(O0,null,R,{isServer:!0}),s=await P6(K0.middleware,D0);if(s.redirect){let n=s.redirect.path,S0=s.redirect.options.redirectCode||302,j0=new Headers(s.responseHeaders);return j0.set("Location",n),new Response(null,{status:S0,headers:j0})}if(s.abort){let{statusCode:n,message:S0}=s.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${n}</title></head><body><h1>Error ${n}</h1><p>${S0}</p></body></html>`,{status:n,headers:{"Content-Type":"text/html"}})}if(Object.keys(s.state).length>0){let n=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(s.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;C.content=C.content.replace("</head>",`${n}</head>`)}}let d=C.content;if(N&&u6(R)){let O0=b6(d),D0=v6(d),s=d.match(/<title[^>]*>([\s\S]*?)<\/title>/i),n=s?h6(s[1].trim()):"";if(Object.keys(h.params).length>0)d=z0(d,h.params);d=await J0(d,W);let S0=_?.router?.container||"main";return d=m6(d,S0),new Response(d,{status:a,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":O0.layout,"X-STX-Layout-Group":O0.group,"X-STX-Runtime":D0?"true":"false",...n&&{"X-STX-Title":encodeURIComponent(n)},[g6]:f6(),...B1(),"Cache-Control":z$}})}if(N)d=H$(N,d);if(Object.keys(h.params).length>0)d=z0(d,h.params);if(d=await J0(d,W),Y)d=P0(d,G);if(X.native)if(d.includes("<head>"))d=d.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else d="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+d;if(X.titlebarHidden)if(d.includes("<head>"))d=d.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else d=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${d}`;if(C.boundaries&&C.boundaries.length>0){let{renderStreamingPage:O0,streamToResponse:D0}=await import("./chunk-wa3ks5zv.js");return D0(O0(d,C.boundaries,{timeoutMs:30000}),{status:a,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(d,{status:a,headers:{"Content-Type":"text/html",...B1(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...o}})}}if(E.length>0){let C=E.map((a)=>a.route),X0=Y5(x.pathname,C);if(X0){let a=q.get(X0.route.pattern);if(a){let o=a.content;if(N)o=H$(N,o);if(Object.keys(X0.params).length>0)o=z0(o,X0.params);if(o=await J0(o,W),Y)o=P0(o,G);return new Response(o,{status:a.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:a}of V)if(a!=="/"&&x.pathname.startsWith(a)){let o=q.get(a)||q.get(a+"/");if(o){let K0=o.content;if(N)K0=H$(N,K0);if(K0=await J0(K0,W),Y)K0=P0(K0,G);return new Response(K0,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}let Y0=f.get("/");if(Y0){let C=Y0.content;if(C=await J0(C,W),Y)C=P0(C,G);if(X.native)if(C.includes("<head>"))C=C.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else C="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+C;return new Response(C,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let f0=await v(404);if(f0){let C=f0;if(C=await J0(C,W),Y)C=P0(C,G);return new Response(C,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(R){let x=await v(500);if(x)return new Response(x,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${R}
|
|
1611
1611
|
${R.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
1612
1612
|
${B.blue}stx${B.reset} ${B.green}${process.env.stx_VERSION||"v0.0.10"}${B.reset} ${B.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${B.reset}`),console.log(`
|
|
1613
1613
|
${B.bright}\u2192 ${B.cyan}http://localhost:${v0}/${B.reset}`),Y)console.log(`${B.dim} HMR: ws://localhost:${G}${B.reset}`);console.log(`
|
|
@@ -1898,12 +1898,12 @@ Press ${B.cyan}h${B.reset} + ${B.cyan}Enter${B.reset} to show shortcuts`),d0(Z1.
|
|
|
1898
1898
|
<td>@${J.name}</td>
|
|
1899
1899
|
<td>${J.description||"-"}</td>
|
|
1900
1900
|
<td>${J.hasEndTag?"Yes":"No"}</td>
|
|
1901
|
-
</tr>`;Y+="</tbody></table>";for(let J of Z)if(J.example)Y+=`<h3>@${J.name}</h3>`,Y+=`<p>${J.description||""}</p>`,Y+="<h4>Example</h4>",Y+=`<pre><code>${J.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}return Y+="</body></html>",Y}function r4($=[],X=[],Z=[],Q){return JSON.stringify({components:$,templates:X,directives:Z,extraContent:Q||""},null,2)}async function s4($){try{let{componentsDir:X,templatesDir:Z,webComponentsConfig:Q,customDirectives:Y,config:J}=$;if(!J.enabled)return!1;let G=J.outputDir||"docs";if(await _5.promises.mkdir(G,{recursive:!0}),console.log("Generating documentation..."),X)console.log(`Components directory: ${X}`);if(Z)console.log(`Templates directory: ${Z}`);console.log(`Output directory: ${G}`);let W=[];if(J.components!==!1&&X)console.log("Generating component documentation..."),W=await p4(X,Q),console.log(`Found ${W.length} components`);let K=[];if(J.templates!==!1&&Z)console.log("Generating template documentation..."),K=await c4(Z),console.log(`Found ${K.length} templates`);let _=[];if(J.directives!==!1)console.log("Generating directive documentation..."),_=await l4(Y),console.log(`Found ${_.length} directives`);let U=J.format||"markdown",F=J.extraContent,z="",j="";switch(U){case"markdown":z=i4(W,K,_,F),j="md";break;case"html":z=a4(W,K,_,F),j="html";break;case"json":z=r4(W,K,_,F),j="json";break;default:throw Error(`Unsupported documentation format: ${U}`)}let H=k1.join(G,`stx-docs.${j}`);return await Bun.write(H,z),console.log(`Documentation generated: ${H}`),!0}catch(X){return console.error("Error generating documentation:",X),!1}}async function yW($){let X={enabled:!0,outputDir:$.output||"docs",format:$.format||"markdown",components:$.components!==!1,templates:$.templates!==!1,directives:$.directives!==!1,extraContent:$.extraContent},Z=$.componentsDir||w0.componentsDir,Q=$.templatesDir||".";return s4({componentsDir:Z,templatesDir:Q,webComponentsConfig:w0.webComponents,customDirectives:w0.customDirectives,config:X})}import L1 from"process";function S1(){if(typeof globalThis<"u"&&"caches"in globalThis&&"CF"in globalThis)return{platform:"cloudflare",supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!0,capabilities:["kv","r2","d1","durable-objects","queues"]};if(typeof globalThis<"u"&&"Deno"in globalThis)return{platform:"deno",version:globalThis.Deno.version?.deno,supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!0,capabilities:["kv","deploy","ffi"]};if(typeof globalThis<"u"&&"Bun"in globalThis)return{platform:"bun",version:globalThis.Bun.version,supportsStreaming:!0,supportsCrypto:!0,supportsKV:!1,supportsCache:!1,capabilities:["sqlite","ffi","native-modules"]};if(typeof globalThis<"u"&&"EdgeRuntime"in globalThis)return{platform:"vercel",supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!0,capabilities:["edge-config","blob"]};if(typeof globalThis<"u"&&"Netlify"in globalThis)return{platform:"netlify",supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!1,capabilities:["blobs","edge-functions"]};if(typeof globalThis<"u"&&"fastly"in globalThis)return{platform:"fastly",supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!0,capabilities:["dictionary","backend","geolocation"]};if(L1.versions?.node)return{platform:"node",version:L1.versions.node,supportsStreaming:!0,supportsCrypto:!0,supportsKV:!1,supportsCache:!1,capabilities:["fs","child-process","native-modules"]};return{platform:"unknown",supportsStreaming:!1,supportsCrypto:!1,supportsKV:!1,supportsCache:!1,capabilities:[]}}function hW(){let $=S1();return["cloudflare","deno","vercel","netlify","fastly"].includes($.platform)}function dW(){return S1().platform!=="unknown"}function n4($){return{get(X){if($&&X in $){let Z=$[X];return typeof Z==="string"?Z:void 0}if(typeof globalThis<"u"&&"Deno"in globalThis)return globalThis.Deno.env.get(X);if(L1.env)return L1.env[X];return},getOrThrow(X){let Z=this.get(X);if(Z===void 0)throw Error(`Environment variable "${X}" is not set`);return Z},has(X){return this.get(X)!==void 0},all(){let X={};if($){for(let[Z,Q]of Object.entries($))if(typeof Q==="string")X[Z]=Q}if(typeof globalThis<"u"&&"Deno"in globalThis){let Z=globalThis.Deno.env.toObject();Object.assign(X,Z)}if(L1.env){for(let[Z,Q]of Object.entries(L1.env))if(Q!==void 0)X[Z]=Q}return X}}}function o4($){let X=S1();if(X.platform==="cloudflare"&&$)return $;if(X.platform==="deno"&&"Deno"in globalThis)return t4();if(X.platform==="node"||X.platform==="bun")return e4();return}function t4(){let $=null,X=async()=>{if(!$)$=await globalThis.Deno.openKv();return $};return{async get(Z){return(await(await X()).get(["stx",Z])).value},async getWithMetadata(Z){let Q=await X(),Y=await Q.get(["stx",Z]),J=await Q.get(["stx-meta",Z]);return{value:Y.value,metadata:J.value}},async put(Z,Q,Y){let J=await X(),G=Y?.expirationTtl?Y.expirationTtl*1000:void 0;if(await J.set(["stx",Z],Q,G?{expireIn:G}:void 0),Y?.metadata)await J.set(["stx-meta",Z],Y.metadata,G?{expireIn:G}:void 0)},async delete(Z){let Q=await X();await Q.delete(["stx",Z]),await Q.delete(["stx-meta",Z])},async list(Z){let Q=await X(),Y=Z?.prefix?["stx",Z.prefix]:["stx"],J=Q.list({prefix:Y,limit:Z?.limit||100}),G=[];for await(let W of J){let _=W.key.slice(1).join("/");if(!_.startsWith("stx-meta/"))G.push({name:_})}return{keys:G,list_complete:!0}}}}function e4(){let $=new Map,X=()=>{let Z=Date.now();for(let[Q,Y]of $.entries())if(Y.expiration&&Y.expiration<Z)$.delete(Q)};return{async get(Z){X();let Q=$.get(Z);if(!Q)return null;if(Q.expiration&&Q.expiration<Date.now())return $.delete(Z),null;return Q.value},async getWithMetadata(Z){X();let Q=$.get(Z);if(!Q)return{value:null,metadata:null};if(Q.expiration&&Q.expiration<Date.now())return $.delete(Z),{value:null,metadata:null};return{value:Q.value,metadata:Q.metadata||null}},async put(Z,Q,Y){let J=Y?.expiration?Y.expiration*1000:Y?.expirationTtl?Date.now()+Y.expirationTtl*1000:void 0;$.set(Z,{value:Q,metadata:Y?.metadata,expiration:J})},async delete(Z){$.delete(Z)},async list(Z){X();let Q=[];for(let[Y,J]of $.entries()){if(Z?.prefix&&!Y.startsWith(Z.prefix))continue;if(Q.push({name:Y,expiration:J.expiration,metadata:J.metadata}),Z?.limit&&Q.length>=Z.limit)break}return{keys:Q,list_complete:!0}}}}function $X(){let $=S1();if($.platform==="cloudflare"&&"caches"in globalThis)return XX();if($.supportsStreaming)return ZX();return}function XX(){return{async match($){return(await caches.default).match($)},async put($,X){await(await caches.default).put($,X.clone())},async delete($){return(await caches.default).delete($)}}}function ZX(){let $=new Map,X=60000;return{async match(Z){let Q=Z.url,Y=$.get(Q);if(!Y)return;if(Date.now()>Y.expiration){$.delete(Q);return}return Y.response.clone()},async put(Z,Q){let Y=Z.url,J=Q.headers.get("Cache-Control"),G=60000;if(J){let W=J.match(/max-age=(\d+)/);if(W)G=Number.parseInt(W[1],10)*1000}$.set(Y,{response:Q.clone(),expiration:Date.now()+G})},async delete(Z){return $.delete(Z.url)}}}function QX(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,9)}`}function YX($,X){if(X.platform==="cloudflare"){let Z=$.cf;if(Z)return{city:Z.city,country:Z.country,countryCode:Z.country,region:Z.region,latitude:Z.latitude?Number.parseFloat(Z.latitude):void 0,longitude:Z.longitude?Number.parseFloat(Z.longitude):void 0,timezone:Z.timezone}}if(X.platform==="vercel"){let Z={},Q=$.headers.get("x-vercel-ip-city"),Y=$.headers.get("x-vercel-ip-country"),J=$.headers.get("x-vercel-ip-country-region"),G=$.headers.get("x-vercel-ip-latitude"),W=$.headers.get("x-vercel-ip-longitude");if(Q)Z.city=decodeURIComponent(Q);if(Y)Z.countryCode=Y;if(J)Z.region=J;if(G)Z.latitude=Number.parseFloat(G);if(W)Z.longitude=Number.parseFloat(W);return Object.keys(Z).length>0?Z:void 0}if(X.platform==="netlify"){let Z={},Q=$.headers.get("x-nf-geo-city"),Y=$.headers.get("x-nf-geo-country");if(Q)Z.city=Q;if(Y)Z.countryCode=Y;return Object.keys(Z).length>0?Z:void 0}return}function U5($,X,Z){let Q=new Headers($.headers);if(X.origins==="*")Q.set("Access-Control-Allow-Origin","*");else if(X.origins&&Z&&X.origins.includes(Z))Q.set("Access-Control-Allow-Origin",Z),Q.set("Vary","Origin");if(X.methods)Q.set("Access-Control-Allow-Methods",X.methods.join(", "));if(X.headers)Q.set("Access-Control-Allow-Headers",X.headers.join(", "));if(X.exposeHeaders)Q.set("Access-Control-Expose-Headers",X.exposeHeaders.join(", "));if(X.credentials)Q.set("Access-Control-Allow-Credentials","true");if(X.maxAge)Q.set("Access-Control-Max-Age",String(X.maxAge));return new Response($.body,{status:$.status,statusText:$.statusText,headers:Q})}function A$($){let X=S1();return async(Z,Q)=>{let Y=performance.now(),J=QX(),G={runtime:X,platform:Q||{},requestId:J,geo:YX(Z,X),timing:{start:Y,getElapsed:()=>performance.now()-Y},kv:o4(Q?.KV),cache:$X(),env:n4(Q?.env)};try{if(Z.method==="OPTIONS"&&$.cors){let K=new Response(null,{status:204});return K=U5(K,$.cors,Z.headers.get("Origin")||void 0),K}if($.cache?.enabled&&Z.method==="GET"&&G.cache){if(n6(Z,$.cache)){let _=await G.cache.match(Z);if(_){let U=new Response(_.body,_);return U.headers.set("X-Cache","HIT"),U.headers.set("X-Request-Id",J),$.cors?U5(U,$.cors,Z.headers.get("Origin")||void 0):U}}}let W;if($.middleware&&$.middleware.length>0)W=await JX(Z,G,$.middleware,async()=>{let K=await $.render(Z,G);return typeof K==="string"?new Response(K,{headers:{"Content-Type":"text/html; charset=utf-8"}}):K});else{let K=await $.render(Z,G);W=typeof K==="string"?new Response(K,{headers:{"Content-Type":"text/html; charset=utf-8"}}):K}if(W.headers.set("X-Request-Id",J),W.headers.set("X-Response-Time",`${G.timing.getElapsed().toFixed(2)}ms`),$.cache?.enabled&&Z.method==="GET"&&G.cache){if(n6(Z,$.cache)&&W.status===200){let _=$.cache.ttl||60,U=W.clone();U.headers.set("Cache-Control",`public, max-age=${_}`),await G.cache.put(Z,U),W.headers.set("X-Cache","MISS")}}if($.cors)W=U5(W,$.cors,Z.headers.get("Origin")||void 0);return W}catch(W){let K=W instanceof Error?W:Error(String(W));if($.onError)return $.onError(K,Z);return new Response(`Internal Server Error: ${K.message}`,{status:500,headers:{"Content-Type":"text/plain","X-Request-Id":J}})}}}function n6($,X){let Q=new URL($.url).pathname;if(X.excludePaths){for(let Y of X.excludePaths)if(Y.test(Q))return!1}if(X.includePaths){for(let Y of X.includePaths)if(Y.test(Q))return!0;return!1}return!0}async function JX($,X,Z,Q){let Y=0,J=async()=>{if(Y>=Z.length)return Q();let G=Z[Y];return Y++,G($,X,J)};return J()}function uW($,X){let Z=new Headers(X?.headers);return Z.set("Content-Type","text/html; charset=utf-8"),Z.set("Transfer-Encoding","chunked"),new Response($,{...X,headers:Z})}function mW(){let $=new TextEncoder;return new TransformStream({transform(X,Z){Z.enqueue($.encode(X))}})}function pW($){let X=new TextEncoder;return new ReadableStream({async start(Z){for await(let Q of $)Z.enqueue(X.encode(Q));Z.close()}})}function cW($){let X=A$($);return{async fetch(Z,Q,Y){return X(Z,{env:Q,ctx:Y,KV:Q.KV})}}}function lW($){let X=A$($);return(Z)=>X(Z,{})}function iW($){let X=A$($);return(Z)=>X(Z,{})}function aW($){let X=A$($);return(Z,Q)=>{return X(Z,{netlifyContext:Q})}}function rW($){let X=$.headers.get("Cookie");if(!X)return{};let Z={};for(let Q of X.split(";")){let[Y,J]=Q.split("=").map((G)=>G.trim());if(Y&&J)Z[Y]=decodeURIComponent(J)}return Z}function sW($,X,Z){return B5($,X,Z)}function nW($,X){let Z=new Headers(X?.headers);return Z.set("Content-Type","application/json; charset=utf-8"),new Response(JSON.stringify($),{...X,headers:Z})}function oW($,X=302){return new Response(null,{status:X,headers:{Location:$}})}function tW($="Not Found"){return new Response($,{status:404,headers:{"Content-Type":"text/plain"}})}var t6={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function GX($,X={}){let Z={...t6,...X};if($.trim()==="")return`
|
|
1901
|
+
</tr>`;Y+="</tbody></table>";for(let J of Z)if(J.example)Y+=`<h3>@${J.name}</h3>`,Y+=`<p>${J.description||""}</p>`,Y+="<h4>Example</h4>",Y+=`<pre><code>${J.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}return Y+="</body></html>",Y}function r4($=[],X=[],Z=[],Q){return JSON.stringify({components:$,templates:X,directives:Z,extraContent:Q||""},null,2)}async function s4($){try{let{componentsDir:X,templatesDir:Z,webComponentsConfig:Q,customDirectives:Y,config:J}=$;if(!J.enabled)return!1;let G=J.outputDir||"docs";if(await _5.promises.mkdir(G,{recursive:!0}),console.log("Generating documentation..."),X)console.log(`Components directory: ${X}`);if(Z)console.log(`Templates directory: ${Z}`);console.log(`Output directory: ${G}`);let W=[];if(J.components!==!1&&X)console.log("Generating component documentation..."),W=await p4(X,Q),console.log(`Found ${W.length} components`);let K=[];if(J.templates!==!1&&Z)console.log("Generating template documentation..."),K=await c4(Z),console.log(`Found ${K.length} templates`);let _=[];if(J.directives!==!1)console.log("Generating directive documentation..."),_=await l4(Y),console.log(`Found ${_.length} directives`);let U=J.format||"markdown",F=J.extraContent,z="",j="";switch(U){case"markdown":z=i4(W,K,_,F),j="md";break;case"html":z=a4(W,K,_,F),j="html";break;case"json":z=r4(W,K,_,F),j="json";break;default:throw Error(`Unsupported documentation format: ${U}`)}let H=k1.join(G,`stx-docs.${j}`);return await Bun.write(H,z),console.log(`Documentation generated: ${H}`),!0}catch(X){return console.error("Error generating documentation:",X),!1}}async function vW($){let X={enabled:!0,outputDir:$.output||"docs",format:$.format||"markdown",components:$.components!==!1,templates:$.templates!==!1,directives:$.directives!==!1,extraContent:$.extraContent},Z=$.componentsDir||w0.componentsDir,Q=$.templatesDir||".";return s4({componentsDir:Z,templatesDir:Q,webComponentsConfig:w0.webComponents,customDirectives:w0.customDirectives,config:X})}import L1 from"process";function S1(){if(typeof globalThis<"u"&&"caches"in globalThis&&"CF"in globalThis)return{platform:"cloudflare",supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!0,capabilities:["kv","r2","d1","durable-objects","queues"]};if(typeof globalThis<"u"&&"Deno"in globalThis)return{platform:"deno",version:globalThis.Deno.version?.deno,supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!0,capabilities:["kv","deploy","ffi"]};if(typeof globalThis<"u"&&"Bun"in globalThis)return{platform:"bun",version:globalThis.Bun.version,supportsStreaming:!0,supportsCrypto:!0,supportsKV:!1,supportsCache:!1,capabilities:["sqlite","ffi","native-modules"]};if(typeof globalThis<"u"&&"EdgeRuntime"in globalThis)return{platform:"vercel",supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!0,capabilities:["edge-config","blob"]};if(typeof globalThis<"u"&&"Netlify"in globalThis)return{platform:"netlify",supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!1,capabilities:["blobs","edge-functions"]};if(typeof globalThis<"u"&&"fastly"in globalThis)return{platform:"fastly",supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!0,capabilities:["dictionary","backend","geolocation"]};if(L1.versions?.node)return{platform:"node",version:L1.versions.node,supportsStreaming:!0,supportsCrypto:!0,supportsKV:!1,supportsCache:!1,capabilities:["fs","child-process","native-modules"]};return{platform:"unknown",supportsStreaming:!1,supportsCrypto:!1,supportsKV:!1,supportsCache:!1,capabilities:[]}}function dW(){let $=S1();return["cloudflare","deno","vercel","netlify","fastly"].includes($.platform)}function uW(){return S1().platform!=="unknown"}function n4($){return{get(X){if($&&X in $){let Z=$[X];return typeof Z==="string"?Z:void 0}if(typeof globalThis<"u"&&"Deno"in globalThis)return globalThis.Deno.env.get(X);if(L1.env)return L1.env[X];return},getOrThrow(X){let Z=this.get(X);if(Z===void 0)throw Error(`Environment variable "${X}" is not set`);return Z},has(X){return this.get(X)!==void 0},all(){let X={};if($){for(let[Z,Q]of Object.entries($))if(typeof Q==="string")X[Z]=Q}if(typeof globalThis<"u"&&"Deno"in globalThis){let Z=globalThis.Deno.env.toObject();Object.assign(X,Z)}if(L1.env){for(let[Z,Q]of Object.entries(L1.env))if(Q!==void 0)X[Z]=Q}return X}}}function o4($){let X=S1();if(X.platform==="cloudflare"&&$)return $;if(X.platform==="deno"&&"Deno"in globalThis)return t4();if(X.platform==="node"||X.platform==="bun")return e4();return}function t4(){let $=null,X=async()=>{if(!$)$=await globalThis.Deno.openKv();return $};return{async get(Z){return(await(await X()).get(["stx",Z])).value},async getWithMetadata(Z){let Q=await X(),Y=await Q.get(["stx",Z]),J=await Q.get(["stx-meta",Z]);return{value:Y.value,metadata:J.value}},async put(Z,Q,Y){let J=await X(),G=Y?.expirationTtl?Y.expirationTtl*1000:void 0;if(await J.set(["stx",Z],Q,G?{expireIn:G}:void 0),Y?.metadata)await J.set(["stx-meta",Z],Y.metadata,G?{expireIn:G}:void 0)},async delete(Z){let Q=await X();await Q.delete(["stx",Z]),await Q.delete(["stx-meta",Z])},async list(Z){let Q=await X(),Y=Z?.prefix?["stx",Z.prefix]:["stx"],J=Q.list({prefix:Y,limit:Z?.limit||100}),G=[];for await(let W of J){let _=W.key.slice(1).join("/");if(!_.startsWith("stx-meta/"))G.push({name:_})}return{keys:G,list_complete:!0}}}}function e4(){let $=new Map,X=()=>{let Z=Date.now();for(let[Q,Y]of $.entries())if(Y.expiration&&Y.expiration<Z)$.delete(Q)};return{async get(Z){X();let Q=$.get(Z);if(!Q)return null;if(Q.expiration&&Q.expiration<Date.now())return $.delete(Z),null;return Q.value},async getWithMetadata(Z){X();let Q=$.get(Z);if(!Q)return{value:null,metadata:null};if(Q.expiration&&Q.expiration<Date.now())return $.delete(Z),{value:null,metadata:null};return{value:Q.value,metadata:Q.metadata||null}},async put(Z,Q,Y){let J=Y?.expiration?Y.expiration*1000:Y?.expirationTtl?Date.now()+Y.expirationTtl*1000:void 0;$.set(Z,{value:Q,metadata:Y?.metadata,expiration:J})},async delete(Z){$.delete(Z)},async list(Z){X();let Q=[];for(let[Y,J]of $.entries()){if(Z?.prefix&&!Y.startsWith(Z.prefix))continue;if(Q.push({name:Y,expiration:J.expiration,metadata:J.metadata}),Z?.limit&&Q.length>=Z.limit)break}return{keys:Q,list_complete:!0}}}}function $X(){let $=S1();if($.platform==="cloudflare"&&"caches"in globalThis)return XX();if($.supportsStreaming)return ZX();return}function XX(){return{async match($){return(await caches.default).match($)},async put($,X){await(await caches.default).put($,X.clone())},async delete($){return(await caches.default).delete($)}}}function ZX(){let $=new Map,X=60000;return{async match(Z){let Q=Z.url,Y=$.get(Q);if(!Y)return;if(Date.now()>Y.expiration){$.delete(Q);return}return Y.response.clone()},async put(Z,Q){let Y=Z.url,J=Q.headers.get("Cache-Control"),G=60000;if(J){let W=J.match(/max-age=(\d+)/);if(W)G=Number.parseInt(W[1],10)*1000}$.set(Y,{response:Q.clone(),expiration:Date.now()+G})},async delete(Z){return $.delete(Z.url)}}}function QX(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,9)}`}function YX($,X){if(X.platform==="cloudflare"){let Z=$.cf;if(Z)return{city:Z.city,country:Z.country,countryCode:Z.country,region:Z.region,latitude:Z.latitude?Number.parseFloat(Z.latitude):void 0,longitude:Z.longitude?Number.parseFloat(Z.longitude):void 0,timezone:Z.timezone}}if(X.platform==="vercel"){let Z={},Q=$.headers.get("x-vercel-ip-city"),Y=$.headers.get("x-vercel-ip-country"),J=$.headers.get("x-vercel-ip-country-region"),G=$.headers.get("x-vercel-ip-latitude"),W=$.headers.get("x-vercel-ip-longitude");if(Q)Z.city=decodeURIComponent(Q);if(Y)Z.countryCode=Y;if(J)Z.region=J;if(G)Z.latitude=Number.parseFloat(G);if(W)Z.longitude=Number.parseFloat(W);return Object.keys(Z).length>0?Z:void 0}if(X.platform==="netlify"){let Z={},Q=$.headers.get("x-nf-geo-city"),Y=$.headers.get("x-nf-geo-country");if(Q)Z.city=Q;if(Y)Z.countryCode=Y;return Object.keys(Z).length>0?Z:void 0}return}function U5($,X,Z){let Q=new Headers($.headers);if(X.origins==="*")Q.set("Access-Control-Allow-Origin","*");else if(X.origins&&Z&&X.origins.includes(Z))Q.set("Access-Control-Allow-Origin",Z),Q.set("Vary","Origin");if(X.methods)Q.set("Access-Control-Allow-Methods",X.methods.join(", "));if(X.headers)Q.set("Access-Control-Allow-Headers",X.headers.join(", "));if(X.exposeHeaders)Q.set("Access-Control-Expose-Headers",X.exposeHeaders.join(", "));if(X.credentials)Q.set("Access-Control-Allow-Credentials","true");if(X.maxAge)Q.set("Access-Control-Max-Age",String(X.maxAge));return new Response($.body,{status:$.status,statusText:$.statusText,headers:Q})}function A$($){let X=S1();return async(Z,Q)=>{let Y=performance.now(),J=QX(),G={runtime:X,platform:Q||{},requestId:J,geo:YX(Z,X),timing:{start:Y,getElapsed:()=>performance.now()-Y},kv:o4(Q?.KV),cache:$X(),env:n4(Q?.env)};try{if(Z.method==="OPTIONS"&&$.cors){let K=new Response(null,{status:204});return K=U5(K,$.cors,Z.headers.get("Origin")||void 0),K}if($.cache?.enabled&&Z.method==="GET"&&G.cache){if(n6(Z,$.cache)){let _=await G.cache.match(Z);if(_){let U=new Response(_.body,_);return U.headers.set("X-Cache","HIT"),U.headers.set("X-Request-Id",J),$.cors?U5(U,$.cors,Z.headers.get("Origin")||void 0):U}}}let W;if($.middleware&&$.middleware.length>0)W=await JX(Z,G,$.middleware,async()=>{let K=await $.render(Z,G);return typeof K==="string"?new Response(K,{headers:{"Content-Type":"text/html; charset=utf-8"}}):K});else{let K=await $.render(Z,G);W=typeof K==="string"?new Response(K,{headers:{"Content-Type":"text/html; charset=utf-8"}}):K}if(W.headers.set("X-Request-Id",J),W.headers.set("X-Response-Time",`${G.timing.getElapsed().toFixed(2)}ms`),$.cache?.enabled&&Z.method==="GET"&&G.cache){if(n6(Z,$.cache)&&W.status===200){let _=$.cache.ttl||60,U=W.clone();U.headers.set("Cache-Control",`public, max-age=${_}`),await G.cache.put(Z,U),W.headers.set("X-Cache","MISS")}}if($.cors)W=U5(W,$.cors,Z.headers.get("Origin")||void 0);return W}catch(W){let K=W instanceof Error?W:Error(String(W));if($.onError)return $.onError(K,Z);return new Response(`Internal Server Error: ${K.message}`,{status:500,headers:{"Content-Type":"text/plain","X-Request-Id":J}})}}}function n6($,X){let Q=new URL($.url).pathname;if(X.excludePaths){for(let Y of X.excludePaths)if(Y.test(Q))return!1}if(X.includePaths){for(let Y of X.includePaths)if(Y.test(Q))return!0;return!1}return!0}async function JX($,X,Z,Q){let Y=0,J=async()=>{if(Y>=Z.length)return Q();let G=Z[Y];return Y++,G($,X,J)};return J()}function mW($,X){let Z=new Headers(X?.headers);return Z.set("Content-Type","text/html; charset=utf-8"),Z.set("Transfer-Encoding","chunked"),new Response($,{...X,headers:Z})}function pW(){let $=new TextEncoder;return new TransformStream({transform(X,Z){Z.enqueue($.encode(X))}})}function cW($){let X=new TextEncoder;return new ReadableStream({async start(Z){for await(let Q of $)Z.enqueue(X.encode(Q));Z.close()}})}function lW($){let X=A$($);return{async fetch(Z,Q,Y){return X(Z,{env:Q,ctx:Y,KV:Q.KV})}}}function iW($){let X=A$($);return(Z)=>X(Z,{})}function aW($){let X=A$($);return(Z)=>X(Z,{})}function rW($){let X=A$($);return(Z,Q)=>{return X(Z,{netlifyContext:Q})}}function sW($){let X=$.headers.get("Cookie");if(!X)return{};let Z={};for(let Q of X.split(";")){let[Y,J]=Q.split("=").map((G)=>G.trim());if(Y&&J)Z[Y]=decodeURIComponent(J)}return Z}function nW($,X,Z){return B5($,X,Z)}function oW($,X){let Z=new Headers(X?.headers);return Z.set("Content-Type","application/json; charset=utf-8"),new Response(JSON.stringify($),{...X,headers:Z})}function tW($,X=302){return new Response(null,{status:X,headers:{Location:$}})}function eW($="Not Found"){return new Response($,{status:404,headers:{"Content-Type":"text/plain"}})}var t6={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function GX($,X={}){let Z={...t6,...X};if($.trim()==="")return`
|
|
1902
1902
|
`;let Q=$;if(Z.trimTrailingWhitespace)Q=Q.replace(/[ \t]+$/gm,"");if(Q=KX(Q,Z),Q=LX(Q,Z),Q=_X(Q,Z),Z.trimTrailingWhitespace)Q=Q.replace(/[ \t]+$/gm,""),Q=Q.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(Q=Q.replace(/\r\n/g,`
|
|
1903
1903
|
`).replace(/\r/g,`
|
|
1904
1904
|
`),!Q.endsWith(`
|
|
1905
1905
|
`))Q+=`
|
|
1906
|
-
`;return Q}function
|
|
1906
|
+
`;return Q}function X2($,X={}){let Z={...t6,...X};if($.trim()==="")return`
|
|
1907
1907
|
`;let Q=$;if(Q=Q.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(Y,J,G,W,K)=>{let _=W.split(`
|
|
1908
1908
|
`),U=_.filter((L)=>L.trim().length>0);if(U.length===0)return Y;let F=Math.min(...U.map((L)=>{let O=L.match(/^( *)/);return O?O[1].length:0})),z=_.map((L)=>{if(L.trim().length===0)return"";return L.substring(F)}).join(`
|
|
1909
1909
|
`),H=GX(z,Z).trimEnd().split(`
|
|
@@ -1931,7 +1931,7 @@ ${G}`}),X=X.replace(/(<\/[^>]+>)(?=<|$)/g,(Y,J,G,W)=>{let K=W.substring(Math.max
|
|
|
1931
1931
|
`),X=X.replace(/^\n+/,"").replace(/\n+$/,""),X}function KX($,X){let Q=WX($).split(`
|
|
1932
1932
|
`),Y=[],J=0,G=!1,W=X.useTabs?"\t":" ".repeat(X.indentSize);for(let K=0;K<Q.length;K++){let _=Q[K],U=_.trim();if(U===""){Y.push("");continue}let F=U.match(/<script\b/i),z=U.match(/<\/script>/i);if(G&&!z){Y.push(_);continue}let j=U===">";if(o6(U)&&!U.startsWith("<")&&!U.startsWith("@")){Y.push(W.repeat(J)+U);continue}let H=U.startsWith("@end"),L=U.startsWith("@else")||U.startsWith("@elseif"),O=U.startsWith("@")&&BX(U),A=U.startsWith("<!DOCTYPE")||U.startsWith("<!doctype"),V=U.startsWith("<!--"),E=U.startsWith("</"),q=U.startsWith("<")&&!E&&!V&&!A,N=U.includes("/>")||UX(U),I=o6(U);if(E||H)J=Math.max(0,J-1);let M=L?Math.max(0,J-1):J;if(j)Y.push(_);else Y.push(W.repeat(M)+U);if(q&&!N&&!I&&!j||O)J++;if(F)G=!0;if(z)G=!1}return Y.join(`
|
|
1933
1933
|
`)}function _X($,X){if($=$.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(Z,Q,Y)=>{let J=Y.trim().replace(/\s+/g," ");return`@${Q}(${J})`}),$=$.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(Z,Q,Y)=>{if(Y.trim()==="")return`@${Q}`;return`@${Q}(${Y.trim()})`}),X.normalizeWhitespace)$=$.replace(/\{\{\s*([^}]+)\s*\}\}/g,(Z,Q)=>{return`{{ ${Q.trim()} }}`}),$=$.replace(/\{!!\s*([^!]+)\s*!!\}/g,(Z,Q)=>{return`{!! ${Q.trim()} !!}`});return $}function UX($){let X=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if($.includes("/>"))return!0;let Z=$.match(/<(\w+)/);if(Z){let Q=Z[1];return X.includes(Q.toLowerCase())}return!1}function o6($){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test($)}function BX($){let X=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let Z of X)if($.startsWith(`@${Z}`))return!$.includes(`@end${Z}`);return!1}function LX($,X){if(!X.sortAttributes)return $;return $.replace(/<(\w+)([^>]*)>/g,(Z,Q,Y)=>{if(!Y.trim())return Z;if(Y.includes("<")||Y.includes(`
|
|
1934
|
-
`)||Y.includes("@"))return Z;let J=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,G=[],W;while((W=J.exec(Y))!==null)G.push({name:W[1],value:W[2]});G.sort((_,U)=>{if(_.name==="id")return-1;if(U.name==="id")return 1;if(_.name==="class")return-1;if(U.name==="class")return 1;return _.name.localeCompare(U.name)});let K=G.map((_)=>_.value?`${_.name}=${_.value}`:_.name).join(" ");return`<${Q}${K?` ${K}`:""}>`})}import e6 from"fs";import L5 from"path";var
|
|
1934
|
+
`)||Y.includes("@"))return Z;let J=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,G=[],W;while((W=J.exec(Y))!==null)G.push({name:W[1],value:W[2]});G.sort((_,U)=>{if(_.name==="id")return-1;if(U.name==="id")return 1;if(_.name==="class")return-1;if(U.name==="class")return 1;return _.name.localeCompare(U.name)});let K=G.map((_)=>_.value?`${_.name}=${_.value}`:_.name).join(" ");return`<${Q}${K?` ${K}`:""}>`})}import e6 from"fs";import L5 from"path";var J2={basic:{description:"Simple page with script, style, and template sections"},component:{description:"Reusable component with props and slots"},layout:{description:"Layout template with sections and yields"},blog:{description:"Blog post with frontmatter-style variables"},api:{description:"API endpoint template with JSON response"},app:{description:"Full app with stores and components"}};async function G2($="index.stx",X={}){try{let Z=X.force||!1,Q=L5.resolve(process.cwd(),$);if(await Bun.file(Q).exists()){if(!Z)throw Error(`File ${$} already exists. Use --force to overwrite.`);console.warn(`File ${$} already exists. Overwriting...`)}let Y=L5.dirname(Q);if(!e6.existsSync(Y))e6.mkdirSync(Y,{recursive:!0});let J;if(X.template){let G=L5.resolve(process.cwd(),X.template);if(!await Bun.file(G).exists())throw Error(`Template file ${X.template} does not exist.`);if(!G.endsWith(".stx"))console.warn(`Warning: Template file ${X.template} does not have a .stx extension. Using it anyway.`);J=await Bun.file(G).text(),console.warn(`Using template from ${X.template}`)}else if(X.preset)J=$8(X.preset),console.warn(`Using '${X.preset}' preset template`);else J=$8("basic");return await Bun.write(Q,J),console.warn(`Created new stx file: ${$}`),!0}catch(Z){return console.error(`Error creating file: ${Z instanceof Error?Z.message:String(Z)}`),!1}}function $8($){switch($){case"basic":return X8();case"component":return FX();case"layout":return zX();case"blog":return jX();case"api":return HX();case"app":return OX();default:return X8()}}function X8(){return`<script>
|
|
1935
1935
|
const title = "My stx Page"
|
|
1936
1936
|
const description = "A page built with stx"
|
|
1937
1937
|
const features = [
|
|
@@ -2407,14 +2407,14 @@ ${U}`)}else this.warnings.push(`External stylesheet not found: ${_}`)}return""})
|
|
|
2407
2407
|
</table>
|
|
2408
2408
|
</body>
|
|
2409
2409
|
</html>`}generateAnalysisText($){let X=["Bundle Analysis","=".repeat(50),""];for(let Z of $.outputs)X.push(`${Z.path}`),X.push(` Size: ${Z.sizeFormatted}${Z.gzipSizeFormatted?` (gzip: ${Z.gzipSizeFormatted})`:""}`),X.push("");return X.push("=".repeat(50)),X.push(`Total: ${this.formatSize($.totalSize)} (gzip: ${this.formatSize($.totalGzipSize)})`),X.join(`
|
|
2410
|
-
`)}async runPluginHook($,X){if(!this.config.plugins)return;for(let Z of this.config.plugins){let Q=Z[$];if(typeof Q==="function")await Q.call(Z,X||this)}}async runPluginTransform($,X){if(!this.config.plugins)return $;let Z=$;for(let Q of this.config.plugins)if(Q.transform){let Y=await Q.transform(Z,X);if(Y!=null)Z=Y}return Z}generateHash($){return AX("sha256").update($).digest("hex")}getOutputName($,X,Z){let Q=X==="html"?".html":X==="css"?".css":X==="js"?".js":"";return`${$}.${Z.slice(0,8)}${Q}`}formatSize($){if($<1024)return`${$} B`;if($<1048576)return`${($/1024).toFixed(2)} KB`;return`${($/1048576).toFixed(2)} MB`}ensureDir($){if(!P1($))qX($,{recursive:!0})}walkDir($,X){if(!P1($))return;let Z=MX($,{withFileTypes:!0});for(let Q of Z){let Y=C0($,Q.name);if(Q.isDirectory())this.walkDir(Y,X);else X(Y)}}getResult(){let $=Date.now()-this.startTime,X=this.outputs.reduce((Q,Y)=>Q+Y.size,0),Z=this.outputs.reduce((Q,Y)=>Q+(Y.gzipSize||0),0);return{outputs:this.outputs,duration:$,totalSize:X,gzipSize:Z,chunks:this.chunks,assets:this.assets,warnings:this.warnings,errors:this.errors}}}async function
|
|
2410
|
+
`)}async runPluginHook($,X){if(!this.config.plugins)return;for(let Z of this.config.plugins){let Q=Z[$];if(typeof Q==="function")await Q.call(Z,X||this)}}async runPluginTransform($,X){if(!this.config.plugins)return $;let Z=$;for(let Q of this.config.plugins)if(Q.transform){let Y=await Q.transform(Z,X);if(Y!=null)Z=Y}return Z}generateHash($){return AX("sha256").update($).digest("hex")}getOutputName($,X,Z){let Q=X==="html"?".html":X==="css"?".css":X==="js"?".js":"";return`${$}.${Z.slice(0,8)}${Q}`}formatSize($){if($<1024)return`${$} B`;if($<1048576)return`${($/1024).toFixed(2)} KB`;return`${($/1048576).toFixed(2)} MB`}ensureDir($){if(!P1($))qX($,{recursive:!0})}walkDir($,X){if(!P1($))return;let Z=MX($,{withFileTypes:!0});for(let Q of Z){let Y=C0($,Q.name);if(Q.isDirectory())this.walkDir(Y,X);else X(Y)}}getResult(){let $=Date.now()-this.startTime,X=this.outputs.reduce((Q,Y)=>Q+Y.size,0),Z=this.outputs.reduce((Q,Y)=>Q+(Y.gzipSize||0),0);return{outputs:this.outputs,duration:$,totalSize:X,gzipSize:Z,chunks:this.chunks,assets:this.assets,warnings:this.warnings,errors:this.errors}}}async function F2($){return new z5($).build()}function z2($){return new z5($)}function j2($){return{...Q8,...$}}function IX($){return $}var A2="f9c3713";import{existsSync as v1,mkdirSync as j5}from"fs";import{join as p0,dirname as RX}from"path";import{execSync as Y8}from"child_process";var I2={default:{description:"Standard stx project with pages, components, and stores",features:["Pages","Components","Layouts","Stores","Dev server"]},minimal:{description:"Minimal setup with just the essentials",features:["Single page","Basic styles"]},full:{description:"Full-featured project with all stx capabilities",features:["Pages","Components","Layouts","Stores","API routes","PWA","i18n","Testing"]},blog:{description:"Blog template with markdown support",features:["Blog layout","Post pages","Tags","RSS feed","Markdown"]},dashboard:{description:"Admin dashboard template",features:["Sidebar","Charts","Tables","Forms","Auth pages"]},landing:{description:"Marketing landing page template",features:["Hero section","Features","Pricing","CTA","Contact form"]}};async function R2($,X={}){let Z={success:!0,message:"",files:[],errors:[]},Q=X.template||"default",Y=p0(process.cwd(),$);if(v1(Y))return Z.success=!1,Z.message=`Directory ${$} already exists`,Z;try{j5(Y,{recursive:!0});let J=DX(Q);for(let W of J)j5(p0(Y,W),{recursive:!0});let G=wX(Q,$,X);for(let[W,K]of Object.entries(G)){let _=p0(Y,W);g1(RX(_)),await Bun.write(_,K),Z.files.push(W)}if(!X.skipGit)try{Y8("git init",{cwd:Y,stdio:"ignore"}),await Bun.write(p0(Y,".gitignore"),vX()),Z.files.push(".gitignore")}catch{Z.errors.push("Failed to initialize git repository")}if(!X.skipInstall){let W=X.packageManager||QZ();try{console.log(`
|
|
2411
2411
|
Installing dependencies with ${W}...`),Y8(`${W} install`,{cwd:Y,stdio:"inherit"})}catch{Z.errors.push("Failed to install dependencies")}}Z.message=`Created project: ${$}`,console.log(`
|
|
2412
2412
|
\u2705 ${Z.message}
|
|
2413
2413
|
|
|
2414
2414
|
Next steps:
|
|
2415
2415
|
cd ${$}
|
|
2416
2416
|
${X.packageManager||"bun"} run dev
|
|
2417
|
-
`)}catch(J){Z.success=!1,Z.message=`Failed to create project: ${J}`}return Z}function DX($){let X=["pages","components","layouts","partials","public"];switch($){case"minimal":return["src","public"];case"full":return[...X,"src/stores","src/api","src/i18n","src/utils","test"];case"blog":return[...X,"src/posts","src/utils"];case"dashboard":return[...X,"src/stores","src/api","src/utils"];case"landing":return[...X,"src/sections"];default:return[...X,"src/stores"]}}function wX($,X,Z){let Q={};if(Q["package.json"]=SX(X,$,Z),Q["stx.config.ts"]=PX($,Z),Q["README.md"]=yX(X,$),Z.typescript!==!1)Q["tsconfig.json"]=bX();switch($){case"minimal":Q["src/index.stx"]=gX();break;case"blog":Q["pages/index.stx"]=uX(),Q["pages/[slug].stx"]=mX(),Q["layouts/app.stx"]=pX(),Q["components/PostCard.stx"]=cX();break;case"dashboard":Q["pages/index.stx"]=lX(),Q["pages/settings.stx"]=iX(),Q["layouts/app.stx"]=aX(),Q["components/Sidebar.stx"]=rX(),Q["components/StatsCard.stx"]=sX(),Q["src/stores/dashboard.ts"]=nX();break;case"landing":Q["pages/index.stx"]=oX(),Q["layouts/app.stx"]=tX(),Q["src/sections/Hero.stx"]=eX(),Q["src/sections/Features.stx"]=$Z(),Q["src/sections/Pricing.stx"]=XZ(),Q["components/Button.stx"]=ZZ();break;case"full":Q["pages/index.stx"]=J8(),Q["pages/about.stx"]=fX(),Q["layouts/app.stx"]=G8(),Q["components/Header.stx"]=W8(),Q["components/Footer.stx"]=K8(),Q["src/stores/app.ts"]=_8(),Q["src/i18n/en.json"]=hX("en"),Q["test/example.test.ts"]=dX();break;default:Q["pages/index.stx"]=J8(),Q["layouts/app.stx"]=G8(),Q["components/Header.stx"]=W8(),Q["components/Footer.stx"]=K8(),Q["src/stores/app.ts"]=_8()}return Q}async function
|
|
2417
|
+
`)}catch(J){Z.success=!1,Z.message=`Failed to create project: ${J}`}return Z}function DX($){let X=["pages","components","layouts","partials","public"];switch($){case"minimal":return["src","public"];case"full":return[...X,"src/stores","src/api","src/i18n","src/utils","test"];case"blog":return[...X,"src/posts","src/utils"];case"dashboard":return[...X,"src/stores","src/api","src/utils"];case"landing":return[...X,"src/sections"];default:return[...X,"src/stores"]}}function wX($,X,Z){let Q={};if(Q["package.json"]=SX(X,$,Z),Q["stx.config.ts"]=PX($,Z),Q["README.md"]=yX(X,$),Z.typescript!==!1)Q["tsconfig.json"]=bX();switch($){case"minimal":Q["src/index.stx"]=gX();break;case"blog":Q["pages/index.stx"]=uX(),Q["pages/[slug].stx"]=mX(),Q["layouts/app.stx"]=pX(),Q["components/PostCard.stx"]=cX();break;case"dashboard":Q["pages/index.stx"]=lX(),Q["pages/settings.stx"]=iX(),Q["layouts/app.stx"]=aX(),Q["components/Sidebar.stx"]=rX(),Q["components/StatsCard.stx"]=sX(),Q["src/stores/dashboard.ts"]=nX();break;case"landing":Q["pages/index.stx"]=oX(),Q["layouts/app.stx"]=tX(),Q["src/sections/Hero.stx"]=eX(),Q["src/sections/Features.stx"]=$Z(),Q["src/sections/Pricing.stx"]=XZ(),Q["components/Button.stx"]=ZZ();break;case"full":Q["pages/index.stx"]=J8(),Q["pages/about.stx"]=fX(),Q["layouts/app.stx"]=G8(),Q["components/Header.stx"]=W8(),Q["components/Footer.stx"]=K8(),Q["src/stores/app.ts"]=_8(),Q["src/i18n/en.json"]=hX("en"),Q["test/example.test.ts"]=dX();break;default:Q["pages/index.stx"]=J8(),Q["layouts/app.stx"]=G8(),Q["components/Header.stx"]=W8(),Q["components/Footer.stx"]=K8(),Q["src/stores/app.ts"]=_8()}return Q}async function D2($,X={}){let Z={success:!0,message:"",files:[],errors:[]},Q=X.dir||"components",Y=H5($),J=p0(Q,`${Y}.stx`);if(await Bun.file(J).exists()&&!X.force)return Z.success=!1,Z.message=`Component ${Y} already exists. Use --force to overwrite.`,Z;try{g1(Q);let G=TX(Y,X);await Bun.write(J,G),Z.files.push(J),Z.message=`Created component: ${J}`,console.log(`\u2705 ${Z.message}`)}catch(G){Z.success=!1,Z.message=`Failed to create component: ${G}`}return Z}async function w2($,X={}){let Z={success:!0,message:"",files:[],errors:[]},Q=X.dir||"pages",Y=$.toLowerCase().replace(/\s+/g,"-"),J=p0(Q,`${Y}.stx`);if(await Bun.file(J).exists()&&!X.force)return Z.success=!1,Z.message=`Page ${Y} already exists. Use --force to overwrite.`,Z;try{g1(Q);let G=CX(Y,X);await Bun.write(J,G),Z.files.push(J),Z.message=`Created page: ${J}`,console.log(`\u2705 ${Z.message}`)}catch(G){Z.success=!1,Z.message=`Failed to create page: ${G}`}return Z}async function T2($,X={}){let Z={success:!0,message:"",files:[],errors:[]},Q=X.dir||"src/stores",Y=YZ($),J=p0(Q,`${Y}.ts`);if(await Bun.file(J).exists()&&!X.force)return Z.success=!1,Z.message=`Store ${Y} already exists. Use --force to overwrite.`,Z;try{g1(Q);let G=kX(Y,X);await Bun.write(J,G),Z.files.push(J),Z.message=`Created store: ${J}`,console.log(`\u2705 ${Z.message}`)}catch(G){Z.success=!1,Z.message=`Failed to create store: ${G}`}return Z}async function C2($,X={}){let Z={success:!0,message:"",files:[],errors:[]},Q=X.dir||"layouts",Y=$.toLowerCase().replace(/\s+/g,"-"),J=p0(Q,`${Y}.stx`);if(await Bun.file(J).exists()&&!X.force)return Z.success=!1,Z.message=`Layout ${Y} already exists. Use --force to overwrite.`,Z;try{g1(Q);let G=xX(Y,X);await Bun.write(J,G),Z.files.push(J),Z.message=`Created layout: ${J}`,console.log(`\u2705 ${Z.message}`)}catch(G){Z.success=!1,Z.message=`Failed to create layout: ${G}`}return Z}function TX($,X){let Z=[];if(Z.push(`{{-- Component: ${$} --}}`),X.props!==!1)Z.push(`<script>
|
|
2418
2418
|
// Props
|
|
2419
2419
|
const title = props.title || '${$}'
|
|
2420
2420
|
const variant = props.variant || 'default'
|
|
@@ -2881,17 +2881,17 @@ describe('Example', () => {
|
|
|
2881
2881
|
</footer>
|
|
2882
2882
|
@yield('scripts')
|
|
2883
2883
|
</body>
|
|
2884
|
-
</html>`}function eX(){return"<!-- Hero section -->"}function $Z(){return"<!-- Features -->"}function XZ(){return"<!-- Pricing -->"}function ZZ(){return"<!-- Button -->"}function g1($){if(!v1($))j5($,{recursive:!0})}function QZ(){if(v1("bun.lockb"))return"bun";if(v1("pnpm-lock.yaml"))return"pnpm";if(v1("yarn.lock"))return"yarn";return"bun"}function H5($){return $.replace(/[-_\s]+(.)?/g,(X,Z)=>Z?Z.toUpperCase():"").replace(/^./,(X)=>X.toUpperCase())}function YZ($){return $.replace(/[-_\s]+(.)?/g,(X,Z)=>Z?Z.toUpperCase():"").replace(/^./,(X)=>X.toLowerCase())}function e0($){return $.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase()}var{serve:JZ}=globalThis.Bun;import f1 from"fs";import I0 from"path";function
|
|
2884
|
+
</html>`}function eX(){return"<!-- Hero section -->"}function $Z(){return"<!-- Features -->"}function XZ(){return"<!-- Pricing -->"}function ZZ(){return"<!-- Button -->"}function g1($){if(!v1($))j5($,{recursive:!0})}function QZ(){if(v1("bun.lockb"))return"bun";if(v1("pnpm-lock.yaml"))return"pnpm";if(v1("yarn.lock"))return"yarn";return"bun"}function H5($){return $.replace(/[-_\s]+(.)?/g,(X,Z)=>Z?Z.toUpperCase():"").replace(/^./,(X)=>X.toUpperCase())}function YZ($){return $.replace(/[-_\s]+(.)?/g,(X,Z)=>Z?Z.toUpperCase():"").replace(/^./,(X)=>X.toLowerCase())}function e0($){return $.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase()}var{serve:JZ}=globalThis.Bun;import f1 from"fs";import I0 from"path";function u2($,X=200,Z={}){return new Response($,{status:X,headers:{"Content-Type":"text/html; charset=utf-8",...Z}})}async function O5($){let{loadStxConfig:X}=await import("./chunk-2p68bkza.js");return{...await X($.configDir??process.cwd()),...$.stxOptions??{}}}async function GZ($={}){let{port:X=3000,root:Z=".",watch:Q=!0,onRequest:Y,routes:J={},middleware:G=[],on404:W,onError:K}=$,_=I0.resolve(Z),U=await O5($),F=I0.resolve($.configDir??process.cwd()),z=await A5(F,U.serverApi),j=new Map;async function H(q){let N=f1.statSync(q),I=`${q}:${N.mtimeMs}`,M=j.get(I);if(M)return{content:M.content,status:M.status,headers:M.headers};for(let W0 of j.keys())if(W0.startsWith(`${q}:`)&&W0!==I)j.delete(W0);let w=await Bun.file(q).text(),D=w,T=W$(w);if(T)D=T.content.trim();let f=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,c=[],v=[],S;while((S=f.exec(w))!==null){let W0=S[1],R=S[2],x=S[0];if(W0.includes("server"))v.push(R);else c.push(x)}let k=w.match(/<style\b[^>]*>[\s\S]*?<\/style>/gi)||[],H0=D.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,""),G0={__filename:q,__dirname:I0.dirname(q),__stx_options:U};for(let W0 of v)await M0(W0,G0,q);let z0=await V0(H0,G0,q,U,new Set);if(k.length>0){let W0=k.join(`
|
|
2885
2885
|
`);if(z0.match(/(<\/head>)/i))z0=z0.replace(/(<\/head>)/i,`${W0}
|
|
2886
2886
|
$1`)}if(c.length>0){let{interpolateScriptsInTemplate:W0}=await import("./chunk-da0tfpa2.js"),R=W0(c.join(`
|
|
2887
2887
|
`),G0);if(z0.match(/(<\/body>)/i))z0=z0.replace(/(<\/body>)/i,`${R}
|
|
2888
2888
|
$1`);else z0+=`
|
|
2889
2889
|
${R}`}let Z1=T1(G0),l$=C1(G0);return j.set(I,{content:z0,mtime:N.mtimeMs,status:Z1,headers:l$}),{content:z0,status:Z1,headers:l$}}async function L(q){let N=f1.statSync(q),I=`${q}:${N.mtimeMs}`,M=j.get(I);if(M)return M.content;let{content:w}=await T0(q,U);return j.set(I,{content:w,mtime:N.mtimeMs}),w}function O(q){let N=q.startsWith("/")?q.slice(1):q,I=[N,`${N}.stx`,`${N}.md`,`${N}.html`,I0.join(N,"index.stx"),I0.join(N,"index.md"),I0.join(N,"index.html")];for(let M of[_,...U._layerPageDirs??[]])for(let w of I){let D=I0.resolve(M,w);if(!D.startsWith(`${I0.resolve(M)}${I0.sep}`))continue;if(f1.existsSync(D)&&f1.statSync(D).isFile())return D}return null}async function A(q){if(U._layerGraph){let M=await O5($);if(M._layerGraph!==U._layerGraph)Object.assign(U,M),j.clear()}let N=new URL(q.url),I=async()=>{if(J[N.pathname])return await J[N.pathname](q);if(Y){let D=await Y(q);if(D)return D}if(U.apiRouter){let D=await U.apiRouter.handleRequest(q);if(D.status!==404)return D}if(U.apiRoutes?.[N.pathname])return U.apiRoutes[N.pathname](q);let M=await z(q);if(M)return M;let w=O(N.pathname);if(!w||U8(w,F,U.serverApi)){if(W)return await W(q);return new Response("Not Found",{status:404})}try{let D,T="text/html",f,c;if(w.endsWith(".stx")){let v=await H(w);D=v.content,f=v.status,c=v.headers}else if(w.endsWith(".md"))D=await L(w);else if(w.endsWith(".html"))D=await Bun.file(w).text();else if(w.endsWith(".css"))D=await Bun.file(w).text(),T="text/css";else if(w.endsWith(".js"))D=await Bun.file(w).text(),T="text/javascript";else if(w.endsWith(".json"))D=await Bun.file(w).text(),T="application/json";else return new Response(Bun.file(w));return new Response(D,{status:f??200,headers:{"Content-Type":T,...c}})}catch(D){if(K)return await K(D,q);let T=D instanceof Error?D.message:String(D),c=U?.debug===!0?`<h1>Error</h1><pre>${T}
|
|
2890
|
-
${D instanceof Error?D.stack:""}</pre>`:"<h1>Internal Server Error</h1><p>An error occurred while processing your request.</p>";return new Response(c,{status:500,headers:{"Content-Type":"text/html"}})}};for(let M=G.length-1;M>=0;M--){let w=G[M],D=I;I=async()=>await w(q,D)}return await I()}let V=JZ({port:X,fetch:async(q)=>F$(q,await A(q))}),E=null;if(Q)E=f1.watch(_,{recursive:!0},(q,N)=>{if(N&&(N.endsWith(".stx")||N.endsWith(".md")||N.endsWith(".html")))j.clear()});return{server:V,url:V.url.toString(),stop(){if(E)E.close();V.stop()}}}async function
|
|
2890
|
+
${D instanceof Error?D.stack:""}</pre>`:"<h1>Internal Server Error</h1><p>An error occurred while processing your request.</p>";return new Response(c,{status:500,headers:{"Content-Type":"text/html"}})}};for(let M=G.length-1;M>=0;M--){let w=G[M],D=I;I=async()=>await w(q,D)}return await I()}let V=JZ({port:X,fetch:async(q)=>F$(q,await A(q))}),E=null;if(Q)E=f1.watch(_,{recursive:!0},(q,N)=>{if(N&&(N.endsWith(".stx")||N.endsWith(".md")||N.endsWith(".html")))j.clear()});return{server:V,url:V.url.toString(),stop(){if(E)E.close();V.stop()}}}async function m2($,X={}){let Z=I0.resolve($);if(!await Bun.file(Z).exists())throw Error(`File not found: ${Z}`);let Q=Z.endsWith(".md"),Y=Z.endsWith(".stx");if(!Q&&!Y)throw Error(`Unsupported file type: ${Z}. Only .stx and .md files are supported.`);let J=await O5(X);return await GZ({...X,root:I0.dirname(Z),routes:{"/":async()=>{let G,W=200,K;if(Q){let{content:_}=await T0(Z,J);G=_}else{let _=await Bun.file(Z).text(),U=[],F=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,z;while((z=F.exec(_))!==null)if(z[1].includes("server"))U.push(z[2]);let j=U.join(`
|
|
2891
2891
|
`),H=_.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,""),L={__stx_options:J};if(j.trim())await M0(j,L,Z);G=await V0(H,L,Z,J,new Set),W=T1(L)??200,K=C1(L)}return new Response(G,{status:W,headers:{"Content-Type":"text/html",...K}})},...X.routes}})}function WZ($){return $}function KZ($){return $}import{existsSync as _Z,readFileSync as UZ}from"fs";var BZ={strict:!1,allowAny:!0,checkPropertyAccess:!0,checkFunctionCalls:!0,includeBuiltins:!0},B8={console:{kind:"object",properties:{log:{kind:"function",params:[{name:"message",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"void"}},error:{kind:"function",params:[{name:"message",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"void"}},warn:{kind:"function",params:[{name:"message",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"void"}}}},Math:{kind:"object",properties:{abs:{kind:"function",params:[{name:"x",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},floor:{kind:"function",params:[{name:"x",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},ceil:{kind:"function",params:[{name:"x",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},round:{kind:"function",params:[{name:"x",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},max:{kind:"function",params:[{name:"values",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},min:{kind:"function",params:[{name:"values",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},random:{kind:"function",params:[],returnType:{kind:"primitive",value:"number"}},PI:{kind:"primitive",value:"number"},E:{kind:"primitive",value:"number"}}},JSON:{kind:"object",properties:{stringify:{kind:"function",params:[{name:"value",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"string"}},parse:{kind:"function",params:[{name:"text",type:{kind:"primitive",value:"string"}}],returnType:{kind:"primitive",value:"any"}}}},Date:{kind:"function",returnType:{kind:"object",properties:{getTime:{kind:"function",params:[],returnType:{kind:"primitive",value:"number"}},toISOString:{kind:"function",params:[],returnType:{kind:"primitive",value:"string"}},toLocaleDateString:{kind:"function",params:[],returnType:{kind:"primitive",value:"string"}}}}},Array:{kind:"object",properties:{isArray:{kind:"function",params:[{name:"value",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"boolean"}},from:{kind:"function",params:[{name:"arrayLike",type:{kind:"primitive",value:"any"}}],returnType:{kind:"array",elementType:{kind:"primitive",value:"any"}}}}},Object:{kind:"object",properties:{keys:{kind:"function",params:[{name:"obj",type:{kind:"primitive",value:"any"}}],returnType:{kind:"array",elementType:{kind:"primitive",value:"string"}}},values:{kind:"function",params:[{name:"obj",type:{kind:"primitive",value:"any"}}],returnType:{kind:"array",elementType:{kind:"primitive",value:"any"}}},entries:{kind:"function",params:[{name:"obj",type:{kind:"primitive",value:"any"}}],returnType:{kind:"array",elementType:{kind:"primitive",value:"any"}}}}},String:{kind:"function",params:[{name:"value",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"string"}},Number:{kind:"function",params:[{name:"value",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"number"}},Boolean:{kind:"function",params:[{name:"value",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"boolean"}},props:{kind:"object",properties:{}},slot:{kind:"primitive",value:"string"},loop:{kind:"object",properties:{index:{kind:"primitive",value:"number"},iteration:{kind:"primitive",value:"number"},first:{kind:"primitive",value:"boolean"},last:{kind:"primitive",value:"boolean"},even:{kind:"primitive",value:"boolean"},odd:{kind:"primitive",value:"boolean"},count:{kind:"primitive",value:"number"},remaining:{kind:"primitive",value:"number"},depth:{kind:"primitive",value:"number"},parent:{kind:"object",properties:{}}}}};class L8{options;variables=new Map;errors=[];warnings=[];currentFile="";constructor($={}){if(this.options={...BZ,...$},this.options.includeBuiltins)Object.entries(B8).forEach(([X,Z])=>{this.variables.set(X,Z)});if(this.options.customTypes)Object.entries(this.options.customTypes).forEach(([X,Z])=>{this.variables.set(X,Z)})}checkFile($){if(this.currentFile=$,this.errors=[],this.warnings=[],!_Z($))return this.errors.push({message:`File not found: ${$}`,file:$,line:0,column:0,expression:"",severity:"error"}),this.getResult();let X=UZ($,"utf-8");return this.checkTemplate(X,$)}checkTemplate($,X="<inline>"){this.currentFile=X,this.errors=[],this.warnings=[];let Z=$.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(Z)this.analyzeScript(Z[1],$.indexOf(Z[0]));return this.checkDirectives($),this.checkExpressions($),this.getResult()}analyzeScript($,X){let Z=$.split(`
|
|
2892
2892
|
`),Q=this.getLineNumber(X);for(let Y=0;Y<Z.length;Y++){let J=Z[Y],G=Q+Y;this.extractTypedVariables(J,G),this.extractInterfaces(J,Z,Y,G),this.extractTypeAliases(J,G)}}extractTypedVariables($,X){let Z=$.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*:\s*([^=]+?)\s*=/);if(Z){let[,J,G]=Z,W=this.parseTypeAnnotation(G.trim());this.variables.set(J,W);return}let Q=$.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(.+)/);if(Q){let[,J,G]=Q,W=this.inferType(G.trim());this.variables.set(J,W);return}let Y=$.match(/(?:export\s+)?function\s+(\w+)\s*\(([^)]*)\)(?:\s*:\s*(\w+))?/);if(Y){let[,J,G,W]=Y,K=this.parseParams(G),_=W?this.parseTypeAnnotation(W):{kind:"primitive",value:"any"};this.variables.set(J,{kind:"function",params:K,returnType:_})}}extractInterfaces($,X,Z,Q){let Y=$.match(/(?:export\s+)?interface\s+(\w+)\s*\{/);if(Y){let[,J]=Y,G={},W=1,K=Z+1;while(K<X.length&&W>0){let _=X[K].trim();if(_.includes("{"))W++;if(_.includes("}"))W--;let U=_.match(/(\w+)\??\s*:\s*([^;]+)/);if(U&&W>0){let[,F,z]=U;G[F]=this.parseTypeAnnotation(z.trim())}K++}this.variables.set(J,{kind:"object",name:J,properties:G})}}extractTypeAliases($,X){let Z=$.match(/(?:export\s+)?type\s+(\w+)\s*=\s*(.+)/);if(Z){let[,Q,Y]=Z,J=this.parseTypeAnnotation(Y.trim());J.name=Q,this.variables.set(Q,J)}}parseTypeAnnotation($){let X=$.trim();if(X.includes("|"))return{kind:"union",types:X.split("|").map((J)=>this.parseTypeAnnotation(J.trim()))};if(X.includes("&"))return{kind:"intersection",types:X.split("&").map((J)=>this.parseTypeAnnotation(J.trim()))};if(X.endsWith("[]"))return{kind:"array",elementType:this.parseTypeAnnotation(X.slice(0,-2))};let Z=X.match(/^Array<(.+)>$/);if(Z)return{kind:"array",elementType:this.parseTypeAnnotation(Z[1])};if(X.startsWith("{")&&X.endsWith("}")){let Y={},J=X.slice(1,-1).trim();if(J){let G=this.splitByComma(J);for(let W of G){let K=W.match(/(\w+)\??\s*:\s*(.+)/);if(K){let[,_,U]=K;Y[_]=this.parseTypeAnnotation(U.trim())}}}return{kind:"object",properties:Y}}if(X.startsWith('"')||X.startsWith("'"))return{kind:"literal",value:X.slice(1,-1)};if(/^\d+$/.test(X))return{kind:"literal",value:X};if(X==="true"||X==="false")return{kind:"literal",value:X};if(["string","number","boolean","null","undefined","any","unknown","void","never"].includes(X))return{kind:"primitive",value:X};if(this.variables.has(X))return this.variables.get(X);return{kind:"primitive",value:"any"}}inferType($){let X=$.trim().replace(/;$/,"");if(X.startsWith('"')&&X.endsWith('"')||X.startsWith("'")&&X.endsWith("'")||X.startsWith("`")&&X.endsWith("`"))return{kind:"primitive",value:"string"};if(/^-?\d+(\.\d+)?$/.test(X))return{kind:"primitive",value:"number"};if(X==="true"||X==="false")return{kind:"primitive",value:"boolean"};if(X==="null")return{kind:"primitive",value:"null"};if(X==="undefined")return{kind:"primitive",value:"undefined"};if(X.startsWith("[")){let Z=X.slice(1,-1).trim();if(Z){let Q=this.splitByComma(Z)[0];if(Q)return{kind:"array",elementType:this.inferType(Q.trim())}}return{kind:"array",elementType:{kind:"primitive",value:"any"}}}if(X.startsWith("{")){let Z={},Q=this.extractObjectLiteral(X);for(let[Y,J]of Object.entries(Q))Z[Y]=this.inferType(J);return{kind:"object",properties:Z}}if(X.includes("=>")){let Z=X.match(/^\(([^)]*)\)\s*(?::\s*(\w+))?\s*=>/);if(Z){let Q=this.parseParams(Z[1]),Y=Z[2]?this.parseTypeAnnotation(Z[2]):{kind:"primitive",value:"any"};return{kind:"function",params:Q,returnType:Y}}}if(/^\w+$/.test(X)&&this.variables.has(X))return this.variables.get(X);if(X.includes("."))return this.resolvePropertyAccess(X);if(X.includes("(")){let Z=X.split("(")[0],Q=this.variables.get(Z);if(Q?.kind==="function"&&Q.returnType)return Q.returnType}return{kind:"primitive",value:"any"}}parseParams($){if(!$.trim())return[];let X=[],Z=this.splitByComma($);for(let Q of Z){let Y=Q.trim(),J=Y.includes("?"),G=Y.match(/(\w+)\??\s*(?::\s*([^=]+))?(?:\s*=)?/);if(G){let[,W,K]=G,_=K?this.parseTypeAnnotation(K.trim()):{kind:"primitive",value:"any"};X.push({name:W,type:_,optional:J})}}return X}checkExpressions($){let X=/\{\{([\s\S]*?)\}\}/g,Z;while((Z=X.exec($))!==null){let Y=Z[1].trim(),J=Z.index,G=this.getLineNumber(J,$),W=this.getColumn(J,$);if(!Y)continue;if(Y.startsWith("!")||Y.endsWith("!"))continue;this.checkExpression(Y,G,W)}let Q=/\{!!([\s\S]*?)!!\}/g;while((Z=Q.exec($))!==null){let Y=Z[1].trim(),J=Z.index,G=this.getLineNumber(J,$),W=this.getColumn(J,$);if(!Y)continue;this.checkExpression(Y,G,W)}}checkExpression($,X,Z){if($.includes("?")&&$.includes(":")){let J=$.split("?");this.checkExpression(J[0].trim(),X,Z);let G=J.slice(1).join("?").split(":");if(G.length>=2)this.checkExpression(G[0].trim(),X,Z),this.checkExpression(G.slice(1).join(":").trim(),X,Z);return}for(let J of["&&","||","??"])if($.includes(J)){$.split(J).forEach((W)=>this.checkExpression(W.trim(),X,Z));return}for(let J of["===","!==","==","!=",">=","<=",">","<"])if($.includes(J)){$.split(J).forEach((W)=>this.checkExpression(W.trim(),X,Z));return}if($.startsWith("!")){this.checkExpression($.slice(1).trim(),X,Z);return}if(this.isLiteral($))return;let Q=$.match(/^(\w+(?:\.\w+)*)\s*\(/);if(Q){let J=Q[1],G=this.resolvePropertyAccess(J);if(G.kind!=="function"&&G.value!=="any")this.addWarning(`'${J}' is not a function`,X,Z,$);return}if($.includes(".")){if(this.resolvePropertyAccess($).value==="undefined"&&this.options.checkPropertyAccess)this.addWarning(`Property access '${$}' may be undefined`,X,Z,$);return}let Y=$.match(/^\w+/)?.[0];if(Y&&!this.variables.has(Y))this.addError(`Variable '${Y}' is not defined`,X,Z,$)}checkDirectives($){let X=/@if\s*\(([^)]+)\)/g,Z;while((Z=X.exec($))!==null){let G=Z[1].trim(),W=Z.index,K=this.getLineNumber(W,$),_=this.getColumn(W,$);this.checkExpression(G,K,_)}let Q=/@foreach\s*\((\w+)\s+(?:as|in)\s+(\w+)(?:\s*,\s*(\w+))?\)/g;while((Z=Q.exec($))!==null){let[,G,W,K]=Z,_=Z.index,U=this.getLineNumber(_,$),F=this.getColumn(_,$);if(!this.variables.has(G))this.addError(`Collection '${G}' is not defined`,U,F,Z[0]);else{let z=this.variables.get(G);if(z.kind==="array"&&z.elementType)this.variables.set(W,z.elementType);else this.variables.set(W,{kind:"primitive",value:"any"});if(K)this.variables.set(K,{kind:"primitive",value:"number"})}}let Y=/@unless\s*\(([^)]+)\)/g;while((Z=Y.exec($))!==null){let G=Z[1].trim(),W=Z.index,K=this.getLineNumber(W,$),_=this.getColumn(W,$);this.checkExpression(G,K,_)}let J=/@switch\s*\(([^)]+)\)/g;while((Z=J.exec($))!==null){let G=Z[1].trim(),W=Z.index,K=this.getLineNumber(W,$),_=this.getColumn(W,$);this.checkExpression(G,K,_)}}resolvePropertyAccess($){let X=$.split("."),Z=this.variables.get(X[0])||{kind:"primitive",value:"any"};for(let Q=1;Q<X.length;Q++){let Y=X[Q].replace(/\(\)$/,"");if(Z.kind==="object"&&Z.properties)if(Z.properties[Y])Z=Z.properties[Y];else if(!this.options.allowAny)return{kind:"primitive",value:"undefined"};else Z={kind:"primitive",value:"any"};else if(Z.kind==="array"&&Z.elementType)if(["length"].includes(Y))Z={kind:"primitive",value:"number"};else if(["map","filter","find","forEach","some","every","reduce"].includes(Y))Z={kind:"function",returnType:{kind:"primitive",value:"any"}};else if(["join"].includes(Y))Z={kind:"function",returnType:{kind:"primitive",value:"string"}};else Z={kind:"primitive",value:"any"};else if(Z.kind==="primitive"&&Z.value==="string")if(["length"].includes(Y))Z={kind:"primitive",value:"number"};else if(["toUpperCase","toLowerCase","trim","slice","substring"].includes(Y))Z={kind:"function",returnType:{kind:"primitive",value:"string"}};else if(["split"].includes(Y))Z={kind:"function",returnType:{kind:"array",elementType:{kind:"primitive",value:"string"}}};else Z={kind:"primitive",value:"any"};else Z={kind:"primitive",value:"any"}}return Z}isLiteral($){let X=$.trim();if(X.startsWith('"')&&X.endsWith('"')||X.startsWith("'")&&X.endsWith("'")||X.startsWith("`")&&X.endsWith("`"))return!0;if(/^-?\d+(\.\d+)?$/.test(X))return!0;if(X==="true"||X==="false")return!0;if(X==="null"||X==="undefined")return!0;return!1}extractObjectLiteral($){let X={},Z=$.slice(1,-1).trim();if(!Z)return X;let Q=this.splitByComma(Z);for(let Y of Q){let J=Y.indexOf(":");if(J>0){let G=Y.slice(0,J).trim(),W=Y.slice(J+1).trim();X[G]=W}}return X}splitByComma($){let X=[],Z="",Q=0,Y=null;for(let J=0;J<$.length;J++){let G=$[J],W=J>0?$[J-1]:"";if((G==='"'||G==="'"||G==="`")&&W!=="\\"){if(Y===G)Y=null;else if(!Y)Y=G}if(!Y){if(G==="{"||G==="["||G==="(")Q++;if(G==="}"||G==="]"||G===")")Q--;if(G===","&&Q===0){X.push(Z.trim()),Z="";continue}}Z+=G}if(Z.trim())X.push(Z.trim());return X}getLineNumber($,X){return((X||"").slice(0,$).match(/\n/g)||[]).length+1}getColumn($,X){let Q=X.slice(0,$).lastIndexOf(`
|
|
2893
|
-
`);return $-Q}addError($,X,Z,Q,Y,J){this.errors.push({message:$,file:this.currentFile,line:X,column:Z,expression:Q,expected:Y,received:J,severity:"error"})}addWarning($,X,Z,Q,Y,J){let G={message:$,file:this.currentFile,line:X,column:Z,expression:Q,expected:Y,received:J,severity:"warning"};if(this.options.strict)this.errors.push(G);else this.warnings.push(G)}getResult(){return{valid:this.errors.length===0,errors:this.errors,warnings:this.warnings,variables:new Map(this.variables)}}addVariable($,X){this.variables.set($,X)}reset(){if(this.errors=[],this.warnings=[],this.variables.clear(),this.options.includeBuiltins)Object.entries(B8).forEach(([$,X])=>{this.variables.set($,X)})}}function F8($){return new L8($)}function
|
|
2894
|
-
`)}var N5=typeof window<"u"&&typeof document<"u";async function q5($,X,Z){if(!N5)return;try{let Q=$.getAttribute("data-island-id"),Y=document.querySelector(`script[data-island-props="${Q}"]`),J=Y?JSON.parse(Y.textContent||"{}"):{},G=await Z(),W=G.default||G.hydrate;if(typeof W!=="function"){console.error(`Island handler for "${X}" does not export a valid hydration function`);return}await W($,J),$.setAttribute("data-hydrated","true")}catch(Q){console.error(`Failed to hydrate island "${X}":`,Q)}}function
|
|
2893
|
+
`);return $-Q}addError($,X,Z,Q,Y,J){this.errors.push({message:$,file:this.currentFile,line:X,column:Z,expression:Q,expected:Y,received:J,severity:"error"})}addWarning($,X,Z,Q,Y,J){let G={message:$,file:this.currentFile,line:X,column:Z,expression:Q,expected:Y,received:J,severity:"warning"};if(this.options.strict)this.errors.push(G);else this.warnings.push(G)}getResult(){return{valid:this.errors.length===0,errors:this.errors,warnings:this.warnings,variables:new Map(this.variables)}}addVariable($,X){this.variables.set($,X)}reset(){if(this.errors=[],this.warnings=[],this.variables.clear(),this.options.includeBuiltins)Object.entries(B8).forEach(([$,X])=>{this.variables.set($,X)})}}function F8($){return new L8($)}function l2($,X){return F8(X).checkFile($)}function i2($,X){return F8(X).checkTemplate($)}function a2($){let X=[];for(let Z of $.errors){if(X.push(`\x1B[31merror\x1B[0m: ${Z.message}`),X.push(` --> ${Z.file}:${Z.line}:${Z.column}`),Z.expression)X.push(" |"),X.push(` | ${Z.expression}`),X.push(" |");if(Z.expected&&Z.received)X.push(` expected: ${Z.expected}`),X.push(` received: ${Z.received}`);X.push("")}for(let Z of $.warnings){if(X.push(`\x1B[33mwarning\x1B[0m: ${Z.message}`),X.push(` --> ${Z.file}:${Z.line}:${Z.column}`),Z.expression)X.push(" |"),X.push(` | ${Z.expression}`),X.push(" |");X.push("")}if($.valid)X.push("\x1B[32m\u2713 No type errors found\x1B[0m");else X.push(`\x1B[31m\u2717 Found ${$.errors.length} error(s) and ${$.warnings.length} warning(s)\x1B[0m`);return X.join(`
|
|
2894
|
+
`)}var N5=typeof window<"u"&&typeof document<"u";async function q5($,X,Z){if(!N5)return;try{let Q=$.getAttribute("data-island-id"),Y=document.querySelector(`script[data-island-props="${Q}"]`),J=Y?JSON.parse(Y.textContent||"{}"):{},G=await Z(),W=G.default||G.hydrate;if(typeof W!=="function"){console.error(`Island handler for "${X}" does not export a valid hydration function`);return}await W($,J),$.setAttribute("data-hydrated","true")}catch(Q){console.error(`Failed to hydrate island "${X}":`,Q)}}function s2($){if(!N5)return;let X=document.querySelectorAll("[data-island]"),Z=[];if(X.forEach((Q)=>{let Y=Q.getAttribute("data-island"),J=Q.getAttribute("data-priority")||"lazy";if(!Y||!$[Y]||Q.getAttribute("data-hydrated")==="true")return;if(J==="eager")q5(Q,Y,$[Y]);else Z.push([Q,Y])}),Z.length>0&&"IntersectionObserver"in window){let Q=new IntersectionObserver((Y)=>{Y.forEach((J)=>{if(J.isIntersecting){let G=J.target,W=G.getAttribute("data-island");if(W&&$[W]&&G.getAttribute("data-hydrated")!=="true")q5(G,W,$[W]),Q.unobserve(G)}})},{rootMargin:"200px",threshold:0});Z.forEach(([Y])=>{Q.observe(Y)})}else setTimeout(()=>{Z.forEach(([Q,Y])=>{if(Q.getAttribute("data-hydrated")!=="true")q5(Q,Y,$[Y])})},1000)}function n2($){if(!N5)return;Object.entries($).forEach(([X,Z])=>{try{let Y=Z.toString().match(/import\(['"](.+)['"]\)/);if(Y&&Y[1]){let J=document.createElement("link");J.rel="modulepreload",J.href=Y[1],J.setAttribute("data-island-module",X),document.head.appendChild(J)}}catch(Q){console.warn(`Failed to preload island handler for "${X}":`,Q)}})}var z1=typeof window<"u"&&typeof document<"u",V5={color:"#6366f1",initialColor:"",height:"3px",duration:2000,throttle:200,autoFinish:!0,zIndex:999999},F0=null,k0=0,h1=!1,M5=null,F1=null,y0=null;function z8($){if(!z1)return null;let X=document.getElementById("stx-loading-indicator");if(X)X.remove();let Z=document.createElement("div");Z.id="stx-loading-indicator";let Q=$.initialColor?`linear-gradient(to right, ${$.initialColor}, ${$.color})`:$.color;Z.style.cssText=`
|
|
2895
2895
|
position: fixed;
|
|
2896
2896
|
top: 0;
|
|
2897
2897
|
left: 0;
|
|
@@ -2922,7 +2922,7 @@ ${D instanceof Error?D.stack:""}</pre>`:"<h1>Internal Server Error</h1><p>An err
|
|
|
2922
2922
|
0% { transform: translateX(-100%); }
|
|
2923
2923
|
100% { transform: translateX(100%); }
|
|
2924
2924
|
}
|
|
2925
|
-
`,document.head.appendChild(J)}return document.body.appendChild(Z),Z}function q$($,X){if(!z1||!F0)return;if(k0=Math.min(Math.max($,0),100),M5)cancelAnimationFrame(M5);M5=requestAnimationFrame(()=>{if(!F0)return;F0.style.opacity=k0>0?"1":"0",F0.style.transform=`scaleX(${k0/100})`})}function LZ($){if(!z1)return;if(h1=!0,k0=0,!F0)F0=z8($);if(F1)clearTimeout(F1);if(y0)clearInterval(y0);q$(10,$),y0=setInterval(()=>{if(!h1)return;let X=90-k0,Z=Math.max(0.5,X*0.1);if(k0<90)q$(k0+Z,$)},$.throttle)}function FZ($){if(!z1)return;if(h1=!1,y0)clearInterval(y0),y0=null;q$(100,$),F1=setTimeout(()=>{if(F0)F0.style.opacity="0";setTimeout(()=>{if(k0=0,F0)F0.style.transform="scaleX(0)"},300)},200)}function zZ(){if(!z1)return;if(h1=!1,k0=0,y0)clearInterval(y0),y0=null;if(F1)clearTimeout(F1),F1=null;if(F0)F0.style.opacity="0",F0.style.transform="scaleX(0)"}function jZ($){let X={...V5,...$};return{start:()=>LZ(X),set:(Z)=>q$(Z,X),finish:()=>FZ(X),clear:()=>zZ(),get state(){return{isLoading:h1,progress:k0,error:!1}}}}var $1=null;function
|
|
2925
|
+
`,document.head.appendChild(J)}return document.body.appendChild(Z),Z}function q$($,X){if(!z1||!F0)return;if(k0=Math.min(Math.max($,0),100),M5)cancelAnimationFrame(M5);M5=requestAnimationFrame(()=>{if(!F0)return;F0.style.opacity=k0>0?"1":"0",F0.style.transform=`scaleX(${k0/100})`})}function LZ($){if(!z1)return;if(h1=!0,k0=0,!F0)F0=z8($);if(F1)clearTimeout(F1);if(y0)clearInterval(y0);q$(10,$),y0=setInterval(()=>{if(!h1)return;let X=90-k0,Z=Math.max(0.5,X*0.1);if(k0<90)q$(k0+Z,$)},$.throttle)}function FZ($){if(!z1)return;if(h1=!1,y0)clearInterval(y0),y0=null;q$(100,$),F1=setTimeout(()=>{if(F0)F0.style.opacity="0";setTimeout(()=>{if(k0=0,F0)F0.style.transform="scaleX(0)"},300)},200)}function zZ(){if(!z1)return;if(h1=!1,k0=0,y0)clearInterval(y0),y0=null;if(F1)clearTimeout(F1),F1=null;if(F0)F0.style.opacity="0",F0.style.transform="scaleX(0)"}function jZ($){let X={...V5,...$};return{start:()=>LZ(X),set:(Z)=>q$(Z,X),finish:()=>FZ(X),clear:()=>zZ(),get state(){return{isLoading:h1,progress:k0,error:!1}}}}var $1=null;function t2($){if(!z1)return;if($1)$1(),$1=null;let X={...V5,...$},Z=jZ(X);F0=z8(X);let Q=!1,Y=(U)=>{let z=U.target.closest("a");if(!z)return;let j=z.getAttribute("href");if(!j)return;if(j.startsWith("http")||j.startsWith("#")||j.startsWith("mailto:")||j.startsWith("tel:")||z.target==="_blank"||z.hasAttribute("download"))return;Q=!0,Z.start()},J=()=>{if(!Q)Z.start(),Q=!0},G=()=>{if(Q||X.autoFinish)Z.finish(),Q=!1};document.addEventListener("click",Y),window.addEventListener("popstate",J),window.addEventListener("load",G);let W=window.fetch,K=0,_=async function(...U){let F=typeof U[0]==="string"?U[0]:U[0].url,z=F.includes("/api/")||F.startsWith("/api");if(z){if(K++,K===1&&!Q)Z.start()}try{return await W.apply(this,U)}finally{if(z){if(K--,K===0&&!Q)Z.finish()}}};window.fetch=_,$1=()=>{if(document.removeEventListener("click",Y),window.removeEventListener("popstate",J),window.removeEventListener("load",G),window.fetch===_)window.fetch=W}}function e2(){if($1)$1(),$1=null}function $K($){let X={...V5,...$},Z=X.initialColor?`linear-gradient(to right, ${X.initialColor}, ${X.color})`:X.color;return`
|
|
2926
2926
|
<div id="stx-loading-indicator" style="
|
|
2927
2927
|
position: fixed;
|
|
2928
2928
|
top: 0;
|
|
@@ -3016,11 +3016,11 @@ ${D instanceof Error?D.stack:""}</pre>`:"<h1>Internal Server Error</h1><p>An err
|
|
|
3016
3016
|
window.addEventListener('load', function() { window.stxLoading.finish(); });
|
|
3017
3017
|
})();
|
|
3018
3018
|
</script>
|
|
3019
|
-
`}function
|
|
3019
|
+
`}function ZK($,X){let Z=[],Q=`${X}=`;for(let Y=0;Y<$.length;Y++){let J=$[Y];if(J.startsWith(Q)){let G=J.slice(Q.length);if(G)Z.push(G);continue}if(J===X){let G=$[Y+1];if(G!==void 0&&!G.startsWith("-"))Z.push(G),Y++}}return Z}class j8{instances=new Map;componentsByFile=new Map;stateSnapshots=new Map;config;constructor($={}){this.config={preserveState:$.preserveState??!0,maxStateAge:$.maxStateAge??30000,errorRecovery:$.errorRecovery??!0,verbose:$.verbose??!1,serializeState:$.serializeState??this.defaultSerializeState.bind(this),deserializeState:$.deserializeState??this.defaultDeserializeState.bind(this)}}register($){if(this.instances.set($.id,$),!this.componentsByFile.has($.name))this.componentsByFile.set($.name,new Set);if(this.componentsByFile.get($.name).add($.id),this.config.verbose)console.log(`[HMR] Registered component: ${$.name} (${$.id})`)}unregister($){let X=this.instances.get($);if(!X)return;if(this.componentsByFile.get(X.name)?.delete($),this.componentsByFile.get(X.name)?.size===0)this.componentsByFile.delete(X.name);if(this.stateSnapshots.delete($),X.cleanup?.(),this.instances.delete($),this.config.verbose)console.log(`[HMR] Unregistered component: ${X.name} (${$})`)}getInstancesByFile($){let X=this.componentsByFile.get($)||new Set;return Array.from(X).map((Z)=>this.instances.get(Z)).filter(Boolean)}getInstance($){return this.instances.get($)}captureState($){let X=this.instances.get($);if(!X||!this.config.preserveState)return;let Z=this.config.serializeState(X);if(this.stateSnapshots.set($,Z),this.config.verbose)console.log(`[HMR] Captured state for: ${X.name}`)}restoreState($){let X=this.instances.get($),Z=this.stateSnapshots.get($);if(!X||!Z||!this.config.preserveState)return!1;if(Date.now()-Z.timestamp>this.config.maxStateAge){if(this.stateSnapshots.delete($),this.config.verbose)console.log(`[HMR] State expired for: ${X.name}`);return!1}try{if(this.config.deserializeState(Z,X),this.config.verbose)console.log(`[HMR] Restored state for: ${X.name}`);return!0}catch(Q){return console.error(`[HMR] Failed to restore state for ${X.name}:`,Q),!1}}defaultSerializeState($){let X={},Z={};if($.element)$.element.querySelectorAll("[data-stx-ref]").forEach((Y)=>{let J=Y.getAttribute("data-stx-ref"),G=Y.getAttribute("data-stx-value");if(J&&G)try{X[J]=JSON.parse(G)}catch{X[J]=G}});return{refs:X,reactiveObjects:Z,custom:$.state?.custom||{},timestamp:Date.now()}}defaultDeserializeState($,X){if(X.element)Object.entries($.refs).forEach(([Z,Q])=>{let Y=X.element.querySelector(`[data-stx-ref="${Z}"]`);if(Y)Y.setAttribute("data-stx-value",JSON.stringify(Q)),Y.dispatchEvent(new CustomEvent("stx:state-restored",{detail:{name:Z,value:Q},bubbles:!0}))});X.state={...$,timestamp:Date.now()}}getAllInstances(){return Array.from(this.instances.values())}clear(){for(let $ of this.instances.values())$.cleanup?.();this.instances.clear(),this.componentsByFile.clear(),this.stateSnapshots.clear()}}class H8{registry;config;pendingUpdates=new Map;updateQueue=Promise.resolve();constructor($={}){this.config={preserveState:$.preserveState??!0,maxStateAge:$.maxStateAge??30000,errorRecovery:$.errorRecovery??!0,verbose:$.verbose??!1,serializeState:$.serializeState??(()=>({refs:{},reactiveObjects:{},custom:{},timestamp:Date.now()})),deserializeState:$.deserializeState??(()=>{})},this.registry=new j8(this.config)}register($){this.registry.register($)}unregister($){this.registry.unregister($)}async handleUpdate($){return this.updateQueue=this.updateQueue.then(()=>this.processUpdate($)),this.updateQueue}async processUpdate($){let X=this.registry.getInstancesByFile($.file);if(X.length===0){if(this.config.verbose)console.log(`[HMR] No instances found for: ${$.file}`);return}if(this.config.verbose)console.log(`[HMR] Updating ${X.length} instance(s) of: ${$.file}`);for(let Z of X)await this.updateInstance(Z,$);if(typeof window<"u"&&typeof window.dispatchEvent==="function")window.dispatchEvent(new CustomEvent("stx:hmr-update",{detail:{file:$.file,count:X.length}}))}async updateInstance($,X){this.registry.captureState($.id);let Z=!1,Q=$.element?.innerHTML||"";try{if($.element?.dispatchEvent(new CustomEvent("stx:before-hmr-update",{bubbles:!0})),$.cleanup?.(),X.type==="style")await this.updateStyles($,X);else await this.updateComponent($,X);let Y=this.registry.restoreState($.id);if(!Y&&$.setup)await $.setup();$.element?.dispatchEvent(new CustomEvent("stx:after-hmr-update",{detail:{stateRestored:Y},bubbles:!0}))}catch(Y){if(Z=!0,console.error(`[HMR] Error updating component ${$.name}:`,Y),this.config.errorRecovery){if($.element&&Q)$.element.innerHTML=Q,console.log(`[HMR] Recovered previous state for: ${$.name}`);$.element?.dispatchEvent(new CustomEvent("stx:hmr-error",{detail:{error:Y},bubbles:!0}))}}if(!Z&&this.config.verbose)console.log(`[HMR] Successfully updated: ${$.name}`)}async updateComponent($,X){if(!$.element)return;let{html:Z,script:Q}=this.parseComponentCode(X.code);if(Z)$.element.innerHTML=Z;if(Q)await this.executeScript(Q,$);if($.render)$.element.innerHTML=$.render();this.reinitializeInteractivity($)}async updateStyles($,X){if(!$.element)return;let Z=X.code.match(/<style\b[^>]*>([\s\S]*?)<\/style>/i);if(!Z)return;let Q=Z[1],Y=$.id,J=document.querySelector(`style[data-stx-component="${Y}"]`);if(!J)J=document.createElement("style"),J.setAttribute("data-stx-component",Y),document.head.appendChild(J);if(J.textContent=Q,this.config.verbose)console.log(`[HMR] Updated styles for: ${$.name}`)}parseComponentCode($){let X=$,Z="",Q="",Y=$.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(Y)Z=Y[1],X=X.replace(Y[0],"");let J=$.match(/<style\b[^>]*>([\s\S]*?)<\/style>/i);if(J)Q=J[1],X=X.replace(J[0],"");return{html:X.trim(),script:Z.trim(),style:Q.trim()}}async executeScript($,X){try{let Z={element:X.element,props:X.props,...typeof window<"u"?window.stx:{}},Q=`
|
|
3020
3020
|
return (async function() {
|
|
3021
3021
|
${$}
|
|
3022
3022
|
})()
|
|
3023
|
-
`;await Function(...Object.keys(Z),Q)(...Object.values(Z))}catch(Z){throw console.error("[HMR] Script execution error:",Z),Z}}reinitializeInteractivity($){if(!$.element)return;$.element.querySelectorAll("[data-stx-events]").forEach((Z)=>{let Q=Z.getAttribute("data-stx-events");if(!Q)return;try{let Y=JSON.parse(Q);for(let[J,G]of Object.entries(Y))if(typeof window<"u"&&window.stx?.[G])Z.addEventListener(J,window.stx[G])}catch{}}),$.element.dispatchEvent(new CustomEvent("stx:reinitialize",{bubbles:!0}))}getRegistry(){return this.registry}async refresh($){let X=this.registry.getInstancesByFile($);for(let Z of X)if(Z.render&&Z.element)this.registry.captureState(Z.id),Z.element.innerHTML=Z.render(),this.registry.restoreState(Z.id),this.reinitializeInteractivity(Z)}}function
|
|
3023
|
+
`;await Function(...Object.keys(Z),Q)(...Object.values(Z))}catch(Z){throw console.error("[HMR] Script execution error:",Z),Z}}reinitializeInteractivity($){if(!$.element)return;$.element.querySelectorAll("[data-stx-events]").forEach((Z)=>{let Q=Z.getAttribute("data-stx-events");if(!Q)return;try{let Y=JSON.parse(Q);for(let[J,G]of Object.entries(Y))if(typeof window<"u"&&window.stx?.[G])Z.addEventListener(J,window.stx[G])}catch{}}),$.element.dispatchEvent(new CustomEvent("stx:reinitialize",{bubbles:!0}))}getRegistry(){return this.registry}async refresh($){let X=this.registry.getInstancesByFile($);for(let Z of X)if(Z.render&&Z.element)this.registry.captureState(Z.id),Z.element.innerHTML=Z.render(),this.registry.restoreState(Z.id),this.reinitializeInteractivity(Z)}}function YK($){return`
|
|
3024
3024
|
<script data-stx-hmr-client>
|
|
3025
3025
|
(function() {
|
|
3026
3026
|
'use strict';
|
|
@@ -3247,7 +3247,7 @@ else {
|
|
|
3247
3247
|
};
|
|
3248
3248
|
})();
|
|
3249
3249
|
</script>
|
|
3250
|
-
`}function
|
|
3250
|
+
`}function JK($,X,Z,Q){return`
|
|
3251
3251
|
<div data-stx-component="${$}" data-stx-name="${X}">
|
|
3252
3252
|
${Z}
|
|
3253
3253
|
</div>
|
|
@@ -3287,7 +3287,7 @@ else {
|
|
|
3287
3287
|
observer.observe(document.body, { childList: true, subtree: true });
|
|
3288
3288
|
})();
|
|
3289
3289
|
</script>
|
|
3290
|
-
`}var j1=null;function
|
|
3290
|
+
`}var j1=null;function GK($){if(!j1)j1=new H8($);return j1}function WK(){if(j1)j1.getRegistry().clear(),j1=null}function HZ($){let X={refs:$.refs||{},reactive:$.reactive||{},props:$.props||{},routeParams:$.routeParams||{},stores:$.stores||{},meta:$.meta||{},timestamp:Date.now()};return X.checksum=A8(X),JSON.stringify(X).replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/'/g,"\\u0027")}function A8($){let X=JSON.stringify({refs:Object.keys($.refs||{}),reactive:Object.keys($.reactive||{}),props:Object.keys($.props||{})}),Z=0;for(let Q=0;Q<X.length;Q++){let Y=X.charCodeAt(Q);Z=(Z<<5)-Z+Y,Z=Z&Z}return Math.abs(Z).toString(36)}function OZ($){return`<script id="__STX_STATE__" type="application/json">${HZ($)}</script>`}function UK($){if($.length===0)return"";return`data-stx-events='${JSON.stringify($)}'`}function AZ(){if(typeof window>"u")return null;let $=document.getElementById("__STX_STATE__");if(!$)return null;try{let X=JSON.parse($.textContent||"{}");if(X.checksum){if(A8(X)!==X.checksum)console.warn("[Hydration] State checksum mismatch - state may be corrupted")}return X}catch(X){return console.error("[Hydration] Failed to parse state:",X),null}}class q8{state=null;options;root=null;isHydrated=!1;pendingComponents=new Map;hydratedComponents=new Set;constructor($={}){this.options={root:$.root||"#app",strict:$.strict??!1,onHydrating:$.onHydrating||(()=>{}),onHydrated:$.onHydrated||(()=>{}),onError:$.onError||console.error,performance:$.performance??!1,timeout:$.timeout??1e4}}async hydrate(){if(typeof window>"u")return;if(this.isHydrated)return;let $=this.options.performance?performance.now():0;try{this.root=typeof this.options.root==="string"?document.querySelector(this.options.root)||document.body:this.options.root,this.state=AZ(),this.options.onHydrating(),this.root.classList.add("stx-hydrating");let X=new Promise((Z,Q)=>{setTimeout(()=>Q(Error("Hydration timeout")),this.options.timeout)});if(await Promise.race([this.runHydration(),X]),this.isHydrated=!0,this.root.classList.remove("stx-hydrating"),this.root.classList.add("stx-hydrated"),this.options.performance){let Z=performance.now()-$;console.log(`[Hydration] Completed in ${Z.toFixed(2)}ms`)}this.options.onHydrated(),window.dispatchEvent(new CustomEvent("stx:hydrated"))}catch(X){this.root?.classList.remove("stx-hydrating"),this.root?.classList.add("stx-hydration-error"),this.options.onError(X),window.dispatchEvent(new CustomEvent("stx:hydration-error",{detail:{error:X}}))}}async runHydration(){if(!this.root)return;this.restoreGlobalState(),await this.hydrateComponents(),this.bindEventHandlers(),this.initializeReactiveBindings(),this.setupRouterIntegration()}restoreGlobalState(){if(!this.state)return;let $=window.stx;if(!$)return;if(this.state.routeParams&&$.setRouteParams)$.setRouteParams(this.state.routeParams);if(this.state.stores&&$.registerStore)Object.entries(this.state.stores).forEach(([X,Z])=>{$.registerStore(X,Z)});window.dispatchEvent(new CustomEvent("stx:state-restored",{detail:this.state}))}async hydrateComponents(){if(!this.root)return;let $=this.root.querySelectorAll("[data-stx-component]");for(let X of Array.from($)){let Z=X.getAttribute("data-stx-component"),Q=X.getAttribute("data-stx-name")||Z,Y=X.getAttribute("data-stx-hydrate")||"eager",J=X.getAttribute("data-stx-props");if(!Z)continue;let G={id:Z,name:Q||Z,strategy:Y,props:J?JSON.parse(J):{},events:[]};switch(this.pendingComponents.set(Z,G),G.strategy){case"eager":await this.hydrateComponent(X,G);break;case"lazy":case"visible":this.setupVisibleHydration(X,G);break;case"idle":this.setupIdleHydration(X,G);break;case"interaction":this.setupInteractionHydration(X,G);break}}}async hydrateComponent($,X){if(this.hydratedComponents.has(X.id))return;try{let Z=this.state?.refs[X.id]||this.state?.reactive[X.id]||{};this.restoreComponentState($,Z),this.bindComponentEvents($),this.initializeComponentReactivity($,X),this.hydratedComponents.add(X.id),$.classList.add("stx-hydrated"),$.setAttribute("data-hydrated","true"),$.dispatchEvent(new CustomEvent("stx:component-hydrated",{detail:{id:X.id,name:X.name},bubbles:!0}))}catch(Z){if(console.error(`[Hydration] Failed to hydrate component ${X.id}:`,Z),$.classList.add("stx-hydration-error"),this.options.strict)throw Z}}restoreComponentState($,X){if(!X||typeof X!=="object")return;$.querySelectorAll("[data-stx-bind]").forEach((Q)=>{let Y=Q.getAttribute("data-stx-bind");if(!Y||!X[Y])return;let J=X[Y];if(Q instanceof HTMLInputElement)if(Q.type==="checkbox"||Q.type==="radio")Q.checked=Boolean(J);else Q.value=String(J);else if(Q instanceof HTMLSelectElement)Q.value=String(J);else if(Q instanceof HTMLTextAreaElement)Q.value=String(J);else Q.textContent=String(J)})}setupVisibleHydration($,X){if(!("IntersectionObserver"in window)){this.hydrateComponent($,X);return}let Z=new IntersectionObserver((Q)=>{Q.forEach((Y)=>{if(Y.isIntersecting)Z.disconnect(),this.hydrateComponent($,X)})},{rootMargin:"100px",threshold:0});Z.observe($)}setupIdleHydration($,X){let Z=()=>this.hydrateComponent($,X);if("requestIdleCallback"in window)window.requestIdleCallback(Z,{timeout:2000});else setTimeout(Z,200)}setupInteractionHydration($,X){let Z=["mouseenter","touchstart","focusin"],Q=()=>{Z.forEach((Y)=>$.removeEventListener(Y,Q)),this.hydrateComponent($,X)};Z.forEach((Y)=>{$.addEventListener(Y,Q,{once:!0,passive:!0})})}bindEventHandlers(){if(!this.root)return;this.root.querySelectorAll("[data-stx-events]").forEach((X)=>this.bindElementEvents(X)),this.bindDirectiveEvents()}bindElementEvents($){let X=$.getAttribute("data-stx-events");if(!X)return;try{JSON.parse(X).forEach((Q)=>{this.bindSingleEvent($,Q)})}catch(Z){console.error("[Hydration] Failed to parse events:",Z)}}bindDirectiveEvents(){if(!this.root)return;["click","submit","input","change","focus","blur","keydown","keyup","keypress","mouseenter","mouseleave","touchstart","touchend","scroll","resize"].forEach((X)=>{let Z=`data-stx-on-${X}`;this.root.querySelectorAll(`[${Z}]`).forEach((Y)=>{let J=Y.getAttribute(Z);if(!J)return;this.bindSingleEvent(Y,{type:X,handler:J,modifiers:this.parseModifiers(Y,X)})})})}parseModifiers($,X){let Z=[],Q=$.getAttribute(`data-stx-${X}-modifiers`);if(Q)Z.push(...Q.split(",").map((Y)=>Y.trim()));return Z}bindSingleEvent($,X){let Z=this.resolveHandler(X.handler);if(!Z){console.warn(`[Hydration] Handler not found: ${X.handler}`);return}let Q=(G)=>{if(X.modifiers?.includes("prevent")||X.preventDefault)G.preventDefault();if(X.modifiers?.includes("stop")||X.stopPropagation)G.stopPropagation();try{Z.call($,G)}catch(W){console.error("[Hydration] Event handler error:",W)}},Y={};if(X.modifiers?.includes("once"))Y.once=!0;let J=X.modifiers??[];if(O8(X.type,{passive:J.includes("passive"),prevent:J.includes("prevent")||X.preventDefault,nonpassive:J.includes("nonpassive")}))Y.passive=!0;if(X.modifiers?.includes("capture"))Y.capture=!0;$.addEventListener(X.type,Q,Y)}resolveHandler($){let X=window.stx;if(X&&X[$])return X[$];if(window[$])return window[$];try{if($.match(/^\w+\+\+$/)||$.match(/^\w+--$/)){let Y=$.replace(/[+-]+$/,"");return()=>{if(X&&X[Y]){if(typeof X[Y].value<"u")if($.includes("++"))X[Y].value++;else X[Y].value--}}}let Z=$.match(/^(\w+)\s*=\s*(.+)$/);if(Z){let[,Y,J]=Z;return()=>{if(X&&X[Y]){let G=Function(`return ${J}`)();if(typeof X[Y].value<"u")X[Y].value=G}}}let Q=$.match(/^(\w+)\((.*)\)$/);if(Q){let[,Y,J]=Q;return(G)=>{let W=X?.[Y]||window[Y];if(W){let K=J?Function("$event",`return [${J}]`)(G):[];W(...K)}}}return(Y)=>{Function("$event","stx",$)(Y,X)}}catch{return null}}bindComponentEvents($){$.querySelectorAll("[data-stx-events]").forEach((Z)=>{this.bindElementEvents(Z)})}initializeComponentReactivity($,X){if(!window.stx)return;$.querySelectorAll("[data-stx-reactive]").forEach((Y)=>{let J=Y.getAttribute("data-stx-reactive");if(!J)return;this.setupReactiveBinding(Y,J)})}initializeReactiveBindings(){if(!this.root)return;this.getTextNodesWithExpressions(this.root).forEach(({node:Z,expressions:Q})=>{Q.forEach((Y)=>{this.setupTextNodeBinding(Z,Y)})}),this.root.querySelectorAll("[data-stx-bind-attrs]").forEach((Z)=>{let Q=Z.getAttribute("data-stx-bind-attrs");if(!Q)return;try{let Y=JSON.parse(Q);Object.entries(Y).forEach(([J,G])=>{this.setupAttributeBinding(Z,J,G)})}catch{}})}getTextNodesWithExpressions($){let X=[],Z=document.createTreeWalker($,NodeFilter.SHOW_TEXT),Q;while(Q=Z.nextNode()){let J=(Q.textContent||"").match(/\{\{\s*([^}]+)\s*\}\}/g);if(J)X.push({node:Q,expressions:J.map((G)=>G.replace(/\{\{\s*|\s*\}\}/g,""))})}return X}setupTextNodeBinding($,X){let Z=window.stx;if(!Z)return;let Q=$.textContent||"",Y=()=>{try{let G=Function("stx",`with(stx) { return ${X} }`)(Z);$.textContent=Q.replace(new RegExp(`\\{\\{\\s*${X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*\\}\\}`),String(G))}catch{}};Y();let J=X.match(/^(\w+)(\.value)?$/);if(J&&Z[J[1]]?.subscribe)Z[J[1]].subscribe(Y)}setupAttributeBinding($,X,Z){let Q=window.stx;if(!Q)return;let Y=()=>{try{let G=Function("stx",`with(stx) { return ${Z} }`)(Q);if(typeof G==="boolean")if(G)$.setAttribute(X,"");else $.removeAttribute(X);else $.setAttribute(X,String(G))}catch{}};Y();let J=Z.match(/^(\w+)(\.value)?$/);if(J&&Q[J[1]]?.subscribe)Q[J[1]].subscribe(Y)}setupReactiveBinding($,X){let Z=window.stx;if(!Z)return;let Q=()=>{try{let J=Function("stx",`with(stx) { return ${X} }`)(Z);$.textContent=String(J)}catch{}};Q();let Y=X.match(/^(\w+)(\.value)?$/);if(Y&&Z[Y[1]]?.subscribe)Z[Y[1]].subscribe(Q)}setupRouterIntegration(){window.addEventListener("stx:navigate",($)=>{let{url:X}=$.detail||{};if(X){if(window.stx?.setRouteParams){let Q=new URL(X,window.location.origin)}}}),window.addEventListener("stx:load",()=>{this.hydrateComponents(),this.bindEventHandlers()})}get hydrated(){return this.isHydrated}getState(){return this.state}async hydrateById($){let X=this.pendingComponents.get($),Z=document.querySelector(`[data-stx-component="${$}"]`);if(X&&Z)await this.hydrateComponent(Z,X)}}function BK($){return`
|
|
3291
3291
|
${$?OZ($):""}
|
|
3292
3292
|
<script data-stx-hydration-runtime>
|
|
3293
3293
|
(function() {
|
|
@@ -3385,7 +3385,7 @@ else {
|
|
|
3385
3385
|
}
|
|
3386
3386
|
})();
|
|
3387
3387
|
</script>
|
|
3388
|
-
`}var E5=null;function qZ($){if(!E5)E5=new q8($);return E5}async function
|
|
3388
|
+
`}var E5=null;function qZ($){if(!E5)E5=new q8($);return E5}async function LK($){await qZ($).hydrate()}function FK(){return`
|
|
3389
3389
|
<style data-stx-hydration-styles>
|
|
3390
3390
|
/* Pre-hydration state */
|
|
3391
3391
|
[data-stx-component]:not(.stx-hydrated) {
|
|
@@ -3418,7 +3418,7 @@ else {
|
|
|
3418
3418
|
}
|
|
3419
3419
|
}
|
|
3420
3420
|
</style>
|
|
3421
|
-
`}import N8 from"path";V6();class NZ{store=new Map;async get($){let X=this.store.get($);if(!X||X.expires<=Date.now()){if(X)this.store.delete($);return null}return{...X.data}}async set($,X,Z){this.store.set($,{data:{...X},expires:Date.now()+Z*1000})}async delete($){this.store.delete($)}}function MZ($,X){for(let Z of $.getSetCookie())X.append("Set-Cookie",Z);$.forEach((Z,Q)=>{if(Q.toLowerCase()!=="set-cookie")X.set(Q,Z)})}async function
|
|
3421
|
+
`}import N8 from"path";V6();class NZ{store=new Map;async get($){let X=this.store.get($);if(!X||X.expires<=Date.now()){if(X)this.store.delete($);return null}return{...X.data}}async set($,X,Z){this.store.set($,{data:{...X},expires:Date.now()+Z*1000})}async delete($){this.store.delete($)}}function MZ($,X){for(let Z of $.getSetCookie())X.append("Set-Cookie",Z);$.forEach((Z,Q)=>{if(Q.toLowerCase()!=="set-cookie")X.set(Q,Z)})}async function VK($,X={},Z={}){let Q=Z.viewsDir||"./views",Y=Z.layoutsDir||"./layouts",J=!$.includes("<")&&!$.includes("@"),G,W;if(J){if(W=N8.resolve(Q,$),!W.endsWith(".stx"))W+=".stx";if(!await Bun.file(W).exists())return new Response(`Template not found: ${$}`,{status:500});G=await Bun.file(W).text()}else G=$,W="inline-template.stx";let K={...X,props:X,__filename:W,__dirname:N8.dirname(W)};if(Z.ctx)K.csrf_token=Z.ctx.csrfToken,K.csrf_field=`<input type="hidden" name="_token" value="${Z.ctx.csrfToken}">`,K.old=Z.ctx.old,K.errors=Z.ctx.errors,K.session=Z.ctx.session,K.user=Z.ctx.user(),K.isAuthenticated=Z.ctx.isAuthenticated();let _=G.match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(_){let H=_[1];G=G.replace(/<script\s+server\b[^>]*>[\s\S]*?<\/script>/gi,""),await M0(H,K,W)}let U={layoutsDir:Y,...Z.stxOptions},z=await V0(G,K,W,U,new Set),j=new Headers({"Content-Type":"text/html; charset=utf-8"});if(Z.ctx)MZ(Z.ctx.responseHeaders,j);return new Response(z,{headers:j})}var d1={stores:new Map,subscriptions:new Map};function VZ($,X){d1.stores.set($,X)}function V8($){return d1.stores.get($)}function EZ($){return d1.stores.has($)}function IZ(){return Array.from(d1.stores.keys())}var H1=new Map;function M8($){if($==="memory")return{getItem:(X)=>H1.get(X)??null,setItem:(X,Z)=>H1.set(X,Z),removeItem:(X)=>H1.delete(X)};if(typeof window>"u")return{getItem:(X)=>H1.get(X)??null,setItem:(X,Z)=>H1.set(X,Z),removeItem:(X)=>H1.delete(X)};return $==="local"?window.localStorage:window.sessionStorage}function RZ($,X){let Z={};for(let Q of X){let Y=Q.split("."),J=$,G=Z,W=!0;for(let K=0;K<Y.length-1;K++){let _=Y[K];if(J&&typeof J==="object"&&_ in J){if(J=J[_],!(_ in G))G[_]={};G=G[_]}else{W=!1;break}}if(W&&J&&typeof J==="object"){let K=Y[Y.length-1];if(K in J)G[K]=J[K]}}return Z}function E8($,X={}){let{name:Z,persist:Q,devtools:Y=!1,middleware:J=[],equals:G=(O,A)=>O===A}=X,W=$,K=new Set,_=null;if(Q){let O=M8(Q.storage||"local"),A=Q.key||`stx-store:${Z||"unnamed"}`,V=Q.deserialize||JSON.parse;try{let E=O.getItem(A);if(E){let q=V(E);if(Q.paths&&typeof q==="object"&&q!==null)W={...$,...q};else W=q}}catch{}}let U=(O)=>{if(!Q)return;let A=M8(Q.storage||"local"),V=Q.key||`stx-store:${Z||"unnamed"}`,E=Q.serialize||JSON.stringify,q=Q.paths&&typeof O==="object"&&O!==null?RZ(O,Q.paths):O;if(Q.debounce){if(_)clearTimeout(_);_=setTimeout(()=>{A.setItem(V,E(q))},Q.debounce)}else A.setItem(V,E(q))},F=(O,A)=>{for(let V of K)try{V(O,A)}catch(E){console.error("[stx-store] Subscriber error:",E)}},z=Y?(O,A)=>{if(i6(Z||"unnamed",O,W,A),typeof window<"u")window.__STX_DEVTOOLS__?.onStoreChange?.(Z||"unnamed",O,A)}:()=>{},j=(O)=>{let A=W;if(!G(O,A))W=O,U(O),F(O,A),z("set",O)},H=j,L={get:()=>W,set:(O)=>{if(typeof O==="function")H(O(W));else H(O)},subscribe:(O)=>{return K.add(O),()=>{K.delete(O)}},update:(O)=>{if(typeof W!=="object"||W===null)throw Error("update() can only be used with object stores");let A=typeof O==="function"?O(W):O;L.set({...W,...A})},reset:()=>{L.set($),z("reset",$)},name:Z,destroy:()=>{if(K.clear(),_)clearTimeout(_);if(Z)d1.stores.delete(Z)}};for(let O of J.reverse())H=O(j,()=>W,L)(H);if(Z){if(VZ(Z,L),Y)l6(Z,W??{},{},[])}return L}function DZ($){let X=typeof $==="string"?V8($):$;if(!X)throw Error(`Store "${$}" not found`);return X.get()}function wZ($,X,Z){if(typeof X==="function"){if(typeof window<"u"&&window.stx?.defineStore)return window.stx.defineStore($,X,Z);return X()}let Q=X,{state:Y,getters:J={},actions:G={},persist:W,devtools:K=!0}=Q,_=typeof Y==="function"?Y():Y,U=W===!0?{storage:"local",key:`stx-store:${$}`}:W||void 0,F=E8(_,{name:$,persist:U,devtools:K}),z=new Proxy({},{get(j,H){let L=String(H);if(L==="$state")return F.get();if(L==="$subscribe")return F.subscribe;if(L==="$reset")return F.reset;if(L==="$patch")return(A)=>{if(typeof A==="function"){let E={...F.get()};A(E),F.set(E)}else F.update(A)};if(L==="_store")return F;if(L==="$id")return $;if(L in J)return J[L](F.get());if(L in G)return(...A)=>{return G[L].apply(z,A)};let O=F.get();if(O&&typeof O==="object"&&L in O)return O[L];return},set(j,H,L){let O=String(H);if(O.startsWith("$")||O==="_store")return!1;let A=F.get();if(A&&typeof A==="object")return F.set({...A,[O]:L}),!0;return!1},has(j,H){let L=String(H),O=F.get();return L.startsWith("$")||L==="_store"||L in J||L in G||O&&typeof O==="object"&&L in O},ownKeys(){let j=F.get();return[...j&&typeof j==="object"?Object.keys(j):[],...Object.keys(J),...Object.keys(G),"$state","$subscribe","$reset","$patch","$id"]},getOwnPropertyDescriptor(j,H){return{enumerable:!0,configurable:!0,get:()=>this.get(j,H,z)}}});return TZ.set($,z),z}var TZ=new Map;function CZ($){if(typeof window>"u")return;let X=window;X.__STX_STORES__=X.__STX_STORES__||{};for(let[Z,Q]of Object.entries($))X.__STX_STORES__[Z]=Q;window.dispatchEvent(new CustomEvent("stx:stores-ready",{detail:Object.keys($)}))}function l($,X={}){let Z=[];for(let[Y,J]of Object.entries(X)){if(J===void 0||J===null)continue;if(Array.isArray(J))Z.push(`${Y}=${encodeURIComponent(J.join(","))}`);else if(typeof J==="boolean"){if(J)Z.push(`${Y}=true`)}else Z.push(`${Y}=${encodeURIComponent(String(J))}`)}if(Z.length===0)return $;let Q=$.includes("?")?"&":"?";return`${$}${Q}${Z.join("&")}`}function I8($){let X=$.indexOf("?");if(X===-1)return{src:$,params:{}};let Z=$.slice(0,X),Q=$.slice(X+1),Y={};for(let J of Q.split("&")){let[G,W]=J.split("="),K=W?decodeURIComponent(W):"";if(K==="true")Y[G]=!0;else if(K==="false")Y[G]=!1;else if(/^-?\d+$/.test(K))Y[G]=Number.parseInt(K,10);else if(/^-?\d+\.\d+$/.test(K))Y[G]=Number.parseFloat(K);else if(K.includes(","))Y[G]=K.split(",");else Y[G]=K}return{src:Z,params:Y}}function I5(...$){let X={};for(let Z of $)if(Z)Object.assign(X,Z);return X}function R8($,X,Z,Q){let Y={w:X};if(Z)Y.h=Z;if(Q)Y.fit=Q;return l($,Y)}function D8($,X,Z,Q="center"){return l($,{w:X,h:Z,fit:"crop",crop:Q})}function w8($,X,Z="center"){return l($,{w:X,h:X,fit:"crop",crop:Z})}function T8($,X,Z){return l($,{w:X,h:Z,fit:"max"})}function C8($,X,Z){return l($,{w:X,h:Z,fit:"crop"})}function k8($,X){return l($,{blur:Math.min(2000,Math.max(0,X))})}function x8($,X){return l($,{sharp:Math.min(100,Math.max(0,X))})}function S8($){return l($,{sat:-100})}function P8($,X=100){return l($,{sepia:Math.min(100,Math.max(0,X))})}function b8($){return l($,{invert:!0})}function y8($,X){return l($,{bri:Math.min(100,Math.max(-100,X))})}function v8($,X){return l($,{con:Math.min(100,Math.max(-100,X))})}function g8($,X){return l($,{sat:Math.min(100,Math.max(-100,X))})}function f8($,X){return l($,{rot:(X%360+360)%360})}function h8($){return l($,{flip:"h"})}function d8($){return l($,{flip:"v"})}function u8($,X,Z){let Q={fm:X};if(Z!==void 0)Q.q=Z;return l($,Q)}function m8($,X){return l($,{q:Math.min(100,Math.max(1,X))})}function p8($,X=["format","compress"]){return l($,{auto:X})}function c8($,X,Z={}){return l($,{mark:X,markx:Z.x,marky:Z.y,markalpha:Z.alpha,markscale:Z.scale,markalign:Z.align})}var R5={web:{fm:"webp",q:80,auto:["format","compress"]},highQuality:{q:95},thumb:{w:150,h:150,fit:"crop",crop:"center"},avatar:{w:200,h:200,fit:"crop",crop:"faces"},social:{w:1200,h:630,fit:"crop"},preview:{w:400,q:70},placeholder:{w:20,blur:200,q:20}};function l8($,X,Z){return l($,I5(R5[X],Z))}function i8($,X,Z){return X.map((Q)=>l($,{...Z,w:Q}))}function a8($,X,Z=[1,2,3],Q){return Z.map((Y)=>l($,{...Q,w:Math.round(X*Y),dpr:Y}))}function r8($){let X=[];if($.w!==void 0&&($.w<1||$.w>16383))X.push("Width must be between 1 and 16383");if($.h!==void 0&&($.h<1||$.h>16383))X.push("Height must be between 1 and 16383");if($.q!==void 0&&($.q<1||$.q>100))X.push("Quality must be between 1 and 100");if($.blur!==void 0&&($.blur<0||$.blur>2000))X.push("Blur must be between 0 and 2000");if($.rot!==void 0&&($.rot<0||$.rot>359))X.push("Rotation must be between 0 and 359");if($.dpr!==void 0&&($.dpr<1||$.dpr>5))X.push("DPR must be between 1 and 5");return{valid:X.length===0,errors:X}}function s8($){let X={...$};if(X.w!==void 0)X.w=Math.min(16383,Math.max(1,X.w));if(X.h!==void 0)X.h=Math.min(16383,Math.max(1,X.h));if(X.q!==void 0)X.q=Math.min(100,Math.max(1,X.q));if(X.blur!==void 0)X.blur=Math.min(2000,Math.max(0,X.blur));if(X.rot!==void 0)X.rot=(X.rot%360+360)%360;if(X.dpr!==void 0)X.dpr=Math.min(5,Math.max(1,X.dpr));return X}function o8($){let{endpoint:X,accept:Z,maxSize:Q,maxFiles:Y=1,fieldName:J="file",preview:G=!1,dropzone:W=!0,multiple:K=!1,autoUpload:_=!0,showProgress:U=!0,disabled:F=!1,placeholder:z="Drop files here or click to select",label:j}=$,H=$.class||"",L=$.style||"",O=$.id||`stx-upload-${Math.random().toString(36).slice(2,8)}`,A=Array.isArray(Z)?Z.join(","):Z,V=`
|
|
3422
3422
|
<div id="${O}" class="stx-upload${W?" stx-upload-dropzone":""}${F?" stx-upload-disabled":""}${H?" "+H:""}"${L?` style="${L}"`:""}>
|
|
3423
3423
|
${j?`<label class="stx-upload-label">${n8(j)}</label>`:""}
|
|
3424
3424
|
<div class="stx-upload-area" data-stx-upload-area>
|
|
@@ -4310,16 +4310,16 @@ else {
|
|
|
4310
4310
|
})();
|
|
4311
4311
|
`.trim()}function w7(){return{script:[V$(),I$(),D$()].join(`
|
|
4312
4312
|
|
|
4313
|
-
`),css:R$()}}function TQ(){let{script:$,css:X}=w7(),Z=$.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").replace(/\s+/g," ").replace(/\s*([{};,:])\s*/g,"$1").trim(),Q=X.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{};,:])\s*/g,"$1").trim();return{script:Z,css:Q}}var
|
|
4313
|
+
`),css:R$()}}function TQ(){let{script:$,css:X}=w7(),Z=$.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").replace(/\s+/g," ").replace(/\s*([{};,:])\s*/g,"$1").trim(),Q=X.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{};,:])\s*/g,"$1").trim();return{script:Z,css:Q}}var d_={enabled:!0,image:{enabled:!0,defaultWidths:[320,480,640,768,1024,1280,1536,1920],defaultFormats:["avif","webp","jpeg"],defaultQuality:80,placeholderStrategy:"thumbhash",lazyByDefault:!0,enableDpr:!0,defaultDpr:[1,2,3]},video:{enabled:!0,lazyByDefault:!0,defaultControls:!0},upload:{enabled:!0,maxSize:10485760,allowedTypes:["image/*","video/*","audio/*","application/pdf"],maxConcurrent:3},protected:{enabled:!0,expirationSeconds:3600,batchSize:10},cache:{enabled:!0,directory:".stx/media-cache",maxAge:30,maxSize:500}};import w$ from"fs";import X1 from"path";async function T7($,X={},Z={}){let Q=await Bun.file($).text(),Y=Q.match(/<script\s+server\s*>([\s\S]*?)<\/script>/i),J=Y?Y[1]:"",G=Y?Q.replace(/<script\s+server\s*>[\s\S]*?<\/script>/i,""):Q;G=G.replace(/<script\s+client\s*>/gi,"<script>");let W={__filename:$,__dirname:X1.dirname($),props:X,...X};if(J)await M0(J,W,$);let K={...T$,...Z};return await V0(G,W,$,K,new Set)}async function CQ($){let X=performance.now(),Z={success:!0,views:[],errors:[],duration:0},{viewsDir:Q,outputDir:Y,componentsDir:J=X1.join(Q,"components"),layoutsDir:G=X1.join(Q,"layouts"),partialsDir:W=X1.join(Q,"partials"),globalProps:K={},placeholders:_={},views:U,debug:F=!1,generateManifest:z=!0}=$;if(F)console.log("Building STX views..."),console.log(` Source: ${Q}`),console.log(` Output: ${Y}`);w$.mkdirSync(Y,{recursive:!0});let j={componentsDir:J,layoutsDir:G,partialsDir:W,debug:F},H;if(U&&U.length>0)H=U;else H=w$.readdirSync(Q).filter((O)=>O.endsWith(".stx")).map((O)=>({input:O}));for(let L of H){let O=X1.join(Q,L.input),A=L.output||L.input.replace(/\.stx$/,".html"),V=X1.join(Y,A);if(F)console.log(` Building ${L.input}...`);try{let E={...K,...L.props,..._},q=await T7(O,E,j);await Bun.write(V,q),Z.views.push(A)}catch(E){let q=E instanceof Error?E.message:String(E);if(Z.errors.push({file:L.input,error:q}),Z.success=!1,F)console.error(` Error: ${q}`)}}if(z){let L={buildTime:new Date().toISOString(),views:Z.views,placeholders:_,errors:Z.errors.length>0?Z.errors:void 0};await Bun.write(X1.join(Y,"manifest.json"),JSON.stringify(L,null,2))}if(Z.duration=performance.now()-X,F)if(Z.success)console.log(`
|
|
4314
4314
|
\u2705 Built ${Z.views.length} views in ${Z.duration.toFixed(0)}ms`);else console.log(`
|
|
4315
|
-
\u26A0\uFE0F Built ${Z.views.length} views with ${Z.errors.length} errors`);return Z}function
|
|
4316
|
-
File changed: ${Y}, rebuilding...`);let J=await CQ($);X?.(J)}});return{close:()=>Z.close()}}async function
|
|
4315
|
+
\u26A0\uFE0F Built ${Z.views.length} views with ${Z.errors.length} errors`);return Z}function Z9($,X){let Z=w$.watch($.viewsDir,{recursive:!0},async(Q,Y)=>{if(!Y)return;if(Y.endsWith(".stx")||Y.endsWith(".ts")||Y.endsWith(".js")){if($.debug)console.log(`
|
|
4316
|
+
File changed: ${Y}, rebuilding...`);let J=await CQ($);X?.(J)}});return{close:()=>Z.close()}}async function Q9($,X={},Z={}){let Q={...Z,skipDefaultSeoTags:!0,skipSignalsRuntime:!0},Y=await T7($,X,Q);Y=await kQ(Y),Y=Y.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,""),Y=Y.replace(/<style\b([^>]*)>[\s\S]*?<\/style>/gi,(G,W)=>/\bdata-(?:css=["']generated["']|stx-)/i.test(W)?"":G),Y=Y.replace(/<!--\s*stx SEO Tags\s*-->/gi,""),Y=Y.replace(/\n\s*\n\s*\n/g,`
|
|
4317
4317
|
|
|
4318
|
-
`).trim();let J=
|
|
4318
|
+
`).trim();let J=PQ(Y);return{html:Y,text:J}}async function kQ($){try{let{generateCss:X,extractClassNames:Z}=await import("./chunk-gkq323fg.js");if(Z($).size===0)return $;let Y=await X($);if(!Y)return $;let J=xQ(Y);if(J.size===0)return $;return $.replace(/(<[a-z][a-z0-9]*)((?:\s+[a-z][a-z0-9-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]*))?)*\s+)class\s*=\s*"([^"]*)"((?:\s+[a-z][a-z0-9-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]*))?)*\s*)(\/?>)/gi,(G,W,K,_,U,F)=>{let z=_.split(/\s+/).filter(Boolean),j=[];for(let A of z){let V=J.get(A);if(V)j.push(V)}if(j.length===0)return`${W}${K}class="${_}"${U}${F}`;let H=j.join("; "),O=`${K}${U}`.match(/style\s*=\s*"([^"]*)"/);if(O){let A=`${H}; ${O[1]}`,V=K.replace(/style\s*=\s*"[^"]*"/,`style="${A}"`),E=U.replace(/style\s*=\s*"[^"]*"/,`style="${A}"`);return`${W}${V}class="${_}"${E}${F}`}return`${W}${K}class="${_}" style="${H}"${U}${F}`})}catch{return $}}function xQ($){let X=new Map,Z=/\.([a-zA-Z0-9_-]+(?:\\:[a-zA-Z0-9_-]+)*)\s*\{([^}]+)\}/g,Q=Z.exec($);while(Q!==null){let Y=Q[1].replace(/\\/g,""),J=Q[2].split(";").map((G)=>G.trim()).filter(Boolean).join("; ");if(J)X.set(Y,J);Q=Z.exec($)}return X}function SQ($,X){let Z=X.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim(),Q=$.replace(/&/g,"&").trim();if(!Q||Q.startsWith("#")||/^javascript:/i.test(Q))return Z;let Y=Q.replace(/^mailto:/i,"").replace(/^https?:\/\//i,"").replace(/\/$/,"");if(!Z)return Q.replace(/^mailto:/i,"");if(Z.replace(/^https?:\/\//i,"").replace(/\/$/,"")===Y)return Z;return`${Z} (${Q.replace(/^mailto:/i,"")})`}function PQ($){return $.replace(/<head\b[\s\S]*?<\/head>/gi,"").replace(/<(style|script)\b[\s\S]*?<\/\1>/gi,"").replace(/<(div|span|p)\b[^>]*\bstyle="[^"]*display:\s*none[^"]*"[^>]*>[\s\S]*?<\/\1>/gi,"").replace(/<a\b[^>]*?\bhref\s*=\s*(?:"([^"]*)"|'([^']*)')[^>]*>([\s\S]*?)<\/a>/gi,(X,Z,Q,Y)=>SQ(Z??Q??"",Y)).replace(/<br\s*\/?>/gi,`
|
|
4319
4319
|
`).replace(/<\/(p|div|h[1-6]|li|tr)>/gi,`
|
|
4320
4320
|
`).replace(/<\/td>/gi,"\t").replace(/<[^>]*>/g,"").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/©/g,"(c)").replace(/·/g,"-").replace(/\n\s*\n\s*\n/g,`
|
|
4321
4321
|
|
|
4322
|
-
`).trim()}function
|
|
4322
|
+
`).trim()}function bQ($){return $.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function yQ($){let X={};for(let Z of Object.keys($))if(!Z.startsWith("__"))X[Z]=$[Z];return X}function J9($){let{template:X,context:Z={},title:Q="stx App"}=$,Y=yQ(Z),J=bQ(JSON.stringify(Y));return`<!DOCTYPE html>
|
|
4323
4323
|
<html lang="en">
|
|
4324
4324
|
<head>
|
|
4325
4325
|
<meta charset="UTF-8">
|
|
@@ -4339,8 +4339,8 @@ File changed: ${Y}, rebuilding...`);let J=await CQ($);X?.(J)}});return{close:()=
|
|
|
4339
4339
|
}
|
|
4340
4340
|
</script>
|
|
4341
4341
|
</body>
|
|
4342
|
-
</html>`}var A1=Symbol.for("stx.Fragment"),yQ=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),k7=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]),x7={className:"class",htmlFor:"for",tabIndex:"tabindex",autoFocus:"autofocus",autoPlay:"autoplay",crossOrigin:"crossorigin",dateTime:"datetime",encType:"enctype",formAction:"formaction",formEncType:"formenctype",formMethod:"formmethod",formNoValidate:"formnovalidate",formTarget:"formtarget",frameBorder:"frameborder",hrefLang:"hreflang",httpEquiv:"http-equiv",inputMode:"inputmode",maxLength:"maxlength",mediaGroup:"mediagroup",minLength:"minlength",noModule:"nomodule",noValidate:"novalidate",playsInline:"playsinline",readOnly:"readonly",rowSpan:"rowspan",colSpan:"colspan",srcDoc:"srcdoc",srcLang:"srclang",srcSet:"srcset",useMap:"usemap"};function vQ($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function v5($){return $.replace(/&/g,"&").replace(/"/g,""")}function S7($){if($==null||typeof $==="boolean")return[];if(!Array.isArray($))return[C7($)];return $.flat(1/0).map(C7).filter((X)=>X!=="")}function C7($){if($==null||typeof $==="boolean")return"";if(typeof $==="string")return $;if(typeof $==="number")return String($);return $}function q1($,X,Z){let{children:Q,ref:Y,key:J,...G}=X||{};return{type:$,props:Object.keys(G).length>0?G:null,children:S7(Q),key:Z??J??void 0,ref:Y??void 0}}var gQ=q1,fQ=q1;function P7($){return Object.entries($).filter(([,X])=>X!=null&&X!==!1).map(([X,Z])=>{let Q=X.replace(/[A-Z]/g,(J)=>`-${J.toLowerCase()}`),Y=typeof Z==="number"&&!Q.startsWith("--")&&Q!=="opacity"&&Q!=="z-index"&&Q!=="flex-grow"&&Q!=="flex-shrink"&&Q!=="order"&&Q!=="font-weight"&&Q!=="line-height"?`${Z}px`:String(Z);return`${Q}: ${Y}`}).join("; ")}function g5($){if(typeof $==="string")return $;if(Array.isArray($))return $.filter(Boolean).map(g5).join(" ");if(typeof $==="object"&&$!==null)return Object.entries($).filter(([,X])=>X).map(([X])=>X).join(" ");return""}function hQ($){if(!$)return"";let X=[];for(let[Z,Q]of Object.entries($)){if(Z==="key"||Z==="ref"||Z==="children"||Z==="innerHTML"||Z==="dangerouslySetInnerHTML")continue;if(Z.startsWith("on")&&typeof Q==="function")continue;let Y=x7[Z]||Z;if(Y==="class"||Y==="className"){let J=g5(Q);if(J)X.push(` class="${v5(J)}"`);continue}if(Y==="style"){let J=typeof Q==="string"?Q:P7(Q);if(J)X.push(` style="${v5(J)}"`);continue}if(k7.has(Y)){if(Q)X.push(` ${Y}`);continue}if(Q!=null&&Q!==!1)X.push(` ${Y}="${v5(String(Q))}"`)}return X.join("")}function O1($){if($==null||typeof $==="boolean")return"";if(typeof $==="string")return vQ($);if(typeof $==="number")return String($);if(Array.isArray($))return $.map(O1).join("");if($.type===A1)return $.children.map(O1).join("");if(typeof $.type==="function"){let J=$.type({...$.props,children:$.children.length===1?$.children[0]:$.children.length>0?$.children:void 0});return O1(J)}let X=$.type,Z=hQ($.props),Q=$.props?.innerHTML??$.props?.dangerouslySetInnerHTML?.__html;if(Q!=null)return`<${X}${Z}>${Q}</${X}>`;if(yQ.has(X))return`<${X}${Z}>`;let Y=$.children.map(O1).join("");return`<${X}${Z}>${Y}</${X}>`}function dQ($){return new ReadableStream({start(X){X.enqueue(O1($)),X.close()}})}function uQ($,X){if(!X)return;for(let[Z,Q]of Object.entries(X)){if(Z==="key"||Z==="ref"||Z==="children"||Z==="innerHTML"||Z==="dangerouslySetInnerHTML")continue;let Y=x7[Z]||Z;if(Z.startsWith("on")&&typeof Q==="function"){let J=Z.slice(2).toLowerCase();$.addEventListener(J,Q);continue}if(Y==="class"||Y==="className"){let J=g5(Q);if(J)$.setAttribute("class",J);continue}if(Y==="style"){let J=typeof Q==="string"?Q:P7(Q);if(J)$.setAttribute("style",J);continue}if(k7.has(Y)){if(Q)$.setAttribute(Y,"");continue}if(Q!=null&&Q!==!1)$.setAttribute(Y,String(Q))}}function p1($,X){if($==null||typeof $==="boolean")return;if(typeof $==="string"){X.appendChild(document.createTextNode($));return}if(typeof $==="number"){X.appendChild(document.createTextNode(String($)));return}if(Array.isArray($)){for(let Y of $)p1(Y,X);return}if($.type===A1){for(let Y of $.children)p1(Y,X);return}if(typeof $.type==="function"){let Y=$.type({...$.props,children:$.children.length===1?$.children[0]:$.children.length>0?$.children:void 0});p1(Y,X);return}let Z=document.createElement($.type);uQ(Z,$.props);let Q=$.props?.innerHTML??$.props?.dangerouslySetInnerHTML?.__html;if(Q!=null)Z.innerHTML=Q;else for(let Y of $.children)p1(Y,Z);if($.ref){if(typeof $.ref==="function")$.ref(Z)}X.appendChild(Z)}function mQ($){if($.when)return q1(A1,{children:$.children});return $.fallback??null}function pQ($){let X=$.each;if(!X||X.length===0)return $.fallback??null;let Z=Array.isArray($.children)?$.children[0]:$.children,Q=X.map((Y,J)=>Z(Y,J));return q1(A1,{children:Q})}function cQ($){return q1(A1,{children:$.children})}function lQ($,X,...Z){let{key:Q,ref:Y,...J}=X||{};return{type:$,props:Object.keys(J).length>0?J:{},children:S7(Z.length===1?Z[0]:Z),key:Q??void 0,ref:Y??void 0}}function b7($,X){let Z=new Set,Q=new Map,Y=new Map,J={globalProperties:{},performance:!1,compilerOptions:{}},G={config:J,_components:Q,_directives:Y,_installedPlugins:Z,use(W,...K){if(Z.has(W))return G;if(Z.add(W),typeof W==="function")W(G,...K);else if(typeof W.install==="function")W.install(G,...K);return G},provide(W,K){return f5(W,K),G},component(W,K){if(!K)return Q.get(W);return Q.set(W,K),G},directive(W,K){if(!K)return Y.get(W);return Y.set(W,K),G},mount(W){if(typeof document<"u"){let K=globalThis.__stx_globals||(globalThis.__stx_globals={});Object.assign(K,J.globalProperties),document.querySelectorAll("[v-cloak]").forEach((_)=>{_.removeAttribute("v-cloak")})}return G},unmount(){Q.clear(),Y.clear(),Z.clear()}};return G}function iQ($){return class extends HTMLElement{_component;_shadow;constructor(){super();this._shadow=this.attachShadow({mode:"open"}),this._component=$}connectedCallback(){if(this._component?.render){let X=this._component.render();if(typeof X==="string")this._shadow.innerHTML=X}else if(this._component?.template)this._shadow.innerHTML=this._component.template;else if(typeof this._component==="string")this._shadow.innerHTML=this._component}disconnectedCallback(){this._shadow.innerHTML=""}}}function aQ($,...X){let Z=X[0]??{},Q=new Set,Y=String($).replace(/(\/)?:([^/?*]+)([?*])?/g,(W,K,_,U)=>{let F=Z[_];if(Q.add(_),F===void 0||F===null||F===""){if(U==="?")return"";return W}let z=Array.isArray(F)?F.map((j)=>encodeURIComponent(String(j))).join("/"):U==="*"?String(F).split("/").map((j)=>encodeURIComponent(j)).join("/"):encodeURIComponent(String(F));return`${K??""}${z}`}),J=Object.keys(Z).filter((W)=>!Q.has(W));if(J.length===0)return Y;let G=new URLSearchParams;for(let W of J){let K=Z[W];if(Array.isArray(K))K.forEach((_)=>G.append(W,String(_)));else if(K!==void 0&&K!==null)G.set(W,String(K))}return`${Y}?${G.toString()}`}import N1 from"fs";import l0 from"path";function y7($){try{return N1.statSync($).mtimeMs}catch{return null}}function C$($,X){let Z=Math.max(0,Math.round((X-$)/1000));if(Z<60)return`${Z}s ago`;if(Z<3600)return`${Math.round(Z/60)}m ago`;return`${Math.round(Z/3600)}h ago`}function rQ($,X){try{return globalThis.Bun?.resolveSync($,X)??null}catch{return null}}function v7($,X="stx"){let Z=l0.resolve($);for(let Q=0;Q<10;Q++){let Y=l0.join(Z,"pantry","@stacksjs",X);if(N1.existsSync(Y))return Y;let J=l0.dirname(Z);if(J===Z)break;Z=J}return null}async function sQ($={}){let X=$.cwd?l0.resolve($.cwd):process.cwd(),Z=$.resolve??rQ,Q=Date.now(),Y=[],J=Z("@stacksjs/stx",X);Y.push(J?{name:"@stacksjs/stx resolves to",status:"ok",detail:J}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let G=Z("bun-plugin-stx",X);if(G)Y.push({name:"bun-plugin-stx resolves to",status:"ok",detail:G});let W=v7(X,"stx");if(!W)Y.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let K=l0.join(W,"src/signals.ts"),_=[l0.join(W,"dist/index.js"),l0.join(W,"dist/signals.js")].find((H)=>N1.existsSync(H))||null,U=y7(K),F=_?y7(_):null;if(U==null)Y.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${W} but no src/signals.ts to compare`});else if(F==null)Y.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${W} && bun build.ts`});else if(F<U){let H=Math.round((U-F)/1000);Y.push({name:"pantry dist freshness",status:"error",detail:`dist (${C$(F,Q)}) is OLDER than src/signals.ts (${C$(U,Q)}) by ${H}s \u2014 your edit isn't built`,fix:`cd ${W} && bun build.ts`})}else Y.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${C$(U,Q)}, dist ${C$(F,Q)})`});let z=l0.join(X,"node_modules/@stacksjs/stx"),j=null;try{j=N1.lstatSync(z)}catch{j=null}if(!j)Y.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(j.isSymbolicLink()){let H=null;try{H=N1.realpathSync(z)}catch{}let L=(()=>{try{return N1.realpathSync(W)}catch{return W}})();Y.push(H===L?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${H||"(dangling)"}, not pantry`})}else Y.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(Y.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),$.generateRuntime)try{let _=$.generateRuntime().length;Y.push(_>1000?{name:"signals runtime",status:"ok",detail:`generated ${_.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${_} chars \u2014 suspiciously short`})}catch(K){Y.push({name:"signals runtime",status:"error",detail:`failed to generate: ${K.message}`})}return{checks:Y,ok:!Y.some((K)=>K.status==="error")}}function nQ($){let X={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},Z=["stx runtime resolution:"];for(let Q of $.checks)if(Z.push(` ${X[Q.status]} ${Q.name}: ${Q.detail}`),Q.fix)Z.push(` \u2192 ${Q.fix}`);return Z.push(""),Z.push($.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),Z.join(`
|
|
4343
|
-
`)}var{Glob:
|
|
4342
|
+
</html>`}var A1=Symbol.for("stx.Fragment"),vQ=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),k7=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]),x7={className:"class",htmlFor:"for",tabIndex:"tabindex",autoFocus:"autofocus",autoPlay:"autoplay",crossOrigin:"crossorigin",dateTime:"datetime",encType:"enctype",formAction:"formaction",formEncType:"formenctype",formMethod:"formmethod",formNoValidate:"formnovalidate",formTarget:"formtarget",frameBorder:"frameborder",hrefLang:"hreflang",httpEquiv:"http-equiv",inputMode:"inputmode",maxLength:"maxlength",mediaGroup:"mediagroup",minLength:"minlength",noModule:"nomodule",noValidate:"novalidate",playsInline:"playsinline",readOnly:"readonly",rowSpan:"rowspan",colSpan:"colspan",srcDoc:"srcdoc",srcLang:"srclang",srcSet:"srcset",useMap:"usemap"};function gQ($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function v5($){return $.replace(/&/g,"&").replace(/"/g,""")}function S7($){if($==null||typeof $==="boolean")return[];if(!Array.isArray($))return[C7($)];return $.flat(1/0).map(C7).filter((X)=>X!=="")}function C7($){if($==null||typeof $==="boolean")return"";if(typeof $==="string")return $;if(typeof $==="number")return String($);return $}function q1($,X,Z){let{children:Q,ref:Y,key:J,...G}=X||{};return{type:$,props:Object.keys(G).length>0?G:null,children:S7(Q),key:Z??J??void 0,ref:Y??void 0}}var fQ=q1,hQ=q1;function P7($){return Object.entries($).filter(([,X])=>X!=null&&X!==!1).map(([X,Z])=>{let Q=X.replace(/[A-Z]/g,(J)=>`-${J.toLowerCase()}`),Y=typeof Z==="number"&&!Q.startsWith("--")&&Q!=="opacity"&&Q!=="z-index"&&Q!=="flex-grow"&&Q!=="flex-shrink"&&Q!=="order"&&Q!=="font-weight"&&Q!=="line-height"?`${Z}px`:String(Z);return`${Q}: ${Y}`}).join("; ")}function g5($){if(typeof $==="string")return $;if(Array.isArray($))return $.filter(Boolean).map(g5).join(" ");if(typeof $==="object"&&$!==null)return Object.entries($).filter(([,X])=>X).map(([X])=>X).join(" ");return""}function dQ($){if(!$)return"";let X=[];for(let[Z,Q]of Object.entries($)){if(Z==="key"||Z==="ref"||Z==="children"||Z==="innerHTML"||Z==="dangerouslySetInnerHTML")continue;if(Z.startsWith("on")&&typeof Q==="function")continue;let Y=x7[Z]||Z;if(Y==="class"||Y==="className"){let J=g5(Q);if(J)X.push(` class="${v5(J)}"`);continue}if(Y==="style"){let J=typeof Q==="string"?Q:P7(Q);if(J)X.push(` style="${v5(J)}"`);continue}if(k7.has(Y)){if(Q)X.push(` ${Y}`);continue}if(Q!=null&&Q!==!1)X.push(` ${Y}="${v5(String(Q))}"`)}return X.join("")}function O1($){if($==null||typeof $==="boolean")return"";if(typeof $==="string")return gQ($);if(typeof $==="number")return String($);if(Array.isArray($))return $.map(O1).join("");if($.type===A1)return $.children.map(O1).join("");if(typeof $.type==="function"){let J=$.type({...$.props,children:$.children.length===1?$.children[0]:$.children.length>0?$.children:void 0});return O1(J)}let X=$.type,Z=dQ($.props),Q=$.props?.innerHTML??$.props?.dangerouslySetInnerHTML?.__html;if(Q!=null)return`<${X}${Z}>${Q}</${X}>`;if(vQ.has(X))return`<${X}${Z}>`;let Y=$.children.map(O1).join("");return`<${X}${Z}>${Y}</${X}>`}function uQ($){return new ReadableStream({start(X){X.enqueue(O1($)),X.close()}})}function mQ($,X){if(!X)return;for(let[Z,Q]of Object.entries(X)){if(Z==="key"||Z==="ref"||Z==="children"||Z==="innerHTML"||Z==="dangerouslySetInnerHTML")continue;let Y=x7[Z]||Z;if(Z.startsWith("on")&&typeof Q==="function"){let J=Z.slice(2).toLowerCase();$.addEventListener(J,Q);continue}if(Y==="class"||Y==="className"){let J=g5(Q);if(J)$.setAttribute("class",J);continue}if(Y==="style"){let J=typeof Q==="string"?Q:P7(Q);if(J)$.setAttribute("style",J);continue}if(k7.has(Y)){if(Q)$.setAttribute(Y,"");continue}if(Q!=null&&Q!==!1)$.setAttribute(Y,String(Q))}}function p1($,X){if($==null||typeof $==="boolean")return;if(typeof $==="string"){X.appendChild(document.createTextNode($));return}if(typeof $==="number"){X.appendChild(document.createTextNode(String($)));return}if(Array.isArray($)){for(let Y of $)p1(Y,X);return}if($.type===A1){for(let Y of $.children)p1(Y,X);return}if(typeof $.type==="function"){let Y=$.type({...$.props,children:$.children.length===1?$.children[0]:$.children.length>0?$.children:void 0});p1(Y,X);return}let Z=document.createElement($.type);mQ(Z,$.props);let Q=$.props?.innerHTML??$.props?.dangerouslySetInnerHTML?.__html;if(Q!=null)Z.innerHTML=Q;else for(let Y of $.children)p1(Y,Z);if($.ref){if(typeof $.ref==="function")$.ref(Z)}X.appendChild(Z)}function pQ($){if($.when)return q1(A1,{children:$.children});return $.fallback??null}function cQ($){let X=$.each;if(!X||X.length===0)return $.fallback??null;let Z=Array.isArray($.children)?$.children[0]:$.children,Q=X.map((Y,J)=>Z(Y,J));return q1(A1,{children:Q})}function lQ($){return q1(A1,{children:$.children})}function iQ($,X,...Z){let{key:Q,ref:Y,...J}=X||{};return{type:$,props:Object.keys(J).length>0?J:{},children:S7(Z.length===1?Z[0]:Z),key:Q??void 0,ref:Y??void 0}}function b7($,X){let Z=new Set,Q=new Map,Y=new Map,J={globalProperties:{},performance:!1,compilerOptions:{}},G={config:J,_components:Q,_directives:Y,_installedPlugins:Z,use(W,...K){if(Z.has(W))return G;if(Z.add(W),typeof W==="function")W(G,...K);else if(typeof W.install==="function")W.install(G,...K);return G},provide(W,K){return f5(W,K),G},component(W,K){if(!K)return Q.get(W);return Q.set(W,K),G},directive(W,K){if(!K)return Y.get(W);return Y.set(W,K),G},mount(W){if(typeof document<"u"){let K=globalThis.__stx_globals||(globalThis.__stx_globals={});Object.assign(K,J.globalProperties),document.querySelectorAll("[v-cloak]").forEach((_)=>{_.removeAttribute("v-cloak")})}return G},unmount(){Q.clear(),Y.clear(),Z.clear()}};return G}function aQ($){return class extends HTMLElement{_component;_shadow;constructor(){super();this._shadow=this.attachShadow({mode:"open"}),this._component=$}connectedCallback(){if(this._component?.render){let X=this._component.render();if(typeof X==="string")this._shadow.innerHTML=X}else if(this._component?.template)this._shadow.innerHTML=this._component.template;else if(typeof this._component==="string")this._shadow.innerHTML=this._component}disconnectedCallback(){this._shadow.innerHTML=""}}}function rQ($,...X){let Z=X[0]??{},Q=new Set,Y=String($).replace(/(\/)?:([^/?*]+)([?*])?/g,(W,K,_,U)=>{let F=Z[_];if(Q.add(_),F===void 0||F===null||F===""){if(U==="?")return"";return W}let z=Array.isArray(F)?F.map((j)=>encodeURIComponent(String(j))).join("/"):U==="*"?String(F).split("/").map((j)=>encodeURIComponent(j)).join("/"):encodeURIComponent(String(F));return`${K??""}${z}`}),J=Object.keys(Z).filter((W)=>!Q.has(W));if(J.length===0)return Y;let G=new URLSearchParams;for(let W of J){let K=Z[W];if(Array.isArray(K))K.forEach((_)=>G.append(W,String(_)));else if(K!==void 0&&K!==null)G.set(W,String(K))}return`${Y}?${G.toString()}`}import N1 from"fs";import l0 from"path";function y7($){try{return N1.statSync($).mtimeMs}catch{return null}}function C$($,X){let Z=Math.max(0,Math.round((X-$)/1000));if(Z<60)return`${Z}s ago`;if(Z<3600)return`${Math.round(Z/60)}m ago`;return`${Math.round(Z/3600)}h ago`}function sQ($,X){try{return globalThis.Bun?.resolveSync($,X)??null}catch{return null}}function v7($,X="stx"){let Z=l0.resolve($);for(let Q=0;Q<10;Q++){let Y=l0.join(Z,"pantry","@stacksjs",X);if(N1.existsSync(Y))return Y;let J=l0.dirname(Z);if(J===Z)break;Z=J}return null}async function nQ($={}){let X=$.cwd?l0.resolve($.cwd):process.cwd(),Z=$.resolve??sQ,Q=Date.now(),Y=[],J=Z("@stacksjs/stx",X);Y.push(J?{name:"@stacksjs/stx resolves to",status:"ok",detail:J}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let G=Z("bun-plugin-stx",X);if(G)Y.push({name:"bun-plugin-stx resolves to",status:"ok",detail:G});let W=v7(X,"stx");if(!W)Y.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let K=l0.join(W,"src/signals.ts"),_=[l0.join(W,"dist/index.js"),l0.join(W,"dist/signals.js")].find((H)=>N1.existsSync(H))||null,U=y7(K),F=_?y7(_):null;if(U==null)Y.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${W} but no src/signals.ts to compare`});else if(F==null)Y.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${W} && bun build.ts`});else if(F<U){let H=Math.round((U-F)/1000);Y.push({name:"pantry dist freshness",status:"error",detail:`dist (${C$(F,Q)}) is OLDER than src/signals.ts (${C$(U,Q)}) by ${H}s \u2014 your edit isn't built`,fix:`cd ${W} && bun build.ts`})}else Y.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${C$(U,Q)}, dist ${C$(F,Q)})`});let z=l0.join(X,"node_modules/@stacksjs/stx"),j=null;try{j=N1.lstatSync(z)}catch{j=null}if(!j)Y.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(j.isSymbolicLink()){let H=null;try{H=N1.realpathSync(z)}catch{}let L=(()=>{try{return N1.realpathSync(W)}catch{return W}})();Y.push(H===L?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${H||"(dangling)"}, not pantry`})}else Y.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(Y.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),$.generateRuntime)try{let _=$.generateRuntime().length;Y.push(_>1000?{name:"signals runtime",status:"ok",detail:`generated ${_.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${_} chars \u2014 suspiciously short`})}catch(K){Y.push({name:"signals runtime",status:"error",detail:`failed to generate: ${K.message}`})}return{checks:Y,ok:!Y.some((K)=>K.status==="error")}}function oQ($){let X={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},Z=["stx runtime resolution:"];for(let Q of $.checks)if(Z.push(` ${X[Q.status]} ${Q.name}: ${Q.detail}`),Q.fix)Z.push(` \u2192 ${Q.fix}`);return Z.push(""),Z.push($.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),Z.join(`
|
|
4343
|
+
`)}var{Glob:jY}=globalThis.Bun;import{cpSync as a7,existsSync as m$,mkdirSync as r7,readFileSync as s7,readdirSync as HY,rmSync as OY,statSync as AY,unlinkSync as qY,writeFileSync as d$}from"fs";import{dirname as NY,join as x0,relative as MY}from"path";import n7 from"process";import i0 from"path";function f7($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function h7($,X,Z){let Q=f7(X),Y=Z?f7(Z):"";return`<!DOCTYPE html>
|
|
4344
4344
|
<html>
|
|
4345
4345
|
<head>
|
|
4346
4346
|
<title>stx Error</title>
|
|
@@ -4371,38 +4371,38 @@ export { content as default };
|
|
|
4371
4371
|
`,loader:"js"}}}),X.onLoad({filter:/\.(jsx|tsx)$/},async(W)=>{let K=W.path;try{let _=await Bun.file(K).text(),U=K.endsWith(".tsx")?"tsx":"jsx";return{contents:new Bun.Transpiler({loader:U,jsxOptimizationInline:!0}).transformSync(_),loader:"js"}}catch(_){return console.error("JSX Processing Error:",_),{contents:"export default function() { return null; }",loader:"js"}}}),X.onLoad({filter:/\.stx$/},async({path:W})=>{try{let K=new Set;if(Q.cache&&Q.cachePath){let V=await K$(W,Q);if(V){if(Q.debug)console.log(`Using cached version of ${W}`);return{contents:V,loader:"html"}}}let _=await Bun.file(W).text(),U=_,F=_.match(/<template\b[^>]*>([\s\S]*?)<\/template>/i);if(F)U=F[1].trim();let z=u7(_),j=z.client.map((V)=>V.fullTag),H=z.server.map((V)=>V.content),L=U;for(let V of H){let E=V.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");L=L.replace(new RegExp(`<script\\b[^>]*>${E}<\\/script>`,"gi"),"")}for(let V of j){let E=V.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");L=L.replace(E,"")}let O={__filename:W,__dirname:i0.dirname(W),__stx:{webComponentsPath:J,builtComponents:G},__stx_options:Q,__stx_sfc_mode:!0};for(let V of H)await M0(V,O,W);let A=L;if(A=await V0(A,O,W,Q,K),j.length>0){let V=O.__stx_event_bindings||[],q=(await Promise.all(j.map(async(I)=>{let M=I.match(/<script\b[^>]*>([\s\S]*?)<\/script>/);if(!M)return I;return d7(M[1],{eventBindings:V,templateContent:A})}))).join(`
|
|
4372
4372
|
`);if(A.match(/(<\/body>)/i))A=A.replace(/(<\/body>)/i,`${q}
|
|
4373
4373
|
$1`);else A+=`
|
|
4374
|
-
${q}`;O.__stx_event_bindings=[]}if(K.forEach((V)=>Y.add(V)),Q.cache&&Q.cachePath){if(await _$(W,A,K,Q),Q.debug)console.log(`Cached template ${W} with ${K.size} dependencies`)}return{contents:A,loader:"html"}}catch(K){return console.error("stx Plugin Error:",K),{contents:h7("stx Rendering Error",K.message||String(K),W),loader:"html"}}})}}}var m7=g7;function
|
|
4374
|
+
${q}`;O.__stx_event_bindings=[]}if(K.forEach((V)=>Y.add(V)),Q.cache&&Q.cachePath){if(await _$(W,A,K,Q),Q.debug)console.log(`Cached template ${W} with ${K.size} dependencies`)}return{contents:A,loader:"html"}}catch(K){return console.error("stx Plugin Error:",K),{contents:h7("stx Rendering Error",K.message||String(K),W),loader:"html"}}})}}}var m7=g7;function tQ($,X){if(!$)return $;if(/^[a-z][a-z0-9+.-]*:/i.test($)||$.startsWith("//"))return $;return`${X}${$.startsWith("/")?"":"/"}${$}`}function k$($,X,Z={},Q="/"){let Y=X.seo??{},J=Z.title??Y.title??X.name,G=Z.description??Y.description??X.description??"",W=X.url.replace(/\/$/,""),K=`${W}${Q}`,_=tQ(Z.image??Y.image,W),U=Y.siteName??X.name,F=Y.type??"website",z=Y.locale??"en_US",j=[];if(Y.favicon){let T=Y.favicon.toLowerCase().split(".").pop(),f=T==="svg"?"image/svg+xml":T==="ico"?"image/x-icon":T==="png"?"image/png":T==="jpg"||T==="jpeg"?"image/jpeg":"";j.push(`<link rel="icon"${f?` type="${f}"`:""} href="${L0(Y.favicon)}">`)}if(j.push(`<title>${eQ(J)}</title>`,`<link rel="canonical" href="${L0(K)}">`,`<meta name="description" content="${L0(G)}">`,`<meta property="og:title" content="${L0(J)}">`,`<meta property="og:description" content="${L0(G)}">`,`<meta property="og:type" content="${L0(F)}">`,`<meta property="og:url" content="${L0(K)}">`,`<meta property="og:site_name" content="${L0(U)}">`,`<meta property="og:locale" content="${L0(z)}">`,`<meta name="twitter:card" content="${_?"summary_large_image":"summary"}">`,`<meta name="twitter:title" content="${L0(J)}">`,`<meta name="twitter:description" content="${L0(G)}">`),_)j.push(`<meta property="og:image" content="${L0(_)}">`),j.push(`<meta name="twitter:image" content="${L0(_)}">`);if(Y.twitter)j.push(`<meta name="twitter:site" content="@${L0(Y.twitter.replace(/^@/,""))}">`),j.push(`<meta name="twitter:creator" content="@${L0(Y.twitter.replace(/^@/,""))}">`);let H=/<!--\s*stx SEO Tags\s*-->[\s\S]*?<meta\s+name="twitter:description"[^>]*>\s*/i;if(H.test($))$=$.replace(H,"");$=$.replace(/<!--\s*SEO\s*-->[\s\S]*?<!--\s*\/SEO\s*-->\s*/g,""),$=$.replace(/<meta\s+name="title"\s+content="stx Project"[^>]*>\s*/g,"").replace(/<meta\s+name="description"\s+content="A website built with stx[^"]*"[^>]*>\s*/g,"").replace(/<meta\s+property="og:title"\s+content="stx Project"[^>]*>\s*/g,"").replace(/<meta\s+property="og:description"\s+content="A website built with stx[^"]*"[^>]*>\s*/g,"").replace(/<meta\s+name="twitter:title"\s+content="stx Project"[^>]*>\s*/g,"").replace(/<meta\s+name="twitter:description"\s+content="A website built with stx[^"]*"[^>]*>\s*/g,"");let L=$.search(/<\/head>/i),O=L===-1?$:$.slice(0,L),A=/^(?:stx App|stx Project|Document|Untitled)$/i,V=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(O)?.[1]?.trim(),E=V===void 0||V===""||A.test(V),q=(T)=>{if(/^<title[\s>]/i.test(T))return/<title[\s>]/i.test(O)&&!E;if(/rel="canonical"/i.test(T))return/<link[^>]+rel=["']canonical["']/i.test(O);let v=/(?:property|name)="([^"]+)"/i.exec(T)?.[1];if(!v)return!1;return new RegExp(`<meta[^>]+(?:property|name)=["']${v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}["']`,"i").test(O)},N=j.filter((T)=>!q(T));if(N.length===0)return $;let I=$,M=N.find((T)=>/^<title[\s>]/i.test(T));if(M&&E&&/<title[^>]*>[\s\S]*?<\/title>/i.test(I)){if(I=I.replace(/<title[^>]*>[\s\S]*?<\/title>/i,()=>M),N=N.filter((T)=>T!==M),N.length===0)return I}let w=`<!-- SEO -->
|
|
4375
4375
|
${N.join(`
|
|
4376
4376
|
`)}
|
|
4377
4377
|
<!-- /SEO -->`,D=I.search(/<\/head>/i);if(D!==-1)return`${I.slice(0,D)}${w}
|
|
4378
4378
|
${I.slice(D)}`;if(/<head[^>]*>/i.test(I))return I.replace(/<head([^>]*)>/i,`<head$1>
|
|
4379
4379
|
${w}`);return`${w}
|
|
4380
|
-
${I}`}function L0($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function
|
|
4380
|
+
${I}`}function L0($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function eQ($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function x$($,X){let Z=$.url.replace(/\/$/,""),Q=new Date().toISOString().slice(0,10);return['<?xml version="1.0" encoding="UTF-8"?>','<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',X.filter((J)=>J.page?.sitemap!==!1).map((J)=>{let G=`${Z}${J.path}`,W=J.page?.priority??(J.path==="/"?1:0.8),K=J.page?.changefreq??"monthly";return[" <url>",` <loc>${$Y(G)}</loc>`,` <lastmod>${Q}</lastmod>`,` <changefreq>${K}</changefreq>`,` <priority>${W.toFixed(1)}</priority>`," </url>"].join(`
|
|
4381
4381
|
`)}).join(`
|
|
4382
4382
|
`),"</urlset>",""].join(`
|
|
4383
|
-
`)}function
|
|
4383
|
+
`)}function $Y($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function S$($){let X=$.robots??"allow";if(X===!1)return null;if(typeof X==="string"&&X!=="allow"&&X!=="disallow")return X.endsWith(`
|
|
4384
4384
|
`)?X:`${X}
|
|
4385
4385
|
`;let Z=$.sitemap!==!1?`Sitemap: ${$.url.replace(/\/$/,"")}/sitemap.xml
|
|
4386
4386
|
`:"";if(X==="disallow")return["User-agent: *","Disallow: /","",Z].filter(Boolean).join(`
|
|
4387
4387
|
`);return["User-agent: *","Allow: /","",Z].filter(Boolean).join(`
|
|
4388
|
-
`)}var M1=null;async function
|
|
4388
|
+
`)}var M1=null;async function XY(){if(M1!==null)return M1;try{let $=await import("./chunk-cqw3c1xg.js");if(typeof $.getRouterScript==="function")M1=$.getRouterScript();else M1=""}catch{M1=""}return M1}async function h5($,X){let Z=await XY();if(!Z)return $;let Q={interceptAllLinks:!0,container:"main",...X},J=`${`<script>window.__stxRouterConfig=${JSON.stringify(Q)};</script>
|
|
4389
4389
|
`}<script>${Z}</script>`;if(/<\/body>/i.test($))return $.replace(/<\/body>/i,`${J}
|
|
4390
4390
|
</body>`);return`${$}
|
|
4391
|
-
${J}`}var
|
|
4391
|
+
${J}`}var ZY=`window.__stxThemeIcon=function(isDark){try{var want=isDark?'dark':'light';var pick=document.querySelector('link[rel~="icon"][media*="prefers-color-scheme: '+want+'"]');if(!pick)return;var live=document.querySelector('link[rel~="icon"]:not([media])');if(!live){live=document.createElement('link');live.setAttribute('rel','icon');document.head.appendChild(live)}if(pick.type)live.setAttribute('type',pick.type);var href=pick.getAttribute('href');if(live.getAttribute('href')!==href)live.setAttribute('href',href)}catch(e){}};`,QY=($,X,Z,Q)=>`(function(){${ZY}function read(){try{var k=${JSON.stringify(X)};var t=localStorage.getItem(k);return t===null?(${JSON.stringify($)}==='dark'||(${JSON.stringify($)}==='auto'&&window.matchMedia('(prefers-color-scheme: dark)').matches)):t==='dark'}catch(e){return ${JSON.stringify($)}==='dark'}}function apply(){var isDark=read();var html=document.documentElement;html.classList[isDark?'add':'remove']('dark');var color=isDark?${JSON.stringify(Q)}:${JSON.stringify(Z)};if(!document.head)return;var tc=document.querySelector('meta[name="theme-color"]:not([media])');if(!tc){tc=document.createElement('meta');tc.setAttribute('name','theme-color');tc.setAttribute('data-stx-theme-meta','1')}tc.setAttribute('content',color);if(tc!==document.head.firstChild){document.head.insertBefore(tc,document.head.firstChild)}if(window.__stxThemeIcon)window.__stxThemeIcon(isDark)}apply();window.addEventListener('stx:navigate',apply);window.addEventListener('popstate',apply)})();`,YY=($,X,Z)=>`document.addEventListener('click',function(e){var t=e.target&&e.target.closest&&e.target.closest('#theme-toggle');if(!t)return;var html=document.documentElement;var isDark=html.classList.toggle('dark');try{localStorage.setItem(${JSON.stringify($)},isDark?'dark':'light')}catch(e){}var tc=document.querySelector('meta[name="theme-color"]:not([media])');if(tc)tc.setAttribute('content',isDark?${JSON.stringify(Z)}:${JSON.stringify(X)});if(window.__stxThemeIcon)window.__stxThemeIcon(isDark)});`;function P$($,X){if(X.theme===!1)return $;let Z=$.includes(p7),Q=typeof X.theme==="object"&&X.theme!==null?X.theme:{},Y=Q.default??"dark",J=Q.storageKey??"theme",G=Q.colors?.light??"#ffffff",W=Q.colors?.dark??"#000000";if(Y==="dark"&&!Z){if(!/<html\b[^>]*\bclass=/.test($))$=$.replace(/<html\b([^>]*)>/i,'<html$1 class="dark">');else if(!/<html\b[^>]*\bclass="[^"]*\bdark\b/.test($))$=$.replace(/<html\b([^>]*\bclass=")([^"]*)(")/i,"<html$1$2 dark$3")}if(!$.includes("data-stx-theme-meta")&&/<head\b[^>]*>/i.test($)){let K=['<meta name="color-scheme" content="dark light" data-stx-theme-meta="1">',`<meta name="theme-color" media="(prefers-color-scheme: light)" content="${G}" data-stx-theme-meta="1">`,`<meta name="theme-color" media="(prefers-color-scheme: dark)" content="${W}" data-stx-theme-meta="1">`].join(`
|
|
4392
4392
|
`);$=$.replace(/<head\b([^>]*)>/i,`<head$1>
|
|
4393
|
-
${K}`)}if(!Z&&!$.includes("__stxThemeGuard")&&/<head\b[^>]*>/i.test($)){let _=`<script data-stx-theme-guard="1">${`window.__STX_COLOR_MODE__=window.__STX_COLOR_MODE__||${JSON.stringify({storageKey:J,initialMode:Y,darkClass:"dark"})};`}${
|
|
4394
|
-
${_}`)}if(!Z&&!$.includes("__stxThemeToggle")&&/<\/body>/i.test($)){let K=`<script data-stx-theme-toggle="1">${
|
|
4395
|
-
</body>`)}return $}async function c7($,X){if($.length===0)return{succeeded:[],failed:[]};try{return await X($),{succeeded:[...$],failed:[]}}catch{}let Z=[],Q=[];for(let Y of $)try{await X([Y]),Z.push(Y)}catch(J){Q.push({entrypoint:Y,error:U1(J,Y)})}return{succeeded:Z,failed:Q}}import{existsSync as
|
|
4396
|
-
`)){let Y=Q.replace(/#.*$/,"").trimEnd();if(!Y.trim())continue;let J=Y.search(/\S/);if(J===-1)continue;while(Z.length>1&&Z[Z.length-1].indent>=J)Z.pop();let G=Z[Z.length-1].obj,W=Y.match(/^(\s*)(\S[^:]*):\s*(.*)$/);if(!W)continue;let[,,K,_]=W,U=K.trim(),F=_.trim();if(F==="")G[U]={},Z.push({obj:G[U],indent:J});else G[U]=
|
|
4393
|
+
${K}`)}if(!Z&&!$.includes("__stxThemeGuard")&&/<head\b[^>]*>/i.test($)){let _=`<script data-stx-theme-guard="1">${`window.__STX_COLOR_MODE__=window.__STX_COLOR_MODE__||${JSON.stringify({storageKey:J,initialMode:Y,darkClass:"dark"})};`}${QY(Y,J,G,W)};window.__stxThemeGuard=1;</script>`;$=$.replace(/<head\b([^>]*)>/i,`<head$1>
|
|
4394
|
+
${_}`)}if(!Z&&!$.includes("__stxThemeToggle")&&/<\/body>/i.test($)){let K=`<script data-stx-theme-toggle="1">${YY(J,G,W)};window.__stxThemeToggle=1;</script>`;$=$.replace(/<\/body>/i,`${K}
|
|
4395
|
+
</body>`)}return $}async function c7($,X){if($.length===0)return{succeeded:[],failed:[]};try{return await X($),{succeeded:[...$],failed:[]}}catch{}let Z=[],Q=[];for(let Y of $)try{await X([Y]),Z.push(Y)}catch(J){Q.push({entrypoint:Y,error:U1(J,Y)})}return{succeeded:Z,failed:Q}}import{existsSync as JY,readFileSync as GY}from"fs";import{join as WY,resolve as KY}from"path";import _Y from"process";function y$($,X=_Y.cwd()){let Z=$.i18n;if(!Z||!Array.isArray(Z.locales)||Z.locales.length===0)return null;let Q=Z.defaultLocale??Z.locales[0],Y=UY(Z,X);return{locales:Z.locales,defaultLocale:Q,labels:Z.labels??Object.fromEntries(Z.locales.map((J)=>[J,J.toUpperCase()])),translations:Y,pickerSelector:Z.pickerSelector??"#lang-picker"}}function UY($,X){let Z=$.translations??{},Q={},Y=$.translationsDir,J=Y===!1?null:KY(X,typeof Y==="string"&&Y?Y:"translations"),G=$.format??"json";for(let W of $.locales){let K=J?BY(J,W,G):{};Q[W]={...K,...Z[W]??{}}}return Q}function BY($,X,Z){let Q=Z==="json"?[`${X}.json`]:[`${X}.${Z}`,`${X}.${Z==="yaml"?"yml":"yaml"}`];for(let Y of Q){let J=WY($,Y);if(!JY(J))continue;try{let G=GY(J,"utf8"),W=Z==="json"?JSON.parse(G):LY(G);return l7(W)}catch{continue}}return{}}function l7($,X="",Z={}){if(!$||typeof $!=="object")return Z;for(let[Q,Y]of Object.entries($)){let J=X?`${X}.${Q}`:Q;if(Y&&typeof Y==="object"&&!Array.isArray(Y))l7(Y,J,Z);else if(typeof Y==="string")Z[J]=Y;else if(typeof Y==="number"||typeof Y==="boolean")Z[J]=String(Y)}return Z}function LY($){let X={},Z=[{obj:X,indent:-1}];for(let Q of $.split(`
|
|
4396
|
+
`)){let Y=Q.replace(/#.*$/,"").trimEnd();if(!Y.trim())continue;let J=Y.search(/\S/);if(J===-1)continue;while(Z.length>1&&Z[Z.length-1].indent>=J)Z.pop();let G=Z[Z.length-1].obj,W=Y.match(/^(\s*)(\S[^:]*):\s*(.*)$/);if(!W)continue;let[,,K,_]=W,U=K.trim(),F=_.trim();if(F==="")G[U]={},Z.push({obj:G[U],indent:J});else G[U]=FY(F)}return X}function FY($){if($.startsWith("'")&&$.endsWith("'")||$.startsWith('"')&&$.endsWith('"'))return $.slice(1,-1);return $}function d5($,X,Z){let Q=$.translations[X]?.[Z];if(typeof Q==="string")return Q;let Y=$.translations[$.defaultLocale]?.[Z];if(typeof Y==="string")return Y;return Z}function v$($,X,Z){return $.replace(/\{t(!?):([a-zA-Z][\w.-]*)\}/g,(Q,Y,J)=>{let G=d5(X,Z,J);return Y==="!"?G:zY(G)})}function a0($,X,Z){if(X===Z)return $;if($==="/")return`/${X}/`;if($==="/404.html")return`/${X}/404.html`;return`/${X}${$}`}function i7($,X){for(let Z of X){if($===`/${Z}`||$===`/${Z}/`)return{locale:Z,path:"/"};if($.startsWith(`/${Z}/`))return{locale:Z,path:$.slice(Z.length+1)}}return{locale:null,path:$}}function g$($,X,Z){let Q=$.replace(/\/$/,""),Y=[];for(let G of Z.locales){let W=`${Q}${a0(X,G,Z.defaultLocale)}`;Y.push(`<link rel="alternate" hreflang="${b$(G)}" href="${b$(W)}">`)}let J=`${Q}${a0(X,Z.defaultLocale,Z.defaultLocale)}`;return Y.push(`<link rel="alternate" hreflang="x-default" href="${b$(J)}">`),Y.join(`
|
|
4397
4397
|
`)}function f$($,X){let Z=`<meta name="stx-layout-group" content="i18n:${b$(X)}">`;if(/<meta name="stx-layout-group"[^>]*>/i.test($))return $.replace(/<meta name="stx-layout-group"[^>]*>/i,Z);if(/<\/head>/i.test($))return $.replace(/<\/head>/i,`${Z}
|
|
4398
4398
|
</head>`);return`${Z}
|
|
4399
|
-
${$}`}function h$($,X){return`<script data-stx-lang-picker="1">window.__stxI18n=${JSON.stringify({locales:$.locales,defaultLocale:$.defaultLocale,current:X,pickerSelector:$.pickerSelector})};(function(){function cfg(){return window.__stxI18n}function localeFromPath(p){var d=cfg();for(var i=0;i<d.locales.length;i++){var c=d.locales[i];if(p==='/'+c||p==='/'+c+'/')return c;if(p.indexOf('/'+c+'/')===0)return c}return d.defaultLocale}function localePathFor(loc,p){var d=cfg();var stripped=p;for(var i=0;i<d.locales.length;i++){var c=d.locales[i];if(p==='/'+c||p==='/'+c+'/'){stripped='/';break}if(p.indexOf('/'+c+'/')===0){stripped=p.slice(c.length+1);break}}if(loc===d.defaultLocale)return stripped;if(stripped==='/')return '/'+loc+'/';return '/'+loc+stripped}cfg().localizeHref=function(href){try{var u=new URL(href,location.origin);if(u.origin!==location.origin)return href;return localePathFor(localeFromPath(location.pathname),u.pathname)+(u.search||'')+(u.hash||'')}catch(_){return href}};function syncFromUrl(){var d=cfg();var loc=localeFromPath(location.pathname);d.current=loc;var picker=document.querySelector(d.pickerSelector);if(picker){var btns=picker.querySelectorAll('[data-lang]');for(var i=0;i<btns.length;i++){var b=btns[i];if(b.getAttribute('data-lang')===loc)b.setAttribute('aria-current','true');else b.removeAttribute('aria-current')}}if(document.documentElement.lang!==loc)document.documentElement.lang=loc}function onLangClick(e){var d=cfg();var btn=e.target&&e.target.closest&&e.target.closest('[data-lang]');if(!btn)return;var picker=document.querySelector(d.pickerSelector);if(!picker||!picker.contains(btn))return;e.preventDefault();e.stopPropagation();var loc=btn.getAttribute('data-lang');if(!loc||loc===localeFromPath(location.pathname))return;var dest=localePathFor(loc,location.pathname);var r=window.__stxRouter;if(r&&r.navigate)r.navigate(dest,true,true);else location.assign(dest)}syncFromUrl();if(window.__stxLangPickerBound){document.removeEventListener('click',window.__stxLangPickerClick,true);window.removeEventListener('stx:navigate',window.__stxLangPickerSync);window.removeEventListener('popstate',window.__stxLangPickerSync)}window.__stxLangPickerClick=onLangClick;window.__stxLangPickerSync=syncFromUrl;window.__stxLangPickerBound=1;document.addEventListener('click',onLangClick,true);window.addEventListener('stx:navigate',syncFromUrl);window.addEventListener('popstate',syncFromUrl)})();</script>`}function b$($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function
|
|
4400
|
-
${N}`);if(U.succeeded.length===0)throw Error(`Build failed: none of the ${_.length} page(s) could be built`);console.error(`[stx] ${U.failed.length} of ${_.length} page(s) skipped; the rest were built.`)}
|
|
4401
|
-
</body>`);if($.spa!==!1)T=await h5(T,$.router);let f=z?
|
|
4402
|
-
${K}`);return $}function u5($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function
|
|
4399
|
+
${$}`}function h$($,X){return`<script data-stx-lang-picker="1">window.__stxI18n=${JSON.stringify({locales:$.locales,defaultLocale:$.defaultLocale,current:X,pickerSelector:$.pickerSelector})};(function(){function cfg(){return window.__stxI18n}function localeFromPath(p){var d=cfg();for(var i=0;i<d.locales.length;i++){var c=d.locales[i];if(p==='/'+c||p==='/'+c+'/')return c;if(p.indexOf('/'+c+'/')===0)return c}return d.defaultLocale}function localePathFor(loc,p){var d=cfg();var stripped=p;for(var i=0;i<d.locales.length;i++){var c=d.locales[i];if(p==='/'+c||p==='/'+c+'/'){stripped='/';break}if(p.indexOf('/'+c+'/')===0){stripped=p.slice(c.length+1);break}}if(loc===d.defaultLocale)return stripped;if(stripped==='/')return '/'+loc+'/';return '/'+loc+stripped}cfg().localizeHref=function(href){try{var u=new URL(href,location.origin);if(u.origin!==location.origin)return href;return localePathFor(localeFromPath(location.pathname),u.pathname)+(u.search||'')+(u.hash||'')}catch(_){return href}};function syncFromUrl(){var d=cfg();var loc=localeFromPath(location.pathname);d.current=loc;var picker=document.querySelector(d.pickerSelector);if(picker){var btns=picker.querySelectorAll('[data-lang]');for(var i=0;i<btns.length;i++){var b=btns[i];if(b.getAttribute('data-lang')===loc)b.setAttribute('aria-current','true');else b.removeAttribute('aria-current')}}if(document.documentElement.lang!==loc)document.documentElement.lang=loc}function onLangClick(e){var d=cfg();var btn=e.target&&e.target.closest&&e.target.closest('[data-lang]');if(!btn)return;var picker=document.querySelector(d.pickerSelector);if(!picker||!picker.contains(btn))return;e.preventDefault();e.stopPropagation();var loc=btn.getAttribute('data-lang');if(!loc||loc===localeFromPath(location.pathname))return;var dest=localePathFor(loc,location.pathname);var r=window.__stxRouter;if(r&&r.navigate)r.navigate(dest,true,true);else location.assign(dest)}syncFromUrl();if(window.__stxLangPickerBound){document.removeEventListener('click',window.__stxLangPickerClick,true);window.removeEventListener('stx:navigate',window.__stxLangPickerSync);window.removeEventListener('popstate',window.__stxLangPickerSync)}window.__stxLangPickerClick=onLangClick;window.__stxLangPickerSync=syncFromUrl;window.__stxLangPickerBound=1;document.addEventListener('click',onLangClick,true);window.addEventListener('stx:navigate',syncFromUrl);window.addEventListener('popstate',syncFromUrl)})();</script>`}function b$($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function zY($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}async function e7($){let X=Date.now(),Z=$.pagesDir??"pages",Q=$.outDir??"dist",Y=$.publicDir??"public";if(!$.noClean)OY(Q,{recursive:!0,force:!0});r7(Q,{recursive:!0});let J=new jY(`${Z}/**/*.stx`),G=await Array.fromAsync(J.scan(".")),W=$.excludeDirs??["layouts","partials","components"],K=[],_=G.filter((q)=>{let N=q.slice(Z.length).replace(/^[\\/]+/,"");if(N.split(/[\\/]/).slice(0,-1).some((M)=>W.includes(M)))return K.push(q),!1;return!N.split(/[\\/]/).some((M)=>M.startsWith("_"))});if(K.length>0)console.warn(`[stx] ${K.length} file(s) under ${Z}/ skipped as non-pages: ${W.join(", ")}`);if(_.length===0)throw Error(`No .stx files found in ${Z}/`);let U=await c7(_,(q)=>Bun.build({entrypoints:q,outdir:Q,plugins:[m7()],naming:{entry:"[name].[ext]"}}));if(U.failed.length>0){for(let{entrypoint:q,error:N}of U.failed)console.error(`[stx] failed to build ${q}:
|
|
4400
|
+
${N}`);if(U.succeeded.length===0)throw Error(`Build failed: none of the ${_.length} page(s) could be built`);console.error(`[stx] ${U.failed.length} of ${_.length} page(s) skipped; the rest were built.`)}IY(Q);let F=c5(Q).filter((q)=>q.endsWith(".html")),z=y$($,n7.cwd()),j=new Set(F.map(u$));for(let q of F){let N=x0(Q,q),I=s7(N,"utf8"),M=u$(q),w=z?z.locales:[$.seo?.locale?.split(/[_-]/)[0]??"en"];for(let D of w){let T=I;if(T=RY(T),z)T=v$(T,z,D);if(T=await J0(T,n7.cwd()),T=k$(T,$,$.pages?.[M],M),z)T=DY(T,$,z,D,M),T=wY(T,D,z.defaultLocale,j),T=f$(T,D);if(T=P$(T,$),T=TY(T),z)T=T.replace(/<\/body>/i,`${h$(z,D)}
|
|
4401
|
+
</body>`);if($.spa!==!1)T=await h5(T,$.router);let f=z?EY(M,D,z.defaultLocale):q,c=x0(Q,f);if(r7(VY(c),{recursive:!0}),d$(c,T),z&&D!==z.defaultLocale&&f!==q);}}let H=m5(Q);if(H.assets>0)console.log(`[stx] externalized ${H.assets} asset(s) from ${H.pages} page(s) (${(H.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);let L=p5(Q);if(L.assets>0)console.log(`[stx] externalized ${L.assets} repeated asset(s) from ${L.pages} page(s) (${(L.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);if(m$(Y))a7(Y,Q,{recursive:!0});let O=t7();if(O)a7(O,x0(Q,o7),{recursive:!0});let A=x0(Q,"404.html");if(!m$(A)&&m$(x0(Q,"index.html"))){let q=s7(x0(Q,"index.html"),"utf8").replace(/<title>[^<]*<\/title>/i,`<title>404 \u2014 ${CY($.name)}</title>`);d$(A,q)}if($.sitemap!==!1){let q=[],N=F.filter((M)=>M!=="404.html").map(u$),I=z?z.locales:[null];for(let M of N){let w=$.pages?.[M];for(let D of I){let T=D&&z?a0(M,D,z.defaultLocale):M;q.push({path:T,page:w})}}d$(x0(Q,"sitemap.xml"),x$($,q))}let V=S$($);if(V!==null)d$(x0(Q,"robots.txt"),V);let E=F.map(u$);return{outDir:Q,pages:E,durationMs:Date.now()-X}}function VY($){return NY($)}function EY($,X,Z){let Q=a0($,X,Z);if(Q==="/")return"index.html";let Y=Q.replace(/^\//,"").replace(/\/$/,"");if(!Y.includes("/")){if(X!==Z&&Y===X)return`${X}/index.html`;return`${Y}.html`}return`${Y}.html`.replace(/\.html\.html$/,".html")}function u$($){if($==="index.html")return"/";return`/${$.replace(/\.html$/,"").replace(/\/index$/,"")}`}function c5($,X=$){let Z=[];if(!m$($))return Z;for(let Q of HY($,{withFileTypes:!0})){let Y=x0($,Q.name);if(Q.isDirectory())Z.push(...c5(Y,X));else Z.push(MY(X,Y))}return Z}function IY($){for(let X of c5($)){if(!/^chunk-.*\.js(?:\.map)?$/.test(X))continue;let Z=x0($,X);try{if(AY(Z).size===0)qY(Z)}catch{}}}function RY($){return $.replace(/<script[^>]*src=["']\.\/chunk-[^"']*\.js["'][^>]*><\/script>\s*/g,"")}function DY($,X,Z,Q,Y){if(!Z)return $;if(/<html\b[^>]*\blang=/i.test($))$=$.replace(/<html\b([^>]*)\blang="[^"]*"/i,`<html$1lang="${Q}"`);else $=$.replace(/<html\b([^>]*)>/i,`<html$1 lang="${Q}">`);let J=`${X.url.replace(/\/$/,"")}${a0(Y,Q,Z.defaultLocale)}`;if(/<link rel="canonical"/.test($))$=$.replace(/<link rel="canonical"[^>]*>/,`<link rel="canonical" href="${u5(J)}">`);let G=Q.includes("_")||Q.includes("-")?Q:Q.toLowerCase();if(/<meta property="og:locale"/.test($))$=$.replace(/<meta property="og:locale"[^>]*>/,`<meta property="og:locale" content="${u5(G)}">`);if(/<meta property="og:url"/.test($))$=$.replace(/<meta property="og:url"[^>]*>/,`<meta property="og:url" content="${u5(J)}">`);let W=g$(X.url,Y,Z);if(!$.includes("hreflang="))$=$.replace(/<link rel="canonical"[^>]*>/,(K)=>`${W}
|
|
4402
|
+
${K}`);return $}function u5($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function wY($,X,Z,Q){if(X===Z)return $;return $.replace(/<a\b([^>]*?)\bhref="(\/[^"]*)"([^>]*)>/gi,(Y,J,G,W)=>{if(G.startsWith("//"))return Y;if(G===`/${X}`||G===`/${X}/`||G.startsWith(`/${X}/`))return Y;let K=G.match(/^(\/[^?#]*)(.*)$/);if(!K)return Y;let[,_,U]=K,F=_==="/"?"/":_.replace(/\/$/,"");if(!Q.has(F))return Y;let z=F==="/"?`/${X}/`:`/${X}${F}`;return`<a${J}href="${z}${U}"${W}>`})}function TY($){if(/<main\b/i.test($)||/\bdata-stx-content\b/i.test($))return $;let X=$.match(/<body\b[^>]*>/i),Z=$.search(/<\/body\s*>/i);if(!X||Z<0)return $;let Q=X.index+X[0].length,Y=$.slice(Q,Z),J=0,G=[...Y.matchAll(/<\/nav>/gi)];if(G.length>0){let z=G[G.length-1];J=z.index+z[0].length}let W=Y.length,K=Y.search(/<footer\b/i);if(K!==-1)W=Math.min(W,K);let _=Y.search(/<script\b[^>]*data-stx-(?:theme-toggle|reparent-progress)\b/i);if(_!==-1)W=Math.min(W,_);if(W<=J)return $;let U=Y.slice(J,W);if(!U.trim())return $;let F=`${Y.slice(0,J)}
|
|
4403
4403
|
<main>${U}</main>
|
|
4404
|
-
${Y.slice(W)}`;return`${$.slice(0,Q)}${F}${$.slice(Z)}`}function
|
|
4405
|
-
`)Z++,Q=Y+1;return{line:Z,column:X-Q+1}}function
|
|
4404
|
+
${Y.slice(W)}`;return`${$.slice(0,Q)}${F}${$.slice(Z)}`}function CY($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function $3($){return $}var kY=new Set(["if","else","elseif","else-if","for","foreach","show","model","html","text","bind","key","ref","once","memo","slot","teleport","cloak","pre","effect","init"]),xY=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function SY($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function PY($){let X=[],Z=/<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>/gi,Q;while((Q=Z.exec($))!==null)X.push([Q.index,Q.index+Q[0].length]);return X}function bY($,X){for(let[Z,Q]of $)if(X>=Z&&X<Q)return!0;return!1}function c$($,X){let Z=1,Q=0;for(let Y=0;Y<X&&Y<$.length;Y++)if($[Y]===`
|
|
4405
|
+
`)Z++,Q=Y+1;return{line:Z,column:X-Q+1}}function yY($,X,Z){let Q=X.toLowerCase(),Y=$.length,J=1,G=Z;while(G<Y){let W=$.indexOf("<",G);if(W===-1)return-1;if(G=W,$.startsWith("<!--",G)){let U=$.indexOf("-->",G+4);if(U===-1)return-1;G=U+3;continue}if($[G+1]==="/"){let U=/^<\/([a-z][\w-]*)\s*>/i.exec($.slice(G,G+64));if(!U){G++;continue}if(U[1].toLowerCase()===Q){if(J--,G+=U[0].length,J===0)return G;continue}G+=U[0].length;continue}let K=/^<([a-z][\w-]*)\b/i.exec($.slice(G,G+64));if(!K){G++;continue}let _=$.indexOf(">",G);if(_===-1)return-1;if(K[1].toLowerCase()===Q&&$[_-1]!=="/")J++;G=_+1}return-1}function vY($,X,Z){let Q=/@([a-z][\w:-]*)((?:\.[a-z][\w-]*)*)\s*=\s*"([^"]*)"/gi,Y;while((Y=Q.exec($))!==null){if(bY(X,Y.index))continue;let J=Y[1].toLowerCase().split(":")[0];if(kY.has(J))continue;let G=Y[3].trim();if(/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(G)){let W=$.indexOf(Y[3],Y.index),{line:K,column:_}=c$($,W<0?Y.index:W);Z.push({ruleId:"stx/no-bare-function-ref-in-event",message:`Event handler @${Y[1]}="${G}" is a member path, which the runtime does not invoke \u2014 it only auto-calls a plain identifier. Call it: @${Y[1]}="${G}($event)".`,line:K,column:_,severity:"error"})}}}function X3($){let X=$.split("/"),Z=[];for(let Q of X){if(Q===""||Q===".")continue;if(Q==="..")Z.pop();else Z.push(Q)}return Z.join("/")}function gY($,X,Z){let Q=X.replace(/\\/g,"/"),Y=Q.indexOf("resources/stores/");if(Y===-1)return;let J=Q.slice(0,Y+16),G=Q.slice(0,Q.lastIndexOf("/")),W=/\b(import|export)\s+(type\s+)?([^'"]*?)\s*from\s*['"]([^'"]+)['"]/g,K;while((K=W.exec($))!==null){if(K[2])continue;let _=K[1],U=K[4],F;if(U.startsWith("."))F=!X3(`${G}/${U}`).startsWith(X3(J));else F=!0;if(F){let{line:z,column:j}=c$($,K.index),H=_==="export"?"Value re-export":"Value import";Z.push({ruleId:"stx/store-value-imports-must-be-local",message:`${H} from "${U}" is outside resources/stores/ and will be stripped from the store bundle. Use \`${_} type\`, or move the value into the stores dir.`,line:z,column:j,severity:"error"})}}}function fY($){let X=$.trim(),Z=(G)=>{let W=G.match(/[A-Za-z_$][\w$]*/g);return W?W:[]},Q=/\bas\s+(.+)$/.exec(X);if(Q){let G=Q[1].trim(),W=/^([A-Za-z_$][\w$]*)\s*=>\s*([A-Za-z_$][\w$]*)/.exec(G);if(W)return[W[1],W[2]];let K=/^\(([^)]*)\)/.exec(G);if(K)return Z(K[1]);let _=/^([A-Za-z_$][\w$]*)/.exec(G);return _?[_[1]]:[]}let Y=/^\(([^)]*)\)\s+(?:in|of)\s+/.exec(X);if(Y)return Z(Y[1]);let J=/^([A-Za-z_$][\w$]*)\s+(?:in|of)\s+/.exec(X);return J?[J[1]]:[]}function hY($,X){let Z=/(?::for|x-for|@for)\s*=\s*"([^"]*)"/gi,Q;while((Q=Z.exec($))!==null){let Y=fY(Q[1]);if(Y.length===0)continue;let J=$.lastIndexOf("<",Q.index);if(J===-1)continue;let G=/^<([a-z][\w-]*)/i.exec($.slice(J,J+64));if(!G)continue;let W=$.indexOf(">",Q.index);if(W===-1)continue;let _=$[W-1]==="/"||xY.has(G[1].toLowerCase())?W+1:yY($,G[1],W+1),U=_===-1?W+1:_,F=$.indexOf(Q[1],Q.index),z=$.slice(J,U);if(F>=0&&F+Q[1].length<=U){let j=F-J;z=z.slice(0,j)+" ".repeat(Q[1].length)+z.slice(j+Q[1].length)}for(let j of Y){let H=new RegExp(`(?<![.\\w$])${SY(j)}\\s*\\(`,"g"),L;while((L=H.exec(z))!==null){let O=J+L.index,{line:A,column:V}=c$($,O);X.push({ruleId:"stx/no-signal-call-in-for-iteration-var",message:`"${j}" is a :for iteration variable, not a signal \u2014 calling it as "${j}()" leaves it as a function and silently breaks comparisons. Use "${j}" directly.`,line:A,column:V,severity:"error"})}}}}function dY($,X){let Z=/<!--([\s\S]*?)-->/g,Q;while((Q=Z.exec($))!==null){let J=Q[1].indexOf("`");if(J!==-1){let G=Q.index+4+J,{line:W,column:K}=c$($,G);X.push({ruleId:"stx/no-backticks-in-html-comments",message:"Backtick inside an HTML comment leaks into the merged setup function and flips the JS parser into template-literal mode. Remove it or rephrase the comment.",line:W,column:K,severity:"error"})}}}function p$($,X){return $?.[X]!==!1}function uY($,X={}){let Z=[],Q=PY($),Y=(X.filePath??"").replace(/\\/g,"/"),J=X.fileKind??(/\/components?\//i.test(Y)?"component":/\/layouts?\//i.test(Y)?"layout":"view");if(p$(X.rules,"stx/no-bare-function-ref-in-event"))vY($,Q,Z);if(Y&&p$(X.rules,"stx/store-value-imports-must-be-local"))gY($,Y,Z);if(p$(X.rules,"stx/no-signal-call-in-for-iteration-var"))hY($,Z);if(p$(X.rules,"stx/no-backticks-in-html-comments"))dY($,Z);Z.sort((W,K)=>W.line-K.line||W.column-K.column);let G=new Set;return Z.filter((W)=>{let K=`${W.ruleId}:${W.line}:${W.column}`;if(G.has(K))return!1;return G.add(K),!0})}function mY($,X){return $.kind===X}function Z3($){if($===String)return"string";if($===Number)return"number";if($===Boolean)return"boolean";if($===Array)return"array";if($===Object)return"object";if($===Function)return"function";if($===Date)return"date";if($===Symbol)return"symbol";if(typeof $==="function"&&$.name)return $.name;return"unknown"}function pY($,X){if($===null||$===void 0)return!0;if(X===String)return typeof $==="string";if(X===Number)return typeof $==="number"&&!Number.isNaN($);if(X===Boolean)return typeof $==="boolean";if(X===Array)return Array.isArray($);if(X===Object)return typeof $==="object"&&!Array.isArray($);if(X===Function)return typeof $==="function";if(X===Date)return $ instanceof Date;if(X===Symbol)return typeof $==="symbol";if(typeof X==="function")return $ instanceof X;return!0}function Q3($,X,Z,Q){let Y=Q?`[${Q}]`:"";if(Z.required&&(X===void 0||X===null))return{prop:$,message:`${Y} Missing required prop: "${$}"`,value:X,expected:Z.type?Z3(Z.type):void 0};if(X===void 0||X===null)return null;if(Z.type){let J=Array.isArray(Z.type)?Z.type:[Z.type];if(!J.some((W)=>pY(X,W))){let W=J.map((K)=>Z3(K)).join(" | ");return{prop:$,message:`${Y} Invalid prop type for "${$}": expected ${W}, got ${typeof X}`,value:X,expected:W}}}if(Z.validator){if(!Z.validator(X))return{prop:$,message:`${Y} Custom validation failed for prop "${$}"`,value:X}}return null}function cY($){let X=globalThis.__STX_CURRENT_PROPS__||{};if(!$)return X;let Z={...X};for(let[Q,Y]of Object.entries($)){let J=typeof Y==="function"||Array.isArray(Y)?{type:Y}:Y||{};if(Z[Q]===void 0&&J.default!==void 0)Z[Q]=typeof J.default==="function"?J.default():J.default}return Z}function lY($,X={}){let{componentName:Z,throwOnError:Q=!1,logWarnings:Y=!0}=X,J=globalThis.__STX_CURRENT_PROPS__||{},G={...J},W={valid:!0,errors:[],warnings:[]};for(let[K,_]of Object.entries($)){let U=typeof _==="function"||Array.isArray(_)?{type:_}:_||{};if(G[K]===void 0&&U.default!==void 0)G[K]=typeof U.default==="function"?U.default():U.default;let F=Q3(K,G[K],U,Z);if(F){if(W.valid=!1,W.errors.push(F),Y)console.warn(F.message)}}for(let K of Object.keys(J))if(!(K in $)){let _=`${Z?`[${Z}]`:""} Unknown prop: "${K}"`;if(W.warnings.push(_),Y)console.warn(_)}if(Q&&!W.valid){let K=W.errors.map((_)=>_.message).join(`
|
|
4406
4406
|
`);throw Error(`Prop validation failed:
|
|
4407
|
-
${K}`)}return{props:G,validation:W}}function
|
|
4408
|
-
export{
|
|
4407
|
+
${K}`)}return{props:G,validation:W}}function iY($,X){let Z={...$};for(let[Q,Y]of Object.entries(X))if(Z[Q]===void 0)Z[Q]=typeof Y==="function"?Y():Y;return Z}function aY($){return $}function rY($){return{type:$,required:!0}}function sY($,X){return{type:X,default:$}}function nY($,X={}){return{...X,validator:$}}function oY($,X={}){return{...X,validator:(Z)=>$.includes(Z)}}function tY($,X={}){return{...X,type:Array,validator:(Z)=>{if(!Array.isArray(Z))return!1;return!0}}}function eY($,X={}){return{...X,type:Object}}function $J($,X,Z){if(!X)return $;let Q={};for(let[Y,J]of Object.entries(X)){let G=typeof J==="function"||Array.isArray(J)?{type:J}:J||{},W=$[Y];if(W===void 0&&G.default!==void 0)W=typeof G.default==="function"?G.default():G.default;{let K=Q3(Y,W,G,Z);if(K)console.warn(K.message)}Q[Y]=W}for(let[Y,J]of Object.entries($))if(!(Y in Q))Q[Y]=J;return Q}var TB={};
|
|
4408
|
+
export{ZK as o,t$ as p,j6 as q,M4 as r,P0 as s,Z$ as t,Q$ as u,Y$ as v,J$ as w,D1 as x,J3 as y,G3 as z,W3 as A,K3 as B,_3 as C,U3 as D,YJ as E,JJ as F,GJ as G,B3 as H,WJ as I,L3 as J,KJ as K,_J as L,UJ as M,BJ as N,LJ as O,FJ as P,zJ as Q,jJ as R,HJ as S,OJ as T,Y1 as U,AJ as V,qJ as W,NJ as X,MJ as Y,EJ as Z,IJ as _,z3 as $,j3 as aa,RJ as ba,H3 as ca,DJ as da,wJ as ea,TJ as fa,CJ as ga,kJ as ha,xJ as ia,O3 as ja,A3 as ka,SJ as la,PJ as ma,q3 as na,yJ as oa,hJ as pa,dJ as qa,Y6 as ra,D3 as sa,w3 as ta,T3 as ua,C3 as va,r$ as wa,k3 as xa,x3 as ya,S3 as za,P3 as Aa,mJ as Ba,aJ as Ca,rJ as Da,v3 as Ea,sJ as Fa,t3 as Ga,eJ as Ha,T4 as Ia,C4 as Ja,d4 as Ka,u4 as La,m4 as Ma,s6 as Na,p4 as Oa,c4 as Pa,l4 as Qa,i4 as Ra,a4 as Sa,r4 as Ta,s4 as Ua,vW as Va,S1 as Wa,dW as Xa,uW as Ya,n4 as Za,o4 as _a,$X as $a,A$ as ab,mW as bb,pW as cb,cW as db,lW as eb,iW as fb,aW as gb,rW as hb,sW as ib,nW as jb,oW as kb,tW as lb,eW as mb,GX as nb,X2 as ob,J2 as pb,G2 as qb,z5 as rb,F2 as sb,z2 as tb,j2 as ub,IX as vb,A2 as wb,I2 as xb,R2 as yb,D2 as zb,w2 as Ab,T2 as Bb,C2 as Cb,u2 as Db,GZ as Eb,m2 as Fb,WZ as Gb,KZ as Hb,L8 as Ib,F8 as Jb,l2 as Kb,i2 as Lb,a2 as Mb,s2 as Nb,n2 as Ob,jZ as Pb,t2 as Qb,e2 as Rb,$K as Sb,q6 as Tb,H8 as Ub,YK as Vb,JK as Wb,GK as Xb,WK as Yb,HZ as Zb,OZ as _b,UK as $b,AZ as ac,q8 as bc,BK as cc,qZ as dc,LK as ec,FK as fc,NZ as gc,VK as hc,V8 as ic,EZ as jc,IZ as kc,E8 as lc,DZ as mc,wZ as nc,CZ as oc,l as pc,I8 as qc,I5 as rc,R8 as sc,D8 as tc,w8 as uc,T8 as vc,C8 as wc,k8 as xc,x8 as yc,S8 as zc,P8 as Ac,b8 as Bc,y8 as Cc,v8 as Dc,g8 as Ec,f8 as Fc,h8 as Gc,d8 as Hc,u8 as Ic,m8 as Jc,p8 as Kc,c8 as Lc,R5 as Mc,l8 as Nc,i8 as Oc,a8 as Pc,r8 as Qc,s8 as Rc,o8 as Sc,D5 as Tc,w5 as Uc,t8 as Vc,T5 as Wc,C5 as Xc,k5 as Yc,m1 as Zc,N$ as _c,e8 as $c,$7 as ad,X7 as bd,M$ as cd,Q7 as dd,Y7 as ed,J7 as fd,G7 as gd,qQ as hd,NQ as id,x5 as jd,S5 as kd,B7 as ld,c0 as md,L7 as nd,F7 as od,z7 as pd,j7 as qd,H7 as rd,V$ as sd,P5 as td,A7 as ud,E$ as vd,q7 as wd,N7 as xd,M7 as yd,V7 as zd,I$ as Ad,R$ as Bd,b5 as Cd,y5 as Dd,I7 as Ed,R7 as Fd,D7 as Gd,D$ as Hd,w7 as Id,TQ as Jd,d_ as Kd,T7 as Ld,CQ as Md,Z9 as Nd,Q9 as Od,J9 as Pd,A1 as Qd,q1 as Rd,fQ as Sd,hQ as Td,O1 as Ud,uQ as Vd,p1 as Wd,pQ as Xd,cQ as Yd,lQ as Zd,iQ as _d,b7 as $d,aQ as ae,rQ as be,v7 as ce,nQ as de,oQ as ee,k$ as fe,x$ as ge,S$ as he,P$ as ie,y$ as je,d5 as ke,v$ as le,a0 as me,i7 as ne,g$ as oe,f$ as pe,h$ as qe,e7 as re,$3 as se,uY as te,mY as ue,cY as ve,lY as we,iY as xe,aY as ye,rY as ze,sY as Ae,nY as Be,oY as Ce,tY as De,eY as Ee,$J as Fe,TB as Ge,E4 as He,I6 as Ie,R4 as Je,w4 as Ke};
|