@stacksjs/stx 0.2.287 → 0.2.288

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 (179) hide show
  1. package/dist/{chunk-mf4n3x1j.js → chunk-02af607x.js} +1 -1
  2. package/dist/chunk-06706a9a.js +2 -0
  3. package/dist/chunk-0896td83.js +2 -0
  4. package/dist/chunk-08yja60e.js +2 -0
  5. package/dist/{chunk-6hmnaza7.js → chunk-13tawjw8.js} +10 -10
  6. package/dist/{chunk-71t0yan0.js → chunk-1e83cj7k.js} +1 -1
  7. package/dist/chunk-1g6pvs7k.js +11 -0
  8. package/dist/chunk-1gvebxh4.js +2 -0
  9. package/dist/{chunk-ferav3bw.js → chunk-1t9g3mhg.js} +2 -2
  10. package/dist/{chunk-ypmqf7tm.js → chunk-2e6xafcm.js} +1 -1
  11. package/dist/chunk-2rfxs7zm.js +2 -0
  12. package/dist/{chunk-qc1f74ek.js → chunk-2vza9m2x.js} +1 -1
  13. package/dist/{chunk-ccspd3mc.js → chunk-2wtn443n.js} +1 -1
  14. package/dist/{chunk-rbb7dvja.js → chunk-34qkshwh.js} +2 -2
  15. package/dist/{chunk-dgrt76d2.js → chunk-3br3pt6k.js} +1 -1
  16. package/dist/{chunk-kdh37tp8.js → chunk-3p0n9ryv.js} +1 -1
  17. package/dist/chunk-437n7hyx.js +2 -0
  18. package/dist/{chunk-de7fye10.js → chunk-461br5nn.js} +1 -1
  19. package/dist/chunk-4tr92e0v.js +2 -0
  20. package/dist/{chunk-t6nseeb9.js → chunk-4vpsvh6x.js} +1 -1
  21. package/dist/{chunk-k56rjjc0.js → chunk-5j9tvhpq.js} +2 -2
  22. package/dist/{chunk-zqqx1qaj.js → chunk-5yp3vt00.js} +1 -1
  23. package/dist/{chunk-kxzb4et3.js → chunk-5zcg61j9.js} +2 -2
  24. package/dist/{chunk-nkb3scg6.js → chunk-6085vha7.js} +1 -1
  25. package/dist/{chunk-wrzwgkbx.js → chunk-72c7gyqc.js} +3 -3
  26. package/dist/chunk-811cxzn4.js +2 -0
  27. package/dist/{chunk-g4vpzv6b.js → chunk-8883pgj8.js} +1 -1
  28. package/dist/{chunk-vqxmxgaj.js → chunk-8bxtvsgm.js} +1 -1
  29. package/dist/{chunk-fvhm8psm.js → chunk-8daczchh.js} +1 -1
  30. package/dist/chunk-91ffbzmh.js +2 -0
  31. package/dist/chunk-96cqevhm.js +2 -0
  32. package/dist/chunk-978faewt.js +2 -0
  33. package/dist/{chunk-866y9d8b.js → chunk-9veqmqb6.js} +1 -1
  34. package/dist/{chunk-7q9mwh4v.js → chunk-a668m28h.js} +1 -1
  35. package/dist/{chunk-pzm13sdc.js → chunk-a9fxxwrv.js} +2 -2
  36. package/dist/chunk-adkjxvy6.js +2 -0
  37. package/dist/{chunk-sscwkffs.js → chunk-agx0620p.js} +1 -1
  38. package/dist/chunk-ak06mywr.js +2 -0
  39. package/dist/chunk-ayaz0wcj.js +2 -0
  40. package/dist/{chunk-1kah92n2.js → chunk-bphx7ngb.js} +2 -2
  41. package/dist/chunk-bw48gj8j.js +2 -0
  42. package/dist/{chunk-csbgwaa5.js → chunk-byq2xpgb.js} +1 -1
  43. package/dist/chunk-bzsjhyet.js +2 -0
  44. package/dist/{chunk-acn1b56m.js → chunk-ch31zddx.js} +2 -2
  45. package/dist/chunk-cqzqfm7m.js +2 -0
  46. package/dist/{chunk-dhh5q7qt.js → chunk-d0f60jrg.js} +2 -2
  47. package/dist/{chunk-8mjdpr94.js → chunk-dcxtrqfy.js} +1 -1
  48. package/dist/{chunk-b6ej2fdf.js → chunk-drbbt69f.js} +35 -10
  49. package/dist/chunk-e0aybavh.js +2 -0
  50. package/dist/chunk-e63a220e.js +28 -0
  51. package/dist/chunk-e67w1bge.js +2 -0
  52. package/dist/chunk-e7kd0ny8.js +2 -0
  53. package/dist/{chunk-9wr7zcad.js → chunk-ee2tfpec.js} +2 -2
  54. package/dist/{chunk-9n0gvfrg.js → chunk-efr3ejqt.js} +1 -1
  55. package/dist/chunk-evfct6hb.js +2 -0
  56. package/dist/{chunk-5w1e3yxs.js → chunk-favq46aa.js} +1 -1
  57. package/dist/{chunk-19nfvxfw.js → chunk-fcfphfpw.js} +2 -2
  58. package/dist/{chunk-b8rrnqry.js → chunk-ffmtamm2.js} +1 -1
  59. package/dist/{chunk-5kk8gsj2.js → chunk-fv923f7g.js} +1 -1
  60. package/dist/{chunk-jr3jp3ev.js → chunk-fvh9ca47.js} +1 -1
  61. package/dist/chunk-fxk9j0rm.js +2 -0
  62. package/dist/{chunk-zg75gjns.js → chunk-gy933rct.js} +1 -1
  63. package/dist/{chunk-r3ayvdz3.js → chunk-h61qt916.js} +1 -1
  64. package/dist/{chunk-v5e1gxwm.js → chunk-h7v70dbp.js} +1 -1
  65. package/dist/{chunk-bz820epz.js → chunk-hmf9z4jx.js} +1 -1
  66. package/dist/{chunk-7b329e5v.js → chunk-hqh7x9h5.js} +2 -2
  67. package/dist/{chunk-h4xh8cms.js → chunk-hv5v6vc2.js} +2 -2
  68. package/dist/{chunk-xttsqmkm.js → chunk-jem20v5k.js} +1 -1
  69. package/dist/{chunk-pkaabd8h.js → chunk-jj6yp7gm.js} +1 -1
  70. package/dist/{chunk-1kms3b9d.js → chunk-jv91rkhx.js} +1 -1
  71. package/dist/{chunk-a0nfbmeh.js → chunk-jyc9eha6.js} +1 -1
  72. package/dist/{chunk-w3ycm4na.js → chunk-k0y7ta0d.js} +1 -1
  73. package/dist/chunk-k4jt9t4p.js +2 -0
  74. package/dist/{chunk-9y0g8kzt.js → chunk-k70fgb2f.js} +1 -1
  75. package/dist/{chunk-74cv4ta1.js → chunk-k78gvm0g.js} +1 -1
  76. package/dist/{chunk-x650vjcp.js → chunk-kb5j08tq.js} +1 -1
  77. package/dist/{chunk-qy73j6m4.js → chunk-kf8t2wq7.js} +1 -1
  78. package/dist/chunk-kfy1jh6p.js +2 -0
  79. package/dist/chunk-kws4rewx.js +17 -0
  80. package/dist/{chunk-nnd4wq8j.js → chunk-mc58fhgm.js} +1 -1
  81. package/dist/{chunk-n3ggrhb3.js → chunk-mjpqz66q.js} +1 -1
  82. package/dist/{chunk-xgnc1wy6.js → chunk-mmnqd035.js} +1 -1
  83. package/dist/{chunk-54st8g2j.js → chunk-mywp77gt.js} +1 -1
  84. package/dist/{chunk-qzkhpsam.js → chunk-n0j85038.js} +1 -1
  85. package/dist/{chunk-se0p17c2.js → chunk-n5y9gh1q.js} +1 -1
  86. package/dist/{chunk-btav940g.js → chunk-n9kk3jz1.js} +1 -1
  87. package/dist/{chunk-248e84r1.js → chunk-nmkra8q5.js} +1 -1
  88. package/dist/{chunk-1q4y74mh.js → chunk-np5dc1q1.js} +1 -1
  89. package/dist/chunk-nygtwffe.js +5 -0
  90. package/dist/{chunk-tndhnk9e.js → chunk-p0zq5ckb.js} +1 -1
  91. package/dist/chunk-pb16azfa.js +4 -0
  92. package/dist/{chunk-nx5qkm8k.js → chunk-ps20v1ah.js} +1 -1
  93. package/dist/chunk-pv9apyrr.js +2 -0
  94. package/dist/{chunk-y11cxbxd.js → chunk-qj2s3r1w.js} +154 -155
  95. package/dist/chunk-qjkzpd68.js +11 -0
  96. package/dist/chunk-qww39be9.js +2 -0
  97. package/dist/chunk-r90w3x6h.js +2 -0
  98. package/dist/chunk-rb87b7kr.js +2 -0
  99. package/dist/{chunk-qr82je1m.js → chunk-rjqfa3g8.js} +2 -2
  100. package/dist/{chunk-2tk1zkrz.js → chunk-sag55qv7.js} +1 -1
  101. package/dist/chunk-srcbkg7g.js +2 -0
  102. package/dist/chunk-sxderfaa.js +12 -0
  103. package/dist/{chunk-38ejahd9.js → chunk-t5c7rk0h.js} +1 -1
  104. package/dist/chunk-v2z3creg.js +2 -0
  105. package/dist/chunk-vtjfv7kg.js +2 -0
  106. package/dist/{chunk-mkd9kjgb.js → chunk-vvqe2gaz.js} +2 -2
  107. package/dist/{chunk-bfqfs07m.js → chunk-vwzqg4fh.js} +2 -2
  108. package/dist/{chunk-vrrax298.js → chunk-vxxxczmn.js} +1 -1
  109. package/dist/chunk-vzzkhjw7.js +2 -0
  110. package/dist/{chunk-wcm80anz.js → chunk-wvq1g6gr.js} +1 -1
  111. package/dist/{chunk-y7m2dpd3.js → chunk-wyxw61az.js} +1 -1
  112. package/dist/{chunk-rj4kajww.js → chunk-xpct12p7.js} +1 -1
  113. package/dist/chunk-xvndd7h6.js +2 -0
  114. package/dist/{chunk-dtq7y5ym.js → chunk-y5jjrnfa.js} +1 -1
  115. package/dist/{chunk-ya386h70.js → chunk-ym4ggcpy.js} +1 -1
  116. package/dist/{chunk-92mj1t26.js → chunk-ymc99r5x.js} +2 -2
  117. package/dist/{chunk-refwkt87.js → chunk-ynt7y2n5.js} +1 -1
  118. package/dist/chunk-z6azwfb4.js +2 -0
  119. package/dist/chunk-zfnabevq.js +2 -0
  120. package/dist/{chunk-y98jsjqq.js → chunk-zqwmy0av.js} +1 -1
  121. package/dist/{chunk-hcq5dw7a.js → chunk-zvw2qgwt.js} +1 -1
  122. package/dist/cli.js +14 -14
  123. package/dist/client-module-registry.d.ts +36 -0
  124. package/dist/client-module-registry.js +55 -0
  125. package/dist/client-script-bundler.d.ts +39 -0
  126. package/dist/client-script-bundler.js +89 -12
  127. package/dist/client-script.js +5 -18
  128. package/dist/craft-entry.js +1 -1
  129. package/dist/craft.js +1 -1
  130. package/dist/database.js +1 -1
  131. package/dist/process.js +24 -3
  132. package/dist/pwa.js +2 -2
  133. package/dist/signal-processing.js +5 -4
  134. package/dist/ssg.js +2 -2
  135. package/dist/store-loader.js +1 -1
  136. package/dist/strip-literals.d.ts +20 -0
  137. package/dist/strip-literals.js +16 -0
  138. package/dist/utils.js +1 -1
  139. package/dist/visual-testing.js +1 -1
  140. package/package.json +5 -5
  141. package/dist/chunk-122tyfre.js +0 -2
  142. package/dist/chunk-24ps8kft.js +0 -2
  143. package/dist/chunk-2et5hxfv.js +0 -2
  144. package/dist/chunk-2r1rd8f0.js +0 -2
  145. package/dist/chunk-3zv4wz87.js +0 -2
  146. package/dist/chunk-4122k1bh.js +0 -2
  147. package/dist/chunk-45az9zht.js +0 -2
  148. package/dist/chunk-4qr85f07.js +0 -2
  149. package/dist/chunk-4ww3znrr.js +0 -15
  150. package/dist/chunk-5a19dhx5.js +0 -2
  151. package/dist/chunk-6gdycmxr.js +0 -2
  152. package/dist/chunk-74v15e8z.js +0 -2
  153. package/dist/chunk-8fwerspy.js +0 -2
  154. package/dist/chunk-9b22663r.js +0 -2
  155. package/dist/chunk-9hjdgm4d.js +0 -2
  156. package/dist/chunk-awkq3xfx.js +0 -2
  157. package/dist/chunk-bs6kapy7.js +0 -2
  158. package/dist/chunk-d8t4sjsp.js +0 -2
  159. package/dist/chunk-dap191q2.js +0 -2
  160. package/dist/chunk-dsffsqnt.js +0 -2
  161. package/dist/chunk-g9csmj0s.js +0 -2
  162. package/dist/chunk-gtcrpmz1.js +0 -2
  163. package/dist/chunk-h8yqsz9m.js +0 -2
  164. package/dist/chunk-hm0xha6c.js +0 -12
  165. package/dist/chunk-jegt35zh.js +0 -2
  166. package/dist/chunk-mxfh1nxg.js +0 -2
  167. package/dist/chunk-nsp1cw38.js +0 -11
  168. package/dist/chunk-p3242nck.js +0 -2
  169. package/dist/chunk-p98kfh94.js +0 -2
  170. package/dist/chunk-q4p5k2p3.js +0 -2
  171. package/dist/chunk-qpyjak7z.js +0 -2
  172. package/dist/chunk-r7r66978.js +0 -2
  173. package/dist/chunk-rp4rjjmf.js +0 -2
  174. package/dist/chunk-sj9pmene.js +0 -2
  175. package/dist/chunk-svpqxn2c.js +0 -2
  176. package/dist/chunk-t8y1ggdy.js +0 -2
  177. package/dist/chunk-xpp135ad.js +0 -11
  178. package/dist/chunk-ydrz60kr.js +0 -2
  179. package/dist/chunk-z4jhj5e5.js +0 -28
package/dist/cli.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{Ha as a,Te as F,Va as r,Ve as v,We as P,nb as n,o as m,oa as l,ob as p,pe as s,qb as i,qe as t,vb as e}from"./chunk-6hmnaza7.js";import"./chunk-19nfvxfw.js";import"./chunk-ferav3bw.js";import"./chunk-n3ggrhb3.js";import"./chunk-k56rjjc0.js";import"./chunk-vqxmxgaj.js";import"./chunk-mkd9kjgb.js";import"./chunk-7b329e5v.js";import"./chunk-pzm13sdc.js";import"./chunk-nx5qkm8k.js";import"./chunk-kxzb4et3.js";import"./chunk-bz820epz.js";import"./chunk-dhh5q7qt.js";import"./chunk-h4xh8cms.js";import"./chunk-qr82je1m.js";import"./chunk-rbb7dvja.js";import"./chunk-248e84r1.js";import"./chunk-w3ycm4na.js";import"./chunk-1kah92n2.js";import"./chunk-zqqx1qaj.js";import"./chunk-74cv4ta1.js";import"./chunk-wcm80anz.js";import"./chunk-y7m2dpd3.js";import"./chunk-9y0g8kzt.js";import"./chunk-t6nseeb9.js";import"./chunk-xttsqmkm.js";import"./chunk-54st8g2j.js";import"./chunk-nsp1cw38.js";import"./chunk-z4jhj5e5.js";import"./chunk-9n0gvfrg.js";import"./chunk-7q9mwh4v.js";import"./chunk-refwkt87.js";import"./chunk-kdh37tp8.js";import"./chunk-866y9d8b.js";import"./chunk-fed3xsp9.js";import"./chunk-a0nfbmeh.js";import"./chunk-9wr7zcad.js";import"./chunk-71t0yan0.js";import"./chunk-58f0mthg.js";import{cl as u,dl as c}from"./chunk-4ww3znrr.js";import"./chunk-y11cxbxd.js";import{Es as f}from"./chunk-92mj1t26.js";import"./chunk-8mjdpr94.js";import"./chunk-pkaabd8h.js";import"./chunk-xpp135ad.js";import{$s as A}from"./chunk-wrzwgkbx.js";import"./chunk-5kk8gsj2.js";import"./chunk-38ejahd9.js";import"./chunk-ypmqf7tm.js";import"./chunk-de7fye10.js";import"./chunk-v5e1gxwm.js";import"./chunk-b6ej2fdf.js";import"./chunk-x650vjcp.js";import{gv as B}from"./chunk-qc1f74ek.js";import{spawn as o}from"child_process";import L from"fs";import zb from"os";import $ from"path";import w from"process";import{CLI as wb}from"@stacksjs/clapp";var N="0.2.287";var __dirname="/home/runner/work/stx/stx/packages/stx/bin",E=new wb("stx");function h(J){let Z=typeof J==="string"?Number.parseInt(J,10):J;if(Number.isNaN(Z))return{isValid:!1,error:"Port must be a valid number",suggestion:"Try using a number between 1024 and 65535"};if(Z<1024||Z>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 d(J){try{if(!L.existsSync(J)){let K=$.dirname(J),x=$.basename(J);if(L.existsSync(K)){let z=L.readdirSync(K).filter((j)=>j.toLowerCase().includes(x.toLowerCase().substring(0,3))||j.endsWith(".stx")||j.endsWith(".md")),k=z.length>0?`File not found. Similar files in ${K}: ${z.slice(0,3).join(", ")}`:`File not found. Directory ${K} exists but doesn't contain the specified file.`;return{isValid:!1,error:`File does not exist: ${J}`,suggestion:k}}return{isValid:!1,error:`File does not exist: ${J}`,suggestion:"Check the file path and try again"}}if(L.statSync(J).isDirectory())return{isValid:!1,error:`Expected file but got directory: ${J}`,suggestion:"Specify a .stx or .md file path"};return{isValid:!0}}catch(Z){return{isValid:!1,error:`Cannot access file: ${J}`,suggestion:"Check file permissions and path"}}}function y(J){let Z=typeof J==="string"?Number.parseInt(J,10):J;if(Number.isNaN(Z))return{isValid:!1,error:"Timeout must be a valid number",suggestion:"Specify timeout in milliseconds (e.g., 5000 for 5 seconds)"};if(Z<100)return{isValid:!1,error:"Timeout too short (minimum 100ms)",suggestion:"Use a timeout of at least 100ms"};if(Z>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 V=(J)=>J.includes("*")||J.includes("?")||J.includes("{")||J.includes("["),jb=(J)=>J.endsWith(".stx")||J.endsWith(".md");function S(J,Z=1){if(console.error(`\u274C ${J.error}`),J.suggestion)console.error(`\uD83D\uDCA1 suggestion: ${J.suggestion}`);w.exit(Z)}function kb(J){if(!J)return;let Z;try{Z=JSON.parse(J)}catch(K){console.error(`\u274C --info-plist is not valid JSON: ${K.message}`),w.exit(1)}if(typeof Z!=="object"||Z===null||Array.isArray(Z))console.error(`\u274C --info-plist must be a JSON object, e.g. '{"NSFocusStatusUsageDescription":"\u2026"}'`),w.exit(1);for(let[K,x]of Object.entries(Z))if(typeof x!=="string"&&typeof x!=="number"&&typeof x!=="boolean")console.error(`\u274C --info-plist value for "${K}" must be a string, number or boolean`),w.exit(1);return Z}async function Hb(J,Z){try{let K=["test"],x=[];if(J&&J.length>0)for(let W of J)if(V(W))try{let H=await Array.fromAsync(new Bun.Glob(W).scan({onlyFiles:!0,absolute:!0}));if(H.length===0)console.warn(`Warning: No files found matching pattern: ${W}`);else if(x.push(...H),Z.verbose)console.log(`Found ${H.length} file(s) matching pattern: ${W}`)}catch(H){return console.error(`Error expanding glob pattern ${W}:`,H),!1}else x.push(W);if(x.length===0)return console.error("Error: No test files found matching the provided patterns."),!1;if(K.push(...x),Z.filter)K.push("--pattern",Z.filter);if(Z.timeout)K.push("--timeout",Z.timeout.toString());if(Z.reporter&&Z.reporter!=="default")if(Z.reporter==="junit"){let W=$.join(zb.tmpdir(),`stx-test-report-${Date.now()}.xml`);K.push("--reporter",Z.reporter),K.push("--reporter-outfile",W)}else console.warn(`Warning: Reporter '${Z.reporter}' is not supported. Using default reporter.`);if(Z.coverage)K.push("--coverage");if(Z.watch)K.push("--watch");K.push("--preload",$.join(__dirname,"../../../test-utils/happy-dom.ts"));let b={...w.env,STX_TEST_MODE:"true",STX_TEST_UI:Z.ui?"true":"false",STX_TEST_VERBOSE:Z.verbose?"true":"false"},z="bun";if(Z.verbose)console.log(`Running: ${z} ${K.join(" ")}`);let k=performance.now(),j=o(z,K,{stdio:"inherit",shell:!1,env:b});return new Promise((W)=>{j.on("close",(H)=>{let Y=((performance.now()-k)/1000).toFixed(2);if(H===0)W(!0);else W(!1)}),w.on("SIGINT",()=>{console.log(`
4
- Test run interrupted`),j.kill("SIGINT"),w.exit(1)})})}catch(K){return console.error("Error running tests:",K instanceof Error?K.message:String(K)),!1}}var Qb=w.argv.length>=3&&(jb(w.argv[2])&&L.existsSync(w.argv[2])||V(w.argv[2]));if(Qb){let J=w.argv[2],Z={port:3000,watch:!0,cache:!0,markdown:{syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0}}};for(let K=3;K<w.argv.length;K++){let x=w.argv[K];if(x==="--port"&&K+1<w.argv.length){let b=h(w.argv[++K]);if(!b.isValid)S(b);Z.port=Number.parseInt(w.argv[K],10)}else if(x==="--no-watch")Z.watch=!1;else if(x==="--highlight-theme"&&K+1<w.argv.length){if(!Z.markdown)Z.markdown={};if(!Z.markdown.syntaxHighlighting)Z.markdown.syntaxHighlighting={};Z.markdown.syntaxHighlighting.defaultTheme=w.argv[++K]}else if(x==="--no-highlight"){if(!Z.markdown)Z.markdown={};if(!Z.markdown.syntaxHighlighting)Z.markdown.syntaxHighlighting={};Z.markdown.syntaxHighlighting.enabled=!1}else if(x==="--no-highlight-unknown"){if(!Z.markdown)Z.markdown={};if(!Z.markdown.syntaxHighlighting)Z.markdown.syntaxHighlighting={};Z.markdown.syntaxHighlighting.highlightUnknownLanguages=!1}else if(x==="--no-cache")Z.cache=!1;else if(x==="--native")Z.native=!0}if(V(J))try{let K=await Array.fromAsync(new Bun.Glob(J).scan({onlyFiles:!0,absolute:!0})),x=J.endsWith(".stx")?K.filter((j)=>j.endsWith(".stx")):J.endsWith(".md")?K.filter((j)=>j.endsWith(".md")):K.filter((j)=>j.endsWith(".stx")||j.endsWith(".md")),b=J.split("*")[0].replace(/\/$/,"")||".",z=$.resolve(b);try{let j=new Bun.Glob("**/*.stx"),H=(await Array.fromAsync(j.scan({cwd:z,onlyFiles:!0,absolute:!0}))).filter((U)=>/\[.+\]/.test($.basename(U)));for(let U of H)if(!x.includes(U))x.push(U)}catch{}if(x.length===0)console.error(`Error: No STX or Markdown files found matching pattern: ${J}`),w.exit(1);if(!await v(x,Z))w.exit(1)}catch(K){console.error("Failed to process files:",K),w.exit(1)}else F(J,Z).catch((K)=>{console.error("Failed to start dev server:",K),w.exit(1)})}else{let J=function(x,b){let z=[];for(let k=0;k<=b.length;k++)z[k]=[k];for(let k=0;k<=x.length;k++)z[0][k]=k;for(let k=1;k<=b.length;k++)for(let j=1;j<=x.length;j++)if(b.charAt(k-1)===x.charAt(j-1))z[k][j]=z[k-1][j-1];else z[k][j]=Math.min(z[k-1][j-1]+1,z[k][j-1]+1,z[k-1][j]+1);return z[b.length][x.length]};E.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(x)=>{try{if(await r(x))console.log("Documentation generated successfully."),w.exit(0);else console.error("Documentation generation failed."),w.exit(1)}catch(b){console.error("Error generating documentation:",b),w.exit(1)}}),E.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(x,b)=>{try{let{fetchCollections:z,generatePackage:k}=await import("./chunk-qzkhpsam.js");if(x==="list"){console.log(`
3
+ import{Ha as a,Te as F,Va as r,Ve as v,We as P,nb as n,o as m,oa as l,ob as p,pe as s,qb as i,qe as t,vb as e}from"./chunk-13tawjw8.js";import"./chunk-5j9tvhpq.js";import"./chunk-a9fxxwrv.js";import"./chunk-ps20v1ah.js";import"./chunk-fcfphfpw.js";import"./chunk-1t9g3mhg.js";import"./chunk-mjpqz66q.js";import"./chunk-hv5v6vc2.js";import"./chunk-34qkshwh.js";import"./chunk-rjqfa3g8.js";import"./chunk-8bxtvsgm.js";import"./chunk-vvqe2gaz.js";import"./chunk-hqh7x9h5.js";import"./chunk-bphx7ngb.js";import"./chunk-5yp3vt00.js";import"./chunk-5zcg61j9.js";import"./chunk-k78gvm0g.js";import"./chunk-hmf9z4jx.js";import"./chunk-d0f60jrg.js";import"./chunk-mywp77gt.js";import"./chunk-nmkra8q5.js";import"./chunk-k0y7ta0d.js";import"./chunk-a668m28h.js";import"./chunk-ynt7y2n5.js";import"./chunk-wvq1g6gr.js";import"./chunk-wyxw61az.js";import"./chunk-k70fgb2f.js";import"./chunk-4vpsvh6x.js";import"./chunk-jem20v5k.js";import"./chunk-1g6pvs7k.js";import"./chunk-e63a220e.js";import"./chunk-efr3ejqt.js";import"./chunk-3p0n9ryv.js";import"./chunk-9veqmqb6.js";import"./chunk-fed3xsp9.js";import"./chunk-jyc9eha6.js";import"./chunk-ee2tfpec.js";import"./chunk-1e83cj7k.js";import"./chunk-58f0mthg.js";import{cl as u,dl as c}from"./chunk-kws4rewx.js";import"./chunk-qj2s3r1w.js";import{Fs as f}from"./chunk-ymc99r5x.js";import"./chunk-dcxtrqfy.js";import"./chunk-jj6yp7gm.js";import"./chunk-qjkzpd68.js";import"./chunk-t5c7rk0h.js";import{et as A}from"./chunk-72c7gyqc.js";import"./chunk-fv923f7g.js";import"./chunk-2e6xafcm.js";import"./chunk-nygtwffe.js";import"./chunk-461br5nn.js";import"./chunk-h7v70dbp.js";import"./chunk-drbbt69f.js";import"./chunk-kb5j08tq.js";import{kv as B}from"./chunk-2vza9m2x.js";import{spawn as o}from"child_process";import L from"fs";import zb from"os";import $ from"path";import w from"process";import{CLI as wb}from"@stacksjs/clapp";var N="0.2.288";var __dirname="/home/runner/work/stx/stx/packages/stx/bin",E=new wb("stx");function h(J){let Z=typeof J==="string"?Number.parseInt(J,10):J;if(Number.isNaN(Z))return{isValid:!1,error:"Port must be a valid number",suggestion:"Try using a number between 1024 and 65535"};if(Z<1024||Z>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 d(J){try{if(!L.existsSync(J)){let K=$.dirname(J),x=$.basename(J);if(L.existsSync(K)){let z=L.readdirSync(K).filter((j)=>j.toLowerCase().includes(x.toLowerCase().substring(0,3))||j.endsWith(".stx")||j.endsWith(".md")),k=z.length>0?`File not found. Similar files in ${K}: ${z.slice(0,3).join(", ")}`:`File not found. Directory ${K} exists but doesn't contain the specified file.`;return{isValid:!1,error:`File does not exist: ${J}`,suggestion:k}}return{isValid:!1,error:`File does not exist: ${J}`,suggestion:"Check the file path and try again"}}if(L.statSync(J).isDirectory())return{isValid:!1,error:`Expected file but got directory: ${J}`,suggestion:"Specify a .stx or .md file path"};return{isValid:!0}}catch(Z){return{isValid:!1,error:`Cannot access file: ${J}`,suggestion:"Check file permissions and path"}}}function y(J){let Z=typeof J==="string"?Number.parseInt(J,10):J;if(Number.isNaN(Z))return{isValid:!1,error:"Timeout must be a valid number",suggestion:"Specify timeout in milliseconds (e.g., 5000 for 5 seconds)"};if(Z<100)return{isValid:!1,error:"Timeout too short (minimum 100ms)",suggestion:"Use a timeout of at least 100ms"};if(Z>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 V=(J)=>J.includes("*")||J.includes("?")||J.includes("{")||J.includes("["),jb=(J)=>J.endsWith(".stx")||J.endsWith(".md");function S(J,Z=1){if(console.error(`\u274C ${J.error}`),J.suggestion)console.error(`\uD83D\uDCA1 suggestion: ${J.suggestion}`);w.exit(Z)}function kb(J){if(!J)return;let Z;try{Z=JSON.parse(J)}catch(K){console.error(`\u274C --info-plist is not valid JSON: ${K.message}`),w.exit(1)}if(typeof Z!=="object"||Z===null||Array.isArray(Z))console.error(`\u274C --info-plist must be a JSON object, e.g. '{"NSFocusStatusUsageDescription":"\u2026"}'`),w.exit(1);for(let[K,x]of Object.entries(Z))if(typeof x!=="string"&&typeof x!=="number"&&typeof x!=="boolean")console.error(`\u274C --info-plist value for "${K}" must be a string, number or boolean`),w.exit(1);return Z}async function Hb(J,Z){try{let K=["test"],x=[];if(J&&J.length>0)for(let W of J)if(V(W))try{let H=await Array.fromAsync(new Bun.Glob(W).scan({onlyFiles:!0,absolute:!0}));if(H.length===0)console.warn(`Warning: No files found matching pattern: ${W}`);else if(x.push(...H),Z.verbose)console.log(`Found ${H.length} file(s) matching pattern: ${W}`)}catch(H){return console.error(`Error expanding glob pattern ${W}:`,H),!1}else x.push(W);if(x.length===0)return console.error("Error: No test files found matching the provided patterns."),!1;if(K.push(...x),Z.filter)K.push("--pattern",Z.filter);if(Z.timeout)K.push("--timeout",Z.timeout.toString());if(Z.reporter&&Z.reporter!=="default")if(Z.reporter==="junit"){let W=$.join(zb.tmpdir(),`stx-test-report-${Date.now()}.xml`);K.push("--reporter",Z.reporter),K.push("--reporter-outfile",W)}else console.warn(`Warning: Reporter '${Z.reporter}' is not supported. Using default reporter.`);if(Z.coverage)K.push("--coverage");if(Z.watch)K.push("--watch");K.push("--preload",$.join(__dirname,"../../../test-utils/happy-dom.ts"));let b={...w.env,STX_TEST_MODE:"true",STX_TEST_UI:Z.ui?"true":"false",STX_TEST_VERBOSE:Z.verbose?"true":"false"},z="bun";if(Z.verbose)console.log(`Running: ${z} ${K.join(" ")}`);let k=performance.now(),j=o(z,K,{stdio:"inherit",shell:!1,env:b});return new Promise((W)=>{j.on("close",(H)=>{let Y=((performance.now()-k)/1000).toFixed(2);if(H===0)W(!0);else W(!1)}),w.on("SIGINT",()=>{console.log(`
4
+ Test run interrupted`),j.kill("SIGINT"),w.exit(1)})})}catch(K){return console.error("Error running tests:",K instanceof Error?K.message:String(K)),!1}}var Qb=w.argv.length>=3&&(jb(w.argv[2])&&L.existsSync(w.argv[2])||V(w.argv[2]));if(Qb){let J=w.argv[2],Z={port:3000,watch:!0,cache:!0,markdown:{syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0}}};for(let K=3;K<w.argv.length;K++){let x=w.argv[K];if(x==="--port"&&K+1<w.argv.length){let b=h(w.argv[++K]);if(!b.isValid)S(b);Z.port=Number.parseInt(w.argv[K],10)}else if(x==="--no-watch")Z.watch=!1;else if(x==="--highlight-theme"&&K+1<w.argv.length){if(!Z.markdown)Z.markdown={};if(!Z.markdown.syntaxHighlighting)Z.markdown.syntaxHighlighting={};Z.markdown.syntaxHighlighting.defaultTheme=w.argv[++K]}else if(x==="--no-highlight"){if(!Z.markdown)Z.markdown={};if(!Z.markdown.syntaxHighlighting)Z.markdown.syntaxHighlighting={};Z.markdown.syntaxHighlighting.enabled=!1}else if(x==="--no-highlight-unknown"){if(!Z.markdown)Z.markdown={};if(!Z.markdown.syntaxHighlighting)Z.markdown.syntaxHighlighting={};Z.markdown.syntaxHighlighting.highlightUnknownLanguages=!1}else if(x==="--no-cache")Z.cache=!1;else if(x==="--native")Z.native=!0}if(V(J))try{let K=await Array.fromAsync(new Bun.Glob(J).scan({onlyFiles:!0,absolute:!0})),x=J.endsWith(".stx")?K.filter((j)=>j.endsWith(".stx")):J.endsWith(".md")?K.filter((j)=>j.endsWith(".md")):K.filter((j)=>j.endsWith(".stx")||j.endsWith(".md")),b=J.split("*")[0].replace(/\/$/,"")||".",z=$.resolve(b);try{let j=new Bun.Glob("**/*.stx"),H=(await Array.fromAsync(j.scan({cwd:z,onlyFiles:!0,absolute:!0}))).filter((U)=>/\[.+\]/.test($.basename(U)));for(let U of H)if(!x.includes(U))x.push(U)}catch{}if(x.length===0)console.error(`Error: No STX or Markdown files found matching pattern: ${J}`),w.exit(1);if(!await v(x,Z))w.exit(1)}catch(K){console.error("Failed to process files:",K),w.exit(1)}else F(J,Z).catch((K)=>{console.error("Failed to start dev server:",K),w.exit(1)})}else{let J=function(x,b){let z=[];for(let k=0;k<=b.length;k++)z[k]=[k];for(let k=0;k<=x.length;k++)z[0][k]=k;for(let k=1;k<=b.length;k++)for(let j=1;j<=x.length;j++)if(b.charAt(k-1)===x.charAt(j-1))z[k][j]=z[k-1][j-1];else z[k][j]=Math.min(z[k-1][j-1]+1,z[k][j-1]+1,z[k-1][j]+1);return z[b.length][x.length]};E.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(x)=>{try{if(await r(x))console.log("Documentation generated successfully."),w.exit(0);else console.error("Documentation generation failed."),w.exit(1)}catch(b){console.error("Error generating documentation:",b),w.exit(1)}}),E.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(x,b)=>{try{let{fetchCollections:z,generatePackage:k}=await import("./chunk-n0j85038.js");if(x==="list"){console.log(`
5
5
  \uD83D\uDCDA Fetching available icon collections...
6
6
  `);let j=await z(),W=Object.entries(j).sort((H,U)=>U[1].total-H[1].total);console.log(`Available collections:
7
7
  `);for(let[H,U]of W){let Y=U;console.log(` ${H.padEnd(30)} ${Y.name} (${Y.total} icons)`)}console.log(`
8
8
  Total: ${W.length} collections`)}else if(x.startsWith("generate")){let j=x==="generate"?"":x.replace("generate:","").replace("generate-","").replace("generate","").trim();if(!j)console.error("Error: Please specify a collection prefix"),console.error("Usage: stx iconify generate <prefix> [--icons icon1,icon2,...]"),w.exit(1);let W=b.output||$.join(w.cwd(),"packages/collections"),H=b.icons?b.icons.split(",").map((U)=>U.trim()):void 0;await k(j,W,H),console.log(`
9
9
  \u2713 Package generated successfully!`),console.log(`
10
- To use the package:`),console.log(` 1. cd packages/collections/iconify-${j}`),console.log(" 2. bun install"),console.log(" 3. bun run build")}else console.error(`Unknown iconify command: ${x}`),console.error("Available commands: list, generate"),w.exit(1)}catch(z){console.error("Error:",z instanceof Error?z.message:String(z)),w.exit(1)}}),E.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(x,b)=>{try{if(x==="audit"){let{runPwaAudit:z,formatAuditResult:k}=await import("./chunk-tndhnk9e.js"),{loadConfig:j}=await import("./chunk-ydrz60kr.js");console.log(`
10
+ To use the package:`),console.log(` 1. cd packages/collections/iconify-${j}`),console.log(" 2. bun install"),console.log(" 3. bun run build")}else console.error(`Unknown iconify command: ${x}`),console.error("Available commands: list, generate"),w.exit(1)}catch(z){console.error("Error:",z instanceof Error?z.message:String(z)),w.exit(1)}}),E.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(x,b)=>{try{if(x==="audit"){let{runPwaAudit:z,formatAuditResult:k}=await import("./chunk-p0zq5ckb.js"),{loadConfig:j}=await import("./chunk-cqzqfm7m.js");console.log(`
11
11
  \uD83D\uDD0D Running PWA audit...
12
12
  `);let W=await j(),H=b.output||"dist",U=z(W,H);if(console.log(k(U)),U.failed>0)w.exit(1)}else console.error(`Unknown pwa command: ${x}`),console.error("Available commands: audit"),w.exit(1)}catch(z){console.error("Error:",z instanceof Error?z.message:String(z)),w.exit(1)}}),E.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(x,b)=>{try{if(b.port!==void 0){let k=h(b.port);if(!k.isValid)S(k);b.port=Number.parseInt(String(b.port),10)}if(b.timeout!==void 0){let k=y(b.timeout);if(!k.isValid)S(k)}let z={syntaxHighlighting:{enabled:b.highlight!==!1,serverSide:!0,defaultTheme:b.highlightTheme||"github-dark",highlightUnknownLanguages:b.highlightUnknown!==!1}};if(!x){if(!await P(".",{port:b.port,watch:b.watch!==!1,native:b.native||b.titlebarHidden||!1,titlebarHidden:b.titlebarHidden===!0,cache:b.cache!==!1,hotReload:b.hmr!==!1,profile:b.profile===!0,debugDirectives:b.debugDirectives===!0,...b.pages&&{pagesDir:b.pages}}))w.exit(1);return}if(!V(x))try{let k=await import("fs");if(k.existsSync(x)&&k.statSync(x).isDirectory()){if(!await P(x,{port:b.port,watch:b.watch!==!1,native:b.native||b.titlebarHidden||!1,titlebarHidden:b.titlebarHidden===!0,cache:b.cache!==!1,hotReload:b.hmr!==!1,profile:b.profile===!0,debugDirectives:b.debugDirectives===!0,...b.pages&&{pagesDir:b.pages}}))w.exit(1);return}}catch{}if(V(x)){console.log(`Expanding glob pattern: ${x}`);let k=await A.timeAsync("glob-expansion",async()=>{return Array.fromAsync(new Bun.Glob(x).scan({onlyFiles:!0,absolute:!0}))}),j=x.endsWith(".stx")?k.filter((Y)=>Y.endsWith(".stx")):x.endsWith(".md")?k.filter((Y)=>Y.endsWith(".md")):k.filter((Y)=>Y.endsWith(".stx")||Y.endsWith(".md"));if(j.length===0)console.error(`No STX or Markdown files found matching pattern: ${x}`),console.error("Try using patterns like '*.stx' or 'components/**/*.stx'"),w.exit(1);let W=x.split("*")[0].replace(/\/$/,"")||".",H=$.resolve(W);try{let Y=new Bun.Glob("**/*.stx"),X=(await Array.fromAsync(Y.scan({cwd:H,onlyFiles:!0,absolute:!0}))).filter((_)=>/\[.+\]/.test($.basename(_)));for(let _ of X)if(!j.includes(_))j.push(_)}catch{}if(console.log(`Found ${j.length} ${j.length===1?"file":"files"} matching ${x}`),!await v(j,{port:b.port,watch:b.watch!==!1,native:b.native||b.titlebarHidden||!1,titlebarHidden:b.titlebarHidden===!0,markdown:z,cache:b.cache!==!1}))w.exit(1)}else{if(!V(x)){let j=d(x);if(!j.isValid)S(j)}if(!await F(x,{port:b.port,watch:b.watch!==!1,native:b.native||b.titlebarHidden||!1,titlebarHidden:b.titlebarHidden===!0,markdown:z,cache:b.cache!==!1}))w.exit(1)}}catch(z){console.error("Error starting dev server:",z),w.exit(1)}}),E.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(x=".",b)=>{try{console.log(`Scanning ${x} for accessibility issues...`);let z=b.ignore?b.ignore.split(",").map((U)=>U.trim()):[],{results:k,scannedFiles:j}=await f(x,{recursive:b.recursive!==!1,ignorePaths:z});if(j.length===0)console.log(`
13
13
  No .stx files matched ${x}
@@ -69,7 +69,7 @@ Total: ${H} issues in ${W} files`),b.output){let U=`
69
69
  File not found: ${x}`),w.exit(1);if(!x.endsWith(".stx"))console.error(`
70
70
  File must have .stx extension: ${x}`),w.exit(1)}let k=$.resolve(b.pages),j=$.resolve(b.out);if(!x&&!L.existsSync(k))console.error(`
71
71
  Pages directory not found: ${k}`),console.log(`
72
- Create a 'pages' directory with .stx files, or use --pages to specify a different directory.`),w.exit(1);let{buildApp:W}=await import("./chunk-gtcrpmz1.js");c();let H=await W({root:x?$.dirname(x):void 0,debug:b.verbose,ssg:{pagesDir:b.pages,outputDir:b.out,domain:b.domain,baseUrl:b.base,sitemap:b.sitemap,rss:b.rss,minify:b.minify,cache:b.cache!==!1,cleanOutput:b.clean,concurrency:Number.parseInt(b.concurrency,10)||10,publicDir:b.public,trailingSlash:b.trailingSlash,generate404:!0,hooks:b.verbose?{onPageStart:(Y)=>console.log(` Generating: ${Y}`),onPageEnd:(Y,Q)=>console.log(` Generated: ${Y} (${Q.length} bytes)`),onError:(Y,Q)=>console.error(` Error in ${Q}: ${Y.message}`)}:void 0},ssr:{outputDir:b.out==="dist"?".output":b.out,debug:b.verbose}}),U=((performance.now()-z)/1000).toFixed(2);if(H.mode==="ssr"&&H.ssr)console.log(`
72
+ Create a 'pages' directory with .stx files, or use --pages to specify a different directory.`),w.exit(1);let{buildApp:W}=await import("./chunk-srcbkg7g.js");c();let H=await W({root:x?$.dirname(x):void 0,debug:b.verbose,ssg:{pagesDir:b.pages,outputDir:b.out,domain:b.domain,baseUrl:b.base,sitemap:b.sitemap,rss:b.rss,minify:b.minify,cache:b.cache!==!1,cleanOutput:b.clean,concurrency:Number.parseInt(b.concurrency,10)||10,publicDir:b.public,trailingSlash:b.trailingSlash,generate404:!0,hooks:b.verbose?{onPageStart:(Y)=>console.log(` Generating: ${Y}`),onPageEnd:(Y,Q)=>console.log(` Generated: ${Y} (${Q.length} bytes)`),onError:(Y,Q)=>console.error(` Error in ${Q}: ${Y.message}`)}:void 0},ssr:{outputDir:b.out==="dist"?".output":b.out,debug:b.verbose}}),U=((performance.now()-z)/1000).toFixed(2);if(H.mode==="ssr"&&H.ssr)console.log(`
73
73
  Build complete! (SSR)
74
74
  `),console.log(` Pages compiled: ${H.ssr.pageCount}`),console.log(` Output: ${H.ssr.outputDir}`),console.log(` Duration: ${U}s
75
75
  `);else if(H.ssg){if(console.log(`
@@ -84,8 +84,8 @@ Total: ${H} issues in ${W} files`),b.output){let U=`
84
84
  Build completed with ${H.ssg.failedCount} error(s). Fix the issues above and try again.
85
85
  `),w.exit(1);console.log(" To preview locally:"),console.log(` cd ${b.out||"dist"} && npx serve
86
86
  `)}}catch(z){console.error(`
87
- Build failed:`,z instanceof Error?z.message:String(z)),w.exit(1)}}),E.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(x)=>{try{let b=$.resolve(x.output);if(!L.existsSync($.join(b,"manifest.json")))console.error("\n No production build found. Run `stx build --out .output` first.\n"),w.exit(1);let{startProductionServer:z}=await import("./chunk-p3242nck.js");await z({outputDir:b,port:Number.parseInt(x.port,10)||3000})}catch(b){console.error(`
88
- Failed to start production server:`,b instanceof Error?b.message:String(b)),w.exit(1)}}),E.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(x,b)=>{try{let{deploy:z,initNetlify:k,DeployError:j}=await import("./chunk-btav940g.js");if(console.log(`\x1B[1mstx deploy\x1B[0m \x1B[2mv${N}\x1B[0m`),b.init){console.log(`
87
+ Build failed:`,z instanceof Error?z.message:String(z)),w.exit(1)}}),E.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(x)=>{try{let b=$.resolve(x.output);if(!L.existsSync($.join(b,"manifest.json")))console.error("\n No production build found. Run `stx build --out .output` first.\n"),w.exit(1);let{startProductionServer:z}=await import("./chunk-0896td83.js");await z({outputDir:b,port:Number.parseInt(x.port,10)||3000})}catch(b){console.error(`
88
+ Failed to start production server:`,b instanceof Error?b.message:String(b)),w.exit(1)}}),E.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(x,b)=>{try{let{deploy:z,initNetlify:k,DeployError:j}=await import("./chunk-n9kk3jz1.js");if(console.log(`\x1B[1mstx deploy\x1B[0m \x1B[2mv${N}\x1B[0m`),b.init){console.log(`
89
89
  \uD83D\uDCDD Initializing Netlify configuration...
90
90
  `);let H=await k({directory:x||w.cwd(),siteId:b.siteId});if(console.log(`\u2713 Created ${H.configPath}`),H.siteId)console.log("\u2713 Saved site ID to .env.local");console.log(`
91
91
  You can now deploy with: stx deploy`);return}if(b.build!==!1){if(console.log(`
@@ -97,7 +97,7 @@ You can now deploy with: stx deploy`);return}if(b.build!==!1){if(console.log(`
97
97
  `),console.log(` ${b.dryRun?"Would deploy":"Draft URL"}: ${W.url}`),W.siteUrl)console.log(` Site URL: ${W.siteUrl}`);if(!b.dryRun)console.log(`
98
98
  Deploy ID: ${W.deployId}`),console.log(` Duration: ${(W.duration/1000).toFixed(1)}s`),console.log(` Files: ${W.filesUploaded}`)}}catch(z){if(z instanceof Error&&z.name==="DeployError")console.error(`
99
99
  \u274C ${z.message}`),w.exit(1);console.error(`
100
- \u274C Deploy failed:`,z instanceof Error?z.message:String(z)),w.exit(1)}}),E.command("images <input>","Optimize images for production").option("-o, --output <dir>","Output directory",{default:"dist/images"}).option("-w, --widths <sizes>","Output widths (comma-separated)",{default:"320,640,768,1024,1280,1536,1920"}).option("-f, --formats <types>","Output formats (comma-separated)",{default:"webp,jpeg"}).option("-q, --quality <n>","Output quality (1-100)",{default:"80"}).option("--placeholder <type>","Placeholder type: blur, dominant-color, none",{default:"none"}).option("--dry-run","Preview without processing").option("--verbose","Show detailed output").example("stx images public/images").example("stx images public/images -o dist/images").example("stx images public/images --widths 640,1024,1920").example("stx images public/images --formats webp,avif").example("stx images public/images --quality 85").example("stx images public/images --dry-run").action(async(x,b)=>{try{let{optimizeDirectory:z,isSharpAvailable:k,formatSize:j}=await import("./chunk-csbgwaa5.js"),W=await import("fs"),H=await import("path");if(console.log(`\x1B[1mstx images\x1B[0m \x1B[2mv${N}\x1B[0m`),!await k())console.error(`
100
+ \u274C Deploy failed:`,z instanceof Error?z.message:String(z)),w.exit(1)}}),E.command("images <input>","Optimize images for production").option("-o, --output <dir>","Output directory",{default:"dist/images"}).option("-w, --widths <sizes>","Output widths (comma-separated)",{default:"320,640,768,1024,1280,1536,1920"}).option("-f, --formats <types>","Output formats (comma-separated)",{default:"webp,jpeg"}).option("-q, --quality <n>","Output quality (1-100)",{default:"80"}).option("--placeholder <type>","Placeholder type: blur, dominant-color, none",{default:"none"}).option("--dry-run","Preview without processing").option("--verbose","Show detailed output").example("stx images public/images").example("stx images public/images -o dist/images").example("stx images public/images --widths 640,1024,1920").example("stx images public/images --formats webp,avif").example("stx images public/images --quality 85").example("stx images public/images --dry-run").action(async(x,b)=>{try{let{optimizeDirectory:z,isSharpAvailable:k,formatSize:j}=await import("./chunk-byq2xpgb.js"),W=await import("fs"),H=await import("path");if(console.log(`\x1B[1mstx images\x1B[0m \x1B[2mv${N}\x1B[0m`),!await k())console.error(`
101
101
  \u274C sharp is required for image optimization.`),console.log(`
102
102
  Install sharp with:`),console.log(" bun add sharp"),w.exit(1);let Y=b.widths.split(",").map((G)=>Number.parseInt(G.trim(),10)).filter((G)=>!Number.isNaN(G)),Q=b.formats.split(",").map((G)=>G.trim().toLowerCase()),X=Number.parseInt(b.quality,10)||80,_=b.placeholder,q=H.resolve(x);if(!W.existsSync(q))console.error(`
103
103
  \u274C Input directory not found: ${q}`),w.exit(1);if(!W.statSync(q).isDirectory())console.error(`
@@ -110,7 +110,7 @@ Would generate ~${bb} image variants`);return}console.log(`
110
110
  `);let M=await z(q,b.output,{widths:Y,formats:Q,quality:X,placeholder:_,verbose:b.verbose});if(console.log(`
111
111
  \u2713 Optimization complete!
112
112
  `),console.log(` Images processed: ${M.stats.optimizedImages}/${M.stats.totalImages}`),console.log(` Variants created: ${M.stats.variants}`),M.stats.savedBytes>0)console.log(` Estimated savings: ~${j(M.stats.savedBytes)}`)}catch(z){console.error(`
113
- \u274C Image optimization failed:`,z instanceof Error?z.message:String(z)),w.exit(1)}}),E.command("bundle [directory]","Analyze bundle size and composition").option("-o, --output <file>","Output file path").option("--json","Output as JSON").option("--text","Output as text summary").option("--markdown","Output as Markdown").option("--no-open","Do not open HTML report in browser").option("--no-gzip","Do not show gzip sizes").option("--threshold <size>","Fail if total size exceeds threshold (e.g., 500KB, 1MB)").option("--top <n>","Number of top modules to show",{default:"20"}).example("stx bundle").example("stx bundle dist/").example("stx bundle dist/ --json").example("stx bundle dist/ --text").example("stx bundle dist/ --threshold 500KB").example("stx bundle dist/ --no-open").action(async(x,b)=>{try{let{analyze:z,formatBytes:k,parseSize:j}=await import("./chunk-5w1e3yxs.js"),W=await import("path");console.log(`\x1B[1mstx bundle\x1B[0m \x1B[2mv${N}\x1B[0m`);let H=x||"dist",U=W.resolve(H);if(!(await import("fs")).existsSync(U))console.error(`
113
+ \u274C Image optimization failed:`,z instanceof Error?z.message:String(z)),w.exit(1)}}),E.command("bundle [directory]","Analyze bundle size and composition").option("-o, --output <file>","Output file path").option("--json","Output as JSON").option("--text","Output as text summary").option("--markdown","Output as Markdown").option("--no-open","Do not open HTML report in browser").option("--no-gzip","Do not show gzip sizes").option("--threshold <size>","Fail if total size exceeds threshold (e.g., 500KB, 1MB)").option("--top <n>","Number of top modules to show",{default:"20"}).example("stx bundle").example("stx bundle dist/").example("stx bundle dist/ --json").example("stx bundle dist/ --text").example("stx bundle dist/ --threshold 500KB").example("stx bundle dist/ --no-open").action(async(x,b)=>{try{let{analyze:z,formatBytes:k,parseSize:j}=await import("./chunk-favq46aa.js"),W=await import("path");console.log(`\x1B[1mstx bundle\x1B[0m \x1B[2mv${N}\x1B[0m`);let H=x||"dist",U=W.resolve(H);if(!(await import("fs")).existsSync(U))console.error(`
114
114
  \u274C Directory not found: ${U}`),console.log("\nRun `stx build` first to generate build output."),w.exit(1);let Q="html";if(b.json)Q="json";else if(b.text)Q="text";else if(b.markdown)Q="markdown";console.log(`
115
115
  \uD83D\uDCE6 Analyzing: ${U}`);let X=await z({directory:U,output:b.output,format:Q,open:b.open!==!1&&Q==="html",gzip:b.gzip!==!1,threshold:b.threshold,topModules:Number.parseInt(b.top||"20",10),recommendations:!0});if(Q==="html"){if(console.log(`
116
116
  \u2713 Report generated: ${X.outputPath}`),b.open!==!1)console.log(" Opening in browser...")}else console.log(X.report);if(X.exceedsThreshold){let _=b.threshold;console.error(`
@@ -124,7 +124,7 @@ To view it in the development server:`),console.log(` stx dev ${x}
124
124
  \uD83D\uDCDD ${$.relative(w.cwd(),Q)}:`),console.log("--- Original"),console.log("+++ Formatted"),console.log(`@@ Changes in ${$.basename(Q)} @@`),console.log("+ Formatted content would be applied");else await Bun.write(Q,q),console.log(`\u2705 Formatted ${$.relative(w.cwd(),Q)}`),U++}catch(X){console.error(`\u274C Error formatting ${$.relative(w.cwd(),Q)}:`,X),Y++}if(b.check&&Y>0)console.log(`
125
125
  ${Y} files need formatting. Run 'stx format' to fix.`),w.exit(1);else if(!b.check&&!b.diff)console.log(`\u2728 Formatted ${U} files successfully`)}catch(z){console.error("Error formatting files:",z),w.exit(1)}}),E.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(x,b)=>{try{if(b.clear){A.clear(),console.log("\u2705 Performance statistics cleared");return}let z=A.getStats();if(Object.keys(z).length===0){if(b.json){console.log(JSON.stringify({},null,2));return}console.log("No performance data available. Run some STX commands first.");return}if(b.json)console.log(JSON.stringify(z,null,2));else{console.log(`
126
126
  \uD83D\uDCCA STX Performance Statistics
127
- `);for(let[k,j]of Object.entries(z))console.log(`\uD83D\uDD27 ${k}:`),console.log(` Count: ${j.count}`),console.log(` Average: ${j.avgTime.toFixed(2)}ms`),console.log(` Total: ${j.totalTime.toFixed(2)}ms`),console.log(` Min: ${j.minTime.toFixed(2)}ms`),console.log(` Max: ${j.maxTime.toFixed(2)}ms`),console.log("")}}catch(z){console.error("Error showing performance stats:",z),w.exit(1)}}),E.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(x,b)=>{let{formatTypecheckDiagnostics:z,typecheckStxFiles:k}=await import("./chunk-p98kfh94.js"),{resolveStxTargets:j}=await import("./chunk-h8yqsz9m.js"),W=Array.isArray(x)?x:x?[x]:[],H=W.length?W:["**/*.stx"],U=await j(H);if(U.length===0){console.log(`
127
+ `);for(let[k,j]of Object.entries(z))console.log(`\uD83D\uDD27 ${k}:`),console.log(` Count: ${j.count}`),console.log(` Average: ${j.avgTime.toFixed(2)}ms`),console.log(` Total: ${j.totalTime.toFixed(2)}ms`),console.log(` Min: ${j.minTime.toFixed(2)}ms`),console.log(` Max: ${j.maxTime.toFixed(2)}ms`),console.log("")}}catch(z){console.error("Error showing performance stats:",z),w.exit(1)}}),E.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(x,b)=>{let{formatTypecheckDiagnostics:z,typecheckStxFiles:k}=await import("./chunk-zfnabevq.js"),{resolveStxTargets:j}=await import("./chunk-1gvebxh4.js"),W=Array.isArray(x)?x:x?[x]:[],H=W.length?W:["**/*.stx"],U=await j(H);if(U.length===0){console.log(`
128
128
  No .stx files matched ${H.join(", ")}
129
129
  `);return}let Y=m(w.argv,"--lib"),Q=Y.length>0?Y:b.lib?Array.isArray(b.lib)?b.lib:[b.lib]:[],X=await k(U,{client:b.client!==!1,server:b.server!==!1,templates:b.templates!==!1,extraLibs:Q});if(X.failure)console.error(`
130
130
  Type-check did not run.
@@ -135,8 +135,8 @@ ${Y} files need formatting. Run 'stx format' to fix.`),w.exit(1);else if(!b.chec
135
135
  `),w.exit(2);let _=X.diagnostics.filter((q)=>q.category==="error");if(X.diagnostics.length>0)console.error(`
136
136
  ${z(X.diagnostics)}
137
137
  `);if(console.log(` Checked ${X.blockCount} script block(s) and ${X.expressionCount} template expression(s) in ${X.checkedFiles.length} file(s) \u2014 `+`${_.length} error(s), ${X.diagnostics.length-_.length} warning(s)
138
- `),_.length>0)w.exit(1)}),E.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(x,b)=>{let{codemodSource:z,formatCodemodFindings:k}=await import("./chunk-nkb3scg6.js"),j=globalThis.Bun.Glob,W=Array.isArray(x)?x:x?[x]:[],H=W.length?W:["**/*.stx","**/*.ts"],U=b.rule?[b.rule]:void 0;if(b.rule&&b.rule!=="confirm"&&b.rule!=="tooltip")console.error(`Unknown rule "${b.rule}". Expected: confirm | tooltip`),w.exit(1);let Y=new Set,Q=[],X=0,_=new Set;try{let q=Bun.spawnSync(["git","ls-files","--others","--ignored","--exclude-standard","-z"],{cwd:w.cwd(),stdout:"pipe",stderr:"pipe"});for(let O of new TextDecoder().decode(q.stdout).split("\x00"))if(O)_.add($.resolve(w.cwd(),O))}catch{}for(let q of H)for await(let O of new j(q).scan({cwd:w.cwd(),absolute:!0})){if(O.includes("/node_modules/")||O.includes("/dist/")||Y.has(O)||_.has(O))continue;Y.add(O);let M=await Bun.file(O).text(),G=z(M,{file:O,rules:U});if(Q.push(...G.findings),b.fix&&G.code!==M)await Bun.write(O,G.code),X++}if(console.error(k(Q,Boolean(b.fix))),b.fix)console.error(`
139
- ${X} file(s) written.`)}),E.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(x)=>{try{let b;try{b=(await import("./chunk-zg75gjns.js")).generateSignalsRuntime}catch{b=void 0}let z=await s({generateRuntime:b});if(x.json)console.log(JSON.stringify(z,null,2));else console.log(t(z));if(!z.ok)w.exit(1)}catch(b){console.error("Error running doctor:",b),w.exit(1)}}),E.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(x,b)=>{try{let z=d(x);if(!z.isValid)S(z);console.log(`\uD83D\uDD0D Debugging stx template: ${x}
138
+ `),_.length>0)w.exit(1)}),E.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(x,b)=>{let{codemodSource:z,formatCodemodFindings:k}=await import("./chunk-6085vha7.js"),j=globalThis.Bun.Glob,W=Array.isArray(x)?x:x?[x]:[],H=W.length?W:["**/*.stx","**/*.ts"],U=b.rule?[b.rule]:void 0;if(b.rule&&b.rule!=="confirm"&&b.rule!=="tooltip")console.error(`Unknown rule "${b.rule}". Expected: confirm | tooltip`),w.exit(1);let Y=new Set,Q=[],X=0,_=new Set;try{let q=Bun.spawnSync(["git","ls-files","--others","--ignored","--exclude-standard","-z"],{cwd:w.cwd(),stdout:"pipe",stderr:"pipe"});for(let O of new TextDecoder().decode(q.stdout).split("\x00"))if(O)_.add($.resolve(w.cwd(),O))}catch{}for(let q of H)for await(let O of new j(q).scan({cwd:w.cwd(),absolute:!0})){if(O.includes("/node_modules/")||O.includes("/dist/")||Y.has(O)||_.has(O))continue;Y.add(O);let M=await Bun.file(O).text(),G=z(M,{file:O,rules:U});if(Q.push(...G.findings),b.fix&&G.code!==M)await Bun.write(O,G.code),X++}if(console.error(k(Q,Boolean(b.fix))),b.fix)console.error(`
139
+ ${X} file(s) written.`)}),E.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(x)=>{try{let b;try{b=(await import("./chunk-gy933rct.js")).generateSignalsRuntime}catch{b=void 0}let z=await s({generateRuntime:b});if(x.json)console.log(JSON.stringify(z,null,2));else console.log(t(z));if(!z.ok)w.exit(1)}catch(b){console.error("Error running doctor:",b),w.exit(1)}}),E.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(x,b)=>{try{let z=d(x);if(!z.isValid)S(z);console.log(`\uD83D\uDD0D Debugging stx template: ${x}
140
140
  `);let k={};if(b.context)try{k=JSON.parse(b.context)}catch(H){console.error("\u274C Invalid JSON in --context option"),w.exit(1)}let j=await Bun.file(x).text();console.log(`\uD83D\uDCC4 Template Content (${j.length} chars):`),console.log("\u2500".repeat(50)),console.log(j.substring(0,500)+(j.length>500?`
141
141
  ...
142
142
  `:"")),console.log("\u2500".repeat(50));let W=j.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(W)console.log(`
@@ -159,12 +159,12 @@ Press Ctrl+C to stop watching...
159
159
  \uD83D\uDCDD ${$.relative(w.cwd(),Q.file)}`),console.log(` Lines: ${Q.metrics.lines} | Complexity: ${Q.metrics.complexity}/10 | Estimated render: ${Q.performance.estimatedRenderTime}ms`),Q.issues.length>0){let X=Q.issues.filter((_)=>j[_.type]>=W);if(X.length>0)console.log(` Issues (${X.length}):`),X.forEach((_)=>{let q=_.type==="error"?"\u274C":_.type==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";if(console.log(` ${q} ${_.message}`),_.suggestion)console.log(` \uD83D\uDCA1 ${_.suggestion}`)})}if(Q.suggestions.length>0)console.log(` Suggestions (${Q.suggestions.length}):`),Q.suggestions.forEach((X)=>{let _=X.impact==="high"?"\uD83D\uDD25":X.impact==="medium"?"\u26A1":"\uD83D\uDCAB";console.log(` ${_} ${X.message} (${X.impact} impact, ${X.effort} effort)`)})}}else if(Y.length>0&&!b.onlyIssues)console.log(`
160
160
  \uD83D\uDCC4 Files with issues:`),Y.forEach((Q)=>{let X=Q.issues.filter((_)=>j[_.type]>=W).length;if(X>0)console.log(` ${$.relative(w.cwd(),Q.file)} (${X} issues)`)});if(b.saveReport){let Q={summary:U,results:Y,generatedAt:new Date().toISOString(),commandOptions:b};await Bun.write(b.saveReport,JSON.stringify(Q,null,2)),console.log(`
161
161
  \uD83D\uDCCB Analysis report saved to: ${b.saveReport}`)}console.log(`
162
- \u2728 Analysis complete! Use --detailed for more information.`)}catch(z){console.error("Error analyzing templates:",z),w.exit(1)}}),E.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(x,b)=>{let{captureScreenshots:z}=await import("./chunk-24ps8kft.js"),k=x||"dist";try{let j=await z(k,b.out,{width:Number.parseInt(b.width,10),height:Number.parseInt(b.height,10),waitMs:Number.parseInt(b.wait,10),timeoutMs:Number.parseInt(b.timeout,10),fullPage:Boolean(b.fullPage),waitSelector:b.waitSelector,format:b.format,backend:b.backend});for(let W of j)console.log(`\uD83D\uDCF8 ${W.output} (${(W.bytes/1024).toFixed(0)} KB)`);console.log(`
163
- \u2728 Captured ${j.length} screenshot(s) to ${b.out}/ via Bun WebView`)}catch(j){console.error(`Screenshot failed: ${j.message}`),w.exit(1)}}),E.command("version","Show the version of the CLI").action(()=>{console.log(N)}),E.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(x)=>{let{startInteractive:b}=await import("./chunk-122tyfre.js"),z={};if(x.context){let k=$.resolve(x.context);if(L.existsSync(k))try{let j=L.readFileSync(k,"utf-8");z=JSON.parse(j)}catch(j){console.error("Error loading context file:",j),w.exit(1)}else console.error(`Context file not found: ${k}`),w.exit(1)}await b({context:z,cwd:x.cwd?$.resolve(x.cwd):w.cwd(),verbose:x.verbose})}),E.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(x,b)=>{try{let{buildNative:z,getAvailableTargets:k,getAvailableFormats:j}=await import("./chunk-3zv4wz87.js"),W=$.resolve(x);if(!L.existsSync(W))console.error(`\u274C Input file not found: ${x}`),w.exit(1);let H=k();if(b.target&&!["macos","windows","linux","ios","android"].includes(b.target))console.error(`\u274C Invalid target: ${b.target}`),console.error("\uD83D\uDCA1 Available targets: macos, windows, linux, ios, android"),console.error(`\uD83D\uDCA1 Targets available on this machine: ${H.join(", ")}`),w.exit(1);let U=b.target||H[0],Y=j(U);if(b.format&&!Y.includes(b.format))console.error(`\u274C Invalid format for ${U}: ${b.format}`),console.error(`\uD83D\uDCA1 Available formats: ${Y.join(", ")}`),w.exit(1);console.log(`
162
+ \u2728 Analysis complete! Use --detailed for more information.`)}catch(z){console.error("Error analyzing templates:",z),w.exit(1)}}),E.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(x,b)=>{let{captureScreenshots:z}=await import("./chunk-kfy1jh6p.js"),k=x||"dist";try{let j=await z(k,b.out,{width:Number.parseInt(b.width,10),height:Number.parseInt(b.height,10),waitMs:Number.parseInt(b.wait,10),timeoutMs:Number.parseInt(b.timeout,10),fullPage:Boolean(b.fullPage),waitSelector:b.waitSelector,format:b.format,backend:b.backend});for(let W of j)console.log(`\uD83D\uDCF8 ${W.output} (${(W.bytes/1024).toFixed(0)} KB)`);console.log(`
163
+ \u2728 Captured ${j.length} screenshot(s) to ${b.out}/ via Bun WebView`)}catch(j){console.error(`Screenshot failed: ${j.message}`),w.exit(1)}}),E.command("version","Show the version of the CLI").action(()=>{console.log(N)}),E.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(x)=>{let{startInteractive:b}=await import("./chunk-978faewt.js"),z={};if(x.context){let k=$.resolve(x.context);if(L.existsSync(k))try{let j=L.readFileSync(k,"utf-8");z=JSON.parse(j)}catch(j){console.error("Error loading context file:",j),w.exit(1)}else console.error(`Context file not found: ${k}`),w.exit(1)}await b({context:z,cwd:x.cwd?$.resolve(x.cwd):w.cwd(),verbose:x.verbose})}),E.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(x,b)=>{try{let{buildNative:z,getAvailableTargets:k,getAvailableFormats:j}=await import("./chunk-2rfxs7zm.js"),W=$.resolve(x);if(!L.existsSync(W))console.error(`\u274C Input file not found: ${x}`),w.exit(1);let H=k();if(b.target&&!["macos","windows","linux","ios","android"].includes(b.target))console.error(`\u274C Invalid target: ${b.target}`),console.error("\uD83D\uDCA1 Available targets: macos, windows, linux, ios, android"),console.error(`\uD83D\uDCA1 Targets available on this machine: ${H.join(", ")}`),w.exit(1);let U=b.target||H[0],Y=j(U);if(b.format&&!Y.includes(b.format))console.error(`\u274C Invalid format for ${U}: ${b.format}`),console.error(`\uD83D\uDCA1 Available formats: ${Y.join(", ")}`),w.exit(1);console.log(`
164
164
  \uD83D\uDD28 Building native app...`),console.log(` Input: ${x}`),console.log(` Target: ${U}`),console.log(` Format: ${b.format||"default"}`),console.log(` Output: ${b.output}
165
165
  `);let Q=await z({input:W,output:$.resolve(b.output),target:U,format:b.format,name:b.name,version:b.version,description:b.description,author:b.author,bundleId:b.bundleId,icon:b.icon?$.resolve(b.icon):void 0,window:{title:b.title,width:Number.parseInt(b.width,10),height:Number.parseInt(b.height,10),frameless:b.frameless,alwaysOnTop:b.alwaysOnTop},systemTray:b.systemTray,menubarOnly:b.menubarOnly,category:b.category,copyright:b.copyright,minimumSystemVersion:b.minSystemVersion,infoPlist:kb(b.infoPlist),devTools:b.devTools,craftPath:b.craftPath,verbose:b.verbose});if(Q.success){if(console.log("\u2705 Build successful!"),console.log(` Output: ${Q.outputPath}`),Q.duration)console.log(` Duration: ${(Q.duration/1000).toFixed(2)}s`);if(U==="macos"&&Q.format==="app")console.log(`
166
166
  \uD83D\uDCA1 To run: open "${Q.outputPath}"`);else if(U==="linux"&&Q.format==="appimage")console.log(`
167
- \uD83D\uDCA1 To run: chmod +x "${Q.outputPath}" && "${Q.outputPath}"`)}else console.error(`\u274C Build failed: ${Q.error}`),w.exit(1)}catch(z){console.error(`\u274C Build error: ${z.message}`),w.exit(1)}}),E.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(x)=>{try{let{devCommand:b}=await import("./chunk-acn1b56m.js");await b({port:x.port?Number.parseInt(x.port,10):6006,open:x.open,host:x.host})}catch(b){console.error(`\u274C Story error: ${b.message}`),w.exit(1)}}),E.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(x)=>{try{let{buildCommand:b}=await import("./chunk-xgnc1wy6.js");await b({outDir:x.outDir})}catch(b){console.error(`\u274C Story build error: ${b.message}`),w.exit(1)}}),E.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(x)=>{try{let{createContext:b}=await import("./chunk-ccspd3mc.js"),{runVisualTests:z,updateSnapshots:k,formatTestResults:j}=await import("./chunk-fvhm8psm.js"),W=await b({mode:"build"});if(x.update){let H=await k(W,{filter:x.filter?[x.filter]:void 0});console.log(`Updated ${H} snapshots`)}else{let H=await z(W,{filter:x.filter?[x.filter]:void 0});if(console.log(j(H)),H.failed>0)w.exit(1)}}catch(b){console.error(`\u274C Story test error: ${b.message}`),w.exit(1)}}),E.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(x,b)=>{try{let{compileToNative:z}=await import("./chunk-qpyjak7z.js"),k=$.resolve(x);if(!L.existsSync(k))console.error(`\u274C Input file not found: ${x}`),w.exit(1);let j=["macos","windows","linux","ios","android","universal"];if(!j.includes(b.target))console.error(`\u274C Invalid target: ${b.target}`),console.error(`\uD83D\uDCA1 Available targets: ${j.join(", ")}`),w.exit(1);let W=["zig","typescript","json"];if(!W.includes(b.format))console.error(`\u274C Invalid format: ${b.format}`),console.error(`\uD83D\uDCA1 Available formats: ${W.join(", ")}`),w.exit(1);console.log(`
167
+ \uD83D\uDCA1 To run: chmod +x "${Q.outputPath}" && "${Q.outputPath}"`)}else console.error(`\u274C Build failed: ${Q.error}`),w.exit(1)}catch(z){console.error(`\u274C Build error: ${z.message}`),w.exit(1)}}),E.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(x)=>{try{let{devCommand:b}=await import("./chunk-ch31zddx.js");await b({port:x.port?Number.parseInt(x.port,10):6006,open:x.open,host:x.host})}catch(b){console.error(`\u274C Story error: ${b.message}`),w.exit(1)}}),E.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(x)=>{try{let{buildCommand:b}=await import("./chunk-mmnqd035.js");await b({outDir:x.outDir})}catch(b){console.error(`\u274C Story build error: ${b.message}`),w.exit(1)}}),E.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(x)=>{try{let{createContext:b}=await import("./chunk-2wtn443n.js"),{runVisualTests:z,updateSnapshots:k,formatTestResults:j}=await import("./chunk-8daczchh.js"),W=await b({mode:"build"});if(x.update){let H=await k(W,{filter:x.filter?[x.filter]:void 0});console.log(`Updated ${H} snapshots`)}else{let H=await z(W,{filter:x.filter?[x.filter]:void 0});if(console.log(j(H)),H.failed>0)w.exit(1)}}catch(b){console.error(`\u274C Story test error: ${b.message}`),w.exit(1)}}),E.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(x,b)=>{try{let{compileToNative:z}=await import("./chunk-e67w1bge.js"),k=$.resolve(x);if(!L.existsSync(k))console.error(`\u274C Input file not found: ${x}`),w.exit(1);let j=["macos","windows","linux","ios","android","universal"];if(!j.includes(b.target))console.error(`\u274C Invalid target: ${b.target}`),console.error(`\uD83D\uDCA1 Available targets: ${j.join(", ")}`),w.exit(1);let W=["zig","typescript","json"];if(!W.includes(b.format))console.error(`\u274C Invalid format: ${b.format}`),console.error(`\uD83D\uDCA1 Available formats: ${W.join(", ")}`),w.exit(1);console.log(`
168
168
  \uD83D\uDD27 Compiling stx template to native code...`),console.log(` Input: ${x}`),console.log(` Target: ${b.target}`),console.log(` Format: ${b.format}`),console.log(` Output: ${b.output}
169
169
  `);let H=L.readFileSync(k,"utf-8"),U=await z(H,{target:b.target,format:b.format,optimize:b.optimize,treeShake:b.treeShake,hotReload:b.hotReload,debug:b.verbose,sourceMaps:b.sourcemaps,bundle:b.bundle,minify:b.minify}),Y=$.resolve(b.output);if(!L.existsSync(Y))L.mkdirSync(Y,{recursive:!0});let Q=$.basename(x,$.extname(x)),X=b.format==="typescript"?"ts":b.format==="json"?"json":"zig",_=$.join(Y,`${Q}.${X}`);L.writeFileSync(_,U.code);let q=$.join(Y,`${Q}.manifest.json`);if(L.writeFileSync(q,JSON.stringify(U.manifest,null,2)),b.sourcemaps&&U.sourceMaps){let O=$.join(Y,`${Q}.${X}.map`);L.writeFileSync(O,U.sourceMaps)}if(b.target==="universal"&&U.platformCode.size>0)for(let[O,M]of U.platformCode){let G=$.join(Y,`${Q}.${O}.${X}`);L.writeFileSync(G,M)}if(console.log("\u2705 Compilation successful!"),console.log(` Output: ${_}`),console.log(` Manifest: ${q}`),console.log(`
170
170
  \uD83D\uDCCA Statistics:`),console.log(` Compilation time: ${U.stats.compilationTime.toFixed(2)}ms`),console.log(` Total components: ${U.stats.totalComponents}`),console.log(` Native components: ${U.stats.nativeComponents}`),console.log(` Web fallback components: ${U.stats.webComponents}`),console.log(` Bundle size: ${(U.stats.bundleSize/1024).toFixed(2)}KB`),U.stats.warnings.length>0){console.log(`
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Page-level module registry (stacksjs/stx#1957).
3
+ *
4
+ * A component's `<script client>` bundle no longer inlines the modules it
5
+ * imports. Its direct imports become reads of `globalThis.__stxModules[id]`
6
+ * (see `rewriteRegistryImports` in client-script-bundler.ts), and this module
7
+ * builds the ONE bundle per page that fills that registry. Every imported
8
+ * module is therefore bundled once and evaluated once, so module state -- a
9
+ * cache, a session, a list of registered hooks -- is page-wide, the way
10
+ * `@stores` and `@composables` already are.
11
+ *
12
+ * Which modules a page needs is read from the page's own output, not tracked
13
+ * while it renders. Component bundles are cached per script, and a cache hit
14
+ * never runs the build that would have reported its imports; the reads it
15
+ * emitted are in the HTML either way.
16
+ *
17
+ * @module client-module-registry
18
+ */
19
+ /** Module ids read anywhere in `sources`, sorted so the bundle key is stable. */
20
+ export declare function registeredModuleIdsIn(...sources: Array<string | null | undefined>): string[];
21
+ /**
22
+ * Build the script that registers every module in `ids`.
23
+ *
24
+ * Each module is imported as a namespace and stored under its id if nothing is
25
+ * there yet, so re-running the script keeps the instance components already
26
+ * hold. The whole bundle is additionally guarded by its own key: SPA
27
+ * navigation re-executes page scripts, and without the guard every module's
28
+ * top-level code would run again on each navigation.
29
+ *
30
+ * Returns null when there is nothing to register, and on a failed build --
31
+ * the components then throw naming the missing module, which is the failure a
32
+ * developer can act on, rather than the page silently losing its bundles.
33
+ */
34
+ export declare function buildModuleRegistryScript(ids: string[], options?: {
35
+ minify?: boolean;
36
+ }): Promise<string | null>;
@@ -0,0 +1,55 @@
1
+ import path from "node:path";
2
+ const REGISTRY_READ = /__stxModules\["((?:[^"\\]|\\.)*)"\]/g;
3
+ export function registeredModuleIdsIn(...sources) {
4
+ const ids = new Set;
5
+ for (const source of sources) {
6
+ if (!source || !source.includes("__stxModules["))
7
+ continue;
8
+ for (const match of source.matchAll(REGISTRY_READ))
9
+ try {
10
+ ids.add(JSON.parse(`"${match[1]}"`));
11
+ } catch {}
12
+ }
13
+ return [...ids].sort();
14
+ }
15
+ export async function buildModuleRegistryScript(ids, options = {}) {
16
+ if (ids.length === 0)
17
+ return null;
18
+ const root = process.cwd(), imports = [], registrations = [];
19
+ ids.forEach((id, index) => {
20
+ const specifier = id.startsWith("npm:") ? id.slice(4) : path.resolve(root, id), local = `__stxRegistered${index}`, key = JSON.stringify(id);
21
+ imports.push(`import * as ${local} from ${JSON.stringify(specifier)};`);
22
+ registrations.push(`if (!globalThis.__stxModules[${key}]) globalThis.__stxModules[${key}] = ${local};`);
23
+ });
24
+ const entry = [
25
+ ...imports,
26
+ "globalThis.__stxModules = globalThis.__stxModules || {};",
27
+ ...registrations
28
+ ].join(`
29
+ `);
30
+ let code;
31
+ try {
32
+ const { bundleClientScript } = await import("./client-script-bundler.js");
33
+ code = await bundleClientScript(entry, path.join(root, ".stx-module-registry.ts"), {
34
+ projectRoot: root,
35
+ minify: options.minify,
36
+ externalizeUserModules: !1
37
+ });
38
+ } catch (error) {
39
+ console.warn("[stx] could not build the page module registry (#1957):", error);
40
+ return null;
41
+ }
42
+ const { transformAutoImports, generateAutoImportDestructuring } = await import("./client-script.js"), autoImports = transformAutoImports(code), prelude = generateAutoImportDestructuring(autoImports.stxImports, autoImports.browserImports), { transformStoreImports } = await import("./store-imports.js");
43
+ code = transformStoreImports(autoImports.code);
44
+ const bundleKey = JSON.stringify(new Bun.CryptoHasher("md5").update(entry).digest("hex").slice(0, 12));
45
+ return [
46
+ ";(function() {",
47
+ " var __stxBundles = globalThis.__stxModuleBundles || (globalThis.__stxModuleBundles = {});",
48
+ ` if (__stxBundles[${bundleKey}]) return;`,
49
+ ` __stxBundles[${bundleKey}] = true;`,
50
+ prelude,
51
+ code,
52
+ "})();"
53
+ ].join(`
54
+ `);
55
+ }
@@ -69,6 +69,39 @@ export declare function resolveBundlerFallback(): BundlerFallbackMode;
69
69
  * - `import { ... } from '@composables'` (handled by transformStoreImports)
70
70
  */
71
71
  export declare function hasUserImports(code: string): boolean;
72
+ /**
73
+ * Specifier prefix for an import the PAGE serves rather than the bundle
74
+ * inlines (stacksjs/stx#1957).
75
+ *
76
+ * Every component's `<script client>` used to be bundled with its imports
77
+ * inlined, one Bun.build per script. Two components importing one module each
78
+ * carried their own copy of it, so module state -- a cache, a registry, an
79
+ * in-flight promise -- existed once per component instead of once per page,
80
+ * and the page shipped the same code several times. A real page made five
81
+ * `GET /api/me` calls on load because its auth module had five copies.
82
+ *
83
+ * A component's direct imports are now externalised to `stx-module:<id>` and
84
+ * rewritten into reads of `globalThis.__stxModules`, which one page-level
85
+ * bundle populates (see client-module-registry.ts): each imported module is
86
+ * bundled once and evaluated once per page.
87
+ *
88
+ * The id is the path relative to the project root, or `npm:<specifier>` for a
89
+ * package. Never an absolute path: that would put the server's filesystem
90
+ * layout into every page's HTML.
91
+ */
92
+ export declare const MODULE_SPECIFIER_PREFIX = "stx-module:";
93
+ export declare function registryIdForPath(projectRoot: string, resolved: string): string;
94
+ /**
95
+ * Rewrite each `import … from "stx-module:<id>"` Bun left in a bundle into
96
+ * reads of the page registry, returning the declarations to put at the top
97
+ * of the bundle's scope. The page collects the ids it has to serve by scanning
98
+ * for these reads, so their shape -- `globalThis.__stxModules["<id>"]` -- is a
99
+ * contract with client-module-registry.ts.
100
+ *
101
+ * A missing entry throws with the id named: a component whose module never
102
+ * loaded should fail at its first line, not later with an undefined binding.
103
+ */
104
+ export declare function rewriteRegistryImports(code: string, reads: string[]): string;
72
105
  /**
73
106
  * Run one client bundle build at a time.
74
107
  *
@@ -100,4 +133,10 @@ export declare function bundleClientScript(code: string, filePath: string, optio
100
133
  * hands each caller its own answer.
101
134
  */
102
135
  collectInputs?: string[];
136
+ /**
137
+ * Serve the script's own imports from the page registry instead of
138
+ * inlining them (#1957). Default true; the registry's own build turns it
139
+ * off, since that bundle is where the modules are actually inlined.
140
+ */
141
+ externalizeUserModules?: boolean;
103
142
  }): Promise<string>;
@@ -5,7 +5,8 @@ import { stateDir } from "./state-dir.js";
5
5
  import { describeBuildFailure, formatBuildFailure } from "./build-message.js";
6
6
  import { config } from "./config.js";
7
7
  import { depsUnchanged, renderMemo } from "./render-memo.js";
8
- const BUNDLE_CACHE_VERSION = 5, BUNDLE_CACHE_METADATA_VERSION = 1, bundleInputs = new Map, CACHE_ENTRY_LIMIT = 600, SWEEP_EVERY = 100, writesSinceSweep = new Map;
8
+ import { bracketDepths, stripCommentsAndLiterals } from "./strip-literals.js";
9
+ const BUNDLE_CACHE_VERSION = 6, BUNDLE_CACHE_METADATA_VERSION = 1, bundleInputs = new Map, CACHE_ENTRY_LIMIT = 600, SWEEP_EVERY = 100, writesSinceSweep = new Map;
9
10
  async function pruneBundleCache(cacheDir) {
10
11
  const since = writesSinceSweep.get(cacheDir) ?? 0;
11
12
  if (since > 0 && since < SWEEP_EVERY) {
@@ -100,6 +101,50 @@ export function hasUserImports(code) {
100
101
  }
101
102
  return !1;
102
103
  }
104
+ export const MODULE_SPECIFIER_PREFIX = "stx-module:";
105
+ const REGISTRY_MODULE_EXTENSION = /\.(?:[cm]?[jt]sx?|json)$/i;
106
+ export function registryIdForPath(projectRoot, resolved) {
107
+ return path.relative(projectRoot, resolved).split(path.sep).join("/");
108
+ }
109
+ export function rewriteRegistryImports(code, reads) {
110
+ let counter = 0;
111
+ const moduleVar = (id) => {
112
+ const name = `__stxMod${counter++}`, key = JSON.stringify(id);
113
+ reads.push(`var ${name} = globalThis.__stxModules && globalThis.__stxModules[${key}];`, `if (${name} === undefined) throw new Error("[stx] module " + ${JSON.stringify(key)} + " is not registered on this page (#1957)");`);
114
+ return name;
115
+ }, bindNamed = (list, mod) => {
116
+ for (const raw of list.split(",")) {
117
+ const part = raw.trim();
118
+ if (!part)
119
+ continue;
120
+ const match = part.match(/^("(?:[^"\\]|\\.)*"|[\w$]+)(?:\s+as\s+([\w$]+))?$/);
121
+ if (!match)
122
+ continue;
123
+ const imported = match[1].startsWith('"') ? JSON.parse(match[1]) : match[1], local = match[2] ?? imported;
124
+ reads.push(`var ${local} = ${mod}[${JSON.stringify(imported)}];`);
125
+ }
126
+ };
127
+ code = code.replace(/^[ \t]*import\s+([^;"']*?)\s+from\s+["'](stx-module:[^"']+)["'];?[ \t]*$/gm, (_all, rawClause, spec) => {
128
+ const id = spec.slice(MODULE_SPECIFIER_PREFIX.length), mod = moduleVar(id);
129
+ let clause = rawClause.trim();
130
+ const leadingDefault = clause.match(/^([\w$]+)\s*(?:,\s*|$)/);
131
+ if (leadingDefault && !clause.startsWith("{") && !clause.startsWith("*")) {
132
+ reads.push(`var ${leadingDefault[1]} = ${mod}.default;`);
133
+ clause = clause.slice(leadingDefault[0].length).trim();
134
+ }
135
+ const namespace = clause.match(/^\*\s*as\s+([\w$]+)$/);
136
+ if (namespace)
137
+ reads.push(`var ${namespace[1]} = ${mod};`);
138
+ else if (clause.startsWith("{"))
139
+ bindNamed(clause.replace(/^\{|\}$/g, ""), mod);
140
+ return "";
141
+ });
142
+ code = code.replace(/^[ \t]*import\s+["'](stx-module:[^"']+)["'];?[ \t]*$/gm, (_all, spec) => {
143
+ moduleVar(spec.slice(MODULE_SPECIFIER_PREFIX.length));
144
+ return "";
145
+ });
146
+ return code;
147
+ }
103
148
  function probeModuleFile(basePath) {
104
149
  const candidates = [
105
150
  basePath,
@@ -120,8 +165,19 @@ function probeModuleFile(basePath) {
120
165
  } catch {}
121
166
  return;
122
167
  }
123
- function createBundlePlugin(projectRoot, templateDir, tmpEntry, inputFiles) {
124
- const resolveRelative = (importer, request) => {
168
+ function createBundlePlugin(projectRoot, templateDir, tmpEntry, inputFiles, externalizeUserModules) {
169
+ const toRegistry = (importer, resolved) => {
170
+ if (!externalizeUserModules || importer !== tmpEntry || !REGISTRY_MODULE_EXTENSION.test(resolved))
171
+ return null;
172
+ try {
173
+ if (!fs.statSync(resolved, { throwIfNoEntry: !1 })?.isFile())
174
+ return null;
175
+ } catch {
176
+ return null;
177
+ }
178
+ inputFiles.add(resolved);
179
+ return { path: `${MODULE_SPECIFIER_PREFIX}${registryIdForPath(process.cwd(), resolved)}`, external: !0 };
180
+ }, resolveRelative = (importer, request) => {
125
181
  const fromDir = importer === tmpEntry ? templateDir : path.dirname(importer), resolved = path.resolve(fromDir, request);
126
182
  return probeModuleFile(resolved) ?? resolved;
127
183
  };
@@ -139,6 +195,9 @@ function createBundlePlugin(projectRoot, templateDir, tmpEntry, inputFiles) {
139
195
  build.onResolve({ filter: /^\// }, (args) => {
140
196
  const resolved = probeModuleFile(args.path);
141
197
  if (resolved) {
198
+ const registered = toRegistry(args.importer, resolved);
199
+ if (registered)
200
+ return registered;
142
201
  if (resolved !== tmpEntry)
143
202
  inputFiles.add(resolved);
144
203
  return { path: resolved };
@@ -149,7 +208,9 @@ function createBundlePlugin(projectRoot, templateDir, tmpEntry, inputFiles) {
149
208
  };
150
209
  });
151
210
  build.onResolve({ filter: /^\.\.?\// }, (args) => {
152
- const resolved = resolveRelative(args.importer, args.path);
211
+ const resolved = resolveRelative(args.importer, args.path), registered = toRegistry(args.importer, resolved);
212
+ if (registered)
213
+ return registered;
153
214
  inputFiles.add(resolved);
154
215
  return { path: resolved };
155
216
  });
@@ -168,6 +229,9 @@ function createBundlePlugin(projectRoot, templateDir, tmpEntry, inputFiles) {
168
229
  ];
169
230
  for (const candidate of candidates)
170
231
  if (fs.existsSync(candidate) && fs.statSync(candidate, { throwIfNoEntry: !1 })?.isFile()) {
232
+ const registered = toRegistry(args.importer, candidate);
233
+ if (registered)
234
+ return registered;
171
235
  logBundlerDiagnostic(`resolved ${args.path[0]}/ import:`, args.path, "\u2192", candidate);
172
236
  inputFiles.add(candidate);
173
237
  return { path: candidate };
@@ -175,6 +239,11 @@ function createBundlePlugin(projectRoot, templateDir, tmpEntry, inputFiles) {
175
239
  console.warn(`[stx:bundler] could not resolve ${args.path[0]}/ import:`, args.path);
176
240
  return { path: resolved };
177
241
  });
242
+ build.onResolve({ filter: /^(?!node:|bun:)(?:@[\w.-]+\/)?[\w.-]/ }, (args) => {
243
+ if (!externalizeUserModules || args.importer !== tmpEntry)
244
+ return;
245
+ return { path: `${MODULE_SPECIFIER_PREFIX}npm:${args.path}`, external: !0 };
246
+ });
178
247
  build.onLoad({ filter: /\.(?:[cm]?[jt]sx?|json)$/ }, (args) => {
179
248
  const extension = path.extname(args.path).toLowerCase(), loader = extension === ".json" ? "json" : extension === ".tsx" ? "tsx" : extension === ".jsx" ? "jsx" : extension === ".ts" || extension === ".mts" || extension === ".cts" ? "ts" : "js";
180
249
  if (args.path !== tmpEntry)
@@ -198,8 +267,8 @@ export function queueClientBundleBuild(task) {
198
267
  return result;
199
268
  }
200
269
  export async function bundleClientScript(code, filePath, options = {}) {
201
- const projectRoot = options.projectRoot || process.cwd(), minify = options.minify ?? !1, cacheDir = options.cacheDir || stateDir(projectRoot, "bundle-cache"), hasher = new Bun.CryptoHasher("md5");
202
- hasher.update(`${BUNDLE_CACHE_VERSION}\x00${code}\x00${filePath}`);
270
+ const projectRoot = options.projectRoot || process.cwd(), minify = options.minify ?? !1, externalizeUserModules = options.externalizeUserModules ?? !0, cacheDir = options.cacheDir || stateDir(projectRoot, "bundle-cache"), hasher = new Bun.CryptoHasher("md5");
271
+ hasher.update(`${BUNDLE_CACHE_VERSION}\x00${externalizeUserModules ? "registry" : "inline"}\x00${code}\x00${filePath}`);
203
272
  const hash = hasher.digest("hex").slice(0, 12), cachePath = path.join(cacheDir, `${hash}.js`), remembered = bundleMemo.get(cachePath);
204
273
  if (remembered) {
205
274
  if (depsUnchanged(remembered.files)) {
@@ -248,7 +317,7 @@ export async function bundleClientScript(code, filePath, options = {}) {
248
317
  options.collectInputs.push(...(bundleMemo.get(cachePath)?.files ?? []).map((dep) => dep.path));
249
318
  return shared;
250
319
  }
251
- const build = queueClientBundleBuild(() => buildBundle(code, filePath, { projectRoot, minify, cacheDir, hash, cachePath, depsPath, collectInputs: options.collectInputs }));
320
+ const build = queueClientBundleBuild(() => buildBundle(code, filePath, { projectRoot, minify, cacheDir, hash, cachePath, depsPath, collectInputs: options.collectInputs, externalizeUserModules }));
252
321
  inFlightBundles.set(hash, build);
253
322
  try {
254
323
  return await build;
@@ -257,14 +326,16 @@ export async function bundleClientScript(code, filePath, options = {}) {
257
326
  }
258
327
  }
259
328
  async function buildBundle(code, filePath, options) {
260
- const { projectRoot, minify, cacheDir, hash, cachePath, depsPath } = options, tmpDir = stateDir(projectRoot, "bundle-tmp"), tmpEntry = path.join(tmpDir, `${hash}.ts`), tmpOutDir = path.join(tmpDir, "out", hash);
329
+ const { projectRoot, minify, cacheDir, hash, cachePath, depsPath, externalizeUserModules } = options, tmpDir = stateDir(projectRoot, "bundle-tmp"), tmpEntry = path.join(tmpDir, `${hash}.ts`), tmpOutDir = path.join(tmpDir, "out", hash);
261
330
  fs.mkdirSync(tmpDir, { recursive: !0 });
262
331
  fs.mkdirSync(tmpOutDir, { recursive: !0 });
263
- const templateDir = path.dirname(filePath), declNames = new Set, declRegex = /^[ \t]*(export\s+)?(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))/gm, funcRegex = /^[ \t]*(export\s+)?(?:async\s+)?function\s+(\w+)/gm;
332
+ const templateDir = path.dirname(filePath), declNames = new Set, declRegex = /^[ \t]*(export\s+)?(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))/gm, funcRegex = /^[ \t]*(export\s+)?(?:async\s+)?function\s+(\w+)/gm, strippedForScan = stripCommentsAndLiterals(code), { depths: scanDepths, balanced: scanBalanced } = bracketDepths(strippedForScan), isTopLevel = (index) => !scanBalanced || scanDepths[index] === 0;
264
333
  let dm;
265
- while ((dm = declRegex.exec(code)) !== null) {
334
+ while ((dm = declRegex.exec(strippedForScan)) !== null) {
266
335
  if (dm[1])
267
336
  continue;
337
+ if (!isTopLevel(dm.index))
338
+ continue;
268
339
  if (dm[2])
269
340
  dm[2].split(",").forEach((n) => {
270
341
  const t = destructuredLocalName(n);
@@ -274,9 +345,11 @@ async function buildBundle(code, filePath, options) {
274
345
  else if (dm[3])
275
346
  declNames.add(dm[3]);
276
347
  }
277
- while ((dm = funcRegex.exec(code)) !== null) {
348
+ while ((dm = funcRegex.exec(strippedForScan)) !== null) {
278
349
  if (dm[1])
279
350
  continue;
351
+ if (!isTopLevel(dm.index))
352
+ continue;
280
353
  declNames.add(dm[2]);
281
354
  }
282
355
  const exportLine = declNames.size > 0 ? `
@@ -291,7 +364,7 @@ export { ${[...declNames].join(", ")} }` : "";
291
364
  target: "browser",
292
365
  format: "esm",
293
366
  minify,
294
- plugins: [createBundlePlugin(projectRoot, templateDir, tmpEntry, inputFiles)],
367
+ plugins: [createBundlePlugin(projectRoot, templateDir, tmpEntry, inputFiles, externalizeUserModules)],
295
368
  define: {
296
369
  "process.env.NODE_ENV": minify ? '"production"' : '"development"',
297
370
  ...getPublicEnvDefine()
@@ -323,6 +396,8 @@ export { ${[...declNames].join(", ")} }` : "";
323
396
  if (/^[A-Za-z_$][\w$]*$/.test(name))
324
397
  exposedBindings.push([name, name]);
325
398
  }
399
+ const registryReads = [];
400
+ bundled = rewriteRegistryImports(bundled, registryReads);
326
401
  const externalImports = bundled.match(/^\s*import\s+[^;]+;?\s*$/gm) || [];
327
402
  bundled = bundled.replace(/^\s*import\s+[^;]+;?\s*$/gm, "").replace(/^\s*export\s*\{[^}]*\}\s*;?\s*$/gm, "").replace(/^\s*export\s+default\s+.*$/gm, "").trim();
328
403
  const namespace = `__stxBundle_${hash}`, returnedBindings = exposedBindings.map(([publicName, localName]) => `${JSON.stringify(publicName)}: ${localName}`).join(", "), publicDeclarations = exposedBindings.map(([publicName]) => `var ${publicName} = undefined;`).join(`
@@ -332,6 +407,8 @@ export { ${[...declNames].join(", ")} }` : "";
332
407
  `)}
333
408
  ${publicDeclarations}
334
409
  var ${namespace} = (function() {
410
+ ${registryReads.join(`
411
+ `)}
335
412
  ${bundled}
336
413
  return { ${returnedBindings} };
337
414
  })();