@stacksjs/stx 0.2.302 → 0.2.304

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 (271) hide show
  1. package/dist/api-client.d.ts +26 -0
  2. package/dist/api-client.js +22 -0
  3. package/dist/api-handler.d.ts +6 -0
  4. package/dist/api-handler.js +3 -0
  5. package/dist/app-shell.js +11 -2
  6. package/dist/application-layers.d.ts +30 -0
  7. package/dist/application-layers.js +202 -0
  8. package/dist/build.js +9 -1
  9. package/dist/chunk-02hm88m5.js +2 -0
  10. package/dist/{chunk-7eea1cse.js → chunk-09zjty4k.js} +1 -1
  11. package/dist/{chunk-7nfn7nj9.js → chunk-0gz0rhvs.js} +1 -1
  12. package/dist/{chunk-jsfch50r.js → chunk-1c2j4eby.js} +1 -1
  13. package/dist/{chunk-m6wz1hf5.js → chunk-2h94c5hm.js} +2 -2
  14. package/dist/{chunk-mjpqz66q.js → chunk-2ver2s2y.js} +1 -1
  15. package/dist/{chunk-2wcd2031.js → chunk-30nbe9hr.js} +2 -2
  16. package/dist/chunk-39qzhpn6.js +18 -0
  17. package/dist/chunk-3z6bqqr7.js +2 -0
  18. package/dist/chunk-43p1qq7g.js +2 -0
  19. package/dist/{chunk-52rkkkmt.js → chunk-45y8bjrv.js} +287 -352
  20. package/dist/{chunk-2rp09y5j.js → chunk-4evbx7sz.js} +1 -1
  21. package/dist/chunk-4jgr954p.js +2 -0
  22. package/dist/chunk-51j2aqvb.js +2 -0
  23. package/dist/{chunk-8d15pd4g.js → chunk-54f8bpp6.js} +3 -3
  24. package/dist/{chunk-cbwp8prr.js → chunk-5k1hznvq.js} +2 -2
  25. package/dist/chunk-5qfpcgcs.js +2 -0
  26. package/dist/{chunk-7eg7ep8f.js → chunk-5tefa8qb.js} +2 -2
  27. package/dist/chunk-5x2fc4vk.js +30 -0
  28. package/dist/{chunk-683tfkz4.js → chunk-64djh88a.js} +1 -1
  29. package/dist/{chunk-btrmvj2y.js → chunk-695fkras.js} +1 -1
  30. package/dist/chunk-6hcc4973.js +2 -0
  31. package/dist/{chunk-svg37jzs.js → chunk-6vswphz4.js} +2 -2
  32. package/dist/chunk-7gqbr8nr.js +2 -0
  33. package/dist/{chunk-x4prtyjs.js → chunk-7kw3grq5.js} +1 -1
  34. package/dist/{chunk-7jebw3ea.js → chunk-7skk34dh.js} +2 -2
  35. package/dist/chunk-8215nhej.js +12 -0
  36. package/dist/chunk-8ee62a9q.js +2 -0
  37. package/dist/{chunk-jj6yp7gm.js → chunk-8jam44my.js} +1 -1
  38. package/dist/chunk-8z0n5mtg.js +2 -0
  39. package/dist/{chunk-3bc8bqw2.js → chunk-9368t9jm.js} +1 -1
  40. package/dist/chunk-9499k64n.js +6 -0
  41. package/dist/chunk-976g5qe5.js +2 -0
  42. package/dist/{chunk-3jwmcf4k.js → chunk-9c835qjn.js} +1 -1
  43. package/dist/chunk-9px4y692.js +2 -0
  44. package/dist/{chunk-38t0fxh0.js → chunk-9vqnrcrw.js} +2 -2
  45. package/dist/chunk-9wrrr7g3.js +4 -0
  46. package/dist/{chunk-q0y1yxg3.js → chunk-9xzszvn5.js} +1 -1
  47. package/dist/chunk-a07chbgj.js +2 -0
  48. package/dist/{chunk-454kar39.js → chunk-ankp4reb.js} +2 -2
  49. package/dist/{chunk-5d9cy7a0.js → chunk-awj7yy37.js} +1 -1
  50. package/dist/chunk-b1hd8kvy.js +2 -0
  51. package/dist/chunk-b4xwbh8a.js +2 -0
  52. package/dist/{chunk-d6wq91cw.js → chunk-bd9wrcq1.js} +277 -21
  53. package/dist/{chunk-q25mr70f.js → chunk-c131k3mt.js} +1 -1
  54. package/dist/chunk-c3tmzx7q.js +2 -0
  55. package/dist/{chunk-6btbgxh1.js → chunk-c79nfdyj.js} +1 -1
  56. package/dist/{chunk-cfgpk6bh.js → chunk-cbgh359m.js} +1 -1
  57. package/dist/chunk-ckzhp09g.js +2 -0
  58. package/dist/{chunk-weqpt9nt.js → chunk-cr8v8k53.js} +1 -1
  59. package/dist/{chunk-p3wwm6k4.js → chunk-d19tvdvv.js} +1 -1
  60. package/dist/{chunk-nb1zdh1y.js → chunk-d3srvh3q.js} +1 -1
  61. package/dist/{chunk-rqrfq305.js → chunk-d57gb0v2.js} +1 -1
  62. package/dist/{chunk-1xyhk1wr.js → chunk-d5cqnwdd.js} +1 -1
  63. package/dist/chunk-dgpjxmhs.js +2 -0
  64. package/dist/chunk-dvvx1wny.js +3 -0
  65. package/dist/{chunk-ctz53mbz.js → chunk-ej8mv2k6.js} +1 -1
  66. package/dist/{chunk-dv3z80gt.js → chunk-env6knrs.js} +1 -1
  67. package/dist/{chunk-rf10fkrf.js → chunk-ess2pgt5.js} +1 -1
  68. package/dist/chunk-ez28vck6.js +2 -0
  69. package/dist/{chunk-0tbgvp70.js → chunk-fczfdsab.js} +21 -5
  70. package/dist/{chunk-xdq52pwj.js → chunk-fp7ms6e7.js} +1 -1
  71. package/dist/{chunk-qg6pg6ze.js → chunk-fqq5k9ve.js} +1 -1
  72. package/dist/chunk-fvtv1s5j.js +3 -0
  73. package/dist/{chunk-5t0w4h6z.js → chunk-g912mb7x.js} +1 -1
  74. package/dist/chunk-g97atepq.js +2 -0
  75. package/dist/{chunk-wj25qt72.js → chunk-gbwhbasw.js} +1 -1
  76. package/dist/{chunk-38e9wgfc.js → chunk-gfc3qye3.js} +2 -2
  77. package/dist/{chunk-cratkhhb.js → chunk-ghw5p1yk.js} +1 -1
  78. package/dist/{chunk-f0g2q51j.js → chunk-gssbag3e.js} +1 -1
  79. package/dist/{chunk-c9vhtjtr.js → chunk-gt8ja700.js} +2 -2
  80. package/dist/chunk-hay1rzb0.js +3754 -0
  81. package/dist/{chunk-q5sw26s7.js → chunk-hg2afckn.js} +1 -1
  82. package/dist/chunk-hgjjnjas.js +7 -0
  83. package/dist/{chunk-hhnzd03k.js → chunk-hrcxfvh1.js} +1 -1
  84. package/dist/chunk-hzav4hyd.js +2 -0
  85. package/dist/{chunk-29gjwajm.js → chunk-jfzfrmzy.js} +1 -1
  86. package/dist/chunk-jjq9q9jr.js +2 -0
  87. package/dist/{chunk-ddqkj56r.js → chunk-jp2f8yzw.js} +1 -1
  88. package/dist/{chunk-ry3a2674.js → chunk-jsg1rthc.js} +1 -1
  89. package/dist/chunk-jxxv18a0.js +5 -0
  90. package/dist/chunk-kbw2qzqx.js +2 -0
  91. package/dist/chunk-kdxvraec.js +2 -0
  92. package/dist/chunk-krfjb7b8.js +2 -0
  93. package/dist/{chunk-6b4k8fay.js → chunk-kxavsh3m.js} +1 -1
  94. package/dist/{chunk-4tffxxpd.js → chunk-m31n9pkr.js} +1 -1
  95. package/dist/{chunk-fj6fbqgb.js → chunk-m3a20mmb.js} +1 -1
  96. package/dist/{chunk-j21csh4j.js → chunk-mbmqpaq1.js} +1 -1
  97. package/dist/{chunk-y9nyqcha.js → chunk-mwh3ymwc.js} +1 -1
  98. package/dist/{chunk-51g95yts.js → chunk-mygq61f5.js} +2 -2
  99. package/dist/chunk-nqq7y7m9.js +3 -0
  100. package/dist/chunk-nws8fbde.js +2 -0
  101. package/dist/{chunk-q6xfyasj.js → chunk-pcvayb2f.js} +1 -1
  102. package/dist/{chunk-nvxv2wxv.js → chunk-ppyz9623.js} +1 -1
  103. package/dist/chunk-pr14wjkn.js +2 -0
  104. package/dist/{chunk-jb2r696a.js → chunk-qev11kg8.js} +1 -1
  105. package/dist/{chunk-6njgsr6w.js → chunk-qeyw5za9.js} +1 -1
  106. package/dist/chunk-rpfcnq8n.js +2 -0
  107. package/dist/chunk-rrankpmj.js +3 -0
  108. package/dist/chunk-rst1rw09.js +2 -0
  109. package/dist/{chunk-3p0zgfgz.js → chunk-rzevgemj.js} +2 -2
  110. package/dist/{chunk-aa6kt84c.js → chunk-sart9ehj.js} +1 -1
  111. package/dist/chunk-sb7ana2z.js +19 -0
  112. package/dist/chunk-snt2773t.js +2 -0
  113. package/dist/{chunk-jptkc64r.js → chunk-t3qb9s6s.js} +2 -2
  114. package/dist/{chunk-w8yac9xp.js → chunk-t41aaehf.js} +1 -1
  115. package/dist/{chunk-qjkzpd68.js → chunk-t51mwjyq.js} +1 -1
  116. package/dist/chunk-tt4r8q4v.js +2 -0
  117. package/dist/chunk-vd3h9z7e.js +2 -0
  118. package/dist/{chunk-6rzwef28.js → chunk-vd5xvsnv.js} +1 -1
  119. package/dist/chunk-wbecqx03.js +2 -0
  120. package/dist/{chunk-dcxtrqfy.js → chunk-wfffa8zm.js} +1 -1
  121. package/dist/{chunk-22p0ezj6.js → chunk-wx13qmaw.js} +1 -1
  122. package/dist/chunk-xd5ahrtn.js +2 -0
  123. package/dist/{chunk-vh0qr8k9.js → chunk-xganfzgn.js} +2 -2
  124. package/dist/chunk-xq1swv2e.js +2 -0
  125. package/dist/chunk-xsfwcj6x.js +2 -0
  126. package/dist/{chunk-91007tan.js → chunk-xwxdwqn9.js} +1 -1
  127. package/dist/{chunk-634gaa9d.js → chunk-xz3evxqp.js} +1 -1
  128. package/dist/chunk-xzgvcrnz.js +2 -0
  129. package/dist/chunk-y2kmm6bt.js +43 -0
  130. package/dist/{chunk-v8474ah4.js → chunk-y4nzmkea.js} +1 -1
  131. package/dist/chunk-y7wsk78j.js +3 -0
  132. package/dist/{chunk-6w8fa3b8.js → chunk-ya5m5vbn.js} +1 -1
  133. package/dist/{chunk-ps20v1ah.js → chunk-ym3r8ktq.js} +1 -1
  134. package/dist/chunk-yyebm8q4.js +2 -0
  135. package/dist/chunk-yyyxt326.js +2 -0
  136. package/dist/chunk-yz16bgs3.js +28 -0
  137. package/dist/{chunk-em8p71et.js → chunk-z9ezmjwd.js} +2 -2
  138. package/dist/chunk-zbtfhxhn.js +2 -0
  139. package/dist/chunk-zggm7kjd.js +17 -0
  140. package/dist/{chunk-mdf3jbe6.js → chunk-zhcs8m2a.js} +2 -2
  141. package/dist/{chunk-f9d27v49.js → chunk-zs5y7xnt.js} +1 -1
  142. package/dist/cli.js +14 -14
  143. package/dist/client-script-bundler.js +22 -11
  144. package/dist/component-contract-checks.d.ts +19 -0
  145. package/dist/component-contract-checks.js +147 -0
  146. package/dist/component-contract.d.ts +20 -0
  147. package/dist/component-contract.js +108 -0
  148. package/dist/component-model.d.ts +29 -0
  149. package/dist/component-model.js +59 -0
  150. package/dist/component-registry.js +7 -64
  151. package/dist/component-renderer.d.ts +1 -26
  152. package/dist/component-renderer.js +4 -239
  153. package/dist/component-resolution.d.ts +21 -0
  154. package/dist/component-resolution.js +118 -0
  155. package/dist/component-tags.d.ts +9 -0
  156. package/dist/component-tags.js +174 -0
  157. package/dist/composable-loader.d.ts +2 -13
  158. package/dist/composable-loader.js +15 -26
  159. package/dist/composables/index.d.ts +1 -0
  160. package/dist/composables/index.js +1 -0
  161. package/dist/composables/use-fetch.d.ts +117 -42
  162. package/dist/composables/use-fetch.js +47 -4
  163. package/dist/composition-api.d.ts +43 -19
  164. package/dist/config.d.ts +1 -1
  165. package/dist/config.js +46 -4
  166. package/dist/craft-entry.js +1 -1
  167. package/dist/craft.js +1 -1
  168. package/dist/database.js +1 -1
  169. package/dist/dev-server/serve-app.js +57 -17
  170. package/dist/dev-server/serve-file.js +8 -1
  171. package/dist/expressions.js +1 -1
  172. package/dist/imported-signals.js +1 -1
  173. package/dist/includes.js +8 -2
  174. package/dist/index.d.ts +11 -0
  175. package/dist/index.js +7 -0
  176. package/dist/manifest.d.ts +6 -0
  177. package/dist/misc-directives.d.ts +2 -0
  178. package/dist/misc-directives.js +39 -1
  179. package/dist/process.js +18 -1
  180. package/dist/production-builder.d.ts +4 -0
  181. package/dist/production-builder.js +47 -8
  182. package/dist/production-server.d.ts +4 -1
  183. package/dist/production-server.js +119 -71
  184. package/dist/pwa.js +2 -2
  185. package/dist/render.js +9 -2
  186. package/dist/route-response-cache.d.ts +7 -0
  187. package/dist/route-response-cache.js +72 -0
  188. package/dist/route-rules.d.ts +17 -0
  189. package/dist/route-rules.js +40 -0
  190. package/dist/router.d.ts +1 -0
  191. package/dist/runtime-config-loader.d.ts +5 -0
  192. package/dist/runtime-config-loader.js +42 -0
  193. package/dist/runtime-config-server.d.ts +26 -0
  194. package/dist/runtime-config-server.js +77 -0
  195. package/dist/runtime-config-types.d.ts +2 -0
  196. package/dist/runtime-config-types.js +0 -0
  197. package/dist/runtime-config.d.ts +5 -0
  198. package/dist/runtime-config.js +9 -0
  199. package/dist/runtime-globals.js +3 -0
  200. package/dist/serve.js +32 -10
  201. package/dist/server-api.d.ts +27 -0
  202. package/dist/server-api.js +181 -0
  203. package/dist/server-data.d.ts +17 -0
  204. package/dist/server-data.js +40 -0
  205. package/dist/signal-processing.js +2 -2
  206. package/dist/signals.js +210 -17
  207. package/dist/ssg.js +2 -2
  208. package/dist/stx-virtual-ts.d.ts +6 -0
  209. package/dist/stx-virtual-ts.js +31 -7
  210. package/dist/stx.d.ts +28 -0
  211. package/dist/template-compiler.d.ts +1 -0
  212. package/dist/template-compiler.js +1 -1
  213. package/dist/template-hydrator.js +15 -4
  214. package/dist/typecheck.d.ts +1 -0
  215. package/dist/typecheck.js +4 -3
  216. package/dist/types/config-types.d.ts +17 -0
  217. package/dist/utils.js +15 -5
  218. package/dist/variable-extractor.d.ts +1 -1
  219. package/dist/variable-extractor.js +12 -1
  220. package/dist/visual-testing.js +1 -1
  221. package/dist/vue-template.js +19 -41
  222. package/package.json +5 -5
  223. package/stx.d.ts +28 -0
  224. package/dist/chunk-0p44z42s.js +0 -2
  225. package/dist/chunk-1na1dvda.js +0 -2
  226. package/dist/chunk-2yp8ang5.js +0 -2
  227. package/dist/chunk-35x7s4cr.js +0 -2
  228. package/dist/chunk-39qnycbc.js +0 -2
  229. package/dist/chunk-4qj6pq60.js +0 -2
  230. package/dist/chunk-4r1qdp25.js +0 -19
  231. package/dist/chunk-4xs545h1.js +0 -2
  232. package/dist/chunk-70cf5h11.js +0 -2
  233. package/dist/chunk-7k63nhap.js +0 -28
  234. package/dist/chunk-7w3dttqh.js +0 -2
  235. package/dist/chunk-813dt09p.js +0 -2
  236. package/dist/chunk-9cp3430d.js +0 -2
  237. package/dist/chunk-ac9vpa5z.js +0 -2
  238. package/dist/chunk-b26xazrf.js +0 -2
  239. package/dist/chunk-b2ghmxpj.js +0 -4
  240. package/dist/chunk-btnky17z.js +0 -12
  241. package/dist/chunk-c7av0px6.js +0 -2
  242. package/dist/chunk-cthpzv4p.js +0 -18
  243. package/dist/chunk-d41b0rqp.js +0 -2
  244. package/dist/chunk-dkd0bg8g.js +0 -2
  245. package/dist/chunk-e0s519df.js +0 -2
  246. package/dist/chunk-ebr2344x.js +0 -3
  247. package/dist/chunk-ehp6fez3.js +0 -2
  248. package/dist/chunk-fc5t3cxt.js +0 -2
  249. package/dist/chunk-g6ttsdz1.js +0 -2
  250. package/dist/chunk-gd73rpks.js +0 -2
  251. package/dist/chunk-gv42xz15.js +0 -17
  252. package/dist/chunk-h3t6fjba.js +0 -2
  253. package/dist/chunk-h65nep6y.js +0 -2
  254. package/dist/chunk-h7d01cy7.js +0 -2
  255. package/dist/chunk-jc57j887.js +0 -2
  256. package/dist/chunk-k5xtf38q.js +0 -3
  257. package/dist/chunk-mc4rtf5d.js +0 -2
  258. package/dist/chunk-me5kq4e6.js +0 -22
  259. package/dist/chunk-mzf6c0h7.js +0 -2
  260. package/dist/chunk-n1j7gfe1.js +0 -3
  261. package/dist/chunk-pczxwdes.js +0 -2
  262. package/dist/chunk-pq6rabcy.js +0 -3754
  263. package/dist/chunk-qr59yfq9.js +0 -2
  264. package/dist/chunk-s454ytp4.js +0 -2
  265. package/dist/chunk-s4sp78fn.js +0 -2
  266. package/dist/chunk-shr928nn.js +0 -2
  267. package/dist/chunk-that7v95.js +0 -2
  268. package/dist/chunk-vwnnbzsp.js +0 -2
  269. package/dist/chunk-w63052rn.js +0 -2
  270. package/dist/chunk-w9kzfesd.js +0 -2
  271. package/dist/chunk-zwy5e35f.js +0 -30
@@ -0,0 +1,17 @@
1
+ interface ServerDataScope {
2
+ pending: Map<string, Promise<unknown>>;
3
+ values: Map<string, unknown>;
4
+ }
5
+ /** @internal Shared by nested contexts, never by separate render requests. */
6
+ export declare function serverDataScope(context: Record<string, any>): ServerDataScope;
7
+ /** @internal Run server scripts with their render's data scope, including imports. */
8
+ export declare function withServerData<T>(context: Record<string, any>, run: () => T): T;
9
+ /**
10
+ * Load JSON data once per key in this server render and expose it for hydration.
11
+ * Only call in a server script. Everything returned is sent to the browser;
12
+ * never return credentials or other server-only data.
13
+ */
14
+ export declare function useServerData<T>(key: string, loader: () => T | Promise<T>): Promise<T>;
15
+ /** @internal Data-only tag: no executable serialization or script-breakout. */
16
+ export declare function serverDataTag(context: Record<string, any>): string;
17
+ export {};
@@ -0,0 +1,40 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ const currentScope = new AsyncLocalStorage;
3
+ export function serverDataScope(context) {
4
+ return context.__stx_server_data ??= { pending: new Map, values: new Map };
5
+ }
6
+ export function withServerData(context, run) {
7
+ return currentScope.run(serverDataScope(context), run);
8
+ }
9
+ export async function useServerData(key, loader) {
10
+ const scope = currentScope.getStore();
11
+ if (!scope)
12
+ throw Error("useServerData must run inside a <script server> render");
13
+ if (typeof key !== "string" || !key.trim())
14
+ throw TypeError("useServerData requires a non-empty string key");
15
+ const existing = scope.pending.get(key);
16
+ if (existing)
17
+ return existing;
18
+ const pending = Promise.resolve().then(loader).then((value) => {
19
+ const json = JSON.stringify(value, (_name, entry) => {
20
+ if (entry === void 0 || typeof entry === "function" || typeof entry === "symbol" || typeof entry === "bigint" || typeof entry === "number" && !Number.isFinite(entry))
21
+ throw TypeError(`useServerData(${JSON.stringify(key)}) requires JSON-serializable data`);
22
+ if (entry && typeof entry === "object" && !Array.isArray(entry) && Object.getPrototypeOf(entry) !== Object.prototype && Object.getPrototypeOf(entry) !== null)
23
+ throw TypeError(`useServerData(${JSON.stringify(key)}) requires JSON-serializable data`);
24
+ return entry;
25
+ }), normalized = JSON.parse(json);
26
+ scope.values.set(key, normalized);
27
+ return normalized;
28
+ }).catch((error) => {
29
+ scope.pending.delete(key);
30
+ throw error;
31
+ });
32
+ scope.pending.set(key, pending);
33
+ return pending;
34
+ }
35
+ export function serverDataTag(context) {
36
+ const scope = context.__stx_server_data;
37
+ if (!scope?.values.size)
38
+ return "";
39
+ return `<script data-stx-scoped data-stx-server-data type="application/json">${JSON.stringify(Object.fromEntries(scope.values)).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029")}</script>`;
40
+ }
@@ -99,7 +99,7 @@ function hasTopLevelElseBranch(content) {
99
99
  return !1;
100
100
  }
101
101
  function extractClientSignalNames(template) {
102
- const names = new Set, scriptRe = /<script\b(?![^>]*\bserver\b)(?![^>]*\bsrc\s*=)[^>]*>([\s\S]*?)<\/script>/gi, declRe = /\b(?:const|let|var)\s+([a-zA-Z_$][\w$]*)\s*=\s*(?:state|derived|computed|ref|reactive|signal)\s*(?:<[^>]*>)?\s*\(/g;
102
+ const names = new Set, scriptRe = /<script\b(?![^>]*\bserver\b)(?![^>]*\bsrc\s*=)[^>]*>([\s\S]*?)<\/script>/gi, declRe = /\b(?:const|let|var)\s+([a-zA-Z_$][\w$]*)\s*=\s*(?:state|derived|computed|ref|reactive|signal|useModel)\s*(?:<[^>]*>)?\s*\(/g;
103
103
  let scriptMatch;
104
104
  while ((scriptMatch = scriptRe.exec(template)) !== null) {
105
105
  const body = scriptMatch[1];
@@ -764,7 +764,7 @@ function rebuildSetupOwner(template, ranges, markerAt, setupFnName) {
764
764
  export async function processScriptSetup(template, filePath, serverData) {
765
765
  const scripts = scanScriptTags(template, {
766
766
  skipAttrs: /\bserver\b|\bsrc\s*=|\bdata-stx-scoped\b|\bdata-stx-router\b/
767
- }), SIGNAL_API_RE = /\b(?:state|derived|effect|ref|reactive|computed|watch|watchEffect|useStore|useLocalStorage|useSessionStorage|useCookie|useId|useReactiveProp|useFetch|useRef|useEventListener|useDebounce|useDebouncedValue|useThrottle|useInterval|useTimeout|useToggle|useCounter|useClickOutside|useFocus|useAsync|useColorMode|useDark|useMediaQuery|useScrollLock|usePreferredDark|usePreferredLight|usePreferredReducedMotion|usePreferredContrast|useWebSocket|useRoute|useSearchParams|onMount|onDestroy|defineProps|withDefaults|defineEmits|defineExpose|defineSlots|useOptimistic)\s*(?:<[^>]*>)?\s*\(/, signalScripts = [], { hasUserImports, bundleClientScript } = await importOnce("stx/client-script-bundler", () => import("./client-script-bundler.js"));
767
+ }), SIGNAL_API_RE = /\b(?:state|derived|effect|ref|reactive|computed|watch|watchEffect|useStore|useLocalStorage|useSessionStorage|useCookie|useId|useModel|useReactiveProp|useFetch|useRef|useEventListener|useDebounce|useDebouncedValue|useThrottle|useInterval|useTimeout|useToggle|useCounter|useClickOutside|useFocus|useAsync|useColorMode|useDark|useMediaQuery|useScrollLock|usePreferredDark|usePreferredLight|usePreferredReducedMotion|usePreferredContrast|useWebSocket|useRoute|useSearchParams|onMount|onDestroy|defineProps|withDefaults|defineEmits|defineExpose|defineSlots|useOptimistic)\s*(?:<[^>]*>)?\s*\(/, signalScripts = [], { hasUserImports, bundleClientScript } = await importOnce("stx/client-script-bundler", () => import("./client-script-bundler.js"));
768
768
  for (const s of scripts) {
769
769
  let content = s.body;
770
770
  if (shouldTranspileTypeScript(s.attrs))
package/dist/signals.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { state, derived, effect, batch, onMount, onDestroy, isSignal, isDerived, untrack, peek } from "./signals-api.js";
2
2
  import { runtimeHandledXAttrsLiteral } from "./runtime-globals.js";
3
+ import { createModelSignal } from "./component-model.js";
4
+ import { readHydratedData, clearServerData } from "./composables/use-fetch.js";
3
5
 
4
6
  export * from "./signals-api.js";
5
7
  export function generateSignalsRuntime() {
@@ -118,6 +120,13 @@ console.log('[stx] entering IIFE');
118
120
  // The body is attached rather than only interpolated: err.data is what a
119
121
  // caller needs to render field errors, and err.status is what it needs to
120
122
  // tell 401 from 500 without parsing the message.
123
+ function __stxRawBody(body) {
124
+ return (typeof FormData !== 'undefined' && body instanceof FormData)
125
+ || (typeof Blob !== 'undefined' && body instanceof Blob)
126
+ || (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams)
127
+ || (typeof ArrayBuffer !== 'undefined' && (body instanceof ArrayBuffer || ArrayBuffer.isView(body)));
128
+ }
129
+
121
130
  async function __stxHttpError(response) {
122
131
  var body = null;
123
132
  var text = '';
@@ -152,8 +161,63 @@ console.log('[stx] entering IIFE');
152
161
  // hook fails the request, which is what a token-refresh flow wants.
153
162
  var __stxFetchHooks = { onRequest: null, onResponse: null, onResponseError: null };
154
163
 
164
+ // Double-submit CSRF, echoed for every same-origin unsafe request. A server
165
+ // using the pattern (Stacks does, by default, on every POST/PUT/PATCH/DELETE)
166
+ // plants a readable cookie and rejects any unsafe request whose header does
167
+ // not repeat it. Nothing here repeated it, so a form posting through
168
+ // useMutation - or the framework's own CMS form block - got 403 "CSRF token
169
+ // mismatch" on a stock install. The same thing axios does for XSRF-TOKEN.
170
+ // Only same-origin: the token must never leave for another host.
171
+ var __stxCsrf = { cookie: 'X-CSRF-Token', header: 'X-CSRF-Token' };
172
+
173
+ function __stxCookie(name) {
174
+ if (typeof document === 'undefined' || !document.cookie) return null;
175
+ var parts = document.cookie.split(';');
176
+ for (var i = 0; i < parts.length; i++) {
177
+ var at = parts[i].indexOf('=');
178
+ if (at === -1) continue;
179
+ if (parts[i].slice(0, at).trim() !== name) continue;
180
+ var value = parts[i].slice(at + 1).trim();
181
+ try { return value ? decodeURIComponent(value) : null; } catch (e) { return value || null; }
182
+ }
183
+ return null;
184
+ }
185
+
186
+ function __stxApplyCsrf(url, opts) {
187
+ if (!__stxCsrf) return;
188
+ var method = String((opts && opts.method) || 'GET').toUpperCase();
189
+ if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') return;
190
+ // A path is same-origin by definition; only an absolute URL needs its
191
+ // origin compared, and one that cannot be parsed is not trusted.
192
+ var target = String(url);
193
+ if (/^[a-z][a-z0-9+.-]*:/i.test(target) || target.slice(0, 2) === '//') {
194
+ if (typeof location === 'undefined') return;
195
+ try {
196
+ if (new URL(target).origin !== location.origin) return;
197
+ } catch (e) { return; }
198
+ }
199
+ var token = __stxCookie(__stxCsrf.cookie);
200
+ if (!token) return;
201
+ var headers = __stxHeaders(opts.headers);
202
+ var wanted = __stxCsrf.header.toLowerCase();
203
+ for (var key in headers) {
204
+ // A token the caller set on purpose wins.
205
+ if (key.toLowerCase() === wanted) return;
206
+ }
207
+ headers[__stxCsrf.header] = token;
208
+ opts.headers = headers;
209
+ }
210
+
155
211
  function configureFetch(cfg) {
156
212
  cfg = cfg || {};
213
+ // Unlike the hooks below, CSRF settings persist unless named: an app that
214
+ // installs an Authorization hook has not asked to stop sending the token.
215
+ // \`csrf: false\` turns it off; \`{ cookie, header }\` renames either side.
216
+ if (Object.prototype.hasOwnProperty.call(cfg, 'csrf')) {
217
+ __stxCsrf = cfg.csrf === false || cfg.csrf === null
218
+ ? null
219
+ : { cookie: (cfg.csrf && cfg.csrf.cookie) || 'X-CSRF-Token', header: (cfg.csrf && (cfg.csrf.header || cfg.csrf.cookie)) || 'X-CSRF-Token' };
220
+ }
157
221
  // Replace rather than stack: a module re-evaluated by hot reload or by a
158
222
  // SPA script re-run must not end up with the same interceptor installed
159
223
  // twice, sending two Authorization headers or counting a 401 twice.
@@ -179,6 +243,8 @@ console.log('[stx] entering IIFE');
179
243
  async function __stxFetch(source, url, opts) {
180
244
  var t0 = __stxDevtoolsNow();
181
245
  opts = opts || {};
246
+ // Before the hooks, so an onRequest hook sees (and may override) it.
247
+ __stxApplyCsrf(url, opts);
182
248
  if (__stxFetchHooks.onRequest) {
183
249
  // Normalised first so a hook can write ctx.options.headers.Authorization
184
250
  // without having to create the bag itself.
@@ -655,6 +721,17 @@ else {
655
721
  };
656
722
 
657
723
  signal.update = (fn) => signal.set(fn(value));
724
+ // Notify as if the value changed, for an array or object mutated in place.
725
+ // set() cannot do it: the value is the same reference, so Object.is skips.
726
+ signal.trigger = () => {
727
+ subscribers.forEach(cb => cb(value, value));
728
+ if (isBatching) {
729
+ effects.forEach(effect => pendingEffects.add(effect));
730
+ }
731
+ else {
732
+ effects.forEach(effect => effect());
733
+ }
734
+ };
658
735
  signal.subscribe = (cb) => {
659
736
  subscribers.add(cb);
660
737
  return () => subscribers.delete(cb);
@@ -1114,20 +1191,25 @@ finally {
1114
1191
  // Declarative Data Fetching (Feature #6 - useFetch)
1115
1192
  // ==========================================================================
1116
1193
 
1194
+ var readHydratedData = ${readHydratedData.toString()};
1195
+ var clearServerData = ${clearServerData.toString()};
1196
+
1117
1197
  function useFetch(urlOrFn, options = {}) {
1118
- const data = state(options.initialData ?? null);
1198
+ const hydrated = readHydratedData(options.key, options.hydrate !== false, options.transform);
1199
+ const initial = hydrated ? hydrated.data : (options.initialData ?? null);
1200
+ const data = state(initial);
1119
1201
  // Starts false when nothing will be requested. It used to start true
1120
1202
  // unconditionally while the only thing clearing it was the fetch that
1121
1203
  // immediate:false suppresses \u2014 so the documented way to declare a deferred
1122
1204
  // request produced a composable stuck loading forever, which is exactly the
1123
1205
  // case where a template is most likely driving a spinner off it (#1818).
1124
- const immediate = options.immediate !== false;
1206
+ const immediate = options.immediate !== false && !hydrated;
1125
1207
  const loading = state(immediate);
1126
1208
  // Any request in flight, background ones included. loading answers "is
1127
1209
  // there nothing to show yet"; isFetching answers "is a request open" \u2014 and
1128
1210
  // a background refresh is the case where those two stop agreeing (#1929).
1129
1211
  const isFetching = state(immediate);
1130
- const error = state(null);
1212
+ const error = state(hydrated ? (hydrated.error || null) : null);
1131
1213
  if (options.suspense) registerSuspense(loading, error);
1132
1214
 
1133
1215
  // A superseded or unmounted request must not resolve into a torn-down
@@ -1258,6 +1340,7 @@ else if (immediate) {
1258
1340
  // from the getter made an early component resolve refs from whichever
1259
1341
  // component happened to hydrate last.
1260
1342
  var ownerScope = currentLifecycleScope() || componentScope;
1343
+ var ownerRefs = ownerScope.$refs || (ownerScope.$refs = {});
1261
1344
 
1262
1345
  // Callable, as well as .current / .value.
1263
1346
  //
@@ -1272,7 +1355,7 @@ else if (immediate) {
1272
1355
  //
1273
1356
  // No backticks in here: this whole runtime is a template literal.
1274
1357
  var read = function () {
1275
- return (ownerScope.$refs && ownerScope.$refs[name]) || null;
1358
+ return ownerRefs[name] || null;
1276
1359
  };
1277
1360
  Object.defineProperty(read, 'current', { get: read, enumerable: true });
1278
1361
  Object.defineProperty(read, 'value', { get: read, enumerable: true });
@@ -1716,8 +1799,11 @@ finally {
1716
1799
  var resolvedUrl = typeof url === 'function' ? url() : url;
1717
1800
  var fetchOpts = {
1718
1801
  method: options.method || 'POST',
1719
- headers: { 'Content-Type': 'application/json', ...__stxHeaders(options.headers) },
1720
- body: typeof body === 'string' ? body : JSON.stringify(body)
1802
+ // A file upload is a FormData body. Stringifying it sent "{}", and
1803
+ // the browser has to write its own multipart Content-Type (the
1804
+ // boundary lives there), so raw bodies pass through untouched.
1805
+ headers: __stxRawBody(body) ? __stxHeaders(options.headers) : { 'Content-Type': 'application/json', ...__stxHeaders(options.headers) },
1806
+ body: typeof body === 'string' || __stxRawBody(body) ? body : JSON.stringify(body)
1721
1807
  };
1722
1808
  var response = await __stxFetch('useMutation', resolvedUrl, fetchOpts);
1723
1809
  if (!response.ok) throw await __stxHttpError(response);
@@ -1953,7 +2039,7 @@ catch (e) {
1953
2039
 
1954
2040
  function expressionUsesSignalMethod(expression, name) {
1955
2041
  var escapedName = name.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&');
1956
- return new RegExp('(?:^|[^\\\\w$])' + escapedName + '\\\\s*\\\\.\\\\s*(?:set|update|subscribe|toggle)\\\\s*\\\\(').test(expression);
2042
+ return new RegExp('(?:^|[^\\\\w$])' + escapedName + '\\\\s*\\\\.\\\\s*(?:set|update|subscribe|toggle|input|change)\\\\s*\\\\(').test(expression);
1957
2043
  }
1958
2044
 
1959
2045
  function expressionUsesSignalValue(expression, name) {
@@ -2334,7 +2420,11 @@ catch (e) {
2334
2420
  value = undefined;
2335
2421
  }
2336
2422
 
2337
- if (value === false || value === null || value === undefined) {
2423
+ // ARIA states are strings, unlike HTML boolean attributes.
2424
+ if (name.startsWith('aria-') && typeof value === 'boolean') {
2425
+ el.setAttribute(name, String(value));
2426
+ }
2427
+ else if (value === false || value === null || value === undefined) {
2338
2428
  el.removeAttribute(name);
2339
2429
  }
2340
2430
  else if (value === true) {
@@ -2795,7 +2885,10 @@ catch (e2) {
2795
2885
  }
2796
2886
  return;
2797
2887
  }
2798
- if (v === false || v === null || v === undefined) {
2888
+ if (attrName.startsWith('aria-') && typeof v === 'boolean') {
2889
+ el.setAttribute(attrName, String(v));
2890
+ }
2891
+ else if (v === false || v === null || v === undefined) {
2799
2892
  el.removeAttribute(attrName);
2800
2893
  }
2801
2894
  else if (v === true) {
@@ -2835,14 +2928,36 @@ else if (name === '@html' || name === ':html' || name === 'x-html') {
2835
2928
  el.removeAttribute(name);
2836
2929
  }
2837
2930
  else if (name === 'ref' || name === ':ref' || name === 'x-ref' || name === 'data-stx-ref') {
2838
- // Store ref in scope.$refs and componentScope.$refs
2839
- if (scope.$refs) scope.$refs[value] = el;
2840
- if (componentScope.$refs) componentScope.$refs[value] = el;
2931
+ // A page ref can be projected through a component whose own $refs
2932
+ // replaced the compatibility scope's map. The compiler retains the
2933
+ // receiver boundary so named and signal refs use the same caller.
2934
+ var refRoot = el.closest && el.closest('[data-stx-scope]');
2935
+ var refCaller = el.getAttribute('data-stx-ref-caller');
2936
+ var refOwnerScope = findElementScope(el);
2937
+ if (refCaller) {
2938
+ var receiver = refRoot;
2939
+ while (receiver && receiver.getAttribute('data-stx-scope') !== refCaller
2940
+ && receiver.getAttribute('data-stx-template-scope') !== refCaller) {
2941
+ receiver = receiver.parentElement && receiver.parentElement.closest('[data-stx-scope]');
2942
+ }
2943
+ refOwnerScope = receiver && receiver.__stx_parent_scope;
2944
+ }
2945
+ // Only projected refs may reach outside their component. Caller
2946
+ // snapshots exclude unrelated, previously hydrated siblings.
2947
+ if (refCaller && refOwnerScope) {
2948
+ if (refOwnerScope.$refs) refOwnerScope.$refs[value] = el;
2949
+ }
2950
+ else {
2951
+ if (scope.$refs) scope.$refs[value] = el;
2952
+ if (componentScope.$refs) componentScope.$refs[value] = el;
2953
+ }
2841
2954
  // Also fill a same-named signal declared in the script block, so the
2842
2955
  // documented ref() + x-ref pair works and reading the signal returns
2843
2956
  // the element. Without this the signal stayed empty and every read of
2844
2957
  // it silently returned undefined.
2845
- var refTarget = (scope && scope[value]) || componentScope[value];
2958
+ var refTarget = refCaller && refOwnerScope
2959
+ ? refOwnerScope[value]
2960
+ : (scope && scope[value]) || componentScope[value];
2846
2961
  if (refTarget && typeof refTarget === 'function' && refTarget._isSignal && typeof refTarget.set === 'function') {
2847
2962
  refTarget.set(el);
2848
2963
  }
@@ -2850,7 +2965,12 @@ else if (name === 'ref' || name === ':ref' || name === 'x-ref' || name === 'data
2850
2965
  else if (name.startsWith('@') || name.startsWith(':')) {
2851
2966
  // Event handlers: @click, :click, @submit.prevent, :keydown.enter, etc.
2852
2967
  const parts = name.slice(1).split('.');
2853
- const eventName = parts[0];
2968
+ // HTML folds attribute names to lowercase; the forwarding metadata
2969
+ // retains the declared event spelling (e.g. update:modelValue).
2970
+ const parentEventNames = (el.getAttribute && el.getAttribute('data-stx-parent-events') || '').split(/\\s+/);
2971
+ const eventName = parentEventNames.find(function(event) {
2972
+ return event.toLowerCase() === parts[0].toLowerCase();
2973
+ }) || parts[0];
2854
2974
  const modifiers = parts.slice(1);
2855
2975
 
2856
2976
  // Skip special directives (already handled above or in processElement)
@@ -2864,7 +2984,6 @@ else if (name === 'ref' || name === ':ref' || name === 'x-ref' || name === 'data
2864
2984
  el[eventKey] = true;
2865
2985
 
2866
2986
  // Capture scope at setup time so @for loop variables are available when event fires
2867
- const parentEventNames = (el.getAttribute && el.getAttribute('data-stx-parent-events') || '').split(/\\s+/);
2868
2987
  const isForwardedComponentEvent = !!(el.__stx_parent_scope && parentEventNames.includes(eventName));
2869
2988
  const eventCapturedScope = isForwardedComponentEvent
2870
2989
  ? { ...globalHelpers, ...el.__stx_parent_scope }
@@ -5622,6 +5741,18 @@ catch (e) {} }
5622
5741
  return normalizedPrefix + '-' + __stxGeneratedIdCounter;
5623
5742
  }
5624
5743
 
5744
+ var createModelSignal = ${createModelSignal.toString()};
5745
+ function useModel(name, options) {
5746
+ if (typeof name !== 'string') { options = name || {}; name = 'modelValue'; }
5747
+ options = options || {};
5748
+ var source = useReactiveProp(name, options.default, { parse: options.parse });
5749
+ var modifierName = name === 'modelValue' ? 'modelModifiers' : name + 'Modifiers';
5750
+ var modifiers = useReactiveProp(modifierName, {});
5751
+ var emit = window.stx.defineEmits(['update:' + name]);
5752
+ return createModelSignal(source, function() { return modifiers() || {}; },
5753
+ function(value) { emit('update:' + name, value); }, options, onDestroy);
5754
+ }
5755
+
5625
5756
  // Reactive prop binding. Bridges the gap between a parent's clientReactive
5626
5757
  // attribute (e.g. :open="modalOpen()" on a component) and the component's
5627
5758
  // internal state. Returns a signal whose value tracks the named attribute
@@ -6417,6 +6548,7 @@ catch (e) {} }
6417
6548
  onBeforeUnmount: onDestroy,
6418
6549
  onUnmounted: onDestroy,
6419
6550
  useFetch,
6551
+ clearServerData,
6420
6552
  useRef,
6421
6553
  navigate,
6422
6554
  refresh,
@@ -6456,6 +6588,7 @@ catch (e) {} }
6456
6588
  useCookie,
6457
6589
  useId,
6458
6590
  useReactiveProp,
6591
+ useModel,
6459
6592
  useEventListener,
6460
6593
  useWebSocket,
6461
6594
  useColorMode,
@@ -6593,6 +6726,60 @@ catch (e) {} }
6593
6726
  })(gKey, opts.getters[gKey]);
6594
6727
  }
6595
6728
  }
6729
+ // An action that mutates state in place \u2014 this.list.push(x),
6730
+ // this.list[i] = x, delete this.map[k] \u2014 never went through set(),
6731
+ // so nothing that read the list re-ran. A detail page upserting the
6732
+ // record it had just fetched kept rendering "not found" until some
6733
+ // unrelated action happened to reassign the whole list.
6734
+ //
6735
+ // So an array or plain object read through this comes back as a
6736
+ // view that notifies its signal on write. The view is shallow:
6737
+ // elements read through it are the raw ones, so identity checks
6738
+ // (includes, indexOf, ===) still hold.
6739
+ var mutatingArrayMethods = { push: 1, pop: 1, shift: 1, unshift: 1, splice: 1, sort: 1, reverse: 1, fill: 1, copyWithin: 1 };
6740
+ var viewRaw = new WeakMap();
6741
+ var viewCache = new WeakMap();
6742
+ var unwrapView = function(v) {
6743
+ return (v && typeof v === 'object' && viewRaw.has(v)) ? viewRaw.get(v) : v;
6744
+ };
6745
+ var isPlainContainer = function(v) {
6746
+ if (!v || typeof v !== 'object') return false;
6747
+ if (Array.isArray(v)) return true;
6748
+ var proto = Object.getPrototypeOf(v);
6749
+ return proto === Object.prototype || proto === null;
6750
+ };
6751
+ var mutableView = function(sig, raw) {
6752
+ var cached = viewCache.get(raw);
6753
+ if (cached && cached.sig === sig) return cached.view;
6754
+ var view = new Proxy(raw, {
6755
+ get: function(target, p) {
6756
+ if (Array.isArray(target) && typeof p === 'string' && mutatingArrayMethods[p]) {
6757
+ // One notification per call, not one per index it writes.
6758
+ return function() {
6759
+ var args = Array.prototype.map.call(arguments, unwrapView);
6760
+ var out = Array.prototype[p].apply(target, args);
6761
+ sig.trigger();
6762
+ return out === target ? view : out;
6763
+ };
6764
+ }
6765
+ return Reflect.get(target, p, target);
6766
+ },
6767
+ set: function(target, p, v) {
6768
+ target[p] = unwrapView(v);
6769
+ sig.trigger();
6770
+ return true;
6771
+ },
6772
+ deleteProperty: function(target, p) {
6773
+ var had = Object.prototype.hasOwnProperty.call(target, p);
6774
+ delete target[p];
6775
+ if (had) sig.trigger();
6776
+ return true;
6777
+ }
6778
+ });
6779
+ viewRaw.set(view, raw);
6780
+ viewCache.set(raw, { sig: sig, view: view });
6781
+ return view;
6782
+ };
6596
6783
  // Bind actions with proxy for this.propName access
6597
6784
  if (opts.actions) {
6598
6785
  for (var aKey in opts.actions) {
@@ -6600,12 +6787,17 @@ catch (e) {} }
6600
6787
  result[actionKey] = function() {
6601
6788
  var proxy = new Proxy({}, {
6602
6789
  get: function(_, p) {
6603
- if (result[p] && result[p]._isSignal) return result[p]();
6790
+ if (result[p] && result[p]._isSignal) {
6791
+ var current = result[p]();
6792
+ return (typeof result[p].trigger === 'function' && isPlainContainer(current))
6793
+ ? mutableView(result[p], current)
6794
+ : current;
6795
+ }
6604
6796
  if (result[p]) return result[p];
6605
6797
  return undefined;
6606
6798
  },
6607
6799
  set: function(_, p, v) {
6608
- if (result[p] && result[p]._isSignal) { result[p].set(v); return true; }
6800
+ if (result[p] && result[p]._isSignal) { result[p].set(unwrapView(v)); return true; }
6609
6801
  return false;
6610
6802
  }
6611
6803
  });
@@ -7193,6 +7385,7 @@ else {
7193
7385
  window.onMount = onMount;
7194
7386
  window.onDestroy = onDestroy;
7195
7387
  window.useFetch = useFetch;
7388
+ window.clearServerData = clearServerData;
7196
7389
  window.useRef = useRef;
7197
7390
  window.navigate = navigate;
7198
7391
  window.goBack = goBack;
package/dist/ssg.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ak as Uq,Bk as Iq,Fk as Fq}from"./chunk-mdf3jbe6.js";import{Gk as Eq,Hk as Tq,Ik as Dq}from"./chunk-7eea1cse.js";import{bl as _q,el as zq,fl as Aq}from"./chunk-gv42xz15.js";import{Hm as Oq,Hp as P,Wo as Bq,bo as l,eo as Hq,er as n}from"./chunk-pq6rabcy.js";import"./chunk-m6wz1hf5.js";import"./chunk-dcxtrqfy.js";import"./chunk-jj6yp7gm.js";import"./chunk-qjkzpd68.js";import"./chunk-2rp09y5j.js";import{Kt as Xq}from"./chunk-8d15pd4g.js";import{Pt as d}from"./chunk-q25mr70f.js";import"./chunk-jsfch50r.js";import"./chunk-6b4k8fay.js";import"./chunk-jb2r696a.js";import"./chunk-k5xtf38q.js";import{bv as Yq,cv as Vq,dv as jq,ev as Gq,fv as Lq,gv as Nq}from"./chunk-0tbgvp70.js";import"./chunk-xdq52pwj.js";import{wv as y}from"./chunk-ddqkj56r.js";import O from"fs";import j from"path";import{createHash as xq}from"crypto";function yq(q){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(q).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return q}}var Pq=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function Cq(q){return Bun.hash(q).toString(16)}function Qq(q,Z={}){if(!q.includes('type="stx/island"'))return{html:q,chunks:[]};let $=new Map,Q=q.replace(Pq,(J,W,z,A)=>{let G=A.trim();if(!G)return J;if(/\bdata-stx-src=/.test(z))return J;if(Z.minify)G=yq(G);let X=Cq(G);if(!$.has(X))$.set(X,G);let B=Z.integrity?` data-stx-integrity="sha384-${xq("sha384").update(G).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${W}" data-stx-src="/_stx/islands/${X}.js"${B}${z}></script>`}),K=Array.from($,([J,W])=>({hash:J,code:W}));return{html:Q,chunks:K}}var gq=new Set(["visible","idle"]);function Zq(q){if(!q.includes("data-stx-src="))return q;let Z=new Map,$=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,Q;while((Q=$.exec(q))!==null)Z.set(Q[1],Q[2]);let K=new Set,J=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,W;while((W=J.exec(q))!==null)if(gq.has(Z.get(W[1])||""))K.add(W[2]);let z=q.lastIndexOf("</head>");if(K.size===0||z===-1)return q;let A=Array.from(K).filter((G)=>!q.includes(`rel="prefetch" href="${G}"`)).map((G)=>`<link rel="prefetch" href="${G}" as="script">`).join("");if(!A)return q;return q.slice(0,z)+A+q.slice(z)}var fq=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function h(q){let Z=q.trim();if(!Z)return null;let $=/^https?:\/\//i.test(Z)?Z:`https://${Z}`;try{return new URL($).origin+new URL($).pathname.replace(/\/$/,"")}catch{return null}}function mq(q){for(let Z of fq){let $=q[Z];if(!$)continue;let Q=h($);if(Q)return{url:Q,source:"env",via:Z}}return null}function $q(q){if(!q||typeof q!=="object")return null;let Z=q,$=Z.site?.url??Z.url??Z.app?.url;return typeof $==="string"?h($):null}async function dq(q){let{existsSync:Z}=await import("fs"),$=await import("path");for(let Q of["site.config.ts","site.config.js",".config/site.config.ts"]){let K=$.resolve(q,Q);if(!Z(K))continue;try{let J=await import(K),W=$q(J.default??J);if(W)return W}catch{}}return null}async function Kq(q={}){let Z=q.cwd??process.cwd(),$=q.env??process.env;if(q.explicit){let W=h(q.explicit);if(W)return{url:W,source:"option"}}let Q=$q(q.stxConfig);if(Q)return{url:Q,source:"stx.config",via:"site.url"};let K=await dq(Z);if(K)return{url:K,source:"site.config",via:"url"};let J=mq($);if(J)return J;return{url:"http://localhost",source:"fallback"}}function Wq(){return["No site URL configured \u2014 sitemap.xml and robots.txt will point at http://localhost."," Set one in stx.config.ts (site: { url: 'https://example.com' }), in site.config.ts,"," via --domain, or with SITE_URL in the build environment."].join(`
2
+ import{Fk as Uq,Gk as Iq,Kk as Fq}from"./chunk-zhcs8m2a.js";import{Lk as Eq,Mk as Tq,Nk as Dq}from"./chunk-09zjty4k.js";import{gl as _q,jl as zq,kl as Aq}from"./chunk-zggm7kjd.js";import"./chunk-9499k64n.js";import{Tm as Oq,_p as P,np as Bq,ro as l,uo as Hq,xr as n}from"./chunk-hay1rzb0.js";import"./chunk-2h94c5hm.js";import"./chunk-8jam44my.js";import"./chunk-t51mwjyq.js";import"./chunk-wfffa8zm.js";import{_t as Xq}from"./chunk-54f8bpp6.js";import"./chunk-4evbx7sz.js";import"./chunk-jxxv18a0.js";import{mu as d}from"./chunk-c131k3mt.js";import"./chunk-hgjjnjas.js";import"./chunk-nqq7y7m9.js";import"./chunk-1c2j4eby.js";import"./chunk-kxavsh3m.js";import"./chunk-qev11kg8.js";import"./chunk-rrankpmj.js";import{Jv as Yq,Kv as Vq,Lv as jq,Mv as Gq,Nv as Lq,Ov as Nq}from"./chunk-fczfdsab.js";import"./chunk-fp7ms6e7.js";import{cw as y}from"./chunk-jp2f8yzw.js";import O from"fs";import j from"path";import{createHash as xq}from"crypto";function yq(q){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(q).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return q}}var Pq=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function Cq(q){return Bun.hash(q).toString(16)}function Qq(q,Z={}){if(!q.includes('type="stx/island"'))return{html:q,chunks:[]};let $=new Map,Q=q.replace(Pq,(J,W,z,A)=>{let G=A.trim();if(!G)return J;if(/\bdata-stx-src=/.test(z))return J;if(Z.minify)G=yq(G);let X=Cq(G);if(!$.has(X))$.set(X,G);let B=Z.integrity?` data-stx-integrity="sha384-${xq("sha384").update(G).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${W}" data-stx-src="/_stx/islands/${X}.js"${B}${z}></script>`}),K=Array.from($,([J,W])=>({hash:J,code:W}));return{html:Q,chunks:K}}var gq=new Set(["visible","idle"]);function Zq(q){if(!q.includes("data-stx-src="))return q;let Z=new Map,$=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,Q;while((Q=$.exec(q))!==null)Z.set(Q[1],Q[2]);let K=new Set,J=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,W;while((W=J.exec(q))!==null)if(gq.has(Z.get(W[1])||""))K.add(W[2]);let z=q.lastIndexOf("</head>");if(K.size===0||z===-1)return q;let A=Array.from(K).filter((G)=>!q.includes(`rel="prefetch" href="${G}"`)).map((G)=>`<link rel="prefetch" href="${G}" as="script">`).join("");if(!A)return q;return q.slice(0,z)+A+q.slice(z)}var fq=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function h(q){let Z=q.trim();if(!Z)return null;let $=/^https?:\/\//i.test(Z)?Z:`https://${Z}`;try{return new URL($).origin+new URL($).pathname.replace(/\/$/,"")}catch{return null}}function mq(q){for(let Z of fq){let $=q[Z];if(!$)continue;let Q=h($);if(Q)return{url:Q,source:"env",via:Z}}return null}function $q(q){if(!q||typeof q!=="object")return null;let Z=q,$=Z.site?.url??Z.url??Z.app?.url;return typeof $==="string"?h($):null}async function dq(q){let{existsSync:Z}=await import("fs"),$=await import("path");for(let Q of["site.config.ts","site.config.js",".config/site.config.ts"]){let K=$.resolve(q,Q);if(!Z(K))continue;try{let J=await import(K),W=$q(J.default??J);if(W)return W}catch{}}return null}async function Kq(q={}){let Z=q.cwd??process.cwd(),$=q.env??process.env;if(q.explicit){let W=h(q.explicit);if(W)return{url:W,source:"option"}}let Q=$q(q.stxConfig);if(Q)return{url:Q,source:"stx.config",via:"site.url"};let K=await dq(Z);if(K)return{url:K,source:"site.config",via:"url"};let J=mq($);if(J)return J;return{url:"http://localhost",source:"fallback"}}function Wq(){return["No site URL configured \u2014 sitemap.xml and robots.txt will point at http://localhost."," Set one in stx.config.ts (site: { url: 'https://example.com' }), in site.config.ts,"," via --domain, or with SITE_URL in the build environment."].join(`
3
3
  `)}class wq{cacheDir;cache=new Map;loaded=!1;salt;constructor(q,Z=""){this.cacheDir=q,this.salt=Z}async load(){if(this.loaded)return;let q=j.join(this.cacheDir,"build-cache.json");if(await Bun.file(q).exists())try{let Z=JSON.parse(await Bun.file(q).text());for(let[$,Q]of Object.entries(Z))this.cache.set($,Q)}catch{}this.loaded=!0}async save(){await O.promises.mkdir(this.cacheDir,{recursive:!0});let q=j.join(this.cacheDir,"build-cache.json"),Z={};for(let[$,Q]of this.cache)Z[$]=Q;await Bun.write(q,JSON.stringify(Z))}getHash(q,Z){let $=O.statSync(q),Q=`${this.salt}|${q}:${$.mtimeMs}`;for(let J of Z)if(O.existsSync(J)){let W=O.statSync(J);Q+=`:${J}:${W.mtimeMs}`}let K=0;for(let J=0;J<Q.length;J++){let W=Q.charCodeAt(J);K=(K<<5)-K+W,K=K&K}return Math.abs(K).toString(36)}get(q,Z){let $=this.cache.get(q);if(!$)return null;let Q=this.getHash(Z,$.dependencies??[]);if($.hash!==Q)return this.cache.delete(q),null;return $.html}set(q,Z,$,Q){let K=this.getHash(Z,$);this.cache.set(q,{hash:K,html:Q,generatedAt:Date.now(),dependencies:$})}}class Rq{cacheDir;constructor(q){this.cacheDir=q}getFilePath(q){let Z=q.replace(/[^a-zA-Z0-9]/g,"_")+".json";return j.join(this.cacheDir,"isr",Z)}async get(q){let Z=this.getFilePath(q);if(!await Bun.file(Z).exists())return null;try{return JSON.parse(await Bun.file(Z).text())}catch{return null}}async set(q,Z){let $=this.getFilePath(q);await O.promises.mkdir(j.dirname($),{recursive:!0}),await Bun.write($,JSON.stringify(Z))}async invalidate(q){let Z=this.getFilePath(q);if(await Bun.file(Z).exists())await O.promises.unlink(Z)}async invalidatePattern(q){let Z=j.join(this.cacheDir,"isr");if(!O.existsSync(Z))return;let $=await O.promises.readdir(Z);for(let Q of $){let K=Q.replace(/_/g,"/").replace(".json","");if(q.test(K))await O.promises.unlink(j.join(Z,Q))}}async needsRevalidation(q){let Z=await this.get(q);if(!Z)return!0;return Date.now()>Z.revalidateAfter}}async function pq(q){try{let $=(await Bun.file(q).text()).match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(!$)return null;let Q=$[1];if(!Q.includes("getStaticPaths"))return null;let K=Q.match(/(?:export\s+)?(?:async\s+)?function\s+getStaticPaths\s*\([^)]*\)\s*\{([\s\S]*?)\n[\t ]*\}/);if(!K)return null;return await Function(`
4
4
  return (async function getStaticPaths() {
5
5
  ${K[1]}
@@ -41,7 +41,7 @@ ${q.map((Q)=>{let K=new URL(Q.loc,Z).href,J=` <url>
41
41
  ${$.join(`
42
42
  `)}
43
43
  </channel>
44
- </rss>`}async function aq(q={}){let Z=Date.now();Aq();let $=await n(process.cwd()),Q=$.build||{},K=await Kq({explicit:q.domain||Q.domain,stxConfig:$});if(K.source==="fallback"&&(q.sitemap??Q.sitemap??!0))console.warn(Wq());let J={router:q.router??$?.router??{},pagesDir:q.pagesDir||Q.pagesDir||"pages",outputDir:q.outputDir||Q.outputDir||"dist",baseUrl:q.baseUrl||Q.baseUrl||"/",domain:K.url,revalidate:q.revalidate??Q.revalidate??!1,sitemap:q.sitemap??Q.sitemap??!0,sitemapExclude:q.sitemapExclude||Q.sitemapExclude||[],robots:q.robots??Q.robots??!0,rss:q.rss??Q.rss??!1,concurrency:q.concurrency||Q.concurrency||10,cache:q.cache??Q.cache??!0,cacheDir:q.cacheDir||Q.cacheDir||d(process.cwd(),"ssg-cache"),contentLoaders:q.contentLoaders||[],hooks:q.hooks||{},minify:q.minify??Q.minify??!0,generate404:q.generate404??Q.generate404??!0,publicDir:q.publicDir||Q.publicDir||"public",trailingSlash:q.trailingSlash??Q.trailingSlash??!1,cleanOutput:q.cleanOutput??Q.cleanOutput??!0,cacheSalt:q.cacheSalt??"",partialsDir:q.partialsDir||$?.partialsDir||"",componentsDir:q.componentsDir||$?.componentsDir||"",failOnIncludeError:q.failOnIncludeError??!0,chunkIslands:q.chunkIslands===!0,prefetchIslands:q.prefetchIslands===!0,integrityIslands:q.integrityIslands===!0},W={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},z=new Set,A=0,G={},X={};await J.hooks.onBuildStart?.();try{if(J.cleanOutput&&O.existsSync(J.outputDir))await O.promises.rm(J.outputDir,{recursive:!0});await O.promises.mkdir(J.outputDir,{recursive:!0});let L=J.cacheSalt;if(!L){let{resolveUserCssConfig:Y,fingerprintConfig:N}=await import("./chunk-q0y1yxg3.js");try{L=N(await Y(process.cwd()))}catch{}}let{prepareImageDelivery:_}=await import("./chunk-ehp6fez3.js"),F=await _(J.publicDir,J.outputDir);if(F.count>0)console.log(`Optimized ${F.count} image(s) for responsive delivery`),L=[L,F.fingerprint].filter(Boolean).join(":");let C=new wq(J.cacheDir,L);if(J.cache)await C.load();try{let{generateCss:Y}=await import("./chunk-q0y1yxg3.js");await Y('<div class="bg-black"></div>')}catch{}Yq();let kq=$?.routeMiddleware?.dir||"middleware";await jq(process.cwd(),kq);let p=Vq();if(p.length>0)console.log(`Loaded ${p.length} middleware: ${p.join(", ")}`);let bq=$?.routeMiddleware?.global||[];Fq($?.layoutsDir,d(process.cwd()));let i=l(".",{pagesDir:J.pagesDir});console.log(`Found ${i.length} routes`);let g=[];for(let Y of i){let N=await uq(Y);for(let H of N)g.push({route:Y,url:H.url,params:H.params,props:H.props,revalidate:H.revalidate??J.revalidate})}W.totalPages=g.length,console.log(`Generating ${W.totalPages} pages...`);let b=[],s=[];for(let Y=0;Y<g.length;Y+=J.concurrency)s.push(g.slice(Y,Y+J.concurrency));for(let Y of s)await Promise.all(Y.map(async(N)=>{let{route:H,url:V,params:S,props:Sq,revalidate:a}=N;try{await J.hooks.onPageStart?.(V);let w=await Bun.file(H.filePath).text(),R=JJ(w),vq=R?.middleware?Array.isArray(R.middleware)?R.middleware:[R.middleware]:[],t=[...bq,...vq];if(t.length>0){let D=Gq(V,S,R||{}),M=Lq(D,null,void 0,{isServer:!0}),E=await Nq(t,M);if(E.redirect){let U=typeof E.redirect==="string"?E.redirect:E.redirect.path||E.redirect,x=QJ(String(U),V),k=ZJ(V,J);await O.promises.mkdir(j.dirname(k),{recursive:!0}),await Bun.write(k,x),W.successCount++,W.pages.push({route:V,outputPath:k,size:Buffer.byteLength(x),cached:!1}),b.push({loc:V,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${V} \u2192 redirect to ${U}`);return}if(E.abort){let U=typeof E.abort==="string"?E.abort:E.abort?.error?.message||"aborted";console.warn(` \u21B3 ${V} \u2014 middleware aborted: ${U}`);return}}let e=w.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(e)try{if(!await Function("route",`
44
+ </rss>`}async function aq(q={}){let Z=Date.now();Aq();let $=await n(process.cwd()),Q=$.build||{},K=await Kq({explicit:q.domain||Q.domain,stxConfig:$});if(K.source==="fallback"&&(q.sitemap??Q.sitemap??!0))console.warn(Wq());let J={router:q.router??$?.router??{},pagesDir:q.pagesDir||Q.pagesDir||"pages",outputDir:q.outputDir||Q.outputDir||"dist",baseUrl:q.baseUrl||Q.baseUrl||"/",domain:K.url,revalidate:q.revalidate??Q.revalidate??!1,sitemap:q.sitemap??Q.sitemap??!0,sitemapExclude:q.sitemapExclude||Q.sitemapExclude||[],robots:q.robots??Q.robots??!0,rss:q.rss??Q.rss??!1,concurrency:q.concurrency||Q.concurrency||10,cache:q.cache??Q.cache??!0,cacheDir:q.cacheDir||Q.cacheDir||d(process.cwd(),"ssg-cache"),contentLoaders:q.contentLoaders||[],hooks:q.hooks||{},minify:q.minify??Q.minify??!0,generate404:q.generate404??Q.generate404??!0,publicDir:q.publicDir||Q.publicDir||"public",trailingSlash:q.trailingSlash??Q.trailingSlash??!1,cleanOutput:q.cleanOutput??Q.cleanOutput??!0,cacheSalt:q.cacheSalt??"",partialsDir:q.partialsDir||$?.partialsDir||"",componentsDir:q.componentsDir||$?.componentsDir||"",failOnIncludeError:q.failOnIncludeError??!0,chunkIslands:q.chunkIslands===!0,prefetchIslands:q.prefetchIslands===!0,integrityIslands:q.integrityIslands===!0},W={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},z=new Set,A=0,G={},X={};await J.hooks.onBuildStart?.();try{if(J.cleanOutput&&O.existsSync(J.outputDir))await O.promises.rm(J.outputDir,{recursive:!0});await O.promises.mkdir(J.outputDir,{recursive:!0});let L=J.cacheSalt;if(!L){let{resolveUserCssConfig:Y,fingerprintConfig:N}=await import("./chunk-9xzszvn5.js");try{L=N(await Y(process.cwd()))}catch{}}let{prepareImageDelivery:_}=await import("./chunk-xd5ahrtn.js"),F=await _(J.publicDir,J.outputDir);if(F.count>0)console.log(`Optimized ${F.count} image(s) for responsive delivery`),L=[L,F.fingerprint].filter(Boolean).join(":");let C=new wq(J.cacheDir,L);if(J.cache)await C.load();try{let{generateCss:Y}=await import("./chunk-9xzszvn5.js");await Y('<div class="bg-black"></div>')}catch{}Yq();let kq=$?.routeMiddleware?.dir||"middleware";await jq(process.cwd(),kq);let p=Vq();if(p.length>0)console.log(`Loaded ${p.length} middleware: ${p.join(", ")}`);let bq=$?.routeMiddleware?.global||[];Fq($?.layoutsDir,d(process.cwd()));let i=l(".",{pagesDir:J.pagesDir,pagesDirs:$?._layerPageDirs});console.log(`Found ${i.length} routes`);let g=[];for(let Y of i){let N=await uq(Y);for(let H of N)g.push({route:Y,url:H.url,params:H.params,props:H.props,revalidate:H.revalidate??J.revalidate})}W.totalPages=g.length,console.log(`Generating ${W.totalPages} pages...`);let b=[],s=[];for(let Y=0;Y<g.length;Y+=J.concurrency)s.push(g.slice(Y,Y+J.concurrency));for(let Y of s)await Promise.all(Y.map(async(N)=>{let{route:H,url:V,params:S,props:Sq,revalidate:a}=N;try{await J.hooks.onPageStart?.(V);let w=await Bun.file(H.filePath).text(),R=JJ(w),vq=R?.middleware?Array.isArray(R.middleware)?R.middleware:[R.middleware]:[],t=[...bq,...vq];if(t.length>0){let D=Gq(V,S,R||{}),M=Lq(D,null,void 0,{isServer:!0}),E=await Nq(t,M);if(E.redirect){let U=typeof E.redirect==="string"?E.redirect:E.redirect.path||E.redirect,x=QJ(String(U),V),k=ZJ(V,J);await O.promises.mkdir(j.dirname(k),{recursive:!0}),await Bun.write(k,x),W.successCount++,W.pages.push({route:V,outputPath:k,size:Buffer.byteLength(x),cached:!1}),b.push({loc:V,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${V} \u2192 redirect to ${U}`);return}if(E.abort){let U=typeof E.abort==="string"?E.abort:E.abort?.error?.message||"aborted";console.warn(` \u21B3 ${V} \u2014 middleware aborted: ${U}`);return}}let e=w.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(e)try{if(!await Function("route",`
45
45
  const validate = ${e[1]};
46
46
  return validate(route);
47
47
  `)({params:S})){console.warn(`Validation failed for ${V}, skipping...`);return}}catch{}let I=null,qq=!1;if(J.cache){if(I=C.get(V,H.filePath),I)qq=!0,W.cachedCount++}if(!I){let D=await Mq(H,S,Sq,J,$);if(I=D.html,J.failOnIncludeError&&D.includeFailures.length>0)throw Error(`${D.includeFailures.length} include(s) failed to resolve, so this page would have shipped with an error banner where the markup should be:
@@ -312,6 +312,7 @@ export declare interface ScriptBlock {
312
312
  }
313
313
  /** A `{{ }}` interpolation or a directive attribute value. */
314
314
  export declare interface TemplateExpression {
315
+ anchor?: boolean
315
316
  code: string
316
317
  line: number
317
318
  column: number
@@ -328,6 +329,7 @@ export declare interface MappedLine {
328
329
  }
329
330
  export declare interface VirtualFile {
330
331
  text: string
332
+ componentDependencies?: Map<string, string>
331
333
  lineMap: Map<number, MappedLine>
332
334
  sourceLineCount: number
333
335
  }
@@ -344,6 +346,10 @@ export declare interface TemplateBinding {
344
346
  iterable?: string
345
347
  }
346
348
  export declare interface BuildVirtualOptions {
349
+ filePath?: string
350
+ componentsDir?: string
351
+ projectRoot?: string
352
+ readComponent?: (file: string) => string | undefined
347
353
  templateExpressions?: boolean
348
354
  originDir?: string
349
355
  globals?: boolean
@@ -2,6 +2,7 @@ import { BROWSER_CORE_IMPORTS } from "./browser-core-imports.js";
2
2
  import path from "node:path";
3
3
  import { stripCommentsAndLiterals } from "./strip-literals.js";
4
4
  import { STX_RUNTIME_GLOBALS } from "./runtime-globals.js";
5
+ import { componentContractChecks } from "./component-contract-checks.js";
5
6
  const SCRIPT_RE = /<script(\s[^>]*)?>([\s\S]*?)<\/script>/gi;
6
7
  function blankCommentContents(source) {
7
8
  const blank = (match) => match.replace(/[^\n]/g, " ");
@@ -570,7 +571,14 @@ export function absolutizeRelativeSpecifiers(code, originDir) {
570
571
  }
571
572
  export function buildVirtualTypeScript(source, options = {}) {
572
573
  const blocks = extractScriptBlocks(source), sourceLines = source.split(`
573
- `), lines = Array.from({ length: sourceLines.length }, () => ""), lineMap = new Map;
574
+ `), lines = Array.from({ length: sourceLines.length }, () => ""), lineMap = new Map, components = options.filePath && options.templateExpressions !== !1 ? componentContractChecks(source, maskNonTemplateRegions(source), {
575
+ filePath: options.filePath,
576
+ componentsDir: options.componentsDir,
577
+ projectRoot: options.projectRoot,
578
+ readComponent: options.readComponent,
579
+ scriptCode: (text, file) => extractScriptBlocks(text).map((block) => absolutizeRelativeSpecifiers(block.code, path.dirname(file))).join(`
580
+ `)
581
+ }) : void 0;
574
582
  for (const block of blocks)
575
583
  absolutizeRelativeSpecifiers(block.code, options.originDir ?? "").split(`
576
584
  `).forEach((text, i) => {
@@ -579,9 +587,12 @@ export function buildVirtualTypeScript(source, options = {}) {
579
587
  lines[index] = text;
580
588
  });
581
589
  const append = (text, origin) => {
582
- lines.push(text);
583
- if (origin)
584
- lineMap.set(lines.length, origin);
590
+ for (const [index, line] of text.split(`
591
+ `).entries()) {
592
+ lines.push(line);
593
+ if (origin)
594
+ lineMap.set(lines.length, index === 0 ? origin : { ...origin, line: origin.line + index, column: 1, prefixLength: 0 });
595
+ }
585
596
  };
586
597
  if (options.globals !== !1) {
587
598
  append("");
@@ -607,7 +618,20 @@ export function buildVirtualTypeScript(source, options = {}) {
607
618
  }
608
619
  }
609
620
  if (options.templateExpressions !== !1) {
610
- const statements = extractTemplateExpressions(source).map((expression) => ({ expression, statement: expressionStatement(expression) })).filter((entry) => entry.statement !== null);
621
+ if (components?.declarations)
622
+ for (const line of components.declarations.split(`
623
+ `))
624
+ append(line);
625
+ const statements = extractTemplateExpressions(source).map((expression) => {
626
+ const payload = components?.events.get(expression.offset ?? -1);
627
+ if (payload) {
628
+ expression.anchor = !0;
629
+ const code = expression.code.trim(), assignment = /^([\w$]+)\s*=\s*([^=][\s\S]*)$/.exec(code), body = assignment ? `void ((${assignment[2]}) satisfies __StxAssignedValue<typeof ${assignment[1]}>)` : /^[\w$]+(?:\.[\w$]+)*$/.test(code) ? `${code}($event)` : code, prefix = `;(($event: ${payload}): void => { `;
630
+ return { expression, statement: { text: `${prefix}${body} });`, prefixLength: prefix.length } };
631
+ }
632
+ return { expression, statement: expressionStatement(expression) };
633
+ }).filter((entry) => entry.statement !== null);
634
+ statements.push(...components?.checks || []);
611
635
  if (statements.length > 0) {
612
636
  const maskedSource = maskNonTemplateRegions(source), shadowed = [...new Set(blocks.flatMap((block) => collectBlockDeclarations(block.code)))].filter((name) => /^[A-Z_$][\w$]*$/i.test(name));
613
637
  let indent = 0;
@@ -633,7 +657,7 @@ export function buildVirtualTypeScript(source, options = {}) {
633
657
  }
634
658
  append("export {}");
635
659
  return { text: lines.join(`
636
- `), lineMap, sourceLineCount: sourceLines.length };
660
+ `), lineMap, sourceLineCount: sourceLines.length, componentDependencies: components?.dependencies };
637
661
  }
638
662
  export function lineStarts(text) {
639
663
  const starts = [0];
@@ -661,7 +685,7 @@ export function resolvePosition(virtual, line, column) {
661
685
  const mapped = virtual.lineMap.get(line);
662
686
  if (!mapped)
663
687
  return line <= virtual.sourceLineCount ? { line, column } : null;
664
- const within = Math.max(0, column - 1 - (mapped.prefixLength ?? 0));
688
+ const within = mapped.expression?.anchor ? 0 : Math.max(0, column - 1 - (mapped.prefixLength ?? 0));
665
689
  return {
666
690
  line: mapped.line,
667
691
  column: mapped.column + within,