@stacksjs/stx 0.2.460 → 0.2.462

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dist/chunk-03ek5ag5.js +2 -0
  2. package/dist/chunk-0a2w25j8.js +2 -0
  3. package/dist/chunk-0e1rga0j.js +2 -0
  4. package/dist/chunk-0f1f6y2w.js +2 -0
  5. package/dist/chunk-14p5jgqp.js +2 -0
  6. package/dist/{chunk-26gxw0e2.js → chunk-18pagcsc.js} +5 -5
  7. package/dist/chunk-1fccwkkq.js +2 -0
  8. package/dist/{chunk-ab56jdah.js → chunk-1k01h1zb.js} +1 -1
  9. package/dist/chunk-22972c8b.js +2 -0
  10. package/dist/{chunk-w1zvh5y7.js → chunk-2jbyks2t.js} +2 -2
  11. package/dist/{chunk-2cy956js.js → chunk-3rpbzfw5.js} +2 -2
  12. package/dist/{chunk-s25yesdx.js → chunk-3rrzxapr.js} +1 -1
  13. package/dist/{chunk-kp54j5hy.js → chunk-4mcmbvxb.js} +1 -1
  14. package/dist/{chunk-vqdv6ay9.js → chunk-501kq69r.js} +1 -1
  15. package/dist/{chunk-bq2e9qf6.js → chunk-5bqs0ve6.js} +1 -1
  16. package/dist/chunk-5ex4hjt3.js +2 -0
  17. package/dist/{chunk-dxxs52yw.js → chunk-5j5msbks.js} +2 -2
  18. package/dist/{chunk-jfps4n28.js → chunk-5pgvfxtx.js} +2 -2
  19. package/dist/{chunk-w6zz18jt.js → chunk-5w87wmc4.js} +2 -2
  20. package/dist/{chunk-18fa768q.js → chunk-6ths0ktv.js} +1 -1
  21. package/dist/{chunk-fm7crc6s.js → chunk-6wqvgy6x.js} +1 -1
  22. package/dist/{chunk-zchtjtq9.js → chunk-6yt2dpsb.js} +1 -1
  23. package/dist/{chunk-n1dyjhte.js → chunk-7h57dt0z.js} +3 -3
  24. package/dist/chunk-8xkr55v2.js +2 -0
  25. package/dist/{chunk-exgyf65a.js → chunk-8yrk8ybh.js} +3 -3
  26. package/dist/chunk-995ytskb.js +2 -0
  27. package/dist/chunk-9mmsb0zb.js +2 -0
  28. package/dist/{chunk-kppgyqwb.js → chunk-9n10mh5q.js} +1 -1
  29. package/dist/{chunk-ks35e0ze.js → chunk-9y6bn8hk.js} +1 -1
  30. package/dist/{chunk-mhpsz5m0.js → chunk-9yywhkc7.js} +8 -8
  31. package/dist/{chunk-6pyydsn1.js → chunk-a51ftv2n.js} +137 -7
  32. package/dist/{chunk-jkyb1f9r.js → chunk-a6pjaw6w.js} +1 -1
  33. package/dist/chunk-amvnckr7.js +2 -0
  34. package/dist/{chunk-zskhxkbk.js → chunk-b6e36vr2.js} +127 -112
  35. package/dist/{chunk-6cp3afft.js → chunk-b8p9y1kv.js} +2 -2
  36. package/dist/{chunk-12w518qc.js → chunk-bagh6sc1.js} +4 -4
  37. package/dist/chunk-c0wcvbhr.js +2 -0
  38. package/dist/chunk-darbqs38.js +2 -0
  39. package/dist/{chunk-1wtm4ayp.js → chunk-e02b66yn.js} +1 -1
  40. package/dist/chunk-e38fyh0y.js +2 -0
  41. package/dist/chunk-gcz1wex2.js +2 -0
  42. package/dist/{chunk-qxcw9k0z.js → chunk-gn32cr6z.js} +1 -1
  43. package/dist/{chunk-n866vbgj.js → chunk-gxhwg1f4.js} +2 -2
  44. package/dist/{chunk-5erw0wsr.js → chunk-hp901qmd.js} +1 -1
  45. package/dist/chunk-jbdvkj3q.js +2 -0
  46. package/dist/{chunk-9r6nd1nf.js → chunk-jnn745tt.js} +1 -1
  47. package/dist/chunk-jy58t59b.js +2 -0
  48. package/dist/{chunk-xz6dfe70.js → chunk-kggx9jc1.js} +1 -1
  49. package/dist/chunk-khx54f41.js +2 -0
  50. package/dist/{chunk-y15ybsg3.js → chunk-m2yy86d8.js} +4 -4
  51. package/dist/{chunk-5p56w2ke.js → chunk-n1mspzv7.js} +1 -1
  52. package/dist/{chunk-y1hx8re2.js → chunk-n3r5m938.js} +1 -1
  53. package/dist/chunk-n76phhd2.js +2 -0
  54. package/dist/{chunk-9z22zs86.js → chunk-neq30d52.js} +1 -1
  55. package/dist/{chunk-h9e032kq.js → chunk-pf0d8y9n.js} +2 -2
  56. package/dist/{chunk-fyh1w7j0.js → chunk-pq84ycrv.js} +1 -1
  57. package/dist/{chunk-fzs6v9x5.js → chunk-ptxvex42.js} +45 -45
  58. package/dist/{chunk-aeb8621d.js → chunk-q0d0q8r8.js} +2 -2
  59. package/dist/{chunk-ps54xqba.js → chunk-qer8jpr5.js} +1 -1
  60. package/dist/{chunk-1vgmzmsw.js → chunk-qr68w6qf.js} +1 -1
  61. package/dist/chunk-sd2gc341.js +2 -0
  62. package/dist/{chunk-bf519g5n.js → chunk-t0j0d802.js} +1 -1
  63. package/dist/chunk-t1s00kj6.js +2 -0
  64. package/dist/{chunk-ycdzhjt0.js → chunk-ty3j2ryw.js} +1 -1
  65. package/dist/{chunk-4fa3jec9.js → chunk-ver2yf41.js} +1 -1
  66. package/dist/chunk-vvyfeyxk.js +2 -0
  67. package/dist/{chunk-7sbgpmwt.js → chunk-vxhy0a3n.js} +2 -2
  68. package/dist/{chunk-tr7dz5g5.js → chunk-w28dbef2.js} +1 -1
  69. package/dist/{chunk-h356tjvs.js → chunk-wz29ahjp.js} +1 -1
  70. package/dist/{chunk-c491hsm1.js → chunk-x4yqyea2.js} +2 -2
  71. package/dist/{chunk-jdhs9w6h.js → chunk-xq4x3cy0.js} +1 -1
  72. package/dist/chunk-y2p3scx0.js +2 -0
  73. package/dist/{chunk-bf7aa9w7.js → chunk-yfbj4qce.js} +1 -1
  74. package/dist/{chunk-r6pax860.js → chunk-ynvce0q6.js} +2 -2
  75. package/dist/chunk-yxwam84p.js +2 -0
  76. package/dist/{chunk-mp633tnh.js → chunk-zkp2cw7q.js} +1 -1
  77. package/dist/chunk-zxbz8v00.js +2 -0
  78. package/dist/cli.js +9 -9
  79. package/dist/craft-entry.js +1 -1
  80. package/dist/craft.js +1 -1
  81. package/dist/pwa.js +1 -1
  82. package/dist/signals.js +133 -3
  83. package/dist/ssg.js +3 -3
  84. package/dist/utils.js +18 -3
  85. package/package.json +5 -5
  86. package/dist/chunk-0r0cbqpj.js +0 -2
  87. package/dist/chunk-0snysm7z.js +0 -2
  88. package/dist/chunk-3wkrrps3.js +0 -2
  89. package/dist/chunk-5m8q7c5r.js +0 -2
  90. package/dist/chunk-6vye2exm.js +0 -2
  91. package/dist/chunk-80a84qry.js +0 -2
  92. package/dist/chunk-8p2vfjg2.js +0 -2
  93. package/dist/chunk-9r1jj3rm.js +0 -2
  94. package/dist/chunk-cq7se10f.js +0 -2
  95. package/dist/chunk-cy2bskcx.js +0 -2
  96. package/dist/chunk-ef0gstkd.js +0 -2
  97. package/dist/chunk-f8hd3kh3.js +0 -2
  98. package/dist/chunk-fb1711er.js +0 -2
  99. package/dist/chunk-g7ksavh1.js +0 -2
  100. package/dist/chunk-hskrxdcc.js +0 -2
  101. package/dist/chunk-m00nek1y.js +0 -2
  102. package/dist/chunk-nqvb9094.js +0 -2
  103. package/dist/chunk-p0nx92aq.js +0 -2
  104. package/dist/chunk-q0qd0bm4.js +0 -2
  105. package/dist/chunk-q98v7bhs.js +0 -2
  106. package/dist/chunk-r61m4j2j.js +0 -2
  107. package/dist/chunk-rf9hm92z.js +0 -2
  108. package/dist/chunk-rpsjz8jd.js +0 -2
  109. package/dist/chunk-t68s37hg.js +0 -2
  110. package/dist/chunk-twb35cwb.js +0 -2
  111. package/dist/chunk-wz1bgf8q.js +0 -2
package/dist/cli.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import"./chunk-r6pax860.js";import"./chunk-8xz8t9xp.js";import"./chunk-w6zz18jt.js";import"./chunk-w1zvh5y7.js";import"./chunk-h9e032kq.js";import{U}from"./chunk-zskhxkbk.js";import"./chunk-exgyf65a.js";import"./chunk-4fa3jec9.js";import"./chunk-zydg3wgt.js";import"./chunk-y1hx8re2.js";import"./chunk-jz7pvh7b.js";import"./chunk-0trfbqa7.js";import"./chunk-5p56w2ke.js";import"./chunk-mhpsz5m0.js";import"./chunk-z80d9dd2.js";import"./chunk-2bdthb37.js";import"./chunk-rgwvqmhh.js";import"./chunk-rcr57c30.js";import"./chunk-y15ybsg3.js";import"./chunk-z2daw0th.js";import"./chunk-bf7aa9w7.js";import"./chunk-6pyydsn1.js";import"./chunk-tpeyn7wr.js";import"./chunk-5qns2sdz.js";import"./chunk-h356tjvs.js";import"./chunk-ree9weje.js";import"./chunk-zchtjtq9.js";import"./chunk-z3etxty5.js";import"./chunk-jfps4n28.js";import"./chunk-5erw0wsr.js";import"./chunk-26gxw0e2.js";import"./chunk-n866vbgj.js";import"./chunk-6r2709dj.js";import"./chunk-c491hsm1.js";import{gt,mt}from"./chunk-jkyb1f9r.js";import"./chunk-1wtm4ayp.js";import"./chunk-9r6nd1nf.js";import"./chunk-462jmw0a.js";import"./chunk-gkqxnetc.js";import"./chunk-ab56jdah.js";import"./chunk-n1dyjhte.js";import"./chunk-tbjyp03h.js";import"./chunk-fyh1w7j0.js";import"./chunk-ycdzhjt0.js";import{Hs,Vs,Us,Ws,fr,qs,Ks,Xs,gr,mr,bn,wn,vn}from"./chunk-fzs6v9x5.js";import"./chunk-12w518qc.js";import"./chunk-dxxs52yw.js";import{pi}from"./chunk-bq2e9qf6.js";import{u}from"./chunk-cg8hg6cs.js";import{spawn as R}from"child_process";import S from"fs";import M from"os";import f from"path";import n from"process";import{CLI as V}from"@stacksjs/clapp";var j="0.2.460";var __dirname="/home/runner/work/stx/stx/packages/stx/bin",y=new V("stx");function B(h){let p=typeof h==="string"?Number.parseInt(h,10):h;if(Number.isNaN(p))return{isValid:!1,error:"Port must be a valid number",suggestion:"Try using a number between 1024 and 65535"};if(p<1024||p>65535)return{isValid:!1,error:"Port must be between 1024 and 65535",suggestion:"Try using a port between 1024 and 65535"};return{isValid:!0}}function A(h){try{if(!S.existsSync(h)){let x=f.dirname(h),t=f.basename(h);if(S.existsSync(x)){let o=S.readdirSync(x).filter((s)=>s.toLowerCase().includes(t.toLowerCase().substring(0,3))||s.endsWith(".stx")||s.endsWith(".md")),i=o.length>0?`File not found. Similar files in ${x}: ${o.slice(0,3).join(", ")}`:`File not found. Directory ${x} exists but doesn't contain the specified file.`;return{isValid:!1,error:`File does not exist: ${h}`,suggestion:i}}return{isValid:!1,error:`File does not exist: ${h}`,suggestion:"Check the file path and try again"}}if(S.statSync(h).isDirectory())return{isValid:!1,error:`Expected file but got directory: ${h}`,suggestion:"Specify a .stx or .md file path"};return{isValid:!0}}catch(p){return{isValid:!1,error:`Cannot access file: ${h}`,suggestion:"Check file permissions and path"}}}function z(h){let p=typeof h==="string"?Number.parseInt(h,10):h;if(Number.isNaN(p))return{isValid:!1,error:"Timeout must be a valid number",suggestion:"Specify timeout in milliseconds (e.g., 5000 for 5 seconds)"};if(p<100)return{isValid:!1,error:"Timeout too short (minimum 100ms)",suggestion:"Use a timeout of at least 100ms"};if(p>300000)return{isValid:!1,error:"Timeout too long (maximum 5 minutes)",suggestion:"Use a timeout of less than 300000ms (5 minutes)"};return{isValid:!0}}var O=(h)=>h.includes("*")||h.includes("?")||h.includes("{")||h.includes("["),H=(h)=>h.endsWith(".stx")||h.endsWith(".md");function F(h,p=1){if(console.error(`\u274C ${h.error}`),h.suggestion)console.error(`\uD83D\uDCA1 suggestion: ${h.suggestion}`);n.exit(p)}function L(h){if(!h)return;let p;try{p=JSON.parse(h)}catch(x){console.error(`\u274C --info-plist is not valid JSON: ${x.message}`),n.exit(1)}if(typeof p!=="object"||p===null||Array.isArray(p))console.error(`\u274C --info-plist must be a JSON object, e.g. '{"NSFocusStatusUsageDescription":"\u2026"}'`),n.exit(1);for(let[x,t]of Object.entries(p))if(typeof t!=="string"&&typeof t!=="number"&&typeof t!=="boolean")console.error(`\u274C --info-plist value for "${x}" must be a string, number or boolean`),n.exit(1);return p}async function G(h,p){try{let x=["test"],t=[];if(h&&h.length>0)for(let c of h)if(O(c))try{let r=await Array.fromAsync(new Bun.Glob(c).scan({onlyFiles:!0,absolute:!0}));if(r.length===0)console.warn(`Warning: No files found matching pattern: ${c}`);else if(t.push(...r),p.verbose)console.log(`Found ${r.length} file(s) matching pattern: ${c}`)}catch(r){return console.error(`Error expanding glob pattern ${c}:`,r),!1}else t.push(c);if(t.length===0)return console.error("Error: No test files found matching the provided patterns."),!1;if(x.push(...t),p.filter)x.push("--pattern",p.filter);if(p.timeout)x.push("--timeout",p.timeout.toString());if(p.reporter&&p.reporter!=="default")if(p.reporter==="junit"){let c=f.join(M.tmpdir(),`stx-test-report-${Date.now()}.xml`);x.push("--reporter",p.reporter),x.push("--reporter-outfile",c)}else console.warn(`Warning: Reporter '${p.reporter}' is not supported. Using default reporter.`);if(p.coverage)x.push("--coverage");if(p.watch)x.push("--watch");x.push("--preload",f.join(__dirname,"../../../test-utils/happy-dom.ts"));let e={...n.env,STX_TEST_MODE:"true",STX_TEST_UI:p.ui?"true":"false",STX_TEST_VERBOSE:p.verbose?"true":"false"},o="bun";if(p.verbose)console.log(`Running: ${o} ${x.join(" ")}`);let i=performance.now(),s=R(o,x,{stdio:"inherit",shell:!1,env:e});return new Promise((c)=>{s.on("close",(r)=>{let d=((performance.now()-i)/1000).toFixed(2);if(r===0)c(!0);else c(!1)}),n.on("SIGINT",()=>{console.log(`
3
+ import"./chunk-ynvce0q6.js";import"./chunk-8xz8t9xp.js";import"./chunk-5w87wmc4.js";import"./chunk-2jbyks2t.js";import"./chunk-pf0d8y9n.js";import{U}from"./chunk-b6e36vr2.js";import"./chunk-8yrk8ybh.js";import"./chunk-ver2yf41.js";import"./chunk-zydg3wgt.js";import"./chunk-n3r5m938.js";import"./chunk-jz7pvh7b.js";import"./chunk-0trfbqa7.js";import"./chunk-n1mspzv7.js";import"./chunk-9yywhkc7.js";import"./chunk-z80d9dd2.js";import"./chunk-2bdthb37.js";import"./chunk-rgwvqmhh.js";import"./chunk-rcr57c30.js";import"./chunk-m2yy86d8.js";import"./chunk-z2daw0th.js";import"./chunk-yfbj4qce.js";import"./chunk-a51ftv2n.js";import"./chunk-tpeyn7wr.js";import"./chunk-5qns2sdz.js";import"./chunk-wz29ahjp.js";import"./chunk-ree9weje.js";import"./chunk-6yt2dpsb.js";import"./chunk-z3etxty5.js";import"./chunk-5pgvfxtx.js";import"./chunk-hp901qmd.js";import"./chunk-18pagcsc.js";import"./chunk-gxhwg1f4.js";import"./chunk-6r2709dj.js";import"./chunk-x4yqyea2.js";import{gt,mt}from"./chunk-a6pjaw6w.js";import"./chunk-e02b66yn.js";import"./chunk-jnn745tt.js";import"./chunk-462jmw0a.js";import"./chunk-gkqxnetc.js";import"./chunk-1k01h1zb.js";import"./chunk-7h57dt0z.js";import"./chunk-tbjyp03h.js";import"./chunk-pq84ycrv.js";import"./chunk-ty3j2ryw.js";import{Hs,Vs,Us,Ws,fr,qs,Ks,Xs,gr,mr,bn,wn,vn}from"./chunk-ptxvex42.js";import"./chunk-bagh6sc1.js";import"./chunk-5j5msbks.js";import{pi}from"./chunk-5bqs0ve6.js";import{u}from"./chunk-cg8hg6cs.js";import{spawn as R}from"child_process";import S from"fs";import M from"os";import f from"path";import n from"process";import{CLI as V}from"@stacksjs/clapp";var j="0.2.462";var __dirname="/home/runner/work/stx/stx/packages/stx/bin",y=new V("stx");function B(h){let p=typeof h==="string"?Number.parseInt(h,10):h;if(Number.isNaN(p))return{isValid:!1,error:"Port must be a valid number",suggestion:"Try using a number between 1024 and 65535"};if(p<1024||p>65535)return{isValid:!1,error:"Port must be between 1024 and 65535",suggestion:"Try using a port between 1024 and 65535"};return{isValid:!0}}function A(h){try{if(!S.existsSync(h)){let x=f.dirname(h),t=f.basename(h);if(S.existsSync(x)){let o=S.readdirSync(x).filter((s)=>s.toLowerCase().includes(t.toLowerCase().substring(0,3))||s.endsWith(".stx")||s.endsWith(".md")),i=o.length>0?`File not found. Similar files in ${x}: ${o.slice(0,3).join(", ")}`:`File not found. Directory ${x} exists but doesn't contain the specified file.`;return{isValid:!1,error:`File does not exist: ${h}`,suggestion:i}}return{isValid:!1,error:`File does not exist: ${h}`,suggestion:"Check the file path and try again"}}if(S.statSync(h).isDirectory())return{isValid:!1,error:`Expected file but got directory: ${h}`,suggestion:"Specify a .stx or .md file path"};return{isValid:!0}}catch(p){return{isValid:!1,error:`Cannot access file: ${h}`,suggestion:"Check file permissions and path"}}}function z(h){let p=typeof h==="string"?Number.parseInt(h,10):h;if(Number.isNaN(p))return{isValid:!1,error:"Timeout must be a valid number",suggestion:"Specify timeout in milliseconds (e.g., 5000 for 5 seconds)"};if(p<100)return{isValid:!1,error:"Timeout too short (minimum 100ms)",suggestion:"Use a timeout of at least 100ms"};if(p>300000)return{isValid:!1,error:"Timeout too long (maximum 5 minutes)",suggestion:"Use a timeout of less than 300000ms (5 minutes)"};return{isValid:!0}}var O=(h)=>h.includes("*")||h.includes("?")||h.includes("{")||h.includes("["),H=(h)=>h.endsWith(".stx")||h.endsWith(".md");function F(h,p=1){if(console.error(`\u274C ${h.error}`),h.suggestion)console.error(`\uD83D\uDCA1 suggestion: ${h.suggestion}`);n.exit(p)}function L(h){if(!h)return;let p;try{p=JSON.parse(h)}catch(x){console.error(`\u274C --info-plist is not valid JSON: ${x.message}`),n.exit(1)}if(typeof p!=="object"||p===null||Array.isArray(p))console.error(`\u274C --info-plist must be a JSON object, e.g. '{"NSFocusStatusUsageDescription":"\u2026"}'`),n.exit(1);for(let[x,t]of Object.entries(p))if(typeof t!=="string"&&typeof t!=="number"&&typeof t!=="boolean")console.error(`\u274C --info-plist value for "${x}" must be a string, number or boolean`),n.exit(1);return p}async function G(h,p){try{let x=["test"],t=[];if(h&&h.length>0)for(let c of h)if(O(c))try{let r=await Array.fromAsync(new Bun.Glob(c).scan({onlyFiles:!0,absolute:!0}));if(r.length===0)console.warn(`Warning: No files found matching pattern: ${c}`);else if(t.push(...r),p.verbose)console.log(`Found ${r.length} file(s) matching pattern: ${c}`)}catch(r){return console.error(`Error expanding glob pattern ${c}:`,r),!1}else t.push(c);if(t.length===0)return console.error("Error: No test files found matching the provided patterns."),!1;if(x.push(...t),p.filter)x.push("--pattern",p.filter);if(p.timeout)x.push("--timeout",p.timeout.toString());if(p.reporter&&p.reporter!=="default")if(p.reporter==="junit"){let c=f.join(M.tmpdir(),`stx-test-report-${Date.now()}.xml`);x.push("--reporter",p.reporter),x.push("--reporter-outfile",c)}else console.warn(`Warning: Reporter '${p.reporter}' is not supported. Using default reporter.`);if(p.coverage)x.push("--coverage");if(p.watch)x.push("--watch");x.push("--preload",f.join(__dirname,"../../../test-utils/happy-dom.ts"));let e={...n.env,STX_TEST_MODE:"true",STX_TEST_UI:p.ui?"true":"false",STX_TEST_VERBOSE:p.verbose?"true":"false"},o="bun";if(p.verbose)console.log(`Running: ${o} ${x.join(" ")}`);let i=performance.now(),s=R(o,x,{stdio:"inherit",shell:!1,env:e});return new Promise((c)=>{s.on("close",(r)=>{let d=((performance.now()-i)/1000).toFixed(2);if(r===0)c(!0);else c(!1)}),n.on("SIGINT",()=>{console.log(`
4
4
  Test run interrupted`),s.kill("SIGINT"),n.exit(1)})})}catch(x){return console.error("Error running tests:",x instanceof Error?x.message:String(x)),!1}}var J=n.argv.length>=3&&(H(n.argv[2])&&S.existsSync(n.argv[2])||O(n.argv[2]));if(J){let h=n.argv[2],p={port:3000,watch:!0,cache:!0,markdown:{syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0}}};for(let x=3;x<n.argv.length;x++){let t=n.argv[x];if(t==="--port"&&x+1<n.argv.length){let e=B(n.argv[++x]);if(!e.isValid)F(e);p.port=Number.parseInt(n.argv[x],10)}else if(t==="--no-watch")p.watch=!1;else if(t==="--highlight-theme"&&x+1<n.argv.length){if(!p.markdown)p.markdown={};if(!p.markdown.syntaxHighlighting)p.markdown.syntaxHighlighting={};p.markdown.syntaxHighlighting.defaultTheme=n.argv[++x]}else if(t==="--no-highlight"){if(!p.markdown)p.markdown={};if(!p.markdown.syntaxHighlighting)p.markdown.syntaxHighlighting={};p.markdown.syntaxHighlighting.enabled=!1}else if(t==="--no-highlight-unknown"){if(!p.markdown)p.markdown={};if(!p.markdown.syntaxHighlighting)p.markdown.syntaxHighlighting={};p.markdown.syntaxHighlighting.highlightUnknownLanguages=!1}else if(t==="--no-cache")p.cache=!1;else if(t==="--native")p.native=!0}if(O(h))try{let x=await Array.fromAsync(new Bun.Glob(h).scan({onlyFiles:!0,absolute:!0})),t=h.endsWith(".stx")?x.filter((s)=>s.endsWith(".stx")):h.endsWith(".md")?x.filter((s)=>s.endsWith(".md")):x.filter((s)=>s.endsWith(".stx")||s.endsWith(".md")),e=h.split("*")[0].replace(/\/$/,"")||".",o=f.resolve(e);try{let s=new Bun.Glob("**/*.stx"),r=(await Array.fromAsync(s.scan({cwd:o,onlyFiles:!0,absolute:!0}))).filter((l)=>/\[.+\]/.test(f.basename(l)));for(let l of r)if(!t.includes(l))t.push(l)}catch{}if(t.length===0)console.error(`Error: No STX or Markdown files found matching pattern: ${h}`),n.exit(1);if(!await wn(t,p))n.exit(1)}catch(x){console.error("Failed to process files:",x),n.exit(1)}else bn(h,p).catch((x)=>{console.error("Failed to start dev server:",x),n.exit(1)})}else{let h=function(t,e){let o=[];for(let i=0;i<=e.length;i++)o[i]=[i];for(let i=0;i<=t.length;i++)o[0][i]=i;for(let i=1;i<=e.length;i++)for(let s=1;s<=t.length;s++)if(e.charAt(i-1)===t.charAt(s-1))o[i][s]=o[i-1][s-1];else o[i][s]=Math.min(o[i-1][s-1]+1,o[i][s-1]+1,o[i-1][s]+1);return o[e.length][t.length]};y.command("docs","Generate documentation for components, templates, and directives").option("--output <dir>","Output directory for documentation",{default:"docs"}).option("--format <format>","Documentation format (markdown, html, json)",{default:"markdown"}).option("--components-dir <dir>","Components directory",{default:"components"}).option("--templates-dir <dir>","Templates directory",{default:"."}).option("--no-components","Disable components documentation").option("--no-templates","Disable templates documentation").option("--no-directives","Disable directives documentation").option("--extra-content <content>","Extra content to include in documentation").example("stx docs --output docs --format html").action(async(t)=>{try{if(await Ws(t))console.log("Documentation generated successfully."),n.exit(0);else console.error("Documentation generation failed."),n.exit(1)}catch(e){console.error("Error generating documentation:",e),n.exit(1)}}),y.command("iconify <command>","Generate Iconify icon packages").option("--output <dir>","Output directory for generated packages",{default:"packages"}).option("--icons <icons>","Comma-separated list of specific icons to generate").example("stx iconify list").example("stx iconify generate mdi").example("stx iconify generate lucide --icons home,settings,user").action(async(t,e)=>{try{let{fetchCollections:o,generatePackage:i}=await import("./chunk-t61vdbje.js");if(t==="list"){console.log(`
5
5
  \uD83D\uDCDA Fetching available icon collections...
6
6
  `);let s=await o(),c=Object.entries(s).sort((r,l)=>l[1].total-r[1].total);console.log(`Available collections:
7
7
  `);for(let[r,l]of c){let d=l;console.log(` ${r.padEnd(30)} ${d.name} (${d.total} icons)`)}console.log(`
8
8
  Total: ${c.length} collections`)}else if(t.startsWith("generate")){let s=t==="generate"?"":t.replace("generate:","").replace("generate-","").replace("generate","").trim();if(!s)console.error("Error: Please specify a collection prefix"),console.error("Usage: stx iconify generate <prefix> [--icons icon1,icon2,...]"),n.exit(1);let c=e.output||f.join(n.cwd(),"packages/collections"),r=e.icons?e.icons.split(",").map((l)=>l.trim()):void 0;await i(s,c,r),console.log(`
9
9
  \u2713 Package generated successfully!`),console.log(`
10
- To use the package:`),console.log(` 1. cd packages/collections/iconify-${s}`),console.log(" 2. bun install"),console.log(" 3. bun run build")}else console.error(`Unknown iconify command: ${t}`),console.error("Available commands: list, generate"),n.exit(1)}catch(o){console.error("Error:",o instanceof Error?o.message:String(o)),n.exit(1)}}),y.command("pwa <command>","PWA tools - audit configuration and build output").option("--output <dir>","Build output directory to audit",{default:"dist"}).example("stx pwa audit").example("stx pwa audit --output build").action(async(t,e)=>{try{if(t==="audit"){let{runPwaAudit:o,formatAuditResult:i}=await import("./chunk-a32kqsff.js"),{loadConfig:s}=await import("./chunk-0snysm7z.js");console.log(`
10
+ To use the package:`),console.log(` 1. cd packages/collections/iconify-${s}`),console.log(" 2. bun install"),console.log(" 3. bun run build")}else console.error(`Unknown iconify command: ${t}`),console.error("Available commands: list, generate"),n.exit(1)}catch(o){console.error("Error:",o instanceof Error?o.message:String(o)),n.exit(1)}}),y.command("pwa <command>","PWA tools - audit configuration and build output").option("--output <dir>","Build output directory to audit",{default:"dist"}).example("stx pwa audit").example("stx pwa audit --output build").action(async(t,e)=>{try{if(t==="audit"){let{runPwaAudit:o,formatAuditResult:i}=await import("./chunk-a32kqsff.js"),{loadConfig:s}=await import("./chunk-1fccwkkq.js");console.log(`
11
11
  \uD83D\uDD0D Running PWA audit...
12
12
  `);let c=await s(),r=e.output||"dist",l=o(c,r);if(console.log(i(l)),l.failed>0)n.exit(1)}else console.error(`Unknown pwa command: ${t}`),console.error("Available commands: audit"),n.exit(1)}catch(o){console.error("Error:",o instanceof Error?o.message:String(o)),n.exit(1)}}),y.command("dev [file]","Start a development server for an STX app or file").option("--port <port>","Port to use for the dev server",{default:3000}).option("--pages <dir>",'Directory containing page templates (default: pagesDir from stx.config.ts, else "pages")').option("--no-watch","Disable file watching and auto-reload").option("--native","Open in a native desktop window using Zyte").option("--titlebar-hidden","Hide the native titlebar but keep the traffic-light buttons (web content draws under a transparent full-size titlebar). Implies --native.").option("--highlight-theme <theme>","Syntax highlighting theme for Markdown code blocks",{default:"github-dark"}).option("--no-highlight","Disable syntax highlighting for Markdown code blocks").option("--no-highlight-unknown","Disable syntax highlighting for unknown languages in Markdown").option("--no-cache","Disable caching of parsed files").option("--no-hmr","Disable HMR / live-reload script injection (useful for clean network traces)").option("--profile","Print per-directive timing for every page render via performanceMonitor").option("--debug-directives","Log directive ordering and intermediate template state during rendering").example("stx dev").example("stx dev --port 8080").example("stx dev --pages src/pages").example("stx dev template.stx").example("stx dev components/hero.stx --port 8080").example("stx dev **/*.stx").example("stx dev docs/guide.md").example("stx dev template.stx --native").action(async(t,e)=>{try{if(e.port!==void 0){let i=B(e.port);if(!i.isValid)F(i);e.port=Number.parseInt(String(e.port),10)}if(e.timeout!==void 0){let i=z(e.timeout);if(!i.isValid)F(i)}let o={syntaxHighlighting:{enabled:e.highlight!==!1,serverSide:!0,defaultTheme:e.highlightTheme||"github-dark",highlightUnknownLanguages:e.highlightUnknown!==!1}};if(!t){if(!await vn(".",{port:e.port,watch:e.watch!==!1,native:e.native||e.titlebarHidden||!1,titlebarHidden:e.titlebarHidden===!0,cache:e.cache!==!1,hotReload:e.hmr!==!1,profile:e.profile===!0,debugDirectives:e.debugDirectives===!0,...e.pages&&{pagesDir:e.pages}}))n.exit(1);return}if(!O(t))try{let i=await import("fs");if(i.existsSync(t)&&i.statSync(t).isDirectory()){if(!await vn(t,{port:e.port,watch:e.watch!==!1,native:e.native||e.titlebarHidden||!1,titlebarHidden:e.titlebarHidden===!0,cache:e.cache!==!1,hotReload:e.hmr!==!1,profile:e.profile===!0,debugDirectives:e.debugDirectives===!0,...e.pages&&{pagesDir:e.pages}}))n.exit(1);return}}catch{}if(O(t)){console.log(`Expanding glob pattern: ${t}`);let i=await U.timeAsync("glob-expansion",async()=>Array.fromAsync(new Bun.Glob(t).scan({onlyFiles:!0,absolute:!0}))),s=t.endsWith(".stx")?i.filter((d)=>d.endsWith(".stx")):t.endsWith(".md")?i.filter((d)=>d.endsWith(".md")):i.filter((d)=>d.endsWith(".stx")||d.endsWith(".md"));if(s.length===0)console.error(`No STX or Markdown files found matching pattern: ${t}`),console.error("Try using patterns like '*.stx' or 'components/**/*.stx'"),n.exit(1);let c=t.split("*")[0].replace(/\/$/,"")||".",r=f.resolve(c);try{let d=new Bun.Glob("**/*.stx"),m=(await Array.fromAsync(d.scan({cwd:r,onlyFiles:!0,absolute:!0}))).filter((g)=>/\[.+\]/.test(f.basename(g)));for(let g of m)if(!s.includes(g))s.push(g)}catch{}if(console.log(`Found ${s.length} ${s.length===1?"file":"files"} matching ${t}`),!await wn(s,{port:e.port,watch:e.watch!==!1,native:e.native||e.titlebarHidden||!1,titlebarHidden:e.titlebarHidden===!0,markdown:o,cache:e.cache!==!1}))n.exit(1)}else{if(!O(t)){let s=A(t);if(!s.isValid)F(s)}if(!await bn(t,{port:e.port,watch:e.watch!==!1,native:e.native||e.titlebarHidden||!1,titlebarHidden:e.titlebarHidden===!0,markdown:o,cache:e.cache!==!1}))n.exit(1)}}catch(o){console.error("Error starting dev server:",o),n.exit(1)}}),y.command("a11y [target]","Scan .stx files for accessibility issues (directory, file, or glob)").option("--no-recursive","Disable recursive scanning of directories").option("--ignore <paths>","Comma-separated paths to ignore",{default:""}).option("--json","Output results as JSON").option("--output <file>","Write results to a file instead of stdout").option("--fix","Automatically fix common accessibility issues").example("stx a11y ./templates").example('stx a11y "resources/**/*.stx"').example("stx a11y resources/emails/welcome.stx").example("stx a11y --json --output a11y-report.json").action(async(t=".",e)=>{try{console.log(`Scanning ${t} for accessibility issues...`);let o=e.ignore?e.ignore.split(",").map((l)=>l.trim()):[],{results:i,scannedFiles:s}=await pi(t,{recursive:e.recursive!==!1,ignorePaths:o});if(s.length===0)console.log(`
13
13
  No .stx files matched ${t}
@@ -69,7 +69,7 @@ Total: ${r} issues in ${c} files`),e.output){let l=`
69
69
  File not found: ${t}`),n.exit(1);if(!t.endsWith(".stx"))console.error(`
70
70
  File must have .stx extension: ${t}`),n.exit(1)}let i=f.resolve(e.pages),s=f.resolve(e.out);if(!t&&!S.existsSync(i))console.error(`
71
71
  Pages directory not found: ${i}`),console.log(`
72
- Create a 'pages' directory with .stx files, or use --pages to specify a different directory.`),n.exit(1);let{buildApp:c}=await import("./chunk-g7ksavh1.js");mt();let r=await c({root:t?f.dirname(t):void 0,debug:e.verbose,ssg:{pagesDir:e.pages,outputDir:e.out,domain:e.domain,baseUrl:e.base,sitemap:e.sitemap,rss:e.rss,minify:e.minify,cache:e.cache!==!1,cleanOutput:e.clean,concurrency:Number.parseInt(e.concurrency,10)||10,publicDir:e.public,trailingSlash:e.trailingSlash,generate404:!0,hooks:e.verbose?{onPageStart:(d)=>console.log(` Generating: ${d}`),onPageEnd:(d,a)=>console.log(` Generated: ${d} (${a.length} bytes)`),onError:(d,a)=>console.error(` Error in ${a}: ${d.message}`)}:void 0},ssr:{outputDir:e.out==="dist"?".output":e.out,debug:e.verbose}}),l=((performance.now()-o)/1000).toFixed(2);if(r.mode==="ssr"&&r.ssr)console.log(`
72
+ Create a 'pages' directory with .stx files, or use --pages to specify a different directory.`),n.exit(1);let{buildApp:c}=await import("./chunk-e38fyh0y.js");mt();let r=await c({root:t?f.dirname(t):void 0,debug:e.verbose,ssg:{pagesDir:e.pages,outputDir:e.out,domain:e.domain,baseUrl:e.base,sitemap:e.sitemap,rss:e.rss,minify:e.minify,cache:e.cache!==!1,cleanOutput:e.clean,concurrency:Number.parseInt(e.concurrency,10)||10,publicDir:e.public,trailingSlash:e.trailingSlash,generate404:!0,hooks:e.verbose?{onPageStart:(d)=>console.log(` Generating: ${d}`),onPageEnd:(d,a)=>console.log(` Generated: ${d} (${a.length} bytes)`),onError:(d,a)=>console.error(` Error in ${a}: ${d.message}`)}:void 0},ssr:{outputDir:e.out==="dist"?".output":e.out,debug:e.verbose}}),l=((performance.now()-o)/1000).toFixed(2);if(r.mode==="ssr"&&r.ssr)console.log(`
73
73
  Build complete! (SSR)
74
74
  `),console.log(` Pages compiled: ${r.ssr.pageCount}`),console.log(` Output: ${r.ssr.outputDir}`),console.log(` Duration: ${l}s
75
75
  `);else if(r.ssg){if(console.log(`
@@ -84,8 +84,8 @@ Total: ${r} issues in ${c} files`),e.output){let l=`
84
84
  Build completed with ${r.ssg.failedCount} error(s). Fix the issues above and try again.
85
85
  `),n.exit(1);console.log(" To preview locally:"),console.log(` cd ${e.out||"dist"} && npx serve
86
86
  `)}}catch(o){console.error(`
87
- Build failed:`,o instanceof Error?o.message:String(o)),n.exit(1)}}),y.command("start","Start the production server (serves pre-built .output/)").option("--port <number>","Server port",{default:"3000"}).option("--output <dir>","Output directory from stx build",{default:".output"}).example("stx start").example("stx start --port 8080").action(async(t)=>{try{let e=f.resolve(t.output);if(!S.existsSync(f.join(e,"manifest.json")))console.error("\n No production build found. Run `stx build --out .output` first.\n"),n.exit(1);let{startProductionServer:o}=await import("./chunk-cq7se10f.js");await o({outputDir:e,port:Number.parseInt(t.port,10)||3000})}catch(e){console.error(`
88
- Failed to start production server:`,e instanceof Error?e.message:String(e)),n.exit(1)}}),y.command("deploy [directory]","Deploy built site to Netlify").option("--site-id <id>","Netlify site ID (or set NETLIFY_SITE_ID env var)").option("--token <token>","Auth token (or set NETLIFY_AUTH_TOKEN env var)").option("--production","Deploy to production (default: draft preview)").option("--message <msg>","Deploy message/title").option("--no-build","Skip build step before deploy").option("--open","Open deployed URL in browser").option("--dry-run","Preview deployment without uploading").option("--init","Initialize Netlify configuration for this project").example("stx deploy").example("stx deploy --production").example("stx deploy dist --site-id my-site-abc123").example("stx deploy --init").example("stx deploy --dry-run").action(async(t,e)=>{try{let{deploy:o,initNetlify:i,DeployError:s}=await import("./chunk-1vgmzmsw.js");if(console.log(`\x1B[1mstx deploy\x1B[0m \x1B[2mv${j}\x1B[0m`),e.init){console.log(`
87
+ Build failed:`,o instanceof Error?o.message:String(o)),n.exit(1)}}),y.command("start","Start the production server (serves pre-built .output/)").option("--port <number>","Server port",{default:"3000"}).option("--output <dir>","Output directory from stx build",{default:".output"}).example("stx start").example("stx start --port 8080").action(async(t)=>{try{let e=f.resolve(t.output);if(!S.existsSync(f.join(e,"manifest.json")))console.error("\n No production build found. Run `stx build --out .output` first.\n"),n.exit(1);let{startProductionServer:o}=await import("./chunk-darbqs38.js");await o({outputDir:e,port:Number.parseInt(t.port,10)||3000})}catch(e){console.error(`
88
+ Failed to start production server:`,e instanceof Error?e.message:String(e)),n.exit(1)}}),y.command("deploy [directory]","Deploy built site to Netlify").option("--site-id <id>","Netlify site ID (or set NETLIFY_SITE_ID env var)").option("--token <token>","Auth token (or set NETLIFY_AUTH_TOKEN env var)").option("--production","Deploy to production (default: draft preview)").option("--message <msg>","Deploy message/title").option("--no-build","Skip build step before deploy").option("--open","Open deployed URL in browser").option("--dry-run","Preview deployment without uploading").option("--init","Initialize Netlify configuration for this project").example("stx deploy").example("stx deploy --production").example("stx deploy dist --site-id my-site-abc123").example("stx deploy --init").example("stx deploy --dry-run").action(async(t,e)=>{try{let{deploy:o,initNetlify:i,DeployError:s}=await import("./chunk-qr68w6qf.js");if(console.log(`\x1B[1mstx deploy\x1B[0m \x1B[2mv${j}\x1B[0m`),e.init){console.log(`
89
89
  \uD83D\uDCDD Initializing Netlify configuration...
90
90
  `);let r=await i({directory:t||n.cwd(),siteId:e.siteId});if(console.log(`\u2713 Created ${r.configPath}`),r.siteId)console.log("\u2713 Saved site ID to .env.local");console.log(`
91
91
  You can now deploy with: stx deploy`);return}if(e.build!==!1){if(console.log(`
@@ -124,7 +124,7 @@ To view it in the development server:`),console.log(` stx dev ${t}
124
124
  \uD83D\uDCDD ${f.relative(n.cwd(),a)}:`),console.log("--- Original"),console.log("+++ Formatted"),console.log(`@@ Changes in ${f.basename(a)} @@`),console.log("+ Formatted content would be applied");else await Bun.write(a,b),console.log(`\u2705 Formatted ${f.relative(n.cwd(),a)}`),l++}catch(m){console.error(`\u274C Error formatting ${f.relative(n.cwd(),a)}:`,m),d++}if(e.check&&d>0)console.log(`
125
125
  ${d} files need formatting. Run 'stx format' to fix.`),n.exit(1);else if(!e.check&&!e.diff)console.log(`\u2728 Formatted ${l} files successfully`)}catch(o){console.error("Error formatting files:",o),n.exit(1)}}),y.command("perf [command...]","Show performance statistics for STX operations").option("--clear","Clear performance statistics").option("--json","Output as JSON").example("stx perf").example("stx perf --clear").example("stx perf --json").action(async(t,e)=>{try{if(e.clear){U.clear(),console.log("\u2705 Performance statistics cleared");return}let o=U.getStats();if(Object.keys(o).length===0){if(e.json){console.log(JSON.stringify({},null,2));return}console.log("No performance data available. Run some STX commands first.");return}if(e.json)console.log(JSON.stringify(o,null,2));else{console.log(`
126
126
  \uD83D\uDCCA STX Performance Statistics
127
- `);for(let[i,s]of Object.entries(o))console.log(`\uD83D\uDD27 ${i}:`),console.log(` Count: ${s.count}`),console.log(` Average: ${s.avgTime.toFixed(2)}ms`),console.log(` Total: ${s.totalTime.toFixed(2)}ms`),console.log(` Min: ${s.minTime.toFixed(2)}ms`),console.log(` Max: ${s.maxTime.toFixed(2)}ms`),console.log("")}}catch(o){console.error("Error showing performance stats:",o),n.exit(1)}}),y.command("typecheck [patterns...]","Type-check the TypeScript inside .stx script blocks").option("--no-client","Skip <script client> and bare <script> blocks").option("--no-server","Skip <script server> blocks").option("--no-templates","Skip {{ }} and directive expressions in the markup").option("--lib <path>","Extra ambient declaration file (repeatable)").example("stx typecheck").example('stx typecheck "resources/views/**/*.stx"').action(async(t,e)=>{let{formatTypecheckDiagnostics:o,typecheckStxFiles:i}=await import("./chunk-t68s37hg.js"),{resolveStxTargets:s}=await import("./chunk-68txmj8d.js"),c=Array.isArray(t)?t:t?[t]:[],r=c.length?c:["**/*.stx"],l=await s(r);if(l.length===0){console.log(`
127
+ `);for(let[i,s]of Object.entries(o))console.log(`\uD83D\uDD27 ${i}:`),console.log(` Count: ${s.count}`),console.log(` Average: ${s.avgTime.toFixed(2)}ms`),console.log(` Total: ${s.totalTime.toFixed(2)}ms`),console.log(` Min: ${s.minTime.toFixed(2)}ms`),console.log(` Max: ${s.maxTime.toFixed(2)}ms`),console.log("")}}catch(o){console.error("Error showing performance stats:",o),n.exit(1)}}),y.command("typecheck [patterns...]","Type-check the TypeScript inside .stx script blocks").option("--no-client","Skip <script client> and bare <script> blocks").option("--no-server","Skip <script server> blocks").option("--no-templates","Skip {{ }} and directive expressions in the markup").option("--lib <path>","Extra ambient declaration file (repeatable)").example("stx typecheck").example('stx typecheck "resources/views/**/*.stx"').action(async(t,e)=>{let{formatTypecheckDiagnostics:o,typecheckStxFiles:i}=await import("./chunk-995ytskb.js"),{resolveStxTargets:s}=await import("./chunk-68txmj8d.js"),c=Array.isArray(t)?t:t?[t]:[],r=c.length?c:["**/*.stx"],l=await s(r);if(l.length===0){console.log(`
128
128
  No .stx files matched ${r.join(", ")}
129
129
  `);return}let d=Hs(n.argv,"--lib"),a=d.length>0?d:e.lib?Array.isArray(e.lib)?e.lib:[e.lib]:[],m=await i(l,{client:e.client!==!1,server:e.server!==!1,templates:e.templates!==!1,extraLibs:a});if(m.failure)console.error(`
130
130
  Type-check did not run.
@@ -136,7 +136,7 @@ ${d} files need formatting. Run 'stx format' to fix.`),n.exit(1);else if(!e.chec
136
136
  ${o(m.diagnostics)}
137
137
  `);if(console.log(` Checked ${m.blockCount} script block(s) and ${m.expressionCount} template expression(s) in ${m.checkedFiles.length} file(s) \u2014 `+`${g.length} error(s), ${m.diagnostics.length-g.length} warning(s)
138
138
  `),g.length>0)n.exit(1)}),y.command("codemod [patterns...]","Find hand-rolled code that an stx primitive already covers").option("--fix","Write the safe rewrites (default is report-only)").option("--rule <rule>","Run one rule only: confirm | tooltip (rewritable) \xB7 alert | route-params | search-params | navigate | "+"fetch | polling | debounce | click-outside | focus | clipboard | watch (report-only)").example("stx codemod").example("stx codemod --rule route-params").example('stx codemod --fix "resources/views/**/*.stx"').action(async(t,e)=>{let{codemodSource:o,formatCodemodFindings:i}=await import("./chunk-pw34r8r5.js"),s=globalThis.Bun.Glob,c=Array.isArray(t)?t:t?[t]:[],r=c.length?c:["**/*.stx","**/*.ts"],l=e.rule?[e.rule]:void 0;if(e.rule&&e.rule!=="confirm"&&e.rule!=="tooltip")console.error(`Unknown rule "${e.rule}". Expected: confirm | tooltip`),n.exit(1);let d=new Set,a=[],m=0,g=new Set;try{let b=Bun.spawnSync(["git","ls-files","--others","--ignored","--exclude-standard","-z"],{cwd:n.cwd(),stdout:"pipe",stderr:"pipe"});for(let w of new TextDecoder().decode(b.stdout).split("\x00"))if(w)g.add(f.resolve(n.cwd(),w))}catch{}for(let b of r)for await(let w of new s(b).scan({cwd:n.cwd(),absolute:!0})){if(w.includes("/node_modules/")||w.includes("/dist/")||d.has(w)||g.has(w))continue;d.add(w);let k=await Bun.file(w).text(),v=o(k,{file:w,rules:l});if(a.push(...v.findings),e.fix&&v.code!==k)await Bun.write(w,v.code),m++}if(console.error(i(a,Boolean(e.fix))),e.fix)console.error(`
139
- ${m} file(s) written.`)}),y.command("doctor","Diagnose the stx framework-runtime resolution + staleness chain").option("--json","Output the report as JSON").example("stx doctor").example("stx doctor --json").action(async(t)=>{try{let e;try{let i=await import("./chunk-fb1711er.js");e=i.generateSignalsRuntime}catch{e=void 0}let o=await gr({generateRuntime:e});if(t.json)console.log(JSON.stringify(o,null,2));else console.log(mr(o));if(!o.ok)n.exit(1)}catch(e){console.error("Error running doctor:",e),n.exit(1)}}),y.command("debug <file>","Debug STX template processing step by step").option("--step","Step through processing stages interactively").option("--verbose","Show detailed processing information").option("--context <data>","JSON string of context data to use").option("--save-report <file>","Save debug report to file").example("stx debug template.stx").example("stx debug template.stx --step").example(`stx debug template.stx --context '{"name": "John", "items": [1,2,3]}'`).action(async(t,e)=>{try{let o=A(t);if(!o.isValid)F(o);console.log(`\uD83D\uDD0D Debugging stx template: ${t}
139
+ ${m} file(s) written.`)}),y.command("doctor","Diagnose the stx framework-runtime resolution + staleness chain").option("--json","Output the report as JSON").example("stx doctor").example("stx doctor --json").action(async(t)=>{try{let e;try{let i=await import("./chunk-jy58t59b.js");e=i.generateSignalsRuntime}catch{e=void 0}let o=await gr({generateRuntime:e});if(t.json)console.log(JSON.stringify(o,null,2));else console.log(mr(o));if(!o.ok)n.exit(1)}catch(e){console.error("Error running doctor:",e),n.exit(1)}}),y.command("debug <file>","Debug STX template processing step by step").option("--step","Step through processing stages interactively").option("--verbose","Show detailed processing information").option("--context <data>","JSON string of context data to use").option("--save-report <file>","Save debug report to file").example("stx debug template.stx").example("stx debug template.stx --step").example(`stx debug template.stx --context '{"name": "John", "items": [1,2,3]}'`).action(async(t,e)=>{try{let o=A(t);if(!o.isValid)F(o);console.log(`\uD83D\uDD0D Debugging stx template: ${t}
140
140
  `);let i={};if(e.context)try{i=JSON.parse(e.context)}catch(r){console.error("\u274C Invalid JSON in --context option"),n.exit(1)}let s=await Bun.file(t).text();console.log(`\uD83D\uDCC4 Template Content (${s.length} chars):`),console.log("\u2500".repeat(50)),console.log(s.substring(0,500)+(s.length>500?`
141
141
  ...
142
142
  `:"")),console.log("\u2500".repeat(50));let c=s.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(c)console.log(`
@@ -160,11 +160,11 @@ Press Ctrl+C to stop watching...
160
160
  \uD83D\uDCC4 Files with issues:`),d.forEach((a)=>{let m=a.issues.filter((g)=>s[g.type]>=c).length;if(m>0)console.log(` ${f.relative(n.cwd(),a.file)} (${m} issues)`)});if(e.saveReport){let a={summary:l,results:d,generatedAt:new Date().toISOString(),commandOptions:e};await Bun.write(e.saveReport,JSON.stringify(a,null,2)),console.log(`
161
161
  \uD83D\uDCCB Analysis report saved to: ${e.saveReport}`)}console.log(`
162
162
  \u2728 Analysis complete! Use --detailed for more information.`)}catch(o){console.error("Error analyzing templates:",o),n.exit(1)}}),y.command("screenshot [input]","Capture PNG screenshot(s) of page(s) via Bun WebView \u2014 a file, URL, or dist directory").option("--out <dir>","Output directory",{default:"screenshots"}).option("--width <px>","Viewport width",{default:"1440"}).option("--height <px>","Viewport height",{default:"2200"}).option("--wait <ms>","Settle time after navigation before capture",{default:"800"}).option("--timeout <ms>","Hard cap on waiting for navigation",{default:"15000"}).option("--full-page","Capture the entire scrollable page, not just the viewport").option("--wait-selector <sel>","Wait until a CSS selector exists before capturing").option("--format <fmt>","Image format: png | jpeg | webp",{default:"png"}).option("--backend <name>","WebView backend: webkit (macOS, default) | chrome").action(async(t,e)=>{let{captureScreenshots:o}=await import("./chunk-561yczfn.js"),i=t||"dist";try{let s=await o(i,e.out,{width:Number.parseInt(e.width,10),height:Number.parseInt(e.height,10),waitMs:Number.parseInt(e.wait,10),timeoutMs:Number.parseInt(e.timeout,10),fullPage:Boolean(e.fullPage),waitSelector:e.waitSelector,format:e.format,backend:e.backend});for(let c of s)console.log(`\uD83D\uDCF8 ${c.output} (${(c.bytes/1024).toFixed(0)} KB)`);console.log(`
163
- \u2728 Captured ${s.length} screenshot(s) to ${e.out}/ via Bun WebView`)}catch(s){console.error(`Screenshot failed: ${s.message}`),n.exit(1)}}),y.command("version","Show the version of the CLI").action(()=>{console.log(j)}),y.command("interactive","Start interactive REPL mode for template development").alias("i").option("--context <file>","Load initial context from JSON file").option("--cwd <directory>","Set working directory").option("--verbose","Show verbose output").action(async(t)=>{let{startInteractive:e}=await import("./chunk-rpsjz8jd.js"),o={};if(t.context){let i=f.resolve(t.context);if(S.existsSync(i))try{let s=S.readFileSync(i,"utf-8");o=JSON.parse(s)}catch(s){console.error("Error loading context file:",s),n.exit(1)}else console.error(`Context file not found: ${i}`),n.exit(1)}await e({context:o,cwd:t.cwd?f.resolve(t.cwd):n.cwd(),verbose:t.verbose})}),y.command("build:native <input>","Build stx template into a native desktop/mobile app").option("--output <dir>","Output directory",{default:"dist/native"}).option("--target <platform>","Target platform: macos, windows, linux, ios, android").option("--format <format>","Output format: app, dmg, pkg, msi, zip, deb, rpm, appimage, ipa, apk").option("--name <name>","Application name (defaults to filename)").option("--version <version>","Application version",{default:"1.0.0"}).option("--description <desc>","Application description").option("--author <author>","Author/Maintainer name").option("--bundle-id <id>","Bundle identifier (macOS/iOS)").option("--icon <path>","Path to application icon").option("--width <width>","Window width",{default:"1200"}).option("--height <height>","Window height",{default:"800"}).option("--title <title>","Window title").option("--system-tray","Enable system tray/menubar mode").option("--menubar-only","Run without a dock icon (implied by --system-tray)").option("--category <type>","LSApplicationCategoryType (macOS)").option("--copyright <text>","NSHumanReadableCopyright (macOS)").option("--min-system-version <v>","LSMinimumSystemVersion (macOS)").option("--info-plist <json>","Extra Info.plist keys as a JSON object (macOS)").option("--dev-tools","Enable developer tools").option("--frameless","Create frameless window").option("--always-on-top","Keep window always on top").option("--craft-path <path>","Path to Craft binary").option("--verbose","Show verbose output").example("stx build:native app.stx --target macos").example("stx build:native app.stx --target macos --format dmg").example("stx build:native app.stx --target linux --format appimage").example('stx build:native app.stx --name "My App" --icon icon.png').action(async(t,e)=>{try{let{buildNative:o,getAvailableTargets:i,getAvailableFormats:s}=await import("./chunk-8p2vfjg2.js"),c=f.resolve(t);if(!S.existsSync(c))console.error(`\u274C Input file not found: ${t}`),n.exit(1);let r=i();if(e.target&&!["macos","windows","linux","ios","android"].includes(e.target))console.error(`\u274C Invalid target: ${e.target}`),console.error("\uD83D\uDCA1 Available targets: macos, windows, linux, ios, android"),console.error(`\uD83D\uDCA1 Targets available on this machine: ${r.join(", ")}`),n.exit(1);let l=e.target||r[0],d=s(l);if(e.format&&!d.includes(e.format))console.error(`\u274C Invalid format for ${l}: ${e.format}`),console.error(`\uD83D\uDCA1 Available formats: ${d.join(", ")}`),n.exit(1);console.log(`
163
+ \u2728 Captured ${s.length} screenshot(s) to ${e.out}/ via Bun WebView`)}catch(s){console.error(`Screenshot failed: ${s.message}`),n.exit(1)}}),y.command("version","Show the version of the CLI").action(()=>{console.log(j)}),y.command("interactive","Start interactive REPL mode for template development").alias("i").option("--context <file>","Load initial context from JSON file").option("--cwd <directory>","Set working directory").option("--verbose","Show verbose output").action(async(t)=>{let{startInteractive:e}=await import("./chunk-jbdvkj3q.js"),o={};if(t.context){let i=f.resolve(t.context);if(S.existsSync(i))try{let s=S.readFileSync(i,"utf-8");o=JSON.parse(s)}catch(s){console.error("Error loading context file:",s),n.exit(1)}else console.error(`Context file not found: ${i}`),n.exit(1)}await e({context:o,cwd:t.cwd?f.resolve(t.cwd):n.cwd(),verbose:t.verbose})}),y.command("build:native <input>","Build stx template into a native desktop/mobile app").option("--output <dir>","Output directory",{default:"dist/native"}).option("--target <platform>","Target platform: macos, windows, linux, ios, android").option("--format <format>","Output format: app, dmg, pkg, msi, zip, deb, rpm, appimage, ipa, apk").option("--name <name>","Application name (defaults to filename)").option("--version <version>","Application version",{default:"1.0.0"}).option("--description <desc>","Application description").option("--author <author>","Author/Maintainer name").option("--bundle-id <id>","Bundle identifier (macOS/iOS)").option("--icon <path>","Path to application icon").option("--width <width>","Window width",{default:"1200"}).option("--height <height>","Window height",{default:"800"}).option("--title <title>","Window title").option("--system-tray","Enable system tray/menubar mode").option("--menubar-only","Run without a dock icon (implied by --system-tray)").option("--category <type>","LSApplicationCategoryType (macOS)").option("--copyright <text>","NSHumanReadableCopyright (macOS)").option("--min-system-version <v>","LSMinimumSystemVersion (macOS)").option("--info-plist <json>","Extra Info.plist keys as a JSON object (macOS)").option("--dev-tools","Enable developer tools").option("--frameless","Create frameless window").option("--always-on-top","Keep window always on top").option("--craft-path <path>","Path to Craft binary").option("--verbose","Show verbose output").example("stx build:native app.stx --target macos").example("stx build:native app.stx --target macos --format dmg").example("stx build:native app.stx --target linux --format appimage").example('stx build:native app.stx --name "My App" --icon icon.png').action(async(t,e)=>{try{let{buildNative:o,getAvailableTargets:i,getAvailableFormats:s}=await import("./chunk-c0wcvbhr.js"),c=f.resolve(t);if(!S.existsSync(c))console.error(`\u274C Input file not found: ${t}`),n.exit(1);let r=i();if(e.target&&!["macos","windows","linux","ios","android"].includes(e.target))console.error(`\u274C Invalid target: ${e.target}`),console.error("\uD83D\uDCA1 Available targets: macos, windows, linux, ios, android"),console.error(`\uD83D\uDCA1 Targets available on this machine: ${r.join(", ")}`),n.exit(1);let l=e.target||r[0],d=s(l);if(e.format&&!d.includes(e.format))console.error(`\u274C Invalid format for ${l}: ${e.format}`),console.error(`\uD83D\uDCA1 Available formats: ${d.join(", ")}`),n.exit(1);console.log(`
164
164
  \uD83D\uDD28 Building native app...`),console.log(` Input: ${t}`),console.log(` Target: ${l}`),console.log(` Format: ${e.format||"default"}`),console.log(` Output: ${e.output}
165
165
  `);let a=await o({input:c,output:f.resolve(e.output),target:l,format:e.format,name:e.name,version:e.version,description:e.description,author:e.author,bundleId:e.bundleId,icon:e.icon?f.resolve(e.icon):void 0,window:{title:e.title,width:Number.parseInt(e.width,10),height:Number.parseInt(e.height,10),frameless:e.frameless,alwaysOnTop:e.alwaysOnTop},systemTray:e.systemTray,menubarOnly:e.menubarOnly,category:e.category,copyright:e.copyright,minimumSystemVersion:e.minSystemVersion,infoPlist:L(e.infoPlist),devTools:e.devTools,craftPath:e.craftPath,verbose:e.verbose});if(a.success){if(console.log("\u2705 Build successful!"),console.log(` Output: ${a.outputPath}`),a.duration)console.log(` Duration: ${(a.duration/1000).toFixed(2)}s`);if(l==="macos"&&a.format==="app")console.log(`
166
166
  \uD83D\uDCA1 To run: open "${a.outputPath}"`);else if(l==="linux"&&a.format==="appimage")console.log(`
167
- \uD83D\uDCA1 To run: chmod +x "${a.outputPath}" && "${a.outputPath}"`)}else console.error(`\u274C Build failed: ${a.error}`),n.exit(1)}catch(o){console.error(`\u274C Build error: ${o.message}`),n.exit(1)}}),y.command("story","Start component showcase and testing server").option("-p, --port <port>","Server port",{default:"6006"}).option("-o, --open","Open browser automatically",{default:!1}).option("--host <host>","Host to bind to",{default:"localhost"}).example("stx story").example("stx story --port 3000 --open").action(async(t)=>{try{let{devCommand:e}=await import("./chunk-7sbgpmwt.js");await e({port:t.port?Number.parseInt(t.port,10):6006,open:t.open,host:t.host})}catch(e){console.error(`\u274C Story error: ${e.message}`),n.exit(1)}}),y.command("story:build","Build static story site").option("-o, --outDir <dir>","Output directory",{default:".stx/dist/story"}).example("stx story:build").example("stx story:build --outDir ./docs/components").action(async(t)=>{try{let{buildCommand:e}=await import("./chunk-0v5dpk7r.js");await e({outDir:t.outDir})}catch(e){console.error(`\u274C Story build error: ${e.message}`),n.exit(1)}}),y.command("story:test","Run visual regression tests").option("-u, --update","Update snapshots",{default:!1}).option("-f, --filter <name>","Filter components by name").example("stx story:test").example("stx story:test --update").example("stx story:test --filter Button").action(async(t)=>{try{let{createContext:e}=await import("./chunk-j9aberz0.js"),{runVisualTests:o,updateSnapshots:i,formatTestResults:s}=await import("./chunk-kppgyqwb.js"),c=await e({mode:"build"});if(t.update){let r=await i(c,{filter:t.filter?[t.filter]:void 0});console.log(`Updated ${r} snapshots`)}else{let r=await o(c,{filter:t.filter?[t.filter]:void 0});if(console.log(s(r)),r.failed>0)n.exit(1)}}catch(e){console.error(`\u274C Story test error: ${e.message}`),n.exit(1)}}),y.command("native <action> [file]","Compile .stx screens into the JavaScriptCore bundle Craft renders natively").option("--format <format>","bundle (the JavaScriptCore bundle) or ir (the template as JSON)",{default:"ir"}).option("--output <path>","Write to this file instead of stdout").option("--minify","Minify the bundle",{default:!1}).option("--config <file>","Screens config (default: native.config.json in the working directory)").example("stx native compile Screen.stx --format bundle --output native-screen.js").example("stx native compile --format bundle --output native-screen.js --minify").example("stx native compile Screen.stx").action(async(t,e,o)=>{if(t!=="compile")console.error(`Unknown native command: ${t}`),console.error("Usage: stx native compile [file.stx] --format bundle|ir [--output <file>] [--minify] [--config <file>]"),n.exit(1);try{let{runNativeCompile:i}=await import("./chunk-vqdv6ay9.js"),s=await i(e,{format:o.format,output:o.output,minify:Boolean(o.minify),config:o.config});for(let c of s.diagnostics)console.warn(`${c.level}: ${c.message}`);if(s.written)console.log(`Compiled: ${e??"screens"} \u2192 ${f.relative(n.cwd(),s.written)||s.written}`);else console.log(s.output)}catch(i){console.error(i instanceof Error?i.message:String(i)),n.exit(1)}}),y.command("compile <input>","Compile stx template to native Craft component code").option("--target <platform>","Target platform: macos, windows, linux, ios, android, universal",{default:"universal"}).option("--format <format>","Output format: zig, typescript, json",{default:"zig"}).option("--output <path>","Output directory for compiled files",{default:"./dist"}).option("--optimize","Enable optimizations",{default:!0}).option("--tree-shake","Enable tree shaking",{default:!0}).option("--hot-reload","Enable hot reload support",{default:!1}).option("--sourcemaps","Generate source maps",{default:!1}).option("--bundle","Bundle all dependencies",{default:!0}).option("--minify","Minify output",{default:!1}).option("--verbose","Show detailed output",{default:!1}).example("stx compile app.stx").example("stx compile app.stx --target macos --format zig").example("stx compile app.stx --format typescript --output ./native").example("stx compile app.stx --optimize --tree-shake --minify").action(async(t,e)=>{try{let{compileToNative:o}=await import("./chunk-32t5agpk.js"),i=f.resolve(t);if(!S.existsSync(i))console.error(`\u274C Input file not found: ${t}`),n.exit(1);let s=["macos","windows","linux","ios","android","universal"];if(!s.includes(e.target))console.error(`\u274C Invalid target: ${e.target}`),console.error(`\uD83D\uDCA1 Available targets: ${s.join(", ")}`),n.exit(1);let c=["zig","typescript","json"];if(!c.includes(e.format))console.error(`\u274C Invalid format: ${e.format}`),console.error(`\uD83D\uDCA1 Available formats: ${c.join(", ")}`),n.exit(1);console.log(`
167
+ \uD83D\uDCA1 To run: chmod +x "${a.outputPath}" && "${a.outputPath}"`)}else console.error(`\u274C Build failed: ${a.error}`),n.exit(1)}catch(o){console.error(`\u274C Build error: ${o.message}`),n.exit(1)}}),y.command("story","Start component showcase and testing server").option("-p, --port <port>","Server port",{default:"6006"}).option("-o, --open","Open browser automatically",{default:!1}).option("--host <host>","Host to bind to",{default:"localhost"}).example("stx story").example("stx story --port 3000 --open").action(async(t)=>{try{let{devCommand:e}=await import("./chunk-vxhy0a3n.js");await e({port:t.port?Number.parseInt(t.port,10):6006,open:t.open,host:t.host})}catch(e){console.error(`\u274C Story error: ${e.message}`),n.exit(1)}}),y.command("story:build","Build static story site").option("-o, --outDir <dir>","Output directory",{default:".stx/dist/story"}).example("stx story:build").example("stx story:build --outDir ./docs/components").action(async(t)=>{try{let{buildCommand:e}=await import("./chunk-0v5dpk7r.js");await e({outDir:t.outDir})}catch(e){console.error(`\u274C Story build error: ${e.message}`),n.exit(1)}}),y.command("story:test","Run visual regression tests").option("-u, --update","Update snapshots",{default:!1}).option("-f, --filter <name>","Filter components by name").example("stx story:test").example("stx story:test --update").example("stx story:test --filter Button").action(async(t)=>{try{let{createContext:e}=await import("./chunk-j9aberz0.js"),{runVisualTests:o,updateSnapshots:i,formatTestResults:s}=await import("./chunk-9n10mh5q.js"),c=await e({mode:"build"});if(t.update){let r=await i(c,{filter:t.filter?[t.filter]:void 0});console.log(`Updated ${r} snapshots`)}else{let r=await o(c,{filter:t.filter?[t.filter]:void 0});if(console.log(s(r)),r.failed>0)n.exit(1)}}catch(e){console.error(`\u274C Story test error: ${e.message}`),n.exit(1)}}),y.command("native <action> [file]","Compile .stx screens into the JavaScriptCore bundle Craft renders natively").option("--format <format>","bundle (the JavaScriptCore bundle) or ir (the template as JSON)",{default:"ir"}).option("--output <path>","Write to this file instead of stdout").option("--minify","Minify the bundle",{default:!1}).option("--config <file>","Screens config (default: native.config.json in the working directory)").example("stx native compile Screen.stx --format bundle --output native-screen.js").example("stx native compile --format bundle --output native-screen.js --minify").example("stx native compile Screen.stx").action(async(t,e,o)=>{if(t!=="compile")console.error(`Unknown native command: ${t}`),console.error("Usage: stx native compile [file.stx] --format bundle|ir [--output <file>] [--minify] [--config <file>]"),n.exit(1);try{let{runNativeCompile:i}=await import("./chunk-501kq69r.js"),s=await i(e,{format:o.format,output:o.output,minify:Boolean(o.minify),config:o.config});for(let c of s.diagnostics)console.warn(`${c.level}: ${c.message}`);if(s.written)console.log(`Compiled: ${e??"screens"} \u2192 ${f.relative(n.cwd(),s.written)||s.written}`);else console.log(s.output)}catch(i){console.error(i instanceof Error?i.message:String(i)),n.exit(1)}}),y.command("compile <input>","Compile stx template to native Craft component code").option("--target <platform>","Target platform: macos, windows, linux, ios, android, universal",{default:"universal"}).option("--format <format>","Output format: zig, typescript, json",{default:"zig"}).option("--output <path>","Output directory for compiled files",{default:"./dist"}).option("--optimize","Enable optimizations",{default:!0}).option("--tree-shake","Enable tree shaking",{default:!0}).option("--hot-reload","Enable hot reload support",{default:!1}).option("--sourcemaps","Generate source maps",{default:!1}).option("--bundle","Bundle all dependencies",{default:!0}).option("--minify","Minify output",{default:!1}).option("--verbose","Show detailed output",{default:!1}).example("stx compile app.stx").example("stx compile app.stx --target macos --format zig").example("stx compile app.stx --format typescript --output ./native").example("stx compile app.stx --optimize --tree-shake --minify").action(async(t,e)=>{try{let{compileToNative:o}=await import("./chunk-32t5agpk.js"),i=f.resolve(t);if(!S.existsSync(i))console.error(`\u274C Input file not found: ${t}`),n.exit(1);let s=["macos","windows","linux","ios","android","universal"];if(!s.includes(e.target))console.error(`\u274C Invalid target: ${e.target}`),console.error(`\uD83D\uDCA1 Available targets: ${s.join(", ")}`),n.exit(1);let c=["zig","typescript","json"];if(!c.includes(e.format))console.error(`\u274C Invalid format: ${e.format}`),console.error(`\uD83D\uDCA1 Available formats: ${c.join(", ")}`),n.exit(1);console.log(`
168
168
  \uD83D\uDD27 Compiling stx template to native code...`),console.log(` Input: ${t}`),console.log(` Target: ${e.target}`),console.log(` Format: ${e.format}`),console.log(` Output: ${e.output}
169
169
  `);let r=S.readFileSync(i,"utf-8"),l=await o(r,{target:e.target,format:e.format,optimize:e.optimize,treeShake:e.treeShake,hotReload:e.hotReload,debug:e.verbose,sourceMaps:e.sourcemaps,bundle:e.bundle,minify:e.minify}),d=f.resolve(e.output);if(!S.existsSync(d))S.mkdirSync(d,{recursive:!0});let a=f.basename(t,f.extname(t)),m=e.format==="typescript"?"ts":e.format==="json"?"json":"zig",g=f.join(d,`${a}.${m}`);S.writeFileSync(g,l.code);let b=f.join(d,`${a}.manifest.json`);if(S.writeFileSync(b,JSON.stringify(l.manifest,null,2)),e.sourcemaps&&l.sourceMaps){let w=f.join(d,`${a}.${m}.map`);S.writeFileSync(w,l.sourceMaps)}if(e.target==="universal"&&l.platformCode.size>0)for(let[w,k]of l.platformCode){let v=f.join(d,`${a}.${w}.${m}`);S.writeFileSync(v,k)}if(console.log("\u2705 Compilation successful!"),console.log(` Output: ${g}`),console.log(` Manifest: ${b}`),console.log(`
170
170
  \uD83D\uDCCA Statistics:`),console.log(` Compilation time: ${l.stats.compilationTime.toFixed(2)}ms`),console.log(` Total components: ${l.stats.totalComponents}`),console.log(` Native components: ${l.stats.nativeComponents}`),console.log(` Web fallback components: ${l.stats.webComponents}`),console.log(` Bundle size: ${(l.stats.bundleSize/1024).toFixed(2)}KB`),l.stats.warnings.length>0){console.log(`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Br,$o,Eo}from"./chunk-44msrx2e.js";import"./chunk-r6pax860.js";import"./chunk-8xz8t9xp.js";import"./chunk-w6zz18jt.js";import"./chunk-w1zvh5y7.js";import"./chunk-h9e032kq.js";import"./chunk-zskhxkbk.js";import"./chunk-exgyf65a.js";import"./chunk-4fa3jec9.js";import"./chunk-zydg3wgt.js";import"./chunk-y1hx8re2.js";import"./chunk-jz7pvh7b.js";import"./chunk-0trfbqa7.js";import{cu,bo,lu,uu,wo,jr,vo,du,xo,pu,fu,So,ko,Co}from"./chunk-aeb8621d.js";import"./chunk-12w518qc.js";import"./chunk-bq2e9qf6.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
2
+ import{Br,$o,Eo}from"./chunk-44msrx2e.js";import"./chunk-ynvce0q6.js";import"./chunk-8xz8t9xp.js";import"./chunk-5w87wmc4.js";import"./chunk-2jbyks2t.js";import"./chunk-pf0d8y9n.js";import"./chunk-b6e36vr2.js";import"./chunk-8yrk8ybh.js";import"./chunk-ver2yf41.js";import"./chunk-zydg3wgt.js";import"./chunk-n3r5m938.js";import"./chunk-jz7pvh7b.js";import"./chunk-0trfbqa7.js";import{cu,bo,lu,uu,wo,jr,vo,du,xo,pu,fu,So,ko,Co}from"./chunk-q0d0q8r8.js";import"./chunk-bagh6sc1.js";import"./chunk-5bqs0ve6.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
3
3
  `),scripts:t.scripts.join(`
4
4
  `),metadata:{renderTime:0,cacheHit:!0,totalSize:c.html.length,componentCount:t.metadata.componentCount}}}let a;if(n.streaming)a=await H(t.tree,e);else a=h(t.tree,e);let i;if(n.hydrate){let o=j(a,t,e);a=o.html,i=o.data}if(n.minify)a=D(a);if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`;d.set(o,{html:a,timestamp:Date.now()})}let s=performance.now()-r;return{html:a,styles:t.styles.join(`
5
5
  `),scripts:t.scripts.join(`
package/dist/craft.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Br,$o,Eo}from"./chunk-44msrx2e.js";import"./chunk-r6pax860.js";import"./chunk-8xz8t9xp.js";import"./chunk-w6zz18jt.js";import"./chunk-w1zvh5y7.js";import"./chunk-h9e032kq.js";import"./chunk-zskhxkbk.js";import"./chunk-exgyf65a.js";import"./chunk-4fa3jec9.js";import"./chunk-zydg3wgt.js";import"./chunk-y1hx8re2.js";import"./chunk-jz7pvh7b.js";import"./chunk-0trfbqa7.js";import{cu,bo,lu,uu,wo,jr,vo,du,xo,pu,fu,So,ko,Co}from"./chunk-aeb8621d.js";import"./chunk-12w518qc.js";import"./chunk-bq2e9qf6.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
2
+ import{Br,$o,Eo}from"./chunk-44msrx2e.js";import"./chunk-ynvce0q6.js";import"./chunk-8xz8t9xp.js";import"./chunk-5w87wmc4.js";import"./chunk-2jbyks2t.js";import"./chunk-pf0d8y9n.js";import"./chunk-b6e36vr2.js";import"./chunk-8yrk8ybh.js";import"./chunk-ver2yf41.js";import"./chunk-zydg3wgt.js";import"./chunk-n3r5m938.js";import"./chunk-jz7pvh7b.js";import"./chunk-0trfbqa7.js";import{cu,bo,lu,uu,wo,jr,vo,du,xo,pu,fu,So,ko,Co}from"./chunk-q0d0q8r8.js";import"./chunk-bagh6sc1.js";import"./chunk-5bqs0ve6.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
3
3
  `),scripts:t.scripts.join(`
4
4
  `),metadata:{renderTime:0,cacheHit:!0,totalSize:c.html.length,componentCount:t.metadata.componentCount}}}let a;if(n.streaming)a=await H(t.tree,e);else a=h(t.tree,e);let i;if(n.hydrate){let o=j(a,t,e);a=o.html,i=o.data}if(n.minify)a=D(a);if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`;d.set(o,{html:a,timestamp:Date.now()})}let s=performance.now()-r;return{html:a,styles:t.styles.join(`
5
5
  `),scripts:t.scripts.join(`
package/dist/pwa.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
2
  import{Pn,Ie,Oo,Ma}from"./chunk-d3mpxr3s.js";import{An,Fr,Ia,Da,Oa}from"./chunk-tpvc8xnk.js";import{Po,Io,Do,Aa,Pa}from"./chunk-v3yqeh15.js";import{oe,ft,zr}from"./chunk-vg7wfkt5.js";import{Lc,jc,Bc,Fc,ur,sd}from"./chunk-rvgvt161.js";import B from"fs";import w from"path";import O from"fs";import u from"path";var v=[72,96,128,144,152,192,384,512],S=[120,152,167,180],P=[16,32];async function M(n,t){let e={success:!0,generatedFiles:[],errors:[],warnings:[]},r=n.pwa?.icons;if(!r?.src)return e.errors.push("No source icon specified in pwa.icons.src"),e.success=!1,e;let o=u.isAbsolute(r.src)?r.src:u.resolve(process.cwd(),r.src);if(!await Bun.file(o).exists())return e.errors.push(`Source icon not found: ${o}`),e.success=!1,e;let a=u.resolve(t,r.outputDir||"pwa-icons");try{O.mkdirSync(a,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${a}`),e.success=!1,e}let s=r.sizes||v,l=r.generateWebP??!0,p=r.generateAppleIcons??!0;try{let c;try{c=await import("sharp")}catch{return e.errors.push(`sharp is not installed. Install it with: bun add sharp
3
- Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-m00nek1y.js"),o=await Bun.file(e).text();return await r(o,{},e,n,new Set)}catch(r){console.warn(`[PWA] Failed to process custom offline page: ${r}`)}else console.warn(`[PWA] Custom offline page not found: ${e}`)}return E(n)}function E(n){let t=n.pwa?.offline,e=n.pwa?.manifest,r=t?.fallbackTitle||"You are offline",o=t?.fallbackMessage||"Please check your internet connection and try again.",a=e?.themeColor||"#4f46e5",s=e?.shortName||e?.name||"App";return`<!DOCTYPE html>
3
+ Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-yxwam84p.js"),o=await Bun.file(e).text();return await r(o,{},e,n,new Set)}catch(r){console.warn(`[PWA] Failed to process custom offline page: ${r}`)}else console.warn(`[PWA] Custom offline page not found: ${e}`)}return E(n)}function E(n){let t=n.pwa?.offline,e=n.pwa?.manifest,r=t?.fallbackTitle||"You are offline",o=t?.fallbackMessage||"Please check your internet connection and try again.",a=e?.themeColor||"#4f46e5",s=e?.shortName||e?.name||"App";return`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">
package/dist/signals.js CHANGED
@@ -1202,6 +1202,10 @@ finally {
1202
1202
  if (scope) {
1203
1203
  scope.__mountCallbacks = scope.__mountCallbacks || [];
1204
1204
  scope.__mountCallbacks.push(fn);
1205
+ // Kept apart from the queue, which a flush drains: a component behind an
1206
+ // :if mounts again every time it is shown (see suspendSubtreeScopes).
1207
+ scope.__mountHooks = scope.__mountHooks || [];
1208
+ scope.__mountHooks.push(fn);
1205
1209
  return;
1206
1210
  }
1207
1211
  mountCallbacks.push(fn);
@@ -1223,6 +1227,10 @@ finally {
1223
1227
  if (scope) {
1224
1228
  scope.__destroyCallbacks = scope.__destroyCallbacks || [];
1225
1229
  scope.__destroyCallbacks.push(fn);
1230
+ // Registered once, at setup, and owed at every unmount -- including each
1231
+ // time an :if hides the component (see suspendSubtreeScopes).
1232
+ scope.__destroyHooks = scope.__destroyHooks || [];
1233
+ scope.__destroyHooks.push(fn);
1226
1234
  return;
1227
1235
  }
1228
1236
  if (activeDestroySink) {
@@ -4249,7 +4257,20 @@ catch (e2) {
4249
4257
  var resolvedCallerScope = resolveComponentCallerScope(root, callerScope);
4250
4258
  root.__stx_parent_scope = resolvedCallerScope;
4251
4259
  bindParentComponentProps(root, resolvedCallerScope);
4252
- if (!scopeVars || root.__stx_disposers) return;
4260
+ if (!scopeVars) return;
4261
+ if (root.__stx_disposers) {
4262
+ // Bound already, by the page's scope walk: a component behind a false
4263
+ // :if in a PARTIAL is in the list that walk collects, and is detached
4264
+ // by the time it is reached, so it was bound and its mount deferred
4265
+ // (stacksjs/stx#2036). Showing the branch is that mount. Without this
4266
+ // the component rendered and its onMount never ran at all.
4267
+ if (scopeVars.__mountCallbacks && !scopeVars.__mounted && !scopeVars.__suspended && root.isConnected) {
4268
+ scopeVars.__el = root;
4269
+ scopeVars.__mounted = true;
4270
+ runMountCallbacks(scopeVars.__mountCallbacks, scopeDestroySink(scopeVars));
4271
+ }
4272
+ return;
4273
+ }
4253
4274
  scopeVars.__el = root;
4254
4275
  var childScope = { ...resolvedCallerScope, ...scopeVars };
4255
4276
  root.__stx_disposers = trackEffects(function() {
@@ -5156,6 +5177,14 @@ catch (e2) {
5156
5177
  var gone = chain[currentIdx];
5157
5178
  gone.el.__stx_chain_active = false;
5158
5179
  gone.el.__stx_if_visible.set(false);
5180
+ // Unmount what the branch held, as a single :if does, before any of
5181
+ // it leaves the page.
5182
+ var leavingNodes = gone.nodes.filter(function (n) { return n.parentNode; });
5183
+ if (gone.isTemplate && gone.endMarker && gone.endMarker.parentNode) {
5184
+ leavingNodes = [];
5185
+ for (var walk = gone.placeholder.nextSibling; walk && walk !== gone.endMarker; walk = walk.nextSibling) leavingNodes.push(walk);
5186
+ }
5187
+ suspendSubtreeScopes(leavingNodes);
5159
5188
 
5160
5189
  if (gone.isTemplate) {
5161
5190
  // Everything this branch rendered goes, not just the clones it owns:
@@ -5224,6 +5253,15 @@ catch (e) { /* a disposer of its own is not this branch's problem */ }
5224
5253
  stxHost.insert(pickHost, pick.endMarker, anchor);
5225
5254
  }
5226
5255
  pick.el.__stx_shown_at = performance.now();
5256
+ // An element branch shown before keeps its bindings and its scopes;
5257
+ // the components in it mount again (a template branch is cloned afresh
5258
+ // and mounts through hydrateComponentScopes below).
5259
+ if (pick.childrenProcessed) {
5260
+ var shownNodes = pick.nodes;
5261
+ queueMicrotask(function () {
5262
+ if (pick.el.__stx_chain_active) peek(function () { resumeSubtreeScopes(shownNodes); });
5263
+ });
5264
+ }
5227
5265
  if (!pick.childrenProcessed) {
5228
5266
  pick.childrenProcessed = true;
5229
5267
  // Hydrate before the outer scope walk can see the inserted branch.
@@ -5451,6 +5489,9 @@ else if (!value && isInserted) {
5451
5489
  // parent and took a sibling <template :if> with it -- the initial
5452
5490
  // server-rendered state has no marker to stop at.
5453
5491
  if (endMarker && endMarker.parentNode === parent) {
5492
+ var leaving = [];
5493
+ for (var cursor = placeholder.nextSibling; cursor && cursor !== endMarker; cursor = cursor.nextSibling) leaving.push(cursor);
5494
+ suspendSubtreeScopes(leaving);
5454
5495
  var doomed = placeholder.nextSibling;
5455
5496
  while (doomed && doomed !== endMarker) {
5456
5497
  var nextDoomed = doomed.nextSibling;
@@ -5460,6 +5501,7 @@ else if (!value && isInserted) {
5460
5501
  }
5461
5502
  stxHost.remove(endMarker);
5462
5503
  }
5504
+ suspendSubtreeScopes(currentNodes.filter(node => node.parentNode));
5463
5505
  currentNodes.forEach(node => { disposeSubtreeEffects(node); stxHost.remove(node); });
5464
5506
  currentNodes = [];
5465
5507
  isInserted = false;
@@ -5490,10 +5532,21 @@ else {
5490
5532
  // Its children may have become visible while it was detached, so
5491
5533
  // resume their pending bindings now that the subtree is connected.
5492
5534
  peek(resumeDetachedBranches);
5535
+ // Shown before, so the components in it mounted and were suspended
5536
+ // when it hid. They mount again now -- in a microtask, the same
5537
+ // moment their first mount ran, and only if still shown by then.
5538
+ if (childrenProcessed) {
5539
+ queueMicrotask(function() {
5540
+ if (isInserted) peek(function() { resumeSubtreeScopes(currentNodes); });
5541
+ });
5542
+ }
5493
5543
  }
5494
5544
  else if (!value && isInserted) {
5495
5545
  console.log('[stx] bindIf REMOVING element for :if=' + expr, 'el.isConnected:', el.isConnected, 'parent:', parent.tagName);
5496
5546
  el.__stx_if_visible.set(false);
5547
+ // Unmounted, not disposed: the components in it release what they
5548
+ // hold while their markup is still on the page, and keep their scopes.
5549
+ suspendSubtreeScopes(currentNodes);
5497
5550
  // Do NOT disposeSubtreeScopes here. :if is a TOGGLE \u2014 the element is
5498
5551
  // re-shown when the condition flips back \u2014 not a permanent unmount.
5499
5552
  // A nested data-stx-scope inside this subtree is created once by its
@@ -6634,6 +6687,13 @@ catch (e) {} }
6634
6687
  if (initialAttribute.has) {
6635
6688
  lastRaw = initialAttribute.raw;
6636
6689
  initial = parse(lastRaw);
6690
+ } else if (typeof staticValue === 'string' && (opts.parse || typeof defaultValue !== 'string')) {
6691
+ // A prop written as a plain attribute is serialized as the string it was
6692
+ // written as, so it gets the same parse an attribute does. Taken raw,
6693
+ // currentPage="1" reached Pagination as "1": "1" + 1 is "11", the
6694
+ // range maths took the wrong branch, and ten pages rendered as
6695
+ // 1 ... 1 2 3 4 5 6 7 8 9 10 ... 10. A string prop stays a string.
6696
+ initial = parse(staticValue);
6637
6697
  } else {
6638
6698
  initial = staticValue;
6639
6699
  }
@@ -8887,6 +8947,70 @@ catch (e) {
8887
8947
  }
8888
8948
  }
8889
8949
 
8950
+ // :if is a toggle, and a component inside one lives through every toggle:
8951
+ // its scope is registered once and kept (#1737), and showing the branch puts
8952
+ // the same markup back. Its LIFECYCLE follows the toggle, though. Hiding runs
8953
+ // what the component registered to release -- its onDestroy, and whatever
8954
+ // its onMount handed back -- and showing it again runs its onMount again.
8955
+ // Each show is a mount and each hide an unmount, which is the pairing every
8956
+ // component on a page already gets.
8957
+ //
8958
+ // Before this, a hidden component never heard about it and a re-shown one
8959
+ // was never told it was back (the asymmetry stacksjs/stx#2036 stopped short
8960
+ // of). A gated modal shell -- one that traps focus, locks body scroll and
8961
+ // claims Escape from onMount, and releases them in onDestroy -- did all of
8962
+ // that on its first opening and on no later one: the second time it opened
8963
+ // with the page scrolling behind it and Escape doing nothing.
8964
+ //
8965
+ // Only scopes that actually mounted are suspended, so a component whose
8966
+ // first mount is still deferred (behind a false :if, or an stx-hydrate
8967
+ // island) keeps waiting for its own flush.
8968
+ function suspendSubtreeScopes(nodes) {
8969
+ if (!nodes || !window.stx || !window.stx._scopes) return;
8970
+ var ids = [];
8971
+ for (var i = 0; i < nodes.length; i++) {
8972
+ var found = stxHost.scopesIn(nodes[i]);
8973
+ for (var k = 0; k < found.length; k++) {
8974
+ if (ids.indexOf(found[k]) === -1) ids.push(found[k]);
8975
+ }
8976
+ }
8977
+ // Innermost first, the order a page unmounts in: a child releases what it
8978
+ // holds before the component it sits in does.
8979
+ for (var n = ids.length - 1; n >= 0; n--) {
8980
+ var scopeVars = window.stx._scopes[ids[n]];
8981
+ if (!scopeVars || !scopeVars.__mounted) continue;
8982
+ scopeVars.__mounted = false;
8983
+ scopeVars.__suspended = true;
8984
+ var release = scopeVars.__destroyCallbacks || [];
8985
+ // What onDestroy registered at setup is owed again at the next hide;
8986
+ // a cleanup a mount handed back belonged to that mount alone.
8987
+ scopeVars.__destroyCallbacks = (scopeVars.__destroyHooks || []).slice();
8988
+ for (var j = 0; j < release.length; j++) {
8989
+ try { release[j](); }
8990
+ catch (e) { console.warn('[stx] scope destroy error:', e); }
8991
+ }
8992
+ scopeVars.__mountCallbacks = (scopeVars.__mountHooks || []).slice();
8993
+ }
8994
+ }
8995
+
8996
+ // The other half: a suspended scope whose markup is back on the page mounts
8997
+ // again. A scope still off the page (hidden by an :if of its own inside this
8998
+ // branch) is left for that :if to resume.
8999
+ function resumeSubtreeScopes(nodes) {
9000
+ if (!nodes || !window.stx || !window.stx._scopes) return;
9001
+ for (var i = 0; i < nodes.length; i++) {
9002
+ var ids = stxHost.scopesIn(nodes[i]);
9003
+ for (var k = 0; k < ids.length; k++) {
9004
+ var scopeVars = window.stx._scopes[ids[k]];
9005
+ if (!scopeVars || scopeVars.__mounted || !scopeVars.__suspended) continue;
9006
+ if (scopeVars.__el && scopeVars.__el.isConnected === false) continue;
9007
+ scopeVars.__suspended = false;
9008
+ scopeVars.__mounted = true;
9009
+ runMountCallbacks(scopeVars.__mountCallbacks, scopeDestroySink(scopeVars));
9010
+ }
9011
+ }
9012
+ }
9013
+
8890
9014
  function disposeSubtreeScopes(root) {
8891
9015
  if (!root || !window.stx || !window.stx._scopes) return;
8892
9016
  // The host reports which scopes live in this subtree: the document finds
@@ -8898,7 +9022,12 @@ catch (e) {
8898
9022
  if (!scopeId) continue;
8899
9023
  var scopeVars = window.stx._scopes[scopeId];
8900
9024
  if (!scopeVars) continue;
8901
- if (scopeVars.__destroyCallbacks && Array.isArray(scopeVars.__destroyCallbacks)) {
9025
+ // Hidden by an :if, it already released everything on the way out;
9026
+ // running the hooks again would unmount it twice. (A hidden component's
9027
+ // root is detached, so no walk reaches it today; this keeps the next
9028
+ // disposal path that does from unmounting it twice.)
9029
+ var alreadyReleased = scopeVars.__suspended && !scopeVars.__mounted;
9030
+ if (!alreadyReleased && scopeVars.__destroyCallbacks && Array.isArray(scopeVars.__destroyCallbacks)) {
8902
9031
  for (var j = 0; j < scopeVars.__destroyCallbacks.length; j++) {
8903
9032
  try { scopeVars.__destroyCallbacks[j](); }
8904
9033
  catch (e) { console.warn('[stx] scope destroy error:', e); }
@@ -8950,7 +9079,8 @@ catch (e) {
8950
9079
  if (p.__stx_if_bound || p.__stx_chain_member) { retained = true; break; }
8951
9080
  }
8952
9081
  if (retained) continue;
8953
- if (entry.__destroyCallbacks && Array.isArray(entry.__destroyCallbacks)) {
9082
+ // Suspended by an :if: released when it hid, so not again here.
9083
+ if (!(entry.__suspended && !entry.__mounted) && entry.__destroyCallbacks && Array.isArray(entry.__destroyCallbacks)) {
8954
9084
  for (var k = 0; k < entry.__destroyCallbacks.length; k++) {
8955
9085
  try { entry.__destroyCallbacks[k](); }
8956
9086
  catch (e) { console.warn('[stx] scope destroy error:', e); }
package/dist/ssg.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import"./chunk-r6pax860.js";import"./chunk-8xz8t9xp.js";import{Qe,et,tt,nt,rt,st}from"./chunk-w6zz18jt.js";import"./chunk-w1zvh5y7.js";import"./chunk-h9e032kq.js";import{f,je,N,K,n,o}from"./chunk-zskhxkbk.js";import"./chunk-exgyf65a.js";import{Qn}from"./chunk-4fa3jec9.js";import"./chunk-zydg3wgt.js";import"./chunk-y1hx8re2.js";import"./chunk-jz7pvh7b.js";import"./chunk-0trfbqa7.js";import"./chunk-jfps4n28.js";import{ie,gt,mt}from"./chunk-jkyb1f9r.js";import{_o,Ro,Ao}from"./chunk-dxxs52yw.js";import{pt,Gt,Jt}from"./chunk-5pjsc9zv.js";import"./chunk-bq2e9qf6.js";import{a}from"./chunk-7tt84v1y.js";import x from"fs";import g from"path";import{createHash as $t}from"crypto";function Dt(t){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(t).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return t}}var Rt=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function kt(t){return Bun.hash(t).toString(16)}function lt(t,i={}){if(!t.includes('type="stx/island"'))return{html:t,chunks:[]};let s=new Map,r=t.replace(Rt,(e,l,w,y)=>{let h=y.trim();if(!h)return e;if(/\bdata-stx-src=/.test(w))return e;if(i.minify)h=Dt(h);let S=kt(h);if(!s.has(S))s.set(S,h);let P=i.integrity?` data-stx-integrity="sha384-${$t("sha384").update(h).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${l}" data-stx-src="/_stx/islands/${S}.js"${P}${w}></script>`}),c=Array.from(s,([e,l])=>({hash:e,code:l}));return{html:r,chunks:c}}var Ct=new Set(["visible","idle"]);function ut(t){if(!t.includes("data-stx-src="))return t;let i=new Map,s=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,r;while((r=s.exec(t))!==null)i.set(r[1],r[2]);let c=new Set,e=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,l;while((l=e.exec(t))!==null)if(Ct.has(i.get(l[1])||""))c.add(l[2]);let w=t.lastIndexOf("</head>");if(c.size===0||w===-1)return t;let y=Array.from(c).filter((h)=>!t.includes(`rel="prefetch" href="${h}"`)).map((h)=>`<link rel="prefetch" href="${h}" as="script">`).join("");if(!y)return t;return t.slice(0,w)+y+t.slice(w)}var Et=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function q(t){let i=t.trim();if(!i)return null;let s=/^https?:\/\//i.test(i)?i:`https://${i}`;try{return new URL(s).origin+new URL(s).pathname.replace(/\/$/,"")}catch{return null}}function It(t){for(let i of Et){let s=t[i];if(!s)continue;let r=q(s);if(r)return{url:r,source:"env",via:i}}return null}function dt(t){if(!t||typeof t!=="object")return null;let i=t,s=i.site?.url??i.url??i.app?.url;return typeof s==="string"?q(s):null}async function Bt(t){let{existsSync:i}=await import("fs"),s=await import("path");for(let r of["site.config.ts","site.config.js",".config/site.config.ts"]){let c=s.resolve(t,r);if(!i(c))continue;try{let e=await import(c),l=dt(e.default??e);if(l)return l}catch{}}return null}async function ht(t={}){let i=t.cwd??process.cwd(),s=t.env??process.env;if(t.explicit){let l=q(t.explicit);if(l)return{url:l,source:"option"}}let r=dt(t.stxConfig);if(r)return{url:r,source:"stx.config",via:"site.url"};let c=await Bt(i);if(c)return{url:c,source:"site.config",via:"url"};let e=It(s);if(e)return e;return{url:"http://localhost",source:"fallback"}}function ft(){return["No site URL configured \u2014 sitemap.xml and robots.txt will point at http://localhost."," Set one in stx.config.ts (site: { url: 'https://example.com' }), in site.config.ts,"," via --domain, or with SITE_URL in the build environment."].join(`
2
+ import"./chunk-ynvce0q6.js";import"./chunk-8xz8t9xp.js";import{Qe,et,tt,nt,rt,st}from"./chunk-5w87wmc4.js";import"./chunk-2jbyks2t.js";import"./chunk-pf0d8y9n.js";import{f,je,N,K,n,o}from"./chunk-b6e36vr2.js";import"./chunk-8yrk8ybh.js";import{Qn}from"./chunk-ver2yf41.js";import"./chunk-zydg3wgt.js";import"./chunk-n3r5m938.js";import"./chunk-jz7pvh7b.js";import"./chunk-0trfbqa7.js";import"./chunk-5pgvfxtx.js";import{ie,gt,mt}from"./chunk-a6pjaw6w.js";import{To,Ro,Ao}from"./chunk-5j5msbks.js";import{pt,Gt,Jt}from"./chunk-5pjsc9zv.js";import"./chunk-5bqs0ve6.js";import{a}from"./chunk-7tt84v1y.js";import x from"fs";import g from"path";import{createHash as $t}from"crypto";function Dt(t){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(t).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return t}}var Rt=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function kt(t){return Bun.hash(t).toString(16)}function lt(t,i={}){if(!t.includes('type="stx/island"'))return{html:t,chunks:[]};let s=new Map,r=t.replace(Rt,(e,l,w,y)=>{let h=y.trim();if(!h)return e;if(/\bdata-stx-src=/.test(w))return e;if(i.minify)h=Dt(h);let S=kt(h);if(!s.has(S))s.set(S,h);let P=i.integrity?` data-stx-integrity="sha384-${$t("sha384").update(h).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${l}" data-stx-src="/_stx/islands/${S}.js"${P}${w}></script>`}),c=Array.from(s,([e,l])=>({hash:e,code:l}));return{html:r,chunks:c}}var Ct=new Set(["visible","idle"]);function ut(t){if(!t.includes("data-stx-src="))return t;let i=new Map,s=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,r;while((r=s.exec(t))!==null)i.set(r[1],r[2]);let c=new Set,e=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,l;while((l=e.exec(t))!==null)if(Ct.has(i.get(l[1])||""))c.add(l[2]);let w=t.lastIndexOf("</head>");if(c.size===0||w===-1)return t;let y=Array.from(c).filter((h)=>!t.includes(`rel="prefetch" href="${h}"`)).map((h)=>`<link rel="prefetch" href="${h}" as="script">`).join("");if(!y)return t;return t.slice(0,w)+y+t.slice(w)}var Et=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function q(t){let i=t.trim();if(!i)return null;let s=/^https?:\/\//i.test(i)?i:`https://${i}`;try{return new URL(s).origin+new URL(s).pathname.replace(/\/$/,"")}catch{return null}}function It(t){for(let i of Et){let s=t[i];if(!s)continue;let r=q(s);if(r)return{url:r,source:"env",via:i}}return null}function dt(t){if(!t||typeof t!=="object")return null;let i=t,s=i.site?.url??i.url??i.app?.url;return typeof s==="string"?q(s):null}async function Bt(t){let{existsSync:i}=await import("fs"),s=await import("path");for(let r of["site.config.ts","site.config.js",".config/site.config.ts"]){let c=s.resolve(t,r);if(!i(c))continue;try{let e=await import(c),l=dt(e.default??e);if(l)return l}catch{}}return null}async function ht(t={}){let i=t.cwd??process.cwd(),s=t.env??process.env;if(t.explicit){let l=q(t.explicit);if(l)return{url:l,source:"option"}}let r=dt(t.stxConfig);if(r)return{url:r,source:"stx.config",via:"site.url"};let c=await Bt(i);if(c)return{url:c,source:"site.config",via:"url"};let e=It(s);if(e)return e;return{url:"http://localhost",source:"fallback"}}function ft(){return["No site URL configured \u2014 sitemap.xml and robots.txt will point at http://localhost."," Set one in stx.config.ts (site: { url: 'https://example.com' }), in site.config.ts,"," via --domain, or with SITE_URL in the build environment."].join(`
3
3
  `)}class wt{cacheDir;cache=new Map;loaded=!1;salt;constructor(t,i=""){this.cacheDir=t,this.salt=i}async load(){if(this.loaded)return;let t=g.join(this.cacheDir,"build-cache.json");if(await Bun.file(t).exists())try{let i=JSON.parse(await Bun.file(t).text());for(let[s,r]of Object.entries(i))this.cache.set(s,r)}catch{}this.loaded=!0}async save(){await x.promises.mkdir(this.cacheDir,{recursive:!0});let t=g.join(this.cacheDir,"build-cache.json"),i={};for(let[s,r]of this.cache)i[s]=r;await Bun.write(t,JSON.stringify(i))}getHash(t,i){let s=x.statSync(t),r=`${this.salt}|${t}:${s.mtimeMs}`;for(let e of i)if(x.existsSync(e)){let l=x.statSync(e);r+=`:${e}:${l.mtimeMs}`}let c=0;for(let e=0;e<r.length;e++){let l=r.charCodeAt(e);c=(c<<5)-c+l,c=c&c}return Math.abs(c).toString(36)}get(t,i){let s=this.cache.get(t);if(!s)return null;let r=this.getHash(i,s.dependencies??[]);if(s.hash!==r)return this.cache.delete(t),null;return s.html}set(t,i,s,r){let c=this.getHash(i,s);this.cache.set(t,{hash:c,html:r,generatedAt:Date.now(),dependencies:s})}}class yt{cacheDir;constructor(t){this.cacheDir=t}getFilePath(t){let i=t.replace(/[^a-zA-Z0-9]/g,"_")+".json";return g.join(this.cacheDir,"isr",i)}async get(t){let i=this.getFilePath(t);if(!await Bun.file(i).exists())return null;try{return JSON.parse(await Bun.file(i).text())}catch{return null}}async set(t,i){let s=this.getFilePath(t);await x.promises.mkdir(g.dirname(s),{recursive:!0}),await Bun.write(s,JSON.stringify(i))}async invalidate(t){let i=this.getFilePath(t);if(await Bun.file(i).exists())await x.promises.unlink(i)}async invalidatePattern(t){let i=g.join(this.cacheDir,"isr");if(!x.existsSync(i))return;let s=await x.promises.readdir(i);for(let r of s){let c=r.replace(/_/g,"/").replace(".json","");if(t.test(c))await x.promises.unlink(g.join(i,r))}}async needsRevalidation(t){let i=await this.get(t);if(!i)return!0;return Date.now()>i.revalidateAfter}}async function jt(t){try{let s=(await Bun.file(t).text()).match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(!s)return null;let r=s[1];if(!r.includes("getStaticPaths"))return null;let c=r.match(/(?:export\s+)?(?:async\s+)?function\s+getStaticPaths\s*\([^)]*\)\s*\{([\s\S]*?)\n[\t ]*\}/);if(!c)return null;return await Function(`
4
4
  return (async function getStaticPaths() {
5
5
  ${c[1]}
@@ -41,7 +41,7 @@ ${t.map((r)=>{let c=new URL(r.loc,i).href,e=` <url>
41
41
  ${s.join(`
42
42
  `)}
43
43
  </channel>
44
- </rss>`}async function zt(t={}){let i=Date.now();mt();let s=await o(process.cwd()),r=s.build||{},c=await ht({explicit:t.domain||r.domain,stxConfig:s});if(c.source==="fallback"&&(t.sitemap??r.sitemap??!0))console.warn(ft());let e={router:t.router??s?.router??{},pagesDir:t.pagesDir||r.pagesDir||"pages",outputDir:t.outputDir||r.outputDir||"dist",baseUrl:t.baseUrl||r.baseUrl||"/",domain:c.url,revalidate:t.revalidate??r.revalidate??!1,sitemap:t.sitemap??r.sitemap??!0,sitemapExclude:t.sitemapExclude||r.sitemapExclude||[],robots:t.robots??r.robots??!0,rss:t.rss??r.rss??!1,concurrency:t.concurrency||r.concurrency||10,cache:t.cache??r.cache??!0,cacheDir:t.cacheDir||r.cacheDir||a(process.cwd(),"ssg-cache"),contentLoaders:t.contentLoaders||[],hooks:t.hooks||{},minify:t.minify??r.minify??!0,generate404:t.generate404??r.generate404??!0,publicDir:t.publicDir||r.publicDir||"public",trailingSlash:t.trailingSlash??r.trailingSlash??!1,cleanOutput:t.cleanOutput??r.cleanOutput??!0,cacheSalt:t.cacheSalt??"",partialsDir:t.partialsDir||s?.partialsDir||"",componentsDir:t.componentsDir||s?.componentsDir||"",failOnIncludeError:t.failOnIncludeError??!0,failOnServerScriptError:t.failOnServerScriptError??!0,chunkIslands:t.chunkIslands===!0,prefetchIslands:t.prefetchIslands===!0,integrityIslands:t.integrityIslands===!0},l={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},w=new Set,y=0,h={},S={};await e.hooks.onBuildStart?.();try{if(e.cleanOutput&&x.existsSync(e.outputDir))await x.promises.rm(e.outputDir,{recursive:!0});await x.promises.mkdir(e.outputDir,{recursive:!0});let D=e.cacheSalt;if(!D){let{resolveUserCssConfig:u,fingerprintConfig:m}=await import("./chunk-r61m4j2j.js");try{D=m(await u(process.cwd()))}catch{}}let{prepareImageDelivery:p}=await import("./chunk-s25yesdx.js"),b=await p(e.publicDir,e.outputDir);if(b.count>0)console.log(`Optimized ${b.count} image(s) for responsive delivery`),D=[D,b.fingerprint].filter(Boolean).join(":");let B=new wt(e.cacheDir,D);if(e.cache)await B.load();try{let{generateCss:u}=await import("./chunk-r61m4j2j.js");await u('<div class="bg-black"></div>')}catch{}Qe();let xt=s?.routeMiddleware?.dir||"middleware";await tt(process.cwd(),xt);let H=et();if(H.length>0)console.log(`Loaded ${H.length} middleware: ${H.join(", ")}`);let vt=s?.routeMiddleware?.global||[];Ao(s?.layoutsDir,a(process.cwd()));let V=N(".",{pagesDir:e.pagesDir,pagesDirs:s?._layerPageDirs});console.log(`Found ${V.length} routes`);let _=[];for(let u of V){let m=await Ft(u);for(let v of m)_.push({route:u,url:v.url,params:v.params,props:v.props,revalidate:v.revalidate??e.revalidate})}l.totalPages=_.length,console.log(`Generating ${l.totalPages} pages...`);let A=[],X=[];for(let u=0;u<_.length;u+=e.concurrency)X.push(_.slice(u,u+e.concurrency));for(let u of X)await Promise.all(u.map(async(m)=>{let{route:v,url:d,params:L,props:bt,revalidate:Q}=m;try{await e.hooks.onPageStart?.(d);let j=await Bun.file(v.filePath).text(),F=Vt(j),Pt=F?.middleware?Array.isArray(F.middleware)?F.middleware:[F.middleware]:[],it=[...vt,...Pt];if(it.length>0){let C=nt(d,L,F||{}),O=rt(C,null,void 0,{isServer:!0}),E=await st(it,O);if(E.redirect){let R=typeof E.redirect==="string"?E.redirect:E.redirect.path||E.redirect,U=Kt(String(R),d),T=Xt(d,e);await x.promises.mkdir(g.dirname(T),{recursive:!0}),await Bun.write(T,U),l.successCount++,l.pages.push({route:d,outputPath:T,size:Buffer.byteLength(U),cached:!1}),A.push({loc:d,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${d} \u2192 redirect to ${R}`);return}if(E.abort){let R=typeof E.abort==="string"?E.abort:E.abort?.error?.message||"aborted";console.warn(` \u21B3 ${d} \u2014 middleware aborted: ${R}`);return}}let at=j.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(at)try{if(!await Function("route",`
44
+ </rss>`}async function zt(t={}){let i=Date.now();mt();let s=await o(process.cwd()),r=s.build||{},c=await ht({explicit:t.domain||r.domain,stxConfig:s});if(c.source==="fallback"&&(t.sitemap??r.sitemap??!0))console.warn(ft());let e={router:t.router??s?.router??{},pagesDir:t.pagesDir||r.pagesDir||"pages",outputDir:t.outputDir||r.outputDir||"dist",baseUrl:t.baseUrl||r.baseUrl||"/",domain:c.url,revalidate:t.revalidate??r.revalidate??!1,sitemap:t.sitemap??r.sitemap??!0,sitemapExclude:t.sitemapExclude||r.sitemapExclude||[],robots:t.robots??r.robots??!0,rss:t.rss??r.rss??!1,concurrency:t.concurrency||r.concurrency||10,cache:t.cache??r.cache??!0,cacheDir:t.cacheDir||r.cacheDir||a(process.cwd(),"ssg-cache"),contentLoaders:t.contentLoaders||[],hooks:t.hooks||{},minify:t.minify??r.minify??!0,generate404:t.generate404??r.generate404??!0,publicDir:t.publicDir||r.publicDir||"public",trailingSlash:t.trailingSlash??r.trailingSlash??!1,cleanOutput:t.cleanOutput??r.cleanOutput??!0,cacheSalt:t.cacheSalt??"",partialsDir:t.partialsDir||s?.partialsDir||"",componentsDir:t.componentsDir||s?.componentsDir||"",failOnIncludeError:t.failOnIncludeError??!0,failOnServerScriptError:t.failOnServerScriptError??!0,chunkIslands:t.chunkIslands===!0,prefetchIslands:t.prefetchIslands===!0,integrityIslands:t.integrityIslands===!0},l={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},w=new Set,y=0,h={},S={};await e.hooks.onBuildStart?.();try{if(e.cleanOutput&&x.existsSync(e.outputDir))await x.promises.rm(e.outputDir,{recursive:!0});await x.promises.mkdir(e.outputDir,{recursive:!0});let D=e.cacheSalt;if(!D){let{resolveUserCssConfig:u,fingerprintConfig:m}=await import("./chunk-14p5jgqp.js");try{D=m(await u(process.cwd()))}catch{}}let{prepareImageDelivery:p}=await import("./chunk-3rrzxapr.js"),b=await p(e.publicDir,e.outputDir);if(b.count>0)console.log(`Optimized ${b.count} image(s) for responsive delivery`),D=[D,b.fingerprint].filter(Boolean).join(":");let B=new wt(e.cacheDir,D);if(e.cache)await B.load();try{let{generateCss:u}=await import("./chunk-14p5jgqp.js");await u('<div class="bg-black"></div>')}catch{}Qe();let xt=s?.routeMiddleware?.dir||"middleware";await tt(process.cwd(),xt);let H=et();if(H.length>0)console.log(`Loaded ${H.length} middleware: ${H.join(", ")}`);let vt=s?.routeMiddleware?.global||[];Ao(s?.layoutsDir,a(process.cwd()));let V=N(".",{pagesDir:e.pagesDir,pagesDirs:s?._layerPageDirs});console.log(`Found ${V.length} routes`);let _=[];for(let u of V){let m=await Ft(u);for(let v of m)_.push({route:u,url:v.url,params:v.params,props:v.props,revalidate:v.revalidate??e.revalidate})}l.totalPages=_.length,console.log(`Generating ${l.totalPages} pages...`);let A=[],X=[];for(let u=0;u<_.length;u+=e.concurrency)X.push(_.slice(u,u+e.concurrency));for(let u of X)await Promise.all(u.map(async(m)=>{let{route:v,url:d,params:L,props:bt,revalidate:Q}=m;try{await e.hooks.onPageStart?.(d);let j=await Bun.file(v.filePath).text(),F=Vt(j),Pt=F?.middleware?Array.isArray(F.middleware)?F.middleware:[F.middleware]:[],it=[...vt,...Pt];if(it.length>0){let C=nt(d,L,F||{}),O=rt(C,null,void 0,{isServer:!0}),E=await st(it,O);if(E.redirect){let R=typeof E.redirect==="string"?E.redirect:E.redirect.path||E.redirect,U=Kt(String(R),d),T=Xt(d,e);await x.promises.mkdir(g.dirname(T),{recursive:!0}),await Bun.write(T,U),l.successCount++,l.pages.push({route:d,outputPath:T,size:Buffer.byteLength(U),cached:!1}),A.push({loc:d,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${d} \u2192 redirect to ${R}`);return}if(E.abort){let R=typeof E.abort==="string"?E.abort:E.abort?.error?.message||"aborted";console.warn(` \u21B3 ${d} \u2014 middleware aborted: ${R}`);return}}let at=j.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(at)try{if(!await Function("route",`
45
45
  const validate = ${at[1]};
46
46
  return validate(route);
47
47
  `)({params:L})){console.warn(`Validation failed for ${d}, skipping...`);return}}catch{}let k=null,ot=!1;if(e.cache){if(k=B.get(d,v.filePath),k)ot=!0,l.cachedCount++}if(!k){let C=await St(v,L,bt,e,s);if(k=C.html,e.failOnIncludeError&&C.includeFailures.length>0)throw Error(`${C.includeFailures.length} include(s) failed to resolve, so this page would have shipped with an error banner where the markup should be:
@@ -73,7 +73,7 @@ ${u}`)}if(e.cache)await B.save();if(e.generate404){let u=g.join(e.pagesDir,"404.
73
73
  <a href="/">Go home</a>
74
74
  </div>
75
75
  </body>
76
- </html>`)}for(let u of[500]){let m=g.join(e.pagesDir,`${u}.stx`);if(await Bun.file(m).exists()){let v=new Set,d={...s,debug:!1,cache:!1},L=await n(await Bun.file(m).text(),{},m,d,v);await Bun.write(g.join(e.outputDir,`${u}.html`),L)}}let W=g.join(e.pagesDir,"error.stx");if(await Bun.file(W).exists()){let u=new Set,m={...s,debug:!1,cache:!1},v=await n(await Bun.file(W).text(),{},W,m,u);await Bun.write(g.join(e.outputDir,"error.html"),v)}if(e.sitemap&&A.length>0){let u=_t(A,e.domain),m=g.join(e.outputDir,"sitemap.xml");await Bun.write(m,u),l.sitemapPath=m,console.log(`Generated sitemap.xml with ${A.length} URLs`)}if(e.robots!==!1){let u=typeof e.robots==="object"?e.robots:{},m=[...e.sitemapExclude.filter((d)=>typeof d==="string"),...u.disallow||[]],v=Qn({rules:[{userAgent:u.userAgent||"*",allow:u.allow||["/"],...m.length>0?{disallow:m}:{}}],...u.sitemap!==!1&&l.sitemapPath?{sitemap:new URL("/sitemap.xml",e.domain).href}:{}});await Bun.write(g.join(e.outputDir,"robots.txt"),v),console.log("Generated robots.txt")}if(e.rss){let u=typeof e.rss==="object"?e.rss:{title:"Site Feed",description:"Latest updates",link:e.domain},m=[];if(u.getItems)m=await u.getItems();let v=Nt(u,m),d=g.join(e.outputDir,"rss.xml");await Bun.write(d,v),l.rssPath=d,console.log(`Generated rss.xml with ${m.length} items`)}let G=_o(e.outputDir);if(G.assets>0)console.log(`Externalized ${G.assets} asset(s) from ${G.pages} page(s) (${(G.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);let z=Ro(e.outputDir);if(z.assets>0)console.log(`Externalized ${z.assets} repeated asset(s) from ${z.pages} page(s) (${(z.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);if(e.publicDir&&x.existsSync(e.publicDir))await J(e.publicDir,e.outputDir),console.log(`Copied public assets from ${e.publicDir}`);let Z=Jt();if(Z)await J(Z,g.join(e.outputDir,Gt)),console.log(`Copied assets from ${pt}`)}catch(D){throw await e.hooks.onError?.(D),D}if(l.buildTime=Date.now()-i,w.size>0){l.islandChunks={count:w.size,totalBytes:y};let D={generatedChunks:w.size,totalBytes:y,chunks:h,pages:S};await Bun.write(g.join(e.outputDir,"_stx","islands-manifest.json"),JSON.stringify(D,null,2))}await e.hooks.onBuildEnd?.(l);let P=l.islandChunks?`
76
+ </html>`)}for(let u of[500]){let m=g.join(e.pagesDir,`${u}.stx`);if(await Bun.file(m).exists()){let v=new Set,d={...s,debug:!1,cache:!1},L=await n(await Bun.file(m).text(),{},m,d,v);await Bun.write(g.join(e.outputDir,`${u}.html`),L)}}let W=g.join(e.pagesDir,"error.stx");if(await Bun.file(W).exists()){let u=new Set,m={...s,debug:!1,cache:!1},v=await n(await Bun.file(W).text(),{},W,m,u);await Bun.write(g.join(e.outputDir,"error.html"),v)}if(e.sitemap&&A.length>0){let u=_t(A,e.domain),m=g.join(e.outputDir,"sitemap.xml");await Bun.write(m,u),l.sitemapPath=m,console.log(`Generated sitemap.xml with ${A.length} URLs`)}if(e.robots!==!1){let u=typeof e.robots==="object"?e.robots:{},m=[...e.sitemapExclude.filter((d)=>typeof d==="string"),...u.disallow||[]],v=Qn({rules:[{userAgent:u.userAgent||"*",allow:u.allow||["/"],...m.length>0?{disallow:m}:{}}],...u.sitemap!==!1&&l.sitemapPath?{sitemap:new URL("/sitemap.xml",e.domain).href}:{}});await Bun.write(g.join(e.outputDir,"robots.txt"),v),console.log("Generated robots.txt")}if(e.rss){let u=typeof e.rss==="object"?e.rss:{title:"Site Feed",description:"Latest updates",link:e.domain},m=[];if(u.getItems)m=await u.getItems();let v=Nt(u,m),d=g.join(e.outputDir,"rss.xml");await Bun.write(d,v),l.rssPath=d,console.log(`Generated rss.xml with ${m.length} items`)}let G=To(e.outputDir);if(G.assets>0)console.log(`Externalized ${G.assets} asset(s) from ${G.pages} page(s) (${(G.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);let z=Ro(e.outputDir);if(z.assets>0)console.log(`Externalized ${z.assets} repeated asset(s) from ${z.pages} page(s) (${(z.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);if(e.publicDir&&x.existsSync(e.publicDir))await J(e.publicDir,e.outputDir),console.log(`Copied public assets from ${e.publicDir}`);let Z=Jt();if(Z)await J(Z,g.join(e.outputDir,Gt)),console.log(`Copied assets from ${pt}`)}catch(D){throw await e.hooks.onError?.(D),D}if(l.buildTime=Date.now()-i,w.size>0){l.islandChunks={count:w.size,totalBytes:y};let D={generatedChunks:w.size,totalBytes:y,chunks:h,pages:S};await Bun.write(g.join(e.outputDir,"_stx","islands-manifest.json"),JSON.stringify(D,null,2))}await e.hooks.onBuildEnd?.(l);let P=l.islandChunks?`
77
77
  Island chunks: ${l.islandChunks.count} (${(l.islandChunks.totalBytes/1024).toFixed(1)} KB lifted out of inline HTML)`:"";return console.log(`
78
78
  Build complete!
79
79
  Total: ${l.totalPages} pages
package/dist/utils.js CHANGED
@@ -1311,11 +1311,26 @@ async function buildComponentIsland(rawContent, componentFilePath, minify) {
1311
1311
  }
1312
1312
  window.__STX_CURRENT_PROPS__ = __componentProps && typeof __componentProps === 'object' && !Array.isArray(__componentProps) ? __componentProps : {};
1313
1313
 
1314
- // Scope-specific lifecycle callbacks
1314
+ // Scope-specific lifecycle callbacks. The queues drain as they run; the
1315
+ // hook lists keep what setup registered, because a component behind an :if
1316
+ // unmounts at each hide and mounts again at each show (signals.ts,
1317
+ // suspendSubtreeScopes).
1318
+ if (__scopeVars.__suspended && !__scopeVars.__mounted) {
1319
+ // Set up again after an :if hid it -- a <template :if> clones the
1320
+ // component afresh on every show, and the clone's script runs. This run's
1321
+ // hooks close over this run's state, so they replace the ones the hide
1322
+ // kept for a re-show rather than queueing beside them.
1323
+ __scopeVars.__mountCallbacks = [];
1324
+ __scopeVars.__destroyCallbacks = [];
1325
+ __scopeVars.__mountHooks = [];
1326
+ __scopeVars.__destroyHooks = [];
1327
+ }
1315
1328
  __scopeVars.__mountCallbacks = __scopeVars.__mountCallbacks || [];
1316
1329
  __scopeVars.__destroyCallbacks = __scopeVars.__destroyCallbacks || [];
1317
- const onMount = (fn) => __scopeVars.__mountCallbacks.push(fn);
1318
- const onDestroy = (fn) => __scopeVars.__destroyCallbacks.push(fn);
1330
+ __scopeVars.__mountHooks = __scopeVars.__mountHooks || [];
1331
+ __scopeVars.__destroyHooks = __scopeVars.__destroyHooks || [];
1332
+ const onMount = (fn) => { __scopeVars.__mountCallbacks.push(fn); __scopeVars.__mountHooks.push(fn); };
1333
+ const onDestroy = (fn) => { __scopeVars.__destroyCallbacks.push(fn); __scopeVars.__destroyHooks.push(fn); };
1319
1334
 
1320
1335
  try {
1321
1336
  ${content}