@stacksjs/stx 0.2.876 → 0.2.880

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 (276) hide show
  1. package/dist/{chunk-fdjx4vs3.js → chunk-00tq7ghn.js} +2 -2
  2. package/dist/{chunk-nv4c25zj.js → chunk-02qmvcmv.js} +3 -3
  3. package/dist/chunk-08cb7cyw.js +2 -0
  4. package/dist/chunk-0h1dyd38.js +2 -0
  5. package/dist/{chunk-2mt2zc5y.js → chunk-0m4c42qt.js} +10 -10
  6. package/dist/{chunk-x4jzhgdm.js → chunk-19k15mfc.js} +2 -2
  7. package/dist/chunk-1avy0p8v.js +2 -0
  8. package/dist/chunk-1jk46ve0.js +2 -0
  9. package/dist/chunk-1r612xxs.js +2 -0
  10. package/dist/chunk-1z6rrqvm.js +2 -0
  11. package/dist/chunk-2d68p12e.js +2 -0
  12. package/dist/chunk-2haf7t5h.js +2 -0
  13. package/dist/{chunk-1q5w3xav.js → chunk-2r0nrvqe.js} +2 -2
  14. package/dist/chunk-3jp5z1qj.js +2 -0
  15. package/dist/{chunk-dv56x3g8.js → chunk-3q0w0bzd.js} +10 -10
  16. package/dist/{chunk-eknm4jrm.js → chunk-3sema2js.js} +2 -2
  17. package/dist/{chunk-cj44e8mw.js → chunk-3wb82rxw.js} +5 -5
  18. package/dist/chunk-3zds0gmd.js +2 -0
  19. package/dist/{chunk-qnwd5bz4.js → chunk-463weehv.js} +1 -1
  20. package/dist/{chunk-wm029dh0.js → chunk-4fkcn6z5.js} +18 -12
  21. package/dist/{chunk-976kgb3r.js → chunk-4n45qa0b.js} +9 -9
  22. package/dist/chunk-4pjqj54a.js +2 -0
  23. package/dist/{chunk-j0rqa9bk.js → chunk-4r2rfdmr.js} +5 -5
  24. package/dist/{chunk-ft6em3wm.js → chunk-50cnypys.js} +6 -6
  25. package/dist/chunk-53cc06w7.js +2 -0
  26. package/dist/{chunk-y2e2zm6y.js → chunk-57q4nvs9.js} +3 -3
  27. package/dist/{chunk-3mz9bdf7.js → chunk-59er0fc7.js} +3 -3
  28. package/dist/{chunk-6kp4mg3h.js → chunk-5eftxrvv.js} +2 -2
  29. package/dist/chunk-5p3825qw.js +2 -0
  30. package/dist/chunk-5rd0an89.js +2 -0
  31. package/dist/{chunk-pk714ynv.js → chunk-69ezjc8k.js} +4 -4
  32. package/dist/{chunk-75v0yxeh.js → chunk-6c1vm6bs.js} +2 -2
  33. package/dist/{chunk-d3q0cg47.js → chunk-6df3j3qq.js} +3 -3
  34. package/dist/{chunk-kzc2tqzr.js → chunk-6t04tqvh.js} +2 -2
  35. package/dist/chunk-78zgmqhd.js +2 -0
  36. package/dist/chunk-7bsrnpmh.js +33 -0
  37. package/dist/chunk-7dq6ebvp.js +2 -0
  38. package/dist/chunk-7kqgp3p7.js +2 -0
  39. package/dist/{chunk-wzvdr4ta.js → chunk-7mcs59pr.js} +2 -2
  40. package/dist/chunk-83b9k17j.js +2 -0
  41. package/dist/chunk-86nsbxep.js +61 -0
  42. package/dist/{chunk-0g2mg8cw.js → chunk-8e1cv1hh.js} +3 -3
  43. package/dist/chunk-8h5nje66.js +2 -0
  44. package/dist/{chunk-ae8q4gze.js → chunk-8va3fs07.js} +5 -5
  45. package/dist/{chunk-fh72k2ks.js → chunk-93jhfbeg.js} +6 -6
  46. package/dist/{chunk-xmws1gaf.js → chunk-94ctmp0j.js} +2 -2
  47. package/dist/chunk-97kgrevs.js +4 -0
  48. package/dist/{chunk-nn6hvsxp.js → chunk-9cbf0seq.js} +2 -2
  49. package/dist/{chunk-mce3g2wb.js → chunk-9f31gs4m.js} +2 -2
  50. package/dist/chunk-9kza7gxd.js +2 -0
  51. package/dist/{chunk-b4d4tjvx.js → chunk-a0q0kb0s.js} +5 -5
  52. package/dist/chunk-a5gnxdfe.js +2 -0
  53. package/dist/chunk-a60ztvnp.js +3 -0
  54. package/dist/{chunk-s7fhpkvf.js → chunk-a7ryj8z8.js} +6 -6
  55. package/dist/{chunk-gqtb53s8.js → chunk-aaea157p.js} +2 -2
  56. package/dist/{chunk-wp0qpa50.js → chunk-agd2b928.js} +59 -27
  57. package/dist/chunk-aqxh80vh.js +2 -0
  58. package/dist/{chunk-2tcyfrvb.js → chunk-awp8a3t4.js} +2 -2
  59. package/dist/chunk-axra1yas.js +2 -0
  60. package/dist/chunk-az8b0726.js +21 -0
  61. package/dist/chunk-b7d3n4aw.js +2 -0
  62. package/dist/{chunk-r2bxjna3.js → chunk-c0g30cjs.js} +2 -2
  63. package/dist/{chunk-jt5tzddc.js → chunk-c73c0wf9.js} +2 -2
  64. package/dist/{chunk-3922g6sh.js → chunk-cad7e5q1.js} +9 -9
  65. package/dist/{chunk-bjjfr7qt.js → chunk-care745q.js} +2 -2
  66. package/dist/chunk-ce0zbpr5.js +2 -0
  67. package/dist/chunk-cjv89tnb.js +20 -0
  68. package/dist/chunk-cv1vm1w0.js +2 -0
  69. package/dist/{chunk-mw0rb1sf.js → chunk-czcx3nbx.js} +6 -6
  70. package/dist/chunk-d7b30bg6.js +2 -0
  71. package/dist/{chunk-stn7p7f1.js → chunk-dwyhpbpx.js} +2 -2
  72. package/dist/{chunk-y75bds1g.js → chunk-e362e615.js} +30 -30
  73. package/dist/{chunk-ydppkb8y.js → chunk-e41pgmgk.js} +2 -2
  74. package/dist/{chunk-ctjxcaxq.js → chunk-ec5q4nnw.js} +66 -66
  75. package/dist/{chunk-k0t9ye9j.js → chunk-egjmb32c.js} +126 -71
  76. package/dist/{chunk-g15reb1h.js → chunk-ew3vs3jq.js} +8 -8
  77. package/dist/{chunk-jqxerj6k.js → chunk-ezna4dhj.js} +2 -2
  78. package/dist/chunk-f3j1h3ch.js +2 -0
  79. package/dist/{chunk-mkwavsb3.js → chunk-f7znj9xg.js} +3 -3
  80. package/dist/chunk-fz4c5e9m.js +2 -0
  81. package/dist/{chunk-esjr9qhe.js → chunk-g2xy0z0e.js} +2 -2
  82. package/dist/{chunk-fwbccyhw.js → chunk-g83ph305.js} +2 -2
  83. package/dist/{chunk-kywe0f1v.js → chunk-gbncp2gp.js} +2 -2
  84. package/dist/chunk-gm67jt8p.js +2 -0
  85. package/dist/chunk-gmp10259.js +2 -0
  86. package/dist/{chunk-0sa9gqmc.js → chunk-h2tq6cbr.js} +11 -11
  87. package/dist/chunk-h3fv0q25.js +2 -0
  88. package/dist/{chunk-r09kz9bf.js → chunk-h63ma36g.js} +2 -2
  89. package/dist/chunk-hkx51atf.js +2 -0
  90. package/dist/{chunk-w8k9fz1w.js → chunk-hmntqqyd.js} +7 -7
  91. package/dist/{chunk-3w7gacva.js → chunk-hxhmhw23.js} +3 -3
  92. package/dist/chunk-jghpzx5m.js +2 -0
  93. package/dist/chunk-k206d3pn.js +2 -0
  94. package/dist/chunk-k40e0ete.js +4 -0
  95. package/dist/chunk-k6c5t9we.js +38 -0
  96. package/dist/{chunk-f4vgagjb.js → chunk-kee5a3ce.js} +3 -3
  97. package/dist/chunk-kn9tqjgv.js +25 -0
  98. package/dist/chunk-kna1bdm2.js +54 -0
  99. package/dist/{chunk-ttjscvre.js → chunk-mygsektn.js} +3 -3
  100. package/dist/chunk-nb6erf75.js +9 -0
  101. package/dist/chunk-ngzyzcrp.js +2 -0
  102. package/dist/{chunk-h17pfbng.js → chunk-nysbdr4r.js} +2 -2
  103. package/dist/chunk-p55a910x.js +1198 -0
  104. package/dist/chunk-p6hcrg3r.js +3 -0
  105. package/dist/chunk-p746twww.js +2 -0
  106. package/dist/chunk-pa2vt2ej.js +2 -0
  107. package/dist/chunk-pa6kgbmw.js +2 -0
  108. package/dist/{chunk-saqzk45g.js → chunk-pdprhg5k.js} +1 -1
  109. package/dist/chunk-pjjrx9pk.js +2 -0
  110. package/dist/{chunk-7rep2jqh.js → chunk-pm4rpc4a.js} +23 -23
  111. package/dist/chunk-pt3rp3zg.js +2 -0
  112. package/dist/{chunk-4517hny7.js → chunk-q1mb0fbt.js} +2 -2
  113. package/dist/{chunk-k1ew643q.js → chunk-q74affc4.js} +2 -2
  114. package/dist/chunk-qd9v1v8z.js +2 -0
  115. package/dist/chunk-qfwk93fk.js +2 -0
  116. package/dist/chunk-qg1kw5yf.js +2 -0
  117. package/dist/chunk-qn6y5ttj.js +2 -0
  118. package/dist/chunk-qxcc0aar.js +2 -0
  119. package/dist/{chunk-rzd9hyhv.js → chunk-ram5944w.js} +2 -2
  120. package/dist/{chunk-p5m1z6e1.js → chunk-rcxer2km.js} +4 -4
  121. package/dist/chunk-rdxph1tp.js +2 -0
  122. package/dist/chunk-rnrdngnn.js +2 -0
  123. package/dist/{chunk-x2ftkaz3.js → chunk-rsxxajv6.js} +2 -2
  124. package/dist/chunk-rw5sxr5a.js +2 -0
  125. package/dist/chunk-rzcdwybt.js +26 -0
  126. package/dist/chunk-s29hp1qw.js +14 -0
  127. package/dist/chunk-s7xywsqd.js +3 -0
  128. package/dist/{chunk-d6gqh2wv.js → chunk-satrf398.js} +1 -1
  129. package/dist/{chunk-zn6n075d.js → chunk-shcnt6aa.js} +3 -3
  130. package/dist/{chunk-ysfgabpf.js → chunk-sn4ndpd7.js} +3 -3
  131. package/dist/{chunk-zc8a2erc.js → chunk-ssg6ne5b.js} +4 -4
  132. package/dist/{chunk-afxfkb60.js → chunk-sv7fdqmc.js} +6 -6
  133. package/dist/chunk-swz0xprw.js +2 -0
  134. package/dist/chunk-t8r40wgf.js +2 -0
  135. package/dist/{chunk-dbvsa5ya.js → chunk-t94y8g35.js} +2 -2
  136. package/dist/{chunk-df6vjs3p.js → chunk-t9hxyvvc.js} +5 -5
  137. package/dist/{chunk-cvbwxskc.js → chunk-tgzs1kbj.js} +5 -5
  138. package/dist/chunk-tka73egx.js +2 -0
  139. package/dist/{chunk-xtaq95em.js → chunk-v1s838fe.js} +1 -1
  140. package/dist/chunk-v3747589.js +12 -0
  141. package/dist/chunk-v9h2bbhf.js +2 -0
  142. package/dist/chunk-v9mxhch2.js +2 -0
  143. package/dist/chunk-vm42j29z.js +2 -0
  144. package/dist/chunk-w2kdhm7k.js +2 -0
  145. package/dist/chunk-w5zzwe2f.js +2 -0
  146. package/dist/chunk-wbmx0rge.js +2 -0
  147. package/dist/chunk-wjafpvjv.js +2 -0
  148. package/dist/chunk-ws2h92mm.js +3 -0
  149. package/dist/chunk-ws9kr80x.js +2 -0
  150. package/dist/{chunk-zgds9nwv.js → chunk-xf0xacc9.js} +44 -44
  151. package/dist/chunk-xhr35ctb.js +2 -0
  152. package/dist/chunk-xmmr0916.js +2 -0
  153. package/dist/{chunk-yxdhz4ps.js → chunk-xpbakn6t.js} +2 -2
  154. package/dist/chunk-xz4v9tg1.js +3 -0
  155. package/dist/chunk-y7e61pz3.js +3 -0
  156. package/dist/{chunk-v0tdg16k.js → chunk-ybjgnnyf.js} +5 -5
  157. package/dist/chunk-yh2hnt3m.js +12 -0
  158. package/dist/{chunk-w6pzkcjp.js → chunk-ymqm898x.js} +2 -2
  159. package/dist/{chunk-2zaatnnh.js → chunk-yp4tn4zn.js} +4 -4
  160. package/dist/chunk-z7k1xn6k.js +2 -0
  161. package/dist/{chunk-vnkvnenn.js → chunk-z9ffr9gy.js} +7 -7
  162. package/dist/{chunk-nnp6rf4c.js → chunk-zch65qrd.js} +1 -1
  163. package/dist/{chunk-pbakxcv8.js → chunk-zek9t5za.js} +2 -2
  164. package/dist/cli.js +23 -23
  165. package/dist/client/signals-dom-ready-runtime.js +6 -0
  166. package/dist/client/signals-mount-runtime.js +1 -1
  167. package/dist/client-module-registry.js +10 -4
  168. package/dist/client-parameter-bindings.d.ts +5 -0
  169. package/dist/client-parameter-bindings.js +47 -6
  170. package/dist/client-script-bundler.js +4 -3
  171. package/dist/component-library.d.ts +1 -0
  172. package/dist/component-library.js +42 -14
  173. package/dist/composable-loader.js +19 -9
  174. package/dist/craft-entry.js +2 -2
  175. package/dist/craft.js +2 -2
  176. package/dist/html-masking.d.ts +2 -0
  177. package/dist/html-masking.js +10 -0
  178. package/dist/inherited-context.d.ts +1 -1
  179. package/dist/inherited-context.js +43 -14
  180. package/dist/module-syntax.d.ts +2 -0
  181. package/dist/module-syntax.js +21 -0
  182. package/dist/native-component-context.js +42 -16
  183. package/dist/page-module-order.d.ts +10 -0
  184. package/dist/page-module-order.js +139 -0
  185. package/dist/process.js +6 -4
  186. package/dist/pwa.js +3 -3
  187. package/dist/script-attributes.d.ts +4 -0
  188. package/dist/script-attributes.js +10 -0
  189. package/dist/ssg.js +39 -39
  190. package/dist/strip-literals.d.ts +2 -0
  191. package/dist/strip-literals.js +12 -6
  192. package/dist/stx-virtual-ts.d.ts +1 -0
  193. package/dist/stx-virtual-ts.js +21 -27
  194. package/dist/typecheck.js +8 -0
  195. package/package.json +5 -5
  196. package/dist/chunk-027meh1k.js +0 -2
  197. package/dist/chunk-0hs633pt.js +0 -2
  198. package/dist/chunk-0j8zre1m.js +0 -2
  199. package/dist/chunk-0v02qms8.js +0 -2
  200. package/dist/chunk-0z9gttw0.js +0 -2
  201. package/dist/chunk-11dwmcpy.js +0 -3
  202. package/dist/chunk-1a237qky.js +0 -33
  203. package/dist/chunk-1ehjzhnc.js +0 -25
  204. package/dist/chunk-1gfg6qmr.js +0 -2
  205. package/dist/chunk-1kgnk6ds.js +0 -2
  206. package/dist/chunk-1ztp5vkh.js +0 -3
  207. package/dist/chunk-32wvc376.js +0 -2
  208. package/dist/chunk-3k2d2jsn.js +0 -2
  209. package/dist/chunk-3te2y9qf.js +0 -2
  210. package/dist/chunk-40330tm5.js +0 -2
  211. package/dist/chunk-447jc6zc.js +0 -2
  212. package/dist/chunk-4dk6k0ad.js +0 -2
  213. package/dist/chunk-4e48zkq0.js +0 -2
  214. package/dist/chunk-5ep7p8te.js +0 -2
  215. package/dist/chunk-5gx403te.js +0 -1184
  216. package/dist/chunk-6q9a5bph.js +0 -2
  217. package/dist/chunk-7ds9mx4c.js +0 -2
  218. package/dist/chunk-7njy024g.js +0 -2
  219. package/dist/chunk-7tjewwmd.js +0 -2
  220. package/dist/chunk-85xabvtj.js +0 -2
  221. package/dist/chunk-880f8j99.js +0 -2
  222. package/dist/chunk-8f3dbthj.js +0 -2
  223. package/dist/chunk-99e3mxnn.js +0 -20
  224. package/dist/chunk-9gv847nn.js +0 -2
  225. package/dist/chunk-9mz2n39m.js +0 -2
  226. package/dist/chunk-akthsg33.js +0 -54
  227. package/dist/chunk-b1tcym2x.js +0 -2
  228. package/dist/chunk-bdh73gxd.js +0 -4
  229. package/dist/chunk-bspj1rf1.js +0 -2
  230. package/dist/chunk-bx3hpsxn.js +0 -2
  231. package/dist/chunk-byq488g4.js +0 -2
  232. package/dist/chunk-c4s25bm2.js +0 -2
  233. package/dist/chunk-csjqtzwc.js +0 -2
  234. package/dist/chunk-df78j74w.js +0 -4
  235. package/dist/chunk-dgs3d367.js +0 -2
  236. package/dist/chunk-dmf6zcf4.js +0 -2
  237. package/dist/chunk-e2b2f502.js +0 -2
  238. package/dist/chunk-ec6mrad6.js +0 -2
  239. package/dist/chunk-eecctzgp.js +0 -17
  240. package/dist/chunk-fa57bncd.js +0 -2
  241. package/dist/chunk-g4eheg0t.js +0 -24
  242. package/dist/chunk-gfe1jrw9.js +0 -2
  243. package/dist/chunk-gn16yq49.js +0 -2
  244. package/dist/chunk-gvs61tqn.js +0 -2
  245. package/dist/chunk-h2928108.js +0 -2
  246. package/dist/chunk-hat353vx.js +0 -2
  247. package/dist/chunk-jmjgj3nh.js +0 -2
  248. package/dist/chunk-jqtpzzz4.js +0 -12
  249. package/dist/chunk-jvy7z3hz.js +0 -3
  250. package/dist/chunk-k9dne5by.js +0 -12
  251. package/dist/chunk-kq8mffgf.js +0 -2
  252. package/dist/chunk-kx06jzdw.js +0 -2
  253. package/dist/chunk-n5pvdrkb.js +0 -2
  254. package/dist/chunk-ne8q191s.js +0 -2
  255. package/dist/chunk-np8wgbsa.js +0 -3
  256. package/dist/chunk-nthw4dca.js +0 -2
  257. package/dist/chunk-pp99rmjm.js +0 -72
  258. package/dist/chunk-pqmjeea6.js +0 -2
  259. package/dist/chunk-qggwr60r.js +0 -2
  260. package/dist/chunk-qm3v4qb7.js +0 -2
  261. package/dist/chunk-qty0t69x.js +0 -2
  262. package/dist/chunk-rjv6885r.js +0 -2
  263. package/dist/chunk-rm5gbthk.js +0 -2
  264. package/dist/chunk-sgengtap.js +0 -2
  265. package/dist/chunk-snz2cxqv.js +0 -2
  266. package/dist/chunk-szp7ajfm.js +0 -33
  267. package/dist/chunk-ts37jw3s.js +0 -2
  268. package/dist/chunk-v4emesnw.js +0 -2
  269. package/dist/chunk-vnrbjbrw.js +0 -3
  270. package/dist/chunk-vxra53wq.js +0 -2
  271. package/dist/chunk-x76qvq1n.js +0 -2
  272. package/dist/chunk-x85z6dmw.js +0 -2
  273. package/dist/chunk-xkfe03y9.js +0 -2
  274. package/dist/chunk-y4hn1qh0.js +0 -2
  275. package/dist/chunk-yc8ggeh2.js +0 -2
  276. package/dist/chunk-yfed67yc.js +0 -2
@@ -1,3 +1,4 @@
1
+ import { requiresAsyncBody } from "./module-syntax.js";
1
2
  import { extractExports as scopeExports } from "./client-scope-bindings.js";
2
3
  import path from "node:path";
3
4
  import fs from "node:fs";
@@ -11,7 +12,7 @@ import { config, loadStxConfig } from "./config.js";
11
12
  import { isServerApiSource } from "./server-api.js";
12
13
  import { depsUnchanged, renderMemo, snapshotDeps } from "./render-memo.js";
13
14
  import { bracketDepths, stripCommentsAndLiterals } from "./strip-literals.js";
14
- const BUNDLE_CACHE_VERSION = 11;
15
+ const BUNDLE_CACHE_VERSION = 12;
15
16
  function isPrivateClientSource(file, root, serverApi) {
16
17
  return /^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/.test(path.basename(file)) || isServerApiSource(file, root, serverApi);
17
18
  }
@@ -603,13 +604,13 @@ export { ${[...declNames].join(", ")} }` : "";
603
604
  try {
604
605
  bundled = new Bun.Transpiler({ loader: "js", minifyWhitespace: !0 }).transformSync(bundled);
605
606
  } catch {}
606
- const namespace = `__stxBundle_${hash}`, mutableBindings = new Set(scopeExports(code, !0).split(",").map((name) => name.trim())), returnedBindings = exposedBindings.map(([publicName, localName]) => `get ${JSON.stringify(publicName)}() { return ${localName} }${mutableBindings.has(publicName) ? `, set ${JSON.stringify(publicName)}(__stxValue_${localName}) { ${localName} = __stxValue_${localName} }` : ""}`).join(", "), publicDeclarations = exposedBindings.map(([publicName]) => `var ${publicName} = undefined;`).join(`
607
+ const asynchronous = requiresAsyncBody(bundled), namespace = `__stxBundle_${hash}`, mutableBindings = new Set(scopeExports(code, !0).split(",").map((name) => name.trim())), returnedBindings = exposedBindings.map(([publicName, localName]) => `get ${JSON.stringify(publicName)}() { return ${localName} }${mutableBindings.has(publicName) ? `, set ${JSON.stringify(publicName)}(__stxValue_${localName}) { ${localName} = __stxValue_${localName} }` : ""}`).join(", "), publicDeclarations = exposedBindings.map(([publicName]) => `var ${publicName} = undefined;`).join(`
607
608
  `), publicAssignments = exposedBindings.map(([publicName]) => `${publicName} = ${namespace}[${JSON.stringify(publicName)}];`).join(`
608
609
  `);
609
610
  bundled = `${externalImports.join(`
610
611
  `)}
611
612
  ${publicDeclarations}
612
- var ${namespace} = (function() {
613
+ var ${namespace} = ${asynchronous ? "await (async function" : "(function"}() {
613
614
  ${registryReads.join(`
614
615
  `)}
615
616
  ${bundled}
@@ -1,5 +1,6 @@
1
1
  import type { ComponentLibraryBuildResult, ComponentLibraryConfig, ComponentLibraryEvent, ComponentLibraryProperty } from './types.js';
2
2
  export declare function componentScriptSource(source: string): string;
3
+ export declare function componentMetadataBlock(source: string): { code: string, start: number, open: number } | undefined;
3
4
  export declare function parseMetadata(source: string, file: string): SourceMetadata;
4
5
  /** Use Bun's TS parser to distinguish a return object type from the method body. */
5
6
  export declare function clientMethods(code: string, validate?: ClientMethodValidator): ClientMethod[];
@@ -1,5 +1,8 @@
1
+ import { scanHtmlScriptElements } from "./html-masking.js";
1
2
  import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
2
3
  import path from "node:path";
4
+ import { scriptAttributes, scriptContainsCode } from "./script-attributes.js";
5
+ import { topLevelDeclarationSites } from "./client-parameter-bindings.js";
3
6
  import { bracketDepths, stripCommentsAndLiterals } from "./strip-literals.js";
4
7
  function reservedMethodMessage(name) {
5
8
  if (name === "connectedCallback")
@@ -51,11 +54,19 @@ async function discoverStxFiles(inputDir) {
51
54
  export function componentScriptSource(source) {
52
55
  return source.replace(/<!--[\s\S]*?-->|\{\{--[\s\S]*?--\}\}/g, (comment) => comment.replace(/[^\n]/g, " "));
53
56
  }
57
+ export function componentMetadataBlock(source) {
58
+ for (const script of scanHtmlScriptElements(componentScriptSource(source))) {
59
+ const attributes = scriptAttributes(script.attrs);
60
+ if (!attributes.has("component") && !attributes.has("stx:component"))
61
+ continue;
62
+ return { code: source.slice(script.bodyStart, script.bodyEnd), start: script.bodyStart, open: script.start };
63
+ }
64
+ }
54
65
  export function parseMetadata(source, file) {
55
- const match = componentScriptSource(source).match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);
56
- if (!match)
66
+ const block = componentMetadataBlock(source);
67
+ if (!block)
57
68
  return {};
58
- const bodyStart = match.index + match[0].indexOf(">") + 1, raw = source.slice(bodyStart, bodyStart + match[1].length).trim();
69
+ const raw = block.code.trim();
59
70
  if (!raw)
60
71
  return {};
61
72
  try {
@@ -68,9 +79,11 @@ export function parseMetadata(source, file) {
68
79
  }
69
80
  }
70
81
  export function clientMethods(code, validate) {
71
- const masked = stripCommentsAndLiterals(code), pattern = /(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/g, result = [], parser = validate ? void 0 : new Bun.Transpiler({ loader: "ts" });
82
+ const masked = stripCommentsAndLiterals(code), declarations = new Set(topLevelDeclarationSites(code).map((site) => site.start)), pattern = /(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/g, result = [], parser = validate ? void 0 : new Bun.Transpiler({ loader: "ts" });
72
83
  let match;
73
84
  while (match = pattern.exec(masked)) {
85
+ if (!declarations.has(match.index + match[0].indexOf("function")))
86
+ continue;
74
87
  let cursor = pattern.lastIndex;
75
88
  while (/\s/.test(masked[cursor] || ""))
76
89
  cursor++;
@@ -150,17 +163,17 @@ export function methodDeclaration(method) {
150
163
  return `${method.name}${method.generic}(${parameters}): ${method.returns || (method.async ? "Promise<unknown>" : "unknown")}`;
151
164
  }
152
165
  function extractClientMethods(source, file) {
153
- const methods = {}, declarations = {}, types = [], imports = [], scripts = [...componentScriptSource(source).matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];
166
+ const methods = {}, declarations = {}, types = [], imports = [], scripts = scanHtmlScriptElements(componentScriptSource(source));
154
167
  for (const script of scripts) {
155
- const bodyStart = script.index + script[0].indexOf(">") + 1, code = source.slice(bodyStart, bodyStart + script[2].length);
156
- if (/\bserver\b|\bcomponent\b|\bstx:component\b/i.test(script[1]) || /\btype=["']application\//i.test(script[1]))
168
+ const code = source.slice(script.bodyStart, script.bodyEnd), attributes = scriptAttributes(script.attrs);
169
+ if (attributes.has("src") || attributes.has("server") || attributes.has("component") || attributes.has("stx:component") || !scriptContainsCode(attributes))
157
170
  continue;
158
171
  try {
159
172
  new Bun.Transpiler({ loader: "ts" }).transformSync(code);
160
173
  } catch (error) {
161
174
  throw Error(`${file}: failed to transpile <script client> (${error.message})`);
162
175
  }
163
- const extracted = /\bclient\b/i.test(script[1]) ? clientMethods(code) : [], overloads = new Set(extracted.filter((method) => !method.source).map((method) => method.name));
176
+ const extracted = attributes.has("client") ? clientMethods(code) : [], overloads = new Set(extracted.filter((method) => !method.source).map((method) => method.name));
164
177
  for (const method of extracted) {
165
178
  if (RESERVED_METHODS.has(method.name))
166
179
  throw Error(`${file}: client ${reservedMethodMessage(method.name)}`);
@@ -634,10 +647,13 @@ export function parseDefaults(object) {
634
647
  return pairs;
635
648
  }
636
649
  function compileScriptScope(source, file, outputDir) {
637
- const block = [...source.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((script) => !/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(script[1]));
650
+ const block = scanHtmlScriptElements(componentScriptSource(source)).find((script) => {
651
+ const attrs = scriptAttributes(script.attrs);
652
+ return scriptContainsCode(attrs) && !["component", "stx:component", "client", "src"].some((name) => attrs.has(name));
653
+ });
638
654
  if (!block)
639
655
  return { imports: [], body: "", propNames: [], propBindings: {}, defaults: {}, declared: {} };
640
- let code = block[2];
656
+ let code = source.slice(block.bodyStart, block.bodyEnd);
641
657
  const imports = [], propNames = [], propBindings = {}, defaults = {}, declared = {};
642
658
  code = code.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm, (statement) => {
643
659
  if (/from\s*['"]stx['"]/.test(statement))
@@ -757,6 +773,8 @@ const escapeHTML = (value) => String(value ?? '')
757
773
 
758
774
  const valueAt = (host, path) => {
759
775
  const parts = path.trim().split('.');
776
+ if (parts[0] === 'this') parts.shift();
777
+ if (!parts.length) return host;
760
778
  const first = parts.shift();
761
779
  // Render bindings read declared props, including attributes whose names
762
780
  // also belong to the native DOM API. The public element keeps that API.
@@ -951,8 +969,12 @@ export class StxElement extends HTMLElementBase {
951
969
  const definition = this.constructor.definition;
952
970
  const root = this.renderRoot;
953
971
  const active = root.activeElement || (root.contains?.(globalThis.document?.activeElement) ? globalThis.document.activeElement : null);
954
- const focusKey = active && (active.getAttribute?.('data-key') || active.id || active.getAttribute?.('name'));
955
- const selection = active && 'selectionStart' in active ? [active.selectionStart, active.selectionEnd] : null;
972
+ const focusAttribute = active?.getAttribute?.('data-key') ? 'data-key' : active?.id ? 'id' : 'name';
973
+ const focusKey = active?.getAttribute?.(focusAttribute);
974
+ const focusValue = focusAttribute === 'name' && active?.type === 'radio' ? active.value : null;
975
+ const selectionStart = active?.selectionStart, selectionEnd = active?.selectionEnd;
976
+ const selection = Number.isInteger(selectionStart) && Number.isInteger(selectionEnd)
977
+ ? [selectionStart, selectionEnd, active.selectionDirection] : null;
956
978
  // A compiled component renders itself: the control flow and the derived
957
979
  // values were turned into JavaScript at build time, so there is nothing to
958
980
  // interpret here and nothing that needs an eval the page's CSP forbids.
@@ -968,9 +990,15 @@ export class StxElement extends HTMLElementBase {
968
990
  this._bindEvents();
969
991
  if (focusKey) {
970
992
  const escaped = globalThis.CSS?.escape ? globalThis.CSS.escape(focusKey) : focusKey.replace(/["\\\\]/g, '\\$&');
971
- const next = root.querySelector('[data-key="' + escaped + '"],#' + escaped + ',[name="' + escaped + '"]');
993
+ const selector = '[' + focusAttribute + '="' + escaped + '"]';
994
+ // Name-only radio groups share a name, but their chosen member must stay focused.
995
+ const next = focusValue === null ? root.querySelector(selector)
996
+ : [...root.querySelectorAll(selector)].find(element => element.type === 'radio' && element.value === focusValue);
972
997
  next?.focus?.();
973
- if (selection && next?.setSelectionRange) next.setSelectionRange(selection[0], selection[1]);
998
+ // Several input types expose this method but reject text selection. A
999
+ // rerender can also change a text input into one of those types.
1000
+ if (selection && Number.isInteger(next?.selectionStart) && Number.isInteger(next?.selectionEnd) && typeof next?.setSelectionRange === 'function')
1001
+ next.setSelectionRange(selection[0], selection[1], selection[2] || 'none');
974
1002
  }
975
1003
  this.dispatchEvent?.(new CustomEvent('stx:updated', { bubbles: false }));
976
1004
  }
@@ -1,4 +1,8 @@
1
1
  import path from "node:path";
2
+ import { scanHtmlScriptElements } from "./html-masking.js";
3
+ import { requiresAsyncBody } from "./module-syntax.js";
4
+ import { extractTemplateExpressions } from "./stx-virtual-ts.js";
5
+ import { scriptAttributes } from "./script-attributes.js";
2
6
  import { unboundNames } from "./client-parameter-bindings.js";
3
7
  import { bundleClientScript, clientBundleDependencies, hasUserImports, moduleSubstitutionKey } from "./client-script-bundler.js";
4
8
  import { loadStxConfig } from "./config.js";
@@ -108,10 +112,10 @@ function pageUses(page, names) {
108
112
  const all = new Set(names);
109
113
  let markup = "", last = 0;
110
114
  const used = new Set;
111
- for (const match of page.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi)) {
112
- markup += page.slice(last, match.index);
113
- last = match.index + match[0].length;
114
- const attrs = match[1] ?? "", body = match[2] ?? "", type = /\btype\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(attrs), typeName = type ? (type[1] ?? type[2] ?? type[3] ?? "").trim() : void 0;
115
+ for (const script of scanHtmlScriptElements(page)) {
116
+ markup += page.slice(last, script.start);
117
+ last = script.end;
118
+ const attrs = scriptAttributes(script.attrs), body = page.slice(script.bodyStart, script.bodyEnd), type = attrs.get("type"), typeName = typeof type === "string" ? type.trim() : void 0;
115
119
  if (!isScriptType(typeName)) {
116
120
  if (!/json/i.test(typeName ?? ""))
117
121
  markup += ` ${body} `;
@@ -130,8 +134,9 @@ function pageUses(page, names) {
130
134
  used.add(name);
131
135
  }
132
136
  markup += page.slice(last);
133
- for (const name of mentionedNames(markup, all))
134
- used.add(name);
137
+ for (const expression of extractTemplateExpressions(markup))
138
+ for (const name of composableUses(expression.code, all))
139
+ used.add(name);
135
140
  return used;
136
141
  }
137
142
  function selectReachable(modules, codeByFile, pageSources) {
@@ -250,10 +255,13 @@ ${code.trim()}`);
250
255
  `), globalNames = JSON.stringify([...exportedNames]), joinedChunks = chunks.join(`
251
256
 
252
257
  `), runtimeBindings = STX_RUNTIME_GLOBALS.filter((name) => !declaredNames.has(name) && new RegExp(`\\b${name}\\b`).test(joinedChunks)).map((name) => `var ${name} = __stx[${JSON.stringify(name)}];`).join(`
253
- `), bundleKey = JSON.stringify(new Bun.CryptoHasher("md5").update(`${globalNames}\x00${joinedChunks}`).digest("hex").slice(0, 12)), assembled = `;(function(){
258
+ `), bundleKey = JSON.stringify(new Bun.CryptoHasher("md5").update(`${globalNames}\x00${joinedChunks}`).digest("hex").slice(0, 12)), asynchronous = requiresAsyncBody(joinedChunks), assembled = `;${asynchronous ? "await (async function" : "(function"}(){
254
259
  var __bundles = window.__stxComposableBundles || (window.__stxComposableBundles = {});
255
- if (__bundles[${bundleKey}]) return;
256
- __bundles[${bundleKey}] = true;
260
+ if (__bundles[${bundleKey}]) { ${asynchronous ? "await __bundles[" + bundleKey + "];" : ""} return; }
261
+ ${asynchronous ? `var __resolveBundle, __rejectBundle;
262
+ __bundles[${bundleKey}]=new Promise(function(resolve,reject){__resolveBundle=resolve;__rejectBundle=reject;});
263
+ __bundles[${bundleKey}].catch(function(){});
264
+ try {` : `__bundles[${bundleKey}] = true;`}
257
265
  var __published = window.__stxComposableGlobals || (window.__stxComposableGlobals = {});
258
266
  window.__composables = window.__composables || {};
259
267
  var __c = window.__composables;
@@ -275,6 +283,8 @@ ${assignments}
275
283
  window[__n] = __c[__n];
276
284
  __published[__n] = true;
277
285
  }
286
+ ${asynchronous ? `__resolveBundle();
287
+ } catch(error) { delete __bundles[${bundleKey}]; __rejectBundle(error); throw error; }` : ""}
278
288
  })();`, code = isProduction() ? minifyClassicScript(assembled) : assembled;
279
289
  signature = sourceSignature(composableInputs());
280
290
  writeSigned(_cachedComposableScripts, cacheKey, signature, code);
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import"./chunk-5gx403te.js";import{Oo,Na,Da}from"./chunk-y2e2zm6y.js";import"./chunk-y75bds1g.js";import"./chunk-pp99rmjm.js";import"./chunk-fdjx4vs3.js";import"./chunk-3w7gacva.js";import"./chunk-kzc2tqzr.js";import"./chunk-x4jzhgdm.js";import"./chunk-r09kz9bf.js";import"./chunk-wp0qpa50.js";import"./chunk-ctjxcaxq.js";import"./chunk-0sa9gqmc.js";import"./chunk-zc8a2erc.js";import"./chunk-6kp4mg3h.js";import"./chunk-dv56x3g8.js";import"./chunk-k0t9ye9j.js";import"./chunk-3922g6sh.js";import"./chunk-akthsg33.js";import"./chunk-2mt2zc5y.js";import"./chunk-1ehjzhnc.js";import"./chunk-r2bxjna3.js";import"./chunk-f4vgagjb.js";import{Au,Ma,jh,Bh,La,No,is,ja,Ba,Fh,zh,Fa,za,Ha,Va}from"./chunk-7rep2jqh.js";import"./chunk-df6vjs3p.js";import"./chunk-11dwmcpy.js";import"./chunk-dbvsa5ya.js";import"./chunk-w8k9fz1w.js";import"./chunk-xtaq95em.js";import"./chunk-ttjscvre.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
2
+ import"./chunk-p55a910x.js";import{Fo,Ha,Va}from"./chunk-57q4nvs9.js";import"./chunk-e362e615.js";import"./chunk-s29hp1qw.js";import"./chunk-86nsbxep.js";import"./chunk-00tq7ghn.js";import"./chunk-hxhmhw23.js";import"./chunk-a60ztvnp.js";import"./chunk-6t04tqvh.js";import"./chunk-19k15mfc.js";import"./chunk-h63ma36g.js";import"./chunk-agd2b928.js";import"./chunk-ec5q4nnw.js";import"./chunk-h2tq6cbr.js";import"./chunk-ssg6ne5b.js";import"./chunk-5eftxrvv.js";import"./chunk-3q0w0bzd.js";import"./chunk-egjmb32c.js";import"./chunk-cad7e5q1.js";import"./chunk-kna1bdm2.js";import"./chunk-0m4c42qt.js";import"./chunk-kn9tqjgv.js";import"./chunk-c0g30cjs.js";import"./chunk-kee5a3ce.js";import{Fu,Ua,Kh,Gh,Wa,zo,ps,qa,Ka,Xh,Jh,Ga,Xa,Ja,Ya}from"./chunk-pm4rpc4a.js";import"./chunk-t9hxyvvc.js";import"./chunk-xz4v9tg1.js";import"./chunk-t94y8g35.js";import"./chunk-hmntqqyd.js";import"./chunk-v1s838fe.js";import"./chunk-nb6erf75.js";import"./chunk-mygsektn.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
3
3
  `),scripts:t.scripts.join(`
4
4
  `),metadata:{renderTime:0,cacheHit:!0,totalSize:c.html.length,componentCount:t.metadata.componentCount}}}let a;if(n.streaming)a=await H(t.tree,e);else a=h(t.tree,e);let i;if(n.hydrate){let o=j(a,t,e);a=o.html,i=o.data}if(n.minify)a=D(a);if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`;d.set(o,{html:a,timestamp:Date.now()})}let s=performance.now()-r;return{html:a,styles:t.styles.join(`
5
5
  `),scripts:t.scripts.join(`
6
6
  `),hydrationData:i,metadata:{renderTime:s,cacheHit:!1,totalSize:a.length,componentCount:t.metadata.componentCount}}}function V(t,e){let n=[],r=[],a=[],i=new Map,s=[];return y(t.tree,(o,c)=>{if(o.type==="component"&&o.componentName){if(T(o.componentName))n.push(o.componentName)}if(o.type==="element"&&o.tag){let p=J(o);if(p)s.push(p);if(o.props){for(let[l,f]of Object.entries(o.props))if(l.startsWith("on")&&typeof f==="string"){let g=`handler_${i.size}`;i.set(g,f)}}}if(o.isStatic&&o.type==="element")r.push(b(o));else if(!o.isStatic&&o.type!=="text")a.push(o.tag||o.componentName||"unknown")}),{nativeComponents:n,staticHTML:r,dynamicParts:a,eventHandlers:i,nativeWidgets:s}}function Y(t,e={}){let n=R(t),r=P(n,e),a=new Map,i=[];return y(n.tree,(s)=>{if(s.type==="component"&&s.componentName){if(T(s.componentName)){i.push(s.componentName);let o=`<!--craft:${s.componentName}:${s.hydrationKey||"default"}-->`;a.set(s.hydrationKey||s.componentName,o)}}}),{staticHTML:r,dynamicPlaceholders:a,craftComponents:i}}function M(t){let e={type:"fragment",children:[]},n=e,r=[e],a=t,i=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);while(a.length>0){let s=a.match(/^<(@?[\w-]+)([^>]*)>/);if(s){let[p,l,f]=s,g=z(f),u=l.startsWith("@craft-"),C=u?l:l.toLowerCase(),S={type:u?"component":"element",tag:C,props:g,children:[],componentName:u?C.slice(1):void 0,isStatic:!v(f),hydrationKey:F()};if(n.children=n.children||[],n.children.push(S),!i.has(C)&&!f.endsWith("/"))r.push(S),n=S;a=a.slice(p.length);continue}let o=a.match(/^<\/(@?[\w-]+)>/);if(o){let[p,l]=o,g=l.startsWith("@craft-")?l:l.toLowerCase();while(r.length>1){let u=r.pop();if(n=r[r.length-1],u.tag===g)break}a=a.slice(p.length);continue}let c=a.match(/^[^<]+/);if(c){let p=c[0];if(p.trim()){let l={type:"text",text:p,isStatic:!v(p)};n.children=n.children||[],n.children.push(l)}a=a.slice(p.length);continue}a=a.slice(1)}return e}function z(t){let e={},n=/([\w-:@]+)(?:=(?:"([^"]*)"|'([^']*)'|(\S+)))?/g,r;while((r=n.exec(t))!==null){let[,a,i,s,o]=r,c=i??s??o??!0;e[a]=c}return e}function y(t,e,n=[]){if(e(t,n),t.children)t.children.forEach((r,a)=>{y(r,e,[...n,`${a}`])})}function h(t,e){switch(t.type){case"text":return x(t.text||"",e);case"element":case"component":{let n=t.tag||"div",r=N(t.props||{},e),a=(t.children||[]).map((i)=>h(i,e)).join("");if(!t.children||t.children.length===0){if(["input","br","hr","img","meta","link"].includes(n))return`<${n}${r} />`}return`<${n}${r}>${a}</${n}>`}case"fragment":return(t.children||[]).map((n)=>h(n,e)).join("");case"slot":return`<!--slot:${t.slotName||"default"}-->`;default:return""}}function b(t){if(t.type==="text")return t.text||"";let e=t.tag||"div",n=N(t.props||{},{});return`<${e}${n}></${e}>`}function N(t,e){let n=[];for(let[r,a]of Object.entries(t))if(a===!0)n.push(` ${r}`);else if(a!==!1&&a!==null&&a!==void 0){let i=x(String(a),e);n.push(` ${r}="${k(i)}"`)}return n.join("")}async function H(t,e){return h(t,e)}function P(t,e){let n=[];return y(t.tree,(r)=>{if(r.isStatic)n.push(h(r,e))}),n.join("")}function j(t,e,n){let r={templateId:e.id,context:n,dynamicParts:Array.from(e.dynamicParts.entries())},a=`
7
7
  <script data-craft-hydration>
8
8
  window.__CRAFT_HYDRATION__ = ${JSON.stringify(r)};
9
- </script>`;return{html:t+a,data:r}}function O(t){let e=!1,n=!1,r=!1,a=!1,i=0,s=0;function o(c,p){if(s=Math.max(s,p),c.type==="slot")e=!0;if(c.type==="component")i++;if(!c.isStatic)n=!0;if(c.props)for(let l of Object.keys(c.props)){if(l.startsWith("on"))r=!0;if(l==="@async"||l==="data-async")a=!0}if(c.children)c.children.forEach((l)=>o(l,p+1))}return o(t,0),{hasSlots:e,hasDynamicContent:n,hasEventHandlers:r,hasAsyncContent:a,componentCount:i,maxDepth:s,estimatedSize:JSON.stringify(t).length}}function A(t){let e=new Map,n=new Map;return y(t,(r,a)=>{let i=a.join(".");if(r.isStatic)e.set(i,b(r));else n.set(i,r.tag||r.componentName||"dynamic")}),{staticParts:e,dynamicParts:n}}function L(t){let e=[],n=/<script[^>]*>([\s\S]*?)<\/script>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function W(t){let e=[],n=/<style[^>]*>([\s\S]*?)<\/style>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function _(t){let e=[],n=/@include\s*\(\s*['"]([^'"]+)['"]/g,r;while((r=n.exec(t))!==null)e.push(r[1]);let a=/@component\s*\(\s*['"]([^'"]+)['"]/g;while((r=a.exec(t))!==null)e.push(r[1]);let i=/<@craft-[\w-]+/g;while((r=i.exec(t))!==null)e.push(r[0].slice(2));return[...new Set(e)]}function v(t){return/\{\{.*?\}\}|\{\!\!.*?\!\!\}/.test(t)}function x(t,e){let n=t.replace(/\{\{\s*(.+?)\s*\}\}/g,(r,a)=>{try{let i=w(a.trim(),e);return k(String(i??""))}catch{return""}});return n=n.replace(/\{!!\s*(.+?)\s*!!\}/g,(r,a)=>{try{let i=w(a.trim(),e);return String(i??"")}catch{return""}}),n}function w(t,e){if(/^[\w.]+$/.test(t)){let n=t.split("."),r=e;for(let a of n)if(r&&typeof r==="object"&&a in r)r=r[a];else return;return r}try{return Function(...Object.keys(e),`return ${t}`)(...Object.values(e))}catch{return}}function k(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function D(t){return t.replace(/\s+/g," ").replace(/>\s+</g,"><").replace(/\s+>/g,">").replace(/<\s+/g,"<").trim()}function E(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return`tpl_${Math.abs(e).toString(36)}`}function I(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36)}var K=0;function F(){return`h_${++K}`}function T(t){return["craft-button","craft-text-input","craft-textarea","craft-checkbox","craft-radio","craft-select","craft-slider","craft-toggle","craft-date-picker","craft-time-picker","craft-color-picker","craft-file-input","craft-modal","craft-alert","craft-toast","craft-progress","craft-spinner","craft-avatar","craft-badge","craft-card","craft-accordion","craft-tabs","craft-tooltip","craft-popover","craft-dropdown","craft-context-menu","craft-data-table","craft-virtual-list","craft-tree-view","craft-map","craft-chart","craft-video","craft-audio","craft-webview","craft-canvas","craft-image-viewer","craft-pdf-viewer","craft-code-editor","craft-rich-editor"].includes(t)}function J(t){let e=t.tag?.toLowerCase(),n=t.props?.type,r={button:{component:"craft-button",confidence:0.95,reason:"Native button provides better touch feedback"},"input:text":{component:"craft-text-input",confidence:0.9,reason:"Native text input has better keyboard handling"},"input:checkbox":{component:"craft-checkbox",confidence:0.95,reason:"Native checkbox follows platform conventions"},"input:range":{component:"craft-slider",confidence:0.9,reason:"Native slider provides smooth interaction"},"input:date":{component:"craft-date-picker",confidence:0.95,reason:"Native date picker provides platform-specific UI"},"input:time":{component:"craft-time-picker",confidence:0.95,reason:"Native time picker provides platform-specific UI"},"input:color":{component:"craft-color-picker",confidence:0.9,reason:"Native color picker provides platform-specific UI"},textarea:{component:"craft-textarea",confidence:0.85,reason:"Native textarea handles multiline input better"},select:{component:"craft-select",confidence:0.9,reason:"Native select provides platform dropdown UI"},progress:{component:"craft-progress",confidence:0.95,reason:"Native progress bar matches platform style"},video:{component:"craft-video",confidence:0.95,reason:"Native video provides hardware acceleration"},audio:{component:"craft-audio",confidence:0.95,reason:"Native audio provides system integration"},dialog:{component:"craft-modal",confidence:0.9,reason:"Native modal provides proper layering and focus"}},a=n?`${e}:${n}`:e,i=r[a||""]||r[e||""];if(i)return{htmlSelector:a||e||"",nativeComponent:i.component,confidence:i.confidence,reason:i.reason};return null}function U(){m.clear()}function q(){d.clear()}function B(){U(),q()}function G(){return{templateCacheSize:m.size,renderCacheSize:d.size,totalEntries:m.size+d.size}}export{Au as CRAFT_BRIDGE_SCRIPT,No as CRAFT_COMPONENTS,ja as CRAFT_COMPONENT_RUNTIME,is as CRAFT_COMPONENT_STYLES,Oo as NATIVE_COMPONENTS,Fa as buildNative,B as clearAllCaches,q as clearRenderCache,U as clearTemplateCache,R as compileTemplate,Na as compileToNative,Da as createHotReloadServer,za as findCraftBinary,Ma as generateCraftBridgeScript,V as generateCraftOptimizations,Va as getAvailableFormats,Ha as getAvailableTargets,zh as getCraftComponents,G as getSSRCacheStats,La as injectCraftBridge,jh as isCraftEnvironment,Y as prerenderForCraft,Ba as processCraftComponents,Bh as processCraftDirective,Fh as registerCraftComponent,Q as renderSSR};
9
+ </script>`;return{html:t+a,data:r}}function O(t){let e=!1,n=!1,r=!1,a=!1,i=0,s=0;function o(c,p){if(s=Math.max(s,p),c.type==="slot")e=!0;if(c.type==="component")i++;if(!c.isStatic)n=!0;if(c.props)for(let l of Object.keys(c.props)){if(l.startsWith("on"))r=!0;if(l==="@async"||l==="data-async")a=!0}if(c.children)c.children.forEach((l)=>o(l,p+1))}return o(t,0),{hasSlots:e,hasDynamicContent:n,hasEventHandlers:r,hasAsyncContent:a,componentCount:i,maxDepth:s,estimatedSize:JSON.stringify(t).length}}function A(t){let e=new Map,n=new Map;return y(t,(r,a)=>{let i=a.join(".");if(r.isStatic)e.set(i,b(r));else n.set(i,r.tag||r.componentName||"dynamic")}),{staticParts:e,dynamicParts:n}}function L(t){let e=[],n=/<script[^>]*>([\s\S]*?)<\/script>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function W(t){let e=[],n=/<style[^>]*>([\s\S]*?)<\/style>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function _(t){let e=[],n=/@include\s*\(\s*['"]([^'"]+)['"]/g,r;while((r=n.exec(t))!==null)e.push(r[1]);let a=/@component\s*\(\s*['"]([^'"]+)['"]/g;while((r=a.exec(t))!==null)e.push(r[1]);let i=/<@craft-[\w-]+/g;while((r=i.exec(t))!==null)e.push(r[0].slice(2));return[...new Set(e)]}function v(t){return/\{\{.*?\}\}|\{\!\!.*?\!\!\}/.test(t)}function x(t,e){let n=t.replace(/\{\{\s*(.+?)\s*\}\}/g,(r,a)=>{try{let i=w(a.trim(),e);return k(String(i??""))}catch{return""}});return n=n.replace(/\{!!\s*(.+?)\s*!!\}/g,(r,a)=>{try{let i=w(a.trim(),e);return String(i??"")}catch{return""}}),n}function w(t,e){if(/^[\w.]+$/.test(t)){let n=t.split("."),r=e;for(let a of n)if(r&&typeof r==="object"&&a in r)r=r[a];else return;return r}try{return Function(...Object.keys(e),`return ${t}`)(...Object.values(e))}catch{return}}function k(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function D(t){return t.replace(/\s+/g," ").replace(/>\s+</g,"><").replace(/\s+>/g,">").replace(/<\s+/g,"<").trim()}function E(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return`tpl_${Math.abs(e).toString(36)}`}function I(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36)}var K=0;function F(){return`h_${++K}`}function T(t){return["craft-button","craft-text-input","craft-textarea","craft-checkbox","craft-radio","craft-select","craft-slider","craft-toggle","craft-date-picker","craft-time-picker","craft-color-picker","craft-file-input","craft-modal","craft-alert","craft-toast","craft-progress","craft-spinner","craft-avatar","craft-badge","craft-card","craft-accordion","craft-tabs","craft-tooltip","craft-popover","craft-dropdown","craft-context-menu","craft-data-table","craft-virtual-list","craft-tree-view","craft-map","craft-chart","craft-video","craft-audio","craft-webview","craft-canvas","craft-image-viewer","craft-pdf-viewer","craft-code-editor","craft-rich-editor"].includes(t)}function J(t){let e=t.tag?.toLowerCase(),n=t.props?.type,r={button:{component:"craft-button",confidence:0.95,reason:"Native button provides better touch feedback"},"input:text":{component:"craft-text-input",confidence:0.9,reason:"Native text input has better keyboard handling"},"input:checkbox":{component:"craft-checkbox",confidence:0.95,reason:"Native checkbox follows platform conventions"},"input:range":{component:"craft-slider",confidence:0.9,reason:"Native slider provides smooth interaction"},"input:date":{component:"craft-date-picker",confidence:0.95,reason:"Native date picker provides platform-specific UI"},"input:time":{component:"craft-time-picker",confidence:0.95,reason:"Native time picker provides platform-specific UI"},"input:color":{component:"craft-color-picker",confidence:0.9,reason:"Native color picker provides platform-specific UI"},textarea:{component:"craft-textarea",confidence:0.85,reason:"Native textarea handles multiline input better"},select:{component:"craft-select",confidence:0.9,reason:"Native select provides platform dropdown UI"},progress:{component:"craft-progress",confidence:0.95,reason:"Native progress bar matches platform style"},video:{component:"craft-video",confidence:0.95,reason:"Native video provides hardware acceleration"},audio:{component:"craft-audio",confidence:0.95,reason:"Native audio provides system integration"},dialog:{component:"craft-modal",confidence:0.9,reason:"Native modal provides proper layering and focus"}},a=n?`${e}:${n}`:e,i=r[a||""]||r[e||""];if(i)return{htmlSelector:a||e||"",nativeComponent:i.component,confidence:i.confidence,reason:i.reason};return null}function U(){m.clear()}function q(){d.clear()}function B(){U(),q()}function G(){return{templateCacheSize:m.size,renderCacheSize:d.size,totalEntries:m.size+d.size}}export{Fu as CRAFT_BRIDGE_SCRIPT,zo as CRAFT_COMPONENTS,qa as CRAFT_COMPONENT_RUNTIME,ps as CRAFT_COMPONENT_STYLES,Fo as NATIVE_COMPONENTS,Ga as buildNative,B as clearAllCaches,q as clearRenderCache,U as clearTemplateCache,R as compileTemplate,Ha as compileToNative,Va as createHotReloadServer,Xa as findCraftBinary,Ua as generateCraftBridgeScript,V as generateCraftOptimizations,Ya as getAvailableFormats,Ja as getAvailableTargets,Jh as getCraftComponents,G as getSSRCacheStats,Wa as injectCraftBridge,Kh as isCraftEnvironment,Y as prerenderForCraft,Ka as processCraftComponents,Gh as processCraftDirective,Xh as registerCraftComponent,Q as renderSSR};
package/dist/craft.js CHANGED
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import"./chunk-5gx403te.js";import{Oo,Na,Da}from"./chunk-y2e2zm6y.js";import"./chunk-y75bds1g.js";import"./chunk-pp99rmjm.js";import"./chunk-fdjx4vs3.js";import"./chunk-3w7gacva.js";import"./chunk-kzc2tqzr.js";import"./chunk-x4jzhgdm.js";import"./chunk-r09kz9bf.js";import"./chunk-wp0qpa50.js";import"./chunk-ctjxcaxq.js";import"./chunk-0sa9gqmc.js";import"./chunk-zc8a2erc.js";import"./chunk-6kp4mg3h.js";import"./chunk-dv56x3g8.js";import"./chunk-k0t9ye9j.js";import"./chunk-3922g6sh.js";import"./chunk-akthsg33.js";import"./chunk-2mt2zc5y.js";import"./chunk-1ehjzhnc.js";import"./chunk-r2bxjna3.js";import"./chunk-f4vgagjb.js";import{Au,Ma,jh,Bh,La,No,is,ja,Ba,Fh,zh,Fa,za,Ha,Va}from"./chunk-7rep2jqh.js";import"./chunk-df6vjs3p.js";import"./chunk-11dwmcpy.js";import"./chunk-dbvsa5ya.js";import"./chunk-w8k9fz1w.js";import"./chunk-xtaq95em.js";import"./chunk-ttjscvre.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
2
+ import"./chunk-p55a910x.js";import{Fo,Ha,Va}from"./chunk-57q4nvs9.js";import"./chunk-e362e615.js";import"./chunk-s29hp1qw.js";import"./chunk-86nsbxep.js";import"./chunk-00tq7ghn.js";import"./chunk-hxhmhw23.js";import"./chunk-a60ztvnp.js";import"./chunk-6t04tqvh.js";import"./chunk-19k15mfc.js";import"./chunk-h63ma36g.js";import"./chunk-agd2b928.js";import"./chunk-ec5q4nnw.js";import"./chunk-h2tq6cbr.js";import"./chunk-ssg6ne5b.js";import"./chunk-5eftxrvv.js";import"./chunk-3q0w0bzd.js";import"./chunk-egjmb32c.js";import"./chunk-cad7e5q1.js";import"./chunk-kna1bdm2.js";import"./chunk-0m4c42qt.js";import"./chunk-kn9tqjgv.js";import"./chunk-c0g30cjs.js";import"./chunk-kee5a3ce.js";import{Fu,Ua,Kh,Gh,Wa,zo,ps,qa,Ka,Xh,Jh,Ga,Xa,Ja,Ya}from"./chunk-pm4rpc4a.js";import"./chunk-t9hxyvvc.js";import"./chunk-xz4v9tg1.js";import"./chunk-t94y8g35.js";import"./chunk-hmntqqyd.js";import"./chunk-v1s838fe.js";import"./chunk-nb6erf75.js";import"./chunk-mygsektn.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
3
3
  `),scripts:t.scripts.join(`
4
4
  `),metadata:{renderTime:0,cacheHit:!0,totalSize:c.html.length,componentCount:t.metadata.componentCount}}}let a;if(n.streaming)a=await H(t.tree,e);else a=h(t.tree,e);let i;if(n.hydrate){let o=j(a,t,e);a=o.html,i=o.data}if(n.minify)a=D(a);if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`;d.set(o,{html:a,timestamp:Date.now()})}let s=performance.now()-r;return{html:a,styles:t.styles.join(`
5
5
  `),scripts:t.scripts.join(`
6
6
  `),hydrationData:i,metadata:{renderTime:s,cacheHit:!1,totalSize:a.length,componentCount:t.metadata.componentCount}}}function V(t,e){let n=[],r=[],a=[],i=new Map,s=[];return y(t.tree,(o,c)=>{if(o.type==="component"&&o.componentName){if(T(o.componentName))n.push(o.componentName)}if(o.type==="element"&&o.tag){let p=J(o);if(p)s.push(p);if(o.props){for(let[l,f]of Object.entries(o.props))if(l.startsWith("on")&&typeof f==="string"){let g=`handler_${i.size}`;i.set(g,f)}}}if(o.isStatic&&o.type==="element")r.push(b(o));else if(!o.isStatic&&o.type!=="text")a.push(o.tag||o.componentName||"unknown")}),{nativeComponents:n,staticHTML:r,dynamicParts:a,eventHandlers:i,nativeWidgets:s}}function Y(t,e={}){let n=R(t),r=P(n,e),a=new Map,i=[];return y(n.tree,(s)=>{if(s.type==="component"&&s.componentName){if(T(s.componentName)){i.push(s.componentName);let o=`<!--craft:${s.componentName}:${s.hydrationKey||"default"}-->`;a.set(s.hydrationKey||s.componentName,o)}}}),{staticHTML:r,dynamicPlaceholders:a,craftComponents:i}}function M(t){let e={type:"fragment",children:[]},n=e,r=[e],a=t,i=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);while(a.length>0){let s=a.match(/^<(@?[\w-]+)([^>]*)>/);if(s){let[p,l,f]=s,g=z(f),u=l.startsWith("@craft-"),C=u?l:l.toLowerCase(),S={type:u?"component":"element",tag:C,props:g,children:[],componentName:u?C.slice(1):void 0,isStatic:!v(f),hydrationKey:F()};if(n.children=n.children||[],n.children.push(S),!i.has(C)&&!f.endsWith("/"))r.push(S),n=S;a=a.slice(p.length);continue}let o=a.match(/^<\/(@?[\w-]+)>/);if(o){let[p,l]=o,g=l.startsWith("@craft-")?l:l.toLowerCase();while(r.length>1){let u=r.pop();if(n=r[r.length-1],u.tag===g)break}a=a.slice(p.length);continue}let c=a.match(/^[^<]+/);if(c){let p=c[0];if(p.trim()){let l={type:"text",text:p,isStatic:!v(p)};n.children=n.children||[],n.children.push(l)}a=a.slice(p.length);continue}a=a.slice(1)}return e}function z(t){let e={},n=/([\w-:@]+)(?:=(?:"([^"]*)"|'([^']*)'|(\S+)))?/g,r;while((r=n.exec(t))!==null){let[,a,i,s,o]=r,c=i??s??o??!0;e[a]=c}return e}function y(t,e,n=[]){if(e(t,n),t.children)t.children.forEach((r,a)=>{y(r,e,[...n,`${a}`])})}function h(t,e){switch(t.type){case"text":return x(t.text||"",e);case"element":case"component":{let n=t.tag||"div",r=N(t.props||{},e),a=(t.children||[]).map((i)=>h(i,e)).join("");if(!t.children||t.children.length===0){if(["input","br","hr","img","meta","link"].includes(n))return`<${n}${r} />`}return`<${n}${r}>${a}</${n}>`}case"fragment":return(t.children||[]).map((n)=>h(n,e)).join("");case"slot":return`<!--slot:${t.slotName||"default"}-->`;default:return""}}function b(t){if(t.type==="text")return t.text||"";let e=t.tag||"div",n=N(t.props||{},{});return`<${e}${n}></${e}>`}function N(t,e){let n=[];for(let[r,a]of Object.entries(t))if(a===!0)n.push(` ${r}`);else if(a!==!1&&a!==null&&a!==void 0){let i=x(String(a),e);n.push(` ${r}="${k(i)}"`)}return n.join("")}async function H(t,e){return h(t,e)}function P(t,e){let n=[];return y(t.tree,(r)=>{if(r.isStatic)n.push(h(r,e))}),n.join("")}function j(t,e,n){let r={templateId:e.id,context:n,dynamicParts:Array.from(e.dynamicParts.entries())},a=`
7
7
  <script data-craft-hydration>
8
8
  window.__CRAFT_HYDRATION__ = ${JSON.stringify(r)};
9
- </script>`;return{html:t+a,data:r}}function O(t){let e=!1,n=!1,r=!1,a=!1,i=0,s=0;function o(c,p){if(s=Math.max(s,p),c.type==="slot")e=!0;if(c.type==="component")i++;if(!c.isStatic)n=!0;if(c.props)for(let l of Object.keys(c.props)){if(l.startsWith("on"))r=!0;if(l==="@async"||l==="data-async")a=!0}if(c.children)c.children.forEach((l)=>o(l,p+1))}return o(t,0),{hasSlots:e,hasDynamicContent:n,hasEventHandlers:r,hasAsyncContent:a,componentCount:i,maxDepth:s,estimatedSize:JSON.stringify(t).length}}function A(t){let e=new Map,n=new Map;return y(t,(r,a)=>{let i=a.join(".");if(r.isStatic)e.set(i,b(r));else n.set(i,r.tag||r.componentName||"dynamic")}),{staticParts:e,dynamicParts:n}}function L(t){let e=[],n=/<script[^>]*>([\s\S]*?)<\/script>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function W(t){let e=[],n=/<style[^>]*>([\s\S]*?)<\/style>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function _(t){let e=[],n=/@include\s*\(\s*['"]([^'"]+)['"]/g,r;while((r=n.exec(t))!==null)e.push(r[1]);let a=/@component\s*\(\s*['"]([^'"]+)['"]/g;while((r=a.exec(t))!==null)e.push(r[1]);let i=/<@craft-[\w-]+/g;while((r=i.exec(t))!==null)e.push(r[0].slice(2));return[...new Set(e)]}function v(t){return/\{\{.*?\}\}|\{\!\!.*?\!\!\}/.test(t)}function x(t,e){let n=t.replace(/\{\{\s*(.+?)\s*\}\}/g,(r,a)=>{try{let i=w(a.trim(),e);return k(String(i??""))}catch{return""}});return n=n.replace(/\{!!\s*(.+?)\s*!!\}/g,(r,a)=>{try{let i=w(a.trim(),e);return String(i??"")}catch{return""}}),n}function w(t,e){if(/^[\w.]+$/.test(t)){let n=t.split("."),r=e;for(let a of n)if(r&&typeof r==="object"&&a in r)r=r[a];else return;return r}try{return Function(...Object.keys(e),`return ${t}`)(...Object.values(e))}catch{return}}function k(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function D(t){return t.replace(/\s+/g," ").replace(/>\s+</g,"><").replace(/\s+>/g,">").replace(/<\s+/g,"<").trim()}function E(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return`tpl_${Math.abs(e).toString(36)}`}function I(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36)}var K=0;function F(){return`h_${++K}`}function T(t){return["craft-button","craft-text-input","craft-textarea","craft-checkbox","craft-radio","craft-select","craft-slider","craft-toggle","craft-date-picker","craft-time-picker","craft-color-picker","craft-file-input","craft-modal","craft-alert","craft-toast","craft-progress","craft-spinner","craft-avatar","craft-badge","craft-card","craft-accordion","craft-tabs","craft-tooltip","craft-popover","craft-dropdown","craft-context-menu","craft-data-table","craft-virtual-list","craft-tree-view","craft-map","craft-chart","craft-video","craft-audio","craft-webview","craft-canvas","craft-image-viewer","craft-pdf-viewer","craft-code-editor","craft-rich-editor"].includes(t)}function J(t){let e=t.tag?.toLowerCase(),n=t.props?.type,r={button:{component:"craft-button",confidence:0.95,reason:"Native button provides better touch feedback"},"input:text":{component:"craft-text-input",confidence:0.9,reason:"Native text input has better keyboard handling"},"input:checkbox":{component:"craft-checkbox",confidence:0.95,reason:"Native checkbox follows platform conventions"},"input:range":{component:"craft-slider",confidence:0.9,reason:"Native slider provides smooth interaction"},"input:date":{component:"craft-date-picker",confidence:0.95,reason:"Native date picker provides platform-specific UI"},"input:time":{component:"craft-time-picker",confidence:0.95,reason:"Native time picker provides platform-specific UI"},"input:color":{component:"craft-color-picker",confidence:0.9,reason:"Native color picker provides platform-specific UI"},textarea:{component:"craft-textarea",confidence:0.85,reason:"Native textarea handles multiline input better"},select:{component:"craft-select",confidence:0.9,reason:"Native select provides platform dropdown UI"},progress:{component:"craft-progress",confidence:0.95,reason:"Native progress bar matches platform style"},video:{component:"craft-video",confidence:0.95,reason:"Native video provides hardware acceleration"},audio:{component:"craft-audio",confidence:0.95,reason:"Native audio provides system integration"},dialog:{component:"craft-modal",confidence:0.9,reason:"Native modal provides proper layering and focus"}},a=n?`${e}:${n}`:e,i=r[a||""]||r[e||""];if(i)return{htmlSelector:a||e||"",nativeComponent:i.component,confidence:i.confidence,reason:i.reason};return null}function U(){m.clear()}function q(){d.clear()}function B(){U(),q()}function G(){return{templateCacheSize:m.size,renderCacheSize:d.size,totalEntries:m.size+d.size}}export{Au as CRAFT_BRIDGE_SCRIPT,No as CRAFT_COMPONENTS,ja as CRAFT_COMPONENT_RUNTIME,is as CRAFT_COMPONENT_STYLES,Oo as NATIVE_COMPONENTS,Fa as buildNative,B as clearAllCaches,q as clearRenderCache,U as clearTemplateCache,R as compileTemplate,Na as compileToNative,Da as createHotReloadServer,za as findCraftBinary,Ma as generateCraftBridgeScript,V as generateCraftOptimizations,Va as getAvailableFormats,Ha as getAvailableTargets,zh as getCraftComponents,G as getSSRCacheStats,La as injectCraftBridge,jh as isCraftEnvironment,Y as prerenderForCraft,Ba as processCraftComponents,Bh as processCraftDirective,Fh as registerCraftComponent,Q as renderSSR};
9
+ </script>`;return{html:t+a,data:r}}function O(t){let e=!1,n=!1,r=!1,a=!1,i=0,s=0;function o(c,p){if(s=Math.max(s,p),c.type==="slot")e=!0;if(c.type==="component")i++;if(!c.isStatic)n=!0;if(c.props)for(let l of Object.keys(c.props)){if(l.startsWith("on"))r=!0;if(l==="@async"||l==="data-async")a=!0}if(c.children)c.children.forEach((l)=>o(l,p+1))}return o(t,0),{hasSlots:e,hasDynamicContent:n,hasEventHandlers:r,hasAsyncContent:a,componentCount:i,maxDepth:s,estimatedSize:JSON.stringify(t).length}}function A(t){let e=new Map,n=new Map;return y(t,(r,a)=>{let i=a.join(".");if(r.isStatic)e.set(i,b(r));else n.set(i,r.tag||r.componentName||"dynamic")}),{staticParts:e,dynamicParts:n}}function L(t){let e=[],n=/<script[^>]*>([\s\S]*?)<\/script>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function W(t){let e=[],n=/<style[^>]*>([\s\S]*?)<\/style>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function _(t){let e=[],n=/@include\s*\(\s*['"]([^'"]+)['"]/g,r;while((r=n.exec(t))!==null)e.push(r[1]);let a=/@component\s*\(\s*['"]([^'"]+)['"]/g;while((r=a.exec(t))!==null)e.push(r[1]);let i=/<@craft-[\w-]+/g;while((r=i.exec(t))!==null)e.push(r[0].slice(2));return[...new Set(e)]}function v(t){return/\{\{.*?\}\}|\{\!\!.*?\!\!\}/.test(t)}function x(t,e){let n=t.replace(/\{\{\s*(.+?)\s*\}\}/g,(r,a)=>{try{let i=w(a.trim(),e);return k(String(i??""))}catch{return""}});return n=n.replace(/\{!!\s*(.+?)\s*!!\}/g,(r,a)=>{try{let i=w(a.trim(),e);return String(i??"")}catch{return""}}),n}function w(t,e){if(/^[\w.]+$/.test(t)){let n=t.split("."),r=e;for(let a of n)if(r&&typeof r==="object"&&a in r)r=r[a];else return;return r}try{return Function(...Object.keys(e),`return ${t}`)(...Object.values(e))}catch{return}}function k(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function D(t){return t.replace(/\s+/g," ").replace(/>\s+</g,"><").replace(/\s+>/g,">").replace(/<\s+/g,"<").trim()}function E(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return`tpl_${Math.abs(e).toString(36)}`}function I(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36)}var K=0;function F(){return`h_${++K}`}function T(t){return["craft-button","craft-text-input","craft-textarea","craft-checkbox","craft-radio","craft-select","craft-slider","craft-toggle","craft-date-picker","craft-time-picker","craft-color-picker","craft-file-input","craft-modal","craft-alert","craft-toast","craft-progress","craft-spinner","craft-avatar","craft-badge","craft-card","craft-accordion","craft-tabs","craft-tooltip","craft-popover","craft-dropdown","craft-context-menu","craft-data-table","craft-virtual-list","craft-tree-view","craft-map","craft-chart","craft-video","craft-audio","craft-webview","craft-canvas","craft-image-viewer","craft-pdf-viewer","craft-code-editor","craft-rich-editor"].includes(t)}function J(t){let e=t.tag?.toLowerCase(),n=t.props?.type,r={button:{component:"craft-button",confidence:0.95,reason:"Native button provides better touch feedback"},"input:text":{component:"craft-text-input",confidence:0.9,reason:"Native text input has better keyboard handling"},"input:checkbox":{component:"craft-checkbox",confidence:0.95,reason:"Native checkbox follows platform conventions"},"input:range":{component:"craft-slider",confidence:0.9,reason:"Native slider provides smooth interaction"},"input:date":{component:"craft-date-picker",confidence:0.95,reason:"Native date picker provides platform-specific UI"},"input:time":{component:"craft-time-picker",confidence:0.95,reason:"Native time picker provides platform-specific UI"},"input:color":{component:"craft-color-picker",confidence:0.9,reason:"Native color picker provides platform-specific UI"},textarea:{component:"craft-textarea",confidence:0.85,reason:"Native textarea handles multiline input better"},select:{component:"craft-select",confidence:0.9,reason:"Native select provides platform dropdown UI"},progress:{component:"craft-progress",confidence:0.95,reason:"Native progress bar matches platform style"},video:{component:"craft-video",confidence:0.95,reason:"Native video provides hardware acceleration"},audio:{component:"craft-audio",confidence:0.95,reason:"Native audio provides system integration"},dialog:{component:"craft-modal",confidence:0.9,reason:"Native modal provides proper layering and focus"}},a=n?`${e}:${n}`:e,i=r[a||""]||r[e||""];if(i)return{htmlSelector:a||e||"",nativeComponent:i.component,confidence:i.confidence,reason:i.reason};return null}function U(){m.clear()}function q(){d.clear()}function B(){U(),q()}function G(){return{templateCacheSize:m.size,renderCacheSize:d.size,totalEntries:m.size+d.size}}export{Fu as CRAFT_BRIDGE_SCRIPT,zo as CRAFT_COMPONENTS,qa as CRAFT_COMPONENT_RUNTIME,ps as CRAFT_COMPONENT_STYLES,Fo as NATIVE_COMPONENTS,Ga as buildNative,B as clearAllCaches,q as clearRenderCache,U as clearTemplateCache,R as compileTemplate,Ha as compileToNative,Va as createHotReloadServer,Xa as findCraftBinary,Ua as generateCraftBridgeScript,V as generateCraftOptimizations,Ya as getAvailableFormats,Ja as getAvailableTargets,Jh as getCraftComponents,G as getSSRCacheStats,Wa as injectCraftBridge,Kh as isCraftEnvironment,Y as prerenderForCraft,Ka as processCraftComponents,Gh as processCraftDirective,Xh as registerCraftComponent,Q as renderSSR};
@@ -66,6 +66,8 @@ export declare function stashScriptElements(html: string): StashedScripts;
66
66
  export declare function clearStashCache(): void;
67
67
  /** Restore scripts stashed by {@link stashScriptElements}. */
68
68
  export declare function restoreStashedScripts(html: string, scripts: string[]): string;
69
+ /** Shared script boundaries for the compiler, author checker and composable discovery. */
70
+ export declare function scanHtmlScriptElements(html: string): Array<{ start: number, end: number, bodyStart: number, bodyEnd: number, attrs: string }>;
69
71
  export declare interface ElementPositionToken {
70
72
  start: number
71
73
  end: number
@@ -298,3 +298,13 @@ export function restoreStashedScripts(html, scripts) {
298
298
  return html;
299
299
  return html.replace(/\x00STX_SCRIPT_(\d+)\x00/g, (_, idx) => scripts[+idx] ?? "");
300
300
  }
301
+ export function scanHtmlScriptElements(html) {
302
+ const tags = scanHtmlTags(html), result = [];
303
+ for (let index = 0;index < tags.length; index++) {
304
+ const tag = tags[index], close = tags[index + 1];
305
+ if (tag.name.toLowerCase() !== "script" || tag.closing || close?.name.toLowerCase() !== "script" || !close.closing)
306
+ continue;
307
+ result.push({ start: tag.start, end: close.end, bodyStart: tag.end, bodyEnd: close.start, attrs: tag.attributes });
308
+ }
309
+ return result;
310
+ }
@@ -3,7 +3,7 @@ export declare function inheritedContextContract(code: string): Contract | undef
3
3
  /** These names are already present at runtime; only an explicit contract types them. */
4
4
  export declare function inheritedContextBindings(code: string): string;
5
5
  export declare function inheritedContextChecks(source: string, options: InheritedContextOptions): { declarations: string, checks: ContractCheck[], dependencies: Map<string, string> };
6
- declare interface Contract { keys: string[], types: string }
6
+ declare interface Contract { keys: string[], types: string, unsupported?: string, offset: number }
7
7
  export declare interface InheritedContextOptions {
8
8
  filePath: string
9
9
  partialsDir?: string
@@ -1,20 +1,44 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { componentContract, COMPONENT_CONTRACT_HELPERS } from "./component-contract.js";
4
+ import { STX_ENGINE_BINDING_NAMES } from "./engine-bindings.js";
4
5
  import { componentDirectiveExpression } from "./component-library.js";
5
- import { stripCommentsAndLiterals } from "./strip-literals.js";
6
+ import { bracketDepths, stripCommentsAndLiterals } from "./strip-literals.js";
6
7
  import { absolutizeRelativeSpecifiers, blankScriptDirectives, collectBlockDeclarations, extractScriptBlocks, extractTypeDeclarations, maskNonTemplateRegions, typeScopeImports } from "./stx-virtual-ts.js";
8
+ const engineBindings = new Set(STX_ENGINE_BINDING_NAMES);
7
9
  export function inheritedContextContract(code) {
8
10
  const types = extractTypeDeclarations(code), declaration = types.find((type) => type.name === "InheritedContext");
9
11
  if (!declaration)
10
12
  return;
11
- const body = declaration.text.slice(declaration.text.indexOf("{") + 1, declaration.text.lastIndexOf("}"));
12
- return { keys: [...stripCommentsAndLiterals(body).matchAll(/(?:^|[;\n])\s*(?:readonly\s+)?([A-Za-z_$][\w$]*)\??\s*:/g)].map((match) => match[1]), types: types.map((type) => type.text).join(`
13
- `) };
13
+ const supported = /^(?:interface\s+InheritedContext|type\s+InheritedContext\s*=)\s*\{/.test(stripCommentsAndLiterals(declaration.text).trim()), maskedCode = stripCommentsAndLiterals(code), codeDepths = bracketDepths(maskedCode).depths, offset = [...maskedCode.matchAll(/\b(?:interface|type)\s+InheritedContext\b/g)].find((match) => codeDepths[match.index] === 0)?.index ?? 0, body = declaration.text.slice(declaration.text.indexOf("{") + 1, declaration.text.lastIndexOf("}")), masked = stripCommentsAndLiterals(body), depths = bracketDepths(masked).depths, keys = [...masked.matchAll(/(?:^|[;,\n])\s*(?:readonly\s+)?([A-Za-z_$][\w$]*)\??\s*:/g)].filter((match) => depths[match.index] === 0).map((match) => match[1]);
14
+ return { keys: supported ? keys : [], types: types.map((type) => type.text).join(`
15
+ `), offset: Math.max(0, offset), ...!supported ? { unsupported: "InheritedContext requires a local non-generic object interface or object type alias with named properties" } : {} };
16
+ }
17
+ function inheritedValueImports(code) {
18
+ const result = [], masked = stripCommentsAndLiterals(code);
19
+ for (const match of code.matchAll(/\bimport\s+(type\s+)?([\w$*{}\s,]+?)\s+from\s*(['"])([^'"]+)\3/g)) {
20
+ if (match[1] || masked.slice(match.index, match.index + 6) !== "import")
21
+ continue;
22
+ const clause = match[2].trim(), fromStx = ["stx", "@stacksjs/stx"].includes(match[4]);
23
+ if (/^[A-Za-z_$][\w$]*$/.test(clause)) {
24
+ result.push(clause);
25
+ continue;
26
+ }
27
+ if (!clause.startsWith("{") || !clause.endsWith("}"))
28
+ continue;
29
+ for (const entry of clause.slice(1, -1).split(",")) {
30
+ if (/^\s*type\s+/.test(entry))
31
+ continue;
32
+ const [imported, local = imported] = entry.trim().split(/\s+as\s+/);
33
+ if (local && !(fromStx && engineBindings.has(imported)))
34
+ result.push(local);
35
+ }
36
+ }
37
+ return result;
14
38
  }
15
39
  export function inheritedContextBindings(code) {
16
40
  const contract = inheritedContextContract(code);
17
- if (!contract)
41
+ if (!contract || contract.unsupported)
18
42
  return "";
19
43
  const own = new Set(collectBlockDeclarations(code));
20
44
  return contract.keys.filter((key) => !own.has(key)).map((key) => `declare const ${key}: InheritedContext[${JSON.stringify(key)}];`).join(`
@@ -33,11 +57,16 @@ export function inheritedContextChecks(source, options) {
33
57
  `, offset - 1), expression = { code: source.slice(offset, source.indexOf(`
34
58
  `, offset) < 0 ? source.length : source.indexOf(`
35
59
  `, offset)), line, column, kind: "directive", offset, anchor: !0 };
36
- checks.push({ expression, statement: { text, prefixLength: 0 } });
60
+ checks.push({ expression, statement: { text: `;${text}`, prefixLength: 1 } });
37
61
  }
38
62
  function visit(text, currentFile, parentType, parentKeys, anchor, stack) {
39
- const id = `__StxInherited${next++}`, code = extractScriptBlocks(text).filter((block) => block.kind === "server").map((block) => block.code).join(`
40
- `), scope = typeScopeImports(absolutizeRelativeSpecifiers(code, path.dirname(currentFile)), id);
63
+ let id = `__StxInherited${next++}`;
64
+ while ((source + text + [...dependencies.values()].join("")).includes(id))
65
+ id += "_";
66
+ const code = extractScriptBlocks(text).filter((block) => block.kind === "server").map((block) => block.code).join(`
67
+ `), parentValue = `${id}ParentValue`, parentAlias = `${id}ParentType`;
68
+ declarations.push(`type ${parentAlias} = ${parentType};`);
69
+ const scope = typeScopeImports(absolutizeRelativeSpecifiers(code, path.dirname(currentFile)), id);
41
70
  declarations.push(...scope.imports);
42
71
  const contract = inheritedContextContract(code);
43
72
  if (contract && anchor !== void 0) {
@@ -47,10 +76,10 @@ export function inheritedContextChecks(source, options) {
47
76
  ${contract.types}
48
77
  const __contract = defineProps<InheritedContext>();`, `${id}Contract`);
49
78
  declarations.push(projected.declarations);
50
- declarations.push(`declare const ${id}Input: ${parentType};`);
51
- check(anchor, `${id}Input satisfies ${projected.props};`);
79
+ declarations.push(`declare const ${id}Input: ${parentAlias};`);
80
+ check(anchor, contract.unsupported ? `({})[${JSON.stringify(contract.unsupported)}];` : `${id}Input satisfies ${projected.props};`);
52
81
  }
53
- const own = collectBlockDeclarations(code), input = [...new Set([...parentKeys, ...contract?.keys || []])].filter((key) => !own.includes(key)), inheritedType = contract ? `${parentType} & ${id}Contract.__StxProps` : parentType, body = blankScriptDirectives(scope.body).replace(/^[ \t]*export[ \t]+(?=(?:const|let|var|function|async|class|interface|type)\b)/gm, ""), edges = [], masked = maskNonTemplateRegions(text), directive = /@(include|extends|layout)\s*\(/g;
82
+ const own = [...new Set([...collectBlockDeclarations(code), ...inheritedValueImports(code)])], input = [...new Set([...parentKeys, ...contract?.keys || []])].filter((key) => !own.includes(key)), inheritedType = contract ? `${parentAlias} & ${id}Contract.__StxProps` : parentAlias, body = blankScriptDirectives(scope.body).replace(/^[ \t]*export[ \t]+(?=(?:const|let|var|function|async|class|interface|type)\b)/gm, ""), edges = [], masked = maskNonTemplateRegions(text), directive = /@(include|extends|layout)\s*\(/g;
54
83
  let match;
55
84
  while (match = directive.exec(masked)) {
56
85
  const parsed = componentDirectiveExpression(masked, directive.lastIndex - 1);
@@ -72,12 +101,12 @@ const __contract = defineProps<InheritedContext>();`, `${id}Contract`);
72
101
  }
73
102
  edges.push({ name: `edge${edges.length}`, target, kind, args: kind === "include" ? literal[3] || "{}" : "{}", offset: anchor ?? match.index });
74
103
  }
75
- const context = `{ ...parent${own.length ? ", " + own.join(", ") : ""} }`;
104
+ const context = `{ ...${parentValue}${own.length ? ", " + own.join(", ") : ""} }`;
76
105
  declarations.push(`namespace ${id} {
77
106
  ${scope.aliases.join(`
78
107
  `)}
79
- export async function read(parent: ${anchor === void 0 ? "{}" : inheritedType}) {
80
- ${input.length ? `const { ${input.join(", ")} } = parent;` : ""}
108
+ export async function read(${parentValue}: ${anchor === void 0 ? "{}" : inheritedType}) {
109
+ ${input.length ? `const { ${input.join(", ")} } = ${parentValue};` : ""}
81
110
  ${body}
82
111
  return { context: ${context}${edges.map((edge) => `, ${edge.name}: { ...${context}, ...(${edge.args}) }`).join("")} };
83
112
  }
@@ -0,0 +1,2 @@
1
+ /** Ask the compiler parser whether a valid, import-free body needs async scope. */
2
+ export declare function requiresAsyncBody(code: string): boolean;
@@ -0,0 +1,21 @@
1
+ import { hasTopLevelAwait } from "./client-parameter-bindings.js";
2
+ export function requiresAsyncBody(code) {
3
+ const parser = new Bun.Transpiler({ loader: "js" });
4
+ if (hasTopLevelAwait(code)) {
5
+ parser.transformSync(`(async function(){
6
+ ${code}
7
+ })()`);
8
+ return !0;
9
+ }
10
+ try {
11
+ parser.transformSync(`(function(){
12
+ ${code}
13
+ })()`);
14
+ return !1;
15
+ } catch {
16
+ parser.transformSync(`(async function(){
17
+ ${code}
18
+ })()`);
19
+ return !0;
20
+ }
21
+ }
@@ -1,27 +1,41 @@
1
- import { clientMethods, componentScriptSource, componentDirectiveExpression, parseMetadata, parseNativeComponentLoop, typeForProperty } from "./component-library.js";
2
- import { stripCommentsAndLiterals } from "./strip-literals.js";
1
+ import { scanHtmlScriptElements } from "./html-masking.js";
2
+ import { clientMethods, componentScriptSource, componentMetadataBlock, componentDirectiveExpression, parseMetadata, parseNativeComponentLoop, typeForProperty } from "./component-library.js";
3
+ import { scriptAttributes, scriptContainsCode } from "./script-attributes.js";
4
+ import { bracketDepths, stripCommentsAndLiterals } from "./strip-literals.js";
5
+ import { collectImportedNames, extractTypeDeclarations } from "./stx-virtual-ts.js";
3
6
  export function nativeComponentContext(source, validate) {
4
- const scannable = componentScriptSource(source);
5
- if (!/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))/i.test(scannable))
7
+ const scannable = componentScriptSource(source), metadataBlock = componentMetadataBlock(source);
8
+ if (!metadataBlock)
6
9
  return;
7
10
  let metadata;
8
11
  try {
9
12
  metadata = parseMetadata(source, "component");
10
13
  } catch (error) {
11
- const at = source.search(/<script\b(?=[^>]*\bcomponent\b)/i), message = error instanceof Error ? error.message : "Invalid component metadata";
14
+ const at = metadataBlock.open, message = error instanceof Error ? error.message : "Invalid component metadata";
12
15
  return { declarations: "", checks: [{ text: `({})[${JSON.stringify(message)}];`, line: source.slice(0, at).split(`
13
16
  `).length, column: at - source.lastIndexOf(`
14
17
  `, at - 1), origin: "component" }], project: (code) => ({ code, columns: new Map }) };
15
18
  }
16
- const blocks = [...scannable.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].filter((block) => /\bclient\b/.test(block[1]) && !/\bcomponent\b/.test(block[1])), script = blocks.map((block) => {
17
- const at = block.index + block[0].indexOf(">") + 1;
18
- return source.slice(at, at + block[2].length);
19
- }).join(`
20
- `), methods = clientMethods(script, validate), hasState = /\b(?:interface|type)\s+ComponentState\b/.test(stripCommentsAndLiterals(script)), properties = Object.entries(metadata.properties || metadata.props || {}).map(([name, property]) => `${JSON.stringify(name)}: ${typeForProperty(property)}`).join("; "), names = [...new Set(methods.map((method) => method.name))], declarations = [
19
+ const blocks = scanHtmlScriptElements(scannable).filter((block) => {
20
+ const attributes = scriptAttributes(block.attrs);
21
+ return scriptContainsCode(attributes) && attributes.has("client") && !attributes.has("server") && !attributes.has("component") && !attributes.has("stx:component") && !attributes.has("src");
22
+ }), script = blocks.map((block) => source.slice(block.bodyStart, block.bodyEnd)).join(`
23
+ `), methods = clientMethods(script, validate), hasState = extractTypeDeclarations(script).some((type) => type.name === "ComponentState") || collectImportedNames(script).includes("ComponentState"), properties = Object.entries(metadata.properties || metadata.props || {}).map(([name, property]) => `${JSON.stringify(name)}: ${typeForProperty(property)}`).join("; "), names = [...new Set(methods.map((method) => method.name))], declarations = [
21
24
  `interface __StxMetadataProperties { ${properties} }`,
22
25
  "type __StxNativeProperties = Omit<__StxMetadataProperties, keyof HTMLElement> & Pick<HTMLElement, Extract<keyof __StxMetadataProperties, keyof HTMLElement>>;",
23
- hasState ? "declare const __stxStateProperties: Pick<ComponentState, Extract<keyof ComponentState, keyof __StxNativeProperties>>;" : "",
24
- `type __StxNativeComponent = Omit<HTMLElement, keyof __StxNativeProperties | ${hasState ? "keyof ComponentState | " : ""}${names.map((name) => JSON.stringify(name)).join(" | ") || "never"}> & ${hasState ? "Omit<__StxNativeProperties, keyof ComponentState> & ComponentState" : "__StxNativeProperties"} & {`,
26
+ "type __StxAny<T> = 0 extends (1 & T) ? true : false;",
27
+ "type __StxAnyFields<T> = { [K in keyof T]-?: __StxAny<T[K]> extends true ? K : never }[keyof T];",
28
+ "type __StxSpecific<T> = __StxAny<T> extends true ? false : T extends object ? string extends keyof T ? false : number extends keyof T ? false : symbol extends keyof T ? false : __StxAnyFields<T> extends never ? true : false : false;",
29
+ hasState ? "type __StxState = __StxSpecific<ComponentState> extends true ? ComponentState : {};" : "type __StxState = {};",
30
+ hasState ? 'declare function __stxSpecificState(value: __StxSpecific<ComponentState> extends true ? true : "ComponentState requires named explicit fields without any or index signatures"): void;' : "",
31
+ hasState ? "declare const __stxStateProperties: Pick<ComponentState, Extract<keyof ComponentState, keyof __StxInstanceProperties>>;" : "",
32
+ hasState ? 'declare function __stxStateMethods(value: Extract<keyof ComponentState, __StxMethodNames | "emit" | "requestUpdate" | "updateComplete" | "renderRoot"> extends never ? true : "ComponentState cannot redeclare component methods"): void;' : "",
33
+ `type __StxMethodNames = ${names.map((name) => JSON.stringify(name)).join(" | ") || "never"};`,
34
+ "type __StxInstanceProperties = Omit<HTMLElement, __StxMethodNames | keyof __StxNativeProperties> & __StxNativeProperties;",
35
+ 'type __StxPrivateKeys<T> = Exclude<keyof T, keyof HTMLElement | keyof __StxNativeProperties | __StxMethodNames | "emit" | "updateComplete" | "requestUpdate" | "renderRoot">;',
36
+ hasState ? 'declare function __stxOptionalPrivate(value: { [K in __StxPrivateKeys<ComponentState>]-?: {} extends Pick<ComponentState, K> ? never : K }[__StxPrivateKeys<ComponentState>] extends never ? true : "Private ComponentState fields must be optional until initialized"): void;' : "",
37
+ "type __StxRefinedProperties = { [K in keyof __StxNativeProperties]: K extends keyof __StxState ? __StxAny<__StxState[K]> extends true ? __StxNativeProperties[K] : __StxState[K] extends __StxNativeProperties[K] ? __StxState[K] : __StxNativeProperties[K] : __StxNativeProperties[K] };",
38
+ "type __StxNativeComponent = Omit<HTMLElement, keyof __StxNativeProperties | __StxMethodNames> & __StxRefinedProperties & Partial<Pick<__StxState, __StxPrivateKeys<__StxState>>> & {",
25
39
  "readonly updateComplete: Promise<void>; requestUpdate(): Promise<void>; readonly renderRoot: HTMLElement | ShadowRoot;",
26
40
  "emit<T = unknown>(name: string, detail?: T, options?: CustomEventInit<T>): boolean;",
27
41
  ...names.map((name) => `${JSON.stringify(name)}: typeof ${name};`),
@@ -30,17 +44,29 @@ export function nativeComponentContext(source, validate) {
30
44
  `);
31
45
  let stateOffset = -1;
32
46
  for (const block of blocks) {
33
- const bodyStart = block.index + block[0].indexOf(">") + 1, found = /\b(?:interface|type)\s+ComponentState\b/.exec(stripCommentsAndLiterals(source.slice(bodyStart, bodyStart + block[2].length)));
47
+ const bodyStart = block.bodyStart, code = source.slice(bodyStart, block.bodyEnd), masked = stripCommentsAndLiterals(code), depths = bracketDepths(masked).depths, found = [...masked.matchAll(/\b(?:interface|type)\s+ComponentState\b/g)].find((match) => depths[match.index] === 0) ?? (collectImportedNames(code).includes("ComponentState") ? /\bComponentState\b/.exec(masked) : void 0);
34
48
  if (found) {
35
49
  stateOffset = bodyStart + found.index;
36
50
  break;
37
51
  }
38
52
  }
39
- const checks = hasState && stateOffset >= 0 ? [{ origin: "client", text: "__stxStateProperties satisfies Pick<__StxNativeProperties, Extract<keyof ComponentState, keyof __StxNativeProperties>>;", line: source.slice(0, stateOffset).split(`
53
+ const checks = hasState && stateOffset >= 0 ? [{ origin: "client", text: "__stxSpecificState(true); __stxStateMethods(true); __stxOptionalPrivate(true); __stxStateProperties satisfies Pick<__StxInstanceProperties, Extract<keyof ComponentState, keyof __StxInstanceProperties>>;", line: source.slice(0, stateOffset).split(`
40
54
  `).length, column: stateOffset - source.lastIndexOf(`
41
- `, stateOffset - 1) }] : [];
55
+ `, stateOffset - 1) }] : [], { start: metadataStart, code: raw } = metadataBlock, maskedMetadata = stripCommentsAndLiterals(raw), metadataDepths = bracketDepths(maskedMetadata).depths, positions = new Map;
56
+ let inProperties = !1;
57
+ for (const token of raw.matchAll(/"(?:\\.|[^"\\])*"\s*:/g)) {
58
+ const key = JSON.parse(token[0].slice(0, token[0].lastIndexOf(":")).trim());
59
+ if (metadataDepths[token.index] === 1 && ["properties", "props"].includes(key)) {
60
+ inProperties = !0;
61
+ continue;
62
+ }
63
+ if (inProperties && metadataDepths[token.index] === 1)
64
+ inProperties = !1;
65
+ if (inProperties && metadataDepths[token.index] === 2 && !positions.has(key))
66
+ positions.set(key, metadataStart + token.index);
67
+ }
42
68
  for (const [name, property] of Object.entries(metadata.properties || metadata.props || {})) {
43
- const at = source.indexOf(JSON.stringify(name), source.indexOf("<script")), line = source.slice(0, at).split(`
69
+ const at = positions.get(name) ?? metadataStart, line = source.slice(0, at).split(`
44
70
  `).length, column = at - source.lastIndexOf(`
45
71
  `, at - 1);
46
72
  if (!property || typeof property !== "object" || !["string", "number", "boolean", "object", "array"].includes(property.type))