@stacksjs/stx 0.2.303 → 0.2.305

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-rdg1n42s.js → chunk-00rtz7nw.js} +2 -2
  10. package/dist/chunk-02hm88m5.js +2 -0
  11. package/dist/chunk-044mychj.js +2 -0
  12. package/dist/{chunk-7eea1cse.js → chunk-09zjty4k.js} +1 -1
  13. package/dist/{chunk-7nfn7nj9.js → chunk-0gz0rhvs.js} +1 -1
  14. package/dist/chunk-113y4ywy.js +2 -0
  15. package/dist/{chunk-jsfch50r.js → chunk-1c2j4eby.js} +1 -1
  16. package/dist/{chunk-2m6x8tcx.js → chunk-1jbjrc0w.js} +2 -2
  17. package/dist/{chunk-m6wz1hf5.js → chunk-2h94c5hm.js} +2 -2
  18. package/dist/{chunk-mjpqz66q.js → chunk-2ver2s2y.js} +1 -1
  19. package/dist/chunk-3eervtf9.js +2 -0
  20. package/dist/{chunk-2rp09y5j.js → chunk-4evbx7sz.js} +1 -1
  21. package/dist/chunk-4jgr954p.js +2 -0
  22. package/dist/chunk-4mrhxtn3.js +18 -0
  23. package/dist/chunk-57ea6ye2.js +2 -0
  24. package/dist/{chunk-7eg7ep8f.js → chunk-5tefa8qb.js} +2 -2
  25. package/dist/{chunk-683tfkz4.js → chunk-64djh88a.js} +1 -1
  26. package/dist/{chunk-btrmvj2y.js → chunk-695fkras.js} +1 -1
  27. package/dist/{chunk-y7dcdjav.js → chunk-6zt2y7q3.js} +2 -2
  28. package/dist/chunk-7gqbr8nr.js +2 -0
  29. package/dist/{chunk-x4prtyjs.js → chunk-7kw3grq5.js} +1 -1
  30. package/dist/chunk-7m4yhzhb.js +6 -0
  31. package/dist/{chunk-7jebw3ea.js → chunk-7skk34dh.js} +2 -2
  32. package/dist/chunk-8ee62a9q.js +2 -0
  33. package/dist/{chunk-jj6yp7gm.js → chunk-8jam44my.js} +1 -1
  34. package/dist/chunk-8z0n5mtg.js +2 -0
  35. package/dist/chunk-92zzryxw.js +2 -0
  36. package/dist/{chunk-3bc8bqw2.js → chunk-9368t9jm.js} +1 -1
  37. package/dist/{chunk-3jwmcf4k.js → chunk-9c835qjn.js} +1 -1
  38. package/dist/chunk-9nf3hgvq.js +7 -0
  39. package/dist/chunk-a87jqtmd.js +2 -0
  40. package/dist/{chunk-5d9cy7a0.js → chunk-awj7yy37.js} +1 -1
  41. package/dist/chunk-b4xwbh8a.js +2 -0
  42. package/dist/{chunk-1evf3bdg.js → chunk-bd9wrcq1.js} +205 -19
  43. package/dist/chunk-bezqaxqt.js +2 -0
  44. package/dist/chunk-bk95q0bw.js +12 -0
  45. package/dist/{chunk-q25mr70f.js → chunk-c131k3mt.js} +1 -1
  46. package/dist/chunk-c1ae6afc.js +30 -0
  47. package/dist/{chunk-6btbgxh1.js → chunk-c79nfdyj.js} +1 -1
  48. package/dist/{chunk-cfgpk6bh.js → chunk-cbgh359m.js} +1 -1
  49. package/dist/{chunk-weqpt9nt.js → chunk-cr8v8k53.js} +1 -1
  50. package/dist/{chunk-p3wwm6k4.js → chunk-d19tvdvv.js} +1 -1
  51. package/dist/{chunk-nb1zdh1y.js → chunk-d3srvh3q.js} +1 -1
  52. package/dist/{chunk-rqrfq305.js → chunk-d57gb0v2.js} +1 -1
  53. package/dist/{chunk-1xyhk1wr.js → chunk-d5cqnwdd.js} +1 -1
  54. package/dist/chunk-dgpjxmhs.js +2 -0
  55. package/dist/chunk-dvvx1wny.js +3 -0
  56. package/dist/chunk-eans1ct0.js +43 -0
  57. package/dist/{chunk-ctz53mbz.js → chunk-ej8mv2k6.js} +1 -1
  58. package/dist/{chunk-zn6xcc0a.js → chunk-ek8cgwcg.js} +2 -2
  59. package/dist/{chunk-dv3z80gt.js → chunk-env6knrs.js} +1 -1
  60. package/dist/chunk-er848s6f.js +2 -0
  61. package/dist/{chunk-rf10fkrf.js → chunk-ess2pgt5.js} +1 -1
  62. package/dist/chunk-f1cgyd2h.js +3 -0
  63. package/dist/{chunk-hp3rjwnb.js → chunk-f325jzsk.js} +2 -2
  64. package/dist/{chunk-0tbgvp70.js → chunk-fczfdsab.js} +21 -5
  65. package/dist/chunk-fg0nf7cv.js +3754 -0
  66. package/dist/{chunk-xdq52pwj.js → chunk-fp7ms6e7.js} +1 -1
  67. package/dist/{chunk-qg6pg6ze.js → chunk-fqq5k9ve.js} +1 -1
  68. package/dist/{chunk-5t0w4h6z.js → chunk-g912mb7x.js} +1 -1
  69. package/dist/chunk-g97atepq.js +2 -0
  70. package/dist/{chunk-wj25qt72.js → chunk-gbwhbasw.js} +1 -1
  71. package/dist/chunk-gecmqs6p.js +17 -0
  72. package/dist/{chunk-cratkhhb.js → chunk-ghw5p1yk.js} +1 -1
  73. package/dist/{chunk-f0g2q51j.js → chunk-gssbag3e.js} +1 -1
  74. package/dist/{chunk-c9vhtjtr.js → chunk-gt8ja700.js} +2 -2
  75. package/dist/chunk-hftqr8ej.js +2 -0
  76. package/dist/{chunk-ftvmk1nj.js → chunk-hg2afckn.js} +1 -1
  77. package/dist/{chunk-hhnzd03k.js → chunk-hrcxfvh1.js} +1 -1
  78. package/dist/chunk-hzav4hyd.js +2 -0
  79. package/dist/{chunk-29gjwajm.js → chunk-jfzfrmzy.js} +1 -1
  80. package/dist/{chunk-ddqkj56r.js → chunk-jp2f8yzw.js} +1 -1
  81. package/dist/{chunk-ry3a2674.js → chunk-jsg1rthc.js} +1 -1
  82. package/dist/chunk-jxxv18a0.js +5 -0
  83. package/dist/{chunk-95t0k8cz.js → chunk-k23r03qj.js} +1 -1
  84. package/dist/{chunk-6b4k8fay.js → chunk-kxavsh3m.js} +1 -1
  85. package/dist/{chunk-4tffxxpd.js → chunk-m31n9pkr.js} +1 -1
  86. package/dist/{chunk-fj6fbqgb.js → chunk-m3a20mmb.js} +1 -1
  87. package/dist/chunk-m537zgay.js +2 -0
  88. package/dist/chunk-m8n0s4tk.js +28 -0
  89. package/dist/{chunk-j21csh4j.js → chunk-mbmqpaq1.js} +1 -1
  90. package/dist/{chunk-whm6bybj.js → chunk-mv5fdcwc.js} +3 -3
  91. package/dist/{chunk-y9nyqcha.js → chunk-mwh3ymwc.js} +1 -1
  92. package/dist/{chunk-51g95yts.js → chunk-mygq61f5.js} +2 -2
  93. package/dist/chunk-n99ajrwv.js +2 -0
  94. package/dist/chunk-ncrfrp95.js +2 -0
  95. package/dist/chunk-nqq7y7m9.js +3 -0
  96. package/dist/chunk-nws8fbde.js +2 -0
  97. package/dist/{chunk-q6xfyasj.js → chunk-pcvayb2f.js} +1 -1
  98. package/dist/chunk-phcvbqzn.js +2 -0
  99. package/dist/{chunk-nvxv2wxv.js → chunk-ppyz9623.js} +1 -1
  100. package/dist/{chunk-jb2r696a.js → chunk-qev11kg8.js} +1 -1
  101. package/dist/{chunk-6njgsr6w.js → chunk-qeyw5za9.js} +1 -1
  102. package/dist/chunk-qpzxgkc5.js +2 -0
  103. package/dist/chunk-qt2dmyq5.js +2 -0
  104. package/dist/chunk-r2k2sewg.js +2 -0
  105. package/dist/chunk-r808fpme.js +2 -0
  106. package/dist/chunk-rrankpmj.js +3 -0
  107. package/dist/chunk-rvyfyc43.js +2 -0
  108. package/dist/{chunk-3p0zgfgz.js → chunk-rzevgemj.js} +2 -2
  109. package/dist/{chunk-f62fh1fw.js → chunk-s3dnk3gc.js} +2 -2
  110. package/dist/{chunk-aa6kt84c.js → chunk-sart9ehj.js} +1 -1
  111. package/dist/chunk-sen2cxqm.js +2 -0
  112. package/dist/{chunk-jptkc64r.js → chunk-t3qb9s6s.js} +2 -2
  113. package/dist/{chunk-w8yac9xp.js → chunk-t41aaehf.js} +1 -1
  114. package/dist/{chunk-qjkzpd68.js → chunk-t51mwjyq.js} +1 -1
  115. package/dist/chunk-t8fqjb25.js +19 -0
  116. package/dist/{chunk-c6b5nqct.js → chunk-ta398s3d.js} +287 -352
  117. package/dist/chunk-tc6gqeha.js +2 -0
  118. package/dist/chunk-tt4r8q4v.js +2 -0
  119. package/dist/chunk-twbw18vs.js +2 -0
  120. package/dist/{chunk-6rzwef28.js → chunk-vd5xvsnv.js} +1 -1
  121. package/dist/chunk-w6d91maa.js +4 -0
  122. package/dist/{chunk-dcxtrqfy.js → chunk-wfffa8zm.js} +1 -1
  123. package/dist/chunk-wjdfhfj6.js +2 -0
  124. package/dist/chunk-wnamjw6n.js +3 -0
  125. package/dist/{chunk-22p0ezj6.js → chunk-wx13qmaw.js} +1 -1
  126. package/dist/chunk-x10mrzgp.js +2 -0
  127. package/dist/chunk-xd5ahrtn.js +2 -0
  128. package/dist/chunk-xsfwcj6x.js +2 -0
  129. package/dist/{chunk-91007tan.js → chunk-xwxdwqn9.js} +1 -1
  130. package/dist/{chunk-634gaa9d.js → chunk-xz3evxqp.js} +1 -1
  131. package/dist/chunk-xzgvcrnz.js +2 -0
  132. package/dist/{chunk-v8474ah4.js → chunk-y4nzmkea.js} +1 -1
  133. package/dist/{chunk-6w8fa3b8.js → chunk-ya5m5vbn.js} +1 -1
  134. package/dist/chunk-yd7jyyr7.js +2 -0
  135. package/dist/{chunk-ew6tr7b1.js → chunk-ydgdq45a.js} +2 -2
  136. package/dist/{chunk-ps20v1ah.js → chunk-ym3r8ktq.js} +1 -1
  137. package/dist/chunk-yyyxt326.js +2 -0
  138. package/dist/{chunk-yfwyvh02.js → chunk-ze44hhxb.js} +2 -2
  139. package/dist/{chunk-mdf3jbe6.js → chunk-zhcs8m2a.js} +2 -2
  140. package/dist/{chunk-f9d27v49.js → chunk-zs5y7xnt.js} +1 -1
  141. package/dist/chunk-zs95z9tf.js +2 -0
  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 +27 -3
  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 +138 -15
  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-2jd9bxmf.js +0 -2
  226. package/dist/chunk-2yp8ang5.js +0 -2
  227. package/dist/chunk-35x7s4cr.js +0 -2
  228. package/dist/chunk-3bqz5zre.js +0 -2
  229. package/dist/chunk-48p0k8y7.js +0 -2
  230. package/dist/chunk-4b625drg.js +0 -2
  231. package/dist/chunk-593kby1d.js +0 -2
  232. package/dist/chunk-5nac67r4.js +0 -18
  233. package/dist/chunk-70cf5h11.js +0 -2
  234. package/dist/chunk-78akhaws.js +0 -2
  235. package/dist/chunk-9a4q74r6.js +0 -2
  236. package/dist/chunk-9f5329rv.js +0 -2
  237. package/dist/chunk-9rv7akqq.js +0 -30
  238. package/dist/chunk-apjy1a72.js +0 -12
  239. package/dist/chunk-b3p3bzax.js +0 -3
  240. package/dist/chunk-c5hk1fxt.js +0 -2
  241. package/dist/chunk-c9rs5g1s.js +0 -2
  242. package/dist/chunk-dkd0bg8g.js +0 -2
  243. package/dist/chunk-dxhtry04.js +0 -2
  244. package/dist/chunk-ehp6fez3.js +0 -2
  245. package/dist/chunk-em3jb1dn.js +0 -4
  246. package/dist/chunk-ev4djb0p.js +0 -2
  247. package/dist/chunk-frejnjh9.js +0 -2
  248. package/dist/chunk-fvcr26a0.js +0 -22
  249. package/dist/chunk-g6ttsdz1.js +0 -2
  250. package/dist/chunk-gd73rpks.js +0 -2
  251. package/dist/chunk-ggwnrdqz.js +0 -17
  252. package/dist/chunk-h3t6fjba.js +0 -2
  253. package/dist/chunk-jc57j887.js +0 -2
  254. package/dist/chunk-jw248h1d.js +0 -2
  255. package/dist/chunk-k5xtf38q.js +0 -3
  256. package/dist/chunk-m78y5qys.js +0 -19
  257. package/dist/chunk-mc4rtf5d.js +0 -2
  258. package/dist/chunk-mx2wcb15.js +0 -2
  259. package/dist/chunk-p4w3wjbv.js +0 -2
  260. package/dist/chunk-pm3k8dyk.js +0 -2
  261. package/dist/chunk-qr59yfq9.js +0 -2
  262. package/dist/chunk-qsmdvy1z.js +0 -2
  263. package/dist/chunk-rsxmjfxq.js +0 -3754
  264. package/dist/chunk-s4sp78fn.js +0 -2
  265. package/dist/chunk-v2fp9vkh.js +0 -2
  266. package/dist/chunk-vwnnbzsp.js +0 -2
  267. package/dist/chunk-w0g99tx9.js +0 -2
  268. package/dist/chunk-x2pk87q2.js +0 -3
  269. package/dist/chunk-xn0asg46.js +0 -2
  270. package/dist/chunk-xwmw1wtk.js +0 -2
  271. package/dist/chunk-zdx9s3z0.js +0 -28
@@ -0,0 +1,181 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { patternToRegex } from "stx-router";
5
+ import { stateDir } from "./state-dir.js";
6
+ import { resolveRuntimeConfig, withRuntimeConfig } from "./runtime-config-server.js";
7
+ import { isLayerConfigSource } from "./application-layers.js";
8
+ const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"], discoveredSources = new Set;
9
+ export function discoverServerApi(root, options = {}) {
10
+ const directory = path.resolve(root, options.dir ?? "server/api"), routes = [], signatures = new Map;
11
+ if (!fs.existsSync(directory))
12
+ return routes;
13
+ const files = Array.from(new Bun.Glob("**/*.{ts,js,mts,mjs}").scanSync({ cwd: directory })).sort();
14
+ for (const file of files) {
15
+ if (file.endsWith(".d.ts"))
16
+ continue;
17
+ const parts = file.replace(/\.(?:ts|js|mts|mjs)$/, "").split("/");
18
+ let name = parts.pop();
19
+ const dot = name.lastIndexOf("."), suffix = dot >= 0 ? name.slice(dot + 1) : "get", method = suffix.toUpperCase();
20
+ if (!METHODS.includes(method) || suffix !== suffix.toLowerCase())
21
+ throw Error(`Unsupported API method suffix in ${file}; use ${METHODS.map((value) => value.toLowerCase()).join(", ")}`);
22
+ if (dot >= 0)
23
+ name = name.slice(0, dot);
24
+ if (name !== "index")
25
+ parts.push(name);
26
+ const names = new Set, segments = parts.map((part, index) => {
27
+ const parameter = /^\[(\.\.\.)?([A-Za-z_]\w*)\]$/.exec(part);
28
+ if (parameter) {
29
+ if (names.has(parameter[2]) || parameter[1] && index !== parts.length - 1)
30
+ throw Error(`Invalid API parameter in ${file}`);
31
+ names.add(parameter[2]);
32
+ return `:${parameter[2]}${parameter[1] ? "*" : ""}`;
33
+ }
34
+ if (!/^[\w-]+$/.test(part))
35
+ throw Error(`Unsupported API path segment ${part} in ${file}`);
36
+ return part;
37
+ }), pattern = `/api${segments.length ? `/${segments.join("/")}` : ""}`, signature = `${method} ${pattern.replace(/:\w+/g, ":param")}`;
38
+ if (signatures.has(signature))
39
+ throw Error(`Ambiguous API route ${method} ${pattern}: ${signatures.get(signature)} and ${file}`);
40
+ signatures.set(signature, file);
41
+ const filePath = path.join(directory, file);
42
+ discoveredSources.add(path.resolve(filePath));
43
+ discoveredSources.add(fs.realpathSync(filePath));
44
+ routes.push({ pattern, method, filePath });
45
+ }
46
+ return routes.sort((a, b) => {
47
+ const left = a.pattern.split("/"), right = b.pattern.split("/"), rank = (part) => part?.endsWith("*") ? 0 : part?.startsWith(":") ? 1 : 2;
48
+ for (let i = 0;i < Math.max(left.length, right.length); i++) {
49
+ const delta = rank(right[i]) - rank(left[i]);
50
+ if (delta)
51
+ return delta;
52
+ }
53
+ return a.pattern.localeCompare(b.pattern) || a.method.localeCompare(b.method);
54
+ });
55
+ }
56
+ export async function generateApiTypes(root, routes) {
57
+ const target = stateDir(root, "api-types.d.ts"), lines = ["// Generated by stx. Include this file in tsconfig.json.", "declare module '@stacksjs/stx/api-client' {", " interface KnownApiRoutes {"];
58
+ for (const route of routes) {
59
+ const specifier = `./${path.relative(path.dirname(target), route.filePath).replace(/\\/g, "/")}`, { params } = patternToRegex(route.pattern);
60
+ lines.push(` ${JSON.stringify(`${route.method} ${route.pattern}`)}: { params: { ${params.map((name) => `${JSON.stringify(name)}: string`).join("; ")} }; response: Awaited<ReturnType<typeof import(${JSON.stringify(specifier)}).default>> }`);
61
+ }
62
+ lines.push(" }", "}", "export {}", "");
63
+ const content = lines.join(`
64
+ `);
65
+ if (!await Bun.file(target).exists() || await Bun.file(target).text() !== content)
66
+ await Bun.write(target, content);
67
+ return target;
68
+ }
69
+ export async function buildServerApi(root, outputDir, options = {}) {
70
+ const routes = discoverServerApi(root, options);
71
+ await generateApiTypes(root, routes);
72
+ const result = [];
73
+ for (const route of routes) {
74
+ const bundled = await Bun.build({ entrypoints: [route.filePath], target: "bun", format: "esm", minify: !1, splitting: !1 });
75
+ if (!bundled.success)
76
+ throw Error(`API build failed for ${route.filePath}: ${bundled.logs.join(`
77
+ `)}`);
78
+ const output = bundled.outputs.find((file) => file.kind === "entry-point");
79
+ if (!output)
80
+ throw Error(`No API bundle for ${route.filePath}`);
81
+ if (bundled.outputs.length !== 1)
82
+ throw Error(`API endpoint ${route.filePath} emits assets; package those explicitly instead`);
83
+ const filePath = `server/api/endpoint-${new Bun.CryptoHasher("sha256").update(await output.arrayBuffer()).digest("hex").slice(0, 20)}.mjs`;
84
+ await Bun.write(path.join(outputDir, filePath), output);
85
+ result.push({ ...route, filePath });
86
+ }
87
+ return result;
88
+ }
89
+ export function createApiDispatcher(routes, load) {
90
+ const compiled = routes.map((route) => ({ route, ...patternToRegex(route.pattern) }));
91
+ return async (request) => {
92
+ const pathname = new URL(request.url).pathname, matches = compiled.filter((entry) => entry.regex.test(pathname));
93
+ if (!matches.length)
94
+ return null;
95
+ const pattern = matches[0].route.pattern, canonical = (value) => value.replace(/:\w+/g, ":param"), candidates = matches.filter((entry) => canonical(entry.route.pattern) === canonical(pattern)), method = request.method, matched = candidates.find((entry) => entry.route.method === method) ?? (method === "HEAD" ? candidates.find((entry) => entry.route.method === "GET") : void 0);
96
+ if (!matched) {
97
+ const allow = new Set(candidates.map((entry) => entry.route.method));
98
+ if (allow.has("GET"))
99
+ allow.add("HEAD");
100
+ allow.add("OPTIONS");
101
+ return new Response(null, { status: method === "OPTIONS" ? 204 : 405, headers: { Allow: Array.from(allow).sort().join(", ") } });
102
+ }
103
+ const match = matched.regex.exec(pathname), params = Object.create(null);
104
+ try {
105
+ matched.params.forEach((name, i) => {
106
+ params[name] = decodeURIComponent(match[i + 1]);
107
+ });
108
+ } catch {
109
+ return new Response("Invalid URL parameter encoding", { status: 400 });
110
+ }
111
+ try {
112
+ const handler = await load(matched.route);
113
+ if (typeof handler !== "function")
114
+ throw Error(`API endpoint ${matched.route.filePath} must default-export a handler`);
115
+ const value = await handler(request, { params }), response = value instanceof Response ? value : value === void 0 ? new Response(null, { status: 204 }) : Response.json(value);
116
+ if (method === "HEAD")
117
+ return new Response(null, { status: response.status, headers: response.headers });
118
+ return response;
119
+ } catch (error) {
120
+ console.error(`[stx] API error for ${method} ${pattern}:`, error);
121
+ return Response.json({ error: "Internal Server Error" }, { status: 500 });
122
+ }
123
+ };
124
+ }
125
+ export function productionApiDispatcher(outputDir, routes) {
126
+ return createApiDispatcher(routes, async (route) => (await import(pathToFileURL(path.resolve(outputDir, route.filePath)).href)).default);
127
+ }
128
+ export async function createServerApi(root, enabled) {
129
+ if (!enabled)
130
+ return async () => null;
131
+ const options = enabled === !0 ? {} : enabled, initial = discoverServerApi(root, options);
132
+ await generateApiTypes(root, initial);
133
+ return async (request) => {
134
+ if (!new URL(request.url).pathname.match(/^\/api(?:\/|$)/))
135
+ return null;
136
+ try {
137
+ const routes = discoverServerApi(root, options);
138
+ await generateApiTypes(root, routes);
139
+ const { loadStxConfig } = await import("./config.js"), runtimeConfig = resolveRuntimeConfig((await loadStxConfig(root)).runtimeConfig);
140
+ return await withRuntimeConfig(runtimeConfig, () => createApiDispatcher(routes, async (route) => {
141
+ const build = await Bun.build({ entrypoints: [route.filePath], target: "bun", format: "esm", splitting: !1 });
142
+ if (!build.success)
143
+ throw Error(build.logs.join(`
144
+ `));
145
+ const output = build.outputs.find((file) => file.kind === "entry-point");
146
+ if (!output || build.outputs.length !== 1)
147
+ throw Error(`Unsupported API bundle output: ${route.filePath}`);
148
+ return (await import(`data:text/javascript;base64,${Buffer.from(await output.text()).toString("base64")}`)).default;
149
+ })(request));
150
+ } catch (error) {
151
+ console.error("[stx] API discovery failed:", error);
152
+ return Response.json({ error: "API discovery failed; check the server log" }, { status: 500 });
153
+ }
154
+ };
155
+ }
156
+ export function isServerApiSource(filePath, root, enabled) {
157
+ if (isLayerConfigSource(filePath))
158
+ return !0;
159
+ const privateName = /^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/;
160
+ if (privateName.test(path.basename(filePath)))
161
+ return !0;
162
+ try {
163
+ if (privateName.test(path.basename(fs.realpathSync(filePath))))
164
+ return !0;
165
+ } catch {}
166
+ if (discoveredSources.has(path.resolve(filePath)))
167
+ return !0;
168
+ if (!enabled)
169
+ return !1;
170
+ const apiDir = path.resolve(root, typeof enabled === "object" ? enabled.dir ?? "server/api" : "server/api"), canonical = (value) => {
171
+ try {
172
+ return fs.realpathSync(value);
173
+ } catch {
174
+ return path.resolve(value);
175
+ }
176
+ }, file = canonical(filePath);
177
+ return [apiDir, path.resolve(root, "server"), path.resolve(root, ".output/server")].some((value) => {
178
+ const directory = canonical(value);
179
+ return file === directory || file.startsWith(`${directory}${path.sep}`);
180
+ });
181
+ }
@@ -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.
@@ -1125,20 +1191,25 @@ finally {
1125
1191
  // Declarative Data Fetching (Feature #6 - useFetch)
1126
1192
  // ==========================================================================
1127
1193
 
1194
+ var readHydratedData = ${readHydratedData.toString()};
1195
+ var clearServerData = ${clearServerData.toString()};
1196
+
1128
1197
  function useFetch(urlOrFn, options = {}) {
1129
- 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);
1130
1201
  // Starts false when nothing will be requested. It used to start true
1131
1202
  // unconditionally while the only thing clearing it was the fetch that
1132
1203
  // immediate:false suppresses \u2014 so the documented way to declare a deferred
1133
1204
  // request produced a composable stuck loading forever, which is exactly the
1134
1205
  // case where a template is most likely driving a spinner off it (#1818).
1135
- const immediate = options.immediate !== false;
1206
+ const immediate = options.immediate !== false && !hydrated;
1136
1207
  const loading = state(immediate);
1137
1208
  // Any request in flight, background ones included. loading answers "is
1138
1209
  // there nothing to show yet"; isFetching answers "is a request open" \u2014 and
1139
1210
  // a background refresh is the case where those two stop agreeing (#1929).
1140
1211
  const isFetching = state(immediate);
1141
- const error = state(null);
1212
+ const error = state(hydrated ? (hydrated.error || null) : null);
1142
1213
  if (options.suspense) registerSuspense(loading, error);
1143
1214
 
1144
1215
  // A superseded or unmounted request must not resolve into a torn-down
@@ -1269,6 +1340,7 @@ else if (immediate) {
1269
1340
  // from the getter made an early component resolve refs from whichever
1270
1341
  // component happened to hydrate last.
1271
1342
  var ownerScope = currentLifecycleScope() || componentScope;
1343
+ var ownerRefs = ownerScope.$refs || (ownerScope.$refs = {});
1272
1344
 
1273
1345
  // Callable, as well as .current / .value.
1274
1346
  //
@@ -1283,7 +1355,7 @@ else if (immediate) {
1283
1355
  //
1284
1356
  // No backticks in here: this whole runtime is a template literal.
1285
1357
  var read = function () {
1286
- return (ownerScope.$refs && ownerScope.$refs[name]) || null;
1358
+ return ownerRefs[name] || null;
1287
1359
  };
1288
1360
  Object.defineProperty(read, 'current', { get: read, enumerable: true });
1289
1361
  Object.defineProperty(read, 'value', { get: read, enumerable: true });
@@ -1727,8 +1799,11 @@ finally {
1727
1799
  var resolvedUrl = typeof url === 'function' ? url() : url;
1728
1800
  var fetchOpts = {
1729
1801
  method: options.method || 'POST',
1730
- headers: { 'Content-Type': 'application/json', ...__stxHeaders(options.headers) },
1731
- 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)
1732
1807
  };
1733
1808
  var response = await __stxFetch('useMutation', resolvedUrl, fetchOpts);
1734
1809
  if (!response.ok) throw await __stxHttpError(response);
@@ -1964,7 +2039,7 @@ catch (e) {
1964
2039
 
1965
2040
  function expressionUsesSignalMethod(expression, name) {
1966
2041
  var escapedName = name.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&');
1967
- 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);
1968
2043
  }
1969
2044
 
1970
2045
  function expressionUsesSignalValue(expression, name) {
@@ -2345,7 +2420,11 @@ catch (e) {
2345
2420
  value = undefined;
2346
2421
  }
2347
2422
 
2348
- 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) {
2349
2428
  el.removeAttribute(name);
2350
2429
  }
2351
2430
  else if (value === true) {
@@ -2806,7 +2885,10 @@ catch (e2) {
2806
2885
  }
2807
2886
  return;
2808
2887
  }
2809
- 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) {
2810
2892
  el.removeAttribute(attrName);
2811
2893
  }
2812
2894
  else if (v === true) {
@@ -2846,14 +2928,36 @@ else if (name === '@html' || name === ':html' || name === 'x-html') {
2846
2928
  el.removeAttribute(name);
2847
2929
  }
2848
2930
  else if (name === 'ref' || name === ':ref' || name === 'x-ref' || name === 'data-stx-ref') {
2849
- // Store ref in scope.$refs and componentScope.$refs
2850
- if (scope.$refs) scope.$refs[value] = el;
2851
- 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
+ }
2852
2954
  // Also fill a same-named signal declared in the script block, so the
2853
2955
  // documented ref() + x-ref pair works and reading the signal returns
2854
2956
  // the element. Without this the signal stayed empty and every read of
2855
2957
  // it silently returned undefined.
2856
- var refTarget = (scope && scope[value]) || componentScope[value];
2958
+ var refTarget = refCaller && refOwnerScope
2959
+ ? refOwnerScope[value]
2960
+ : (scope && scope[value]) || componentScope[value];
2857
2961
  if (refTarget && typeof refTarget === 'function' && refTarget._isSignal && typeof refTarget.set === 'function') {
2858
2962
  refTarget.set(el);
2859
2963
  }
@@ -2861,7 +2965,12 @@ else if (name === 'ref' || name === ':ref' || name === 'x-ref' || name === 'data
2861
2965
  else if (name.startsWith('@') || name.startsWith(':')) {
2862
2966
  // Event handlers: @click, :click, @submit.prevent, :keydown.enter, etc.
2863
2967
  const parts = name.slice(1).split('.');
2864
- 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];
2865
2974
  const modifiers = parts.slice(1);
2866
2975
 
2867
2976
  // Skip special directives (already handled above or in processElement)
@@ -2875,7 +2984,6 @@ else if (name === 'ref' || name === ':ref' || name === 'x-ref' || name === 'data
2875
2984
  el[eventKey] = true;
2876
2985
 
2877
2986
  // Capture scope at setup time so @for loop variables are available when event fires
2878
- const parentEventNames = (el.getAttribute && el.getAttribute('data-stx-parent-events') || '').split(/\\s+/);
2879
2987
  const isForwardedComponentEvent = !!(el.__stx_parent_scope && parentEventNames.includes(eventName));
2880
2988
  const eventCapturedScope = isForwardedComponentEvent
2881
2989
  ? { ...globalHelpers, ...el.__stx_parent_scope }
@@ -5633,6 +5741,18 @@ catch (e) {} }
5633
5741
  return normalizedPrefix + '-' + __stxGeneratedIdCounter;
5634
5742
  }
5635
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
+
5636
5756
  // Reactive prop binding. Bridges the gap between a parent's clientReactive
5637
5757
  // attribute (e.g. :open="modalOpen()" on a component) and the component's
5638
5758
  // internal state. Returns a signal whose value tracks the named attribute
@@ -6428,6 +6548,7 @@ catch (e) {} }
6428
6548
  onBeforeUnmount: onDestroy,
6429
6549
  onUnmounted: onDestroy,
6430
6550
  useFetch,
6551
+ clearServerData,
6431
6552
  useRef,
6432
6553
  navigate,
6433
6554
  refresh,
@@ -6467,6 +6588,7 @@ catch (e) {} }
6467
6588
  useCookie,
6468
6589
  useId,
6469
6590
  useReactiveProp,
6591
+ useModel,
6470
6592
  useEventListener,
6471
6593
  useWebSocket,
6472
6594
  useColorMode,
@@ -7263,6 +7385,7 @@ else {
7263
7385
  window.onMount = onMount;
7264
7386
  window.onDestroy = onDestroy;
7265
7387
  window.useFetch = useFetch;
7388
+ window.clearServerData = clearServerData;
7266
7389
  window.useRef = useRef;
7267
7390
  window.navigate = navigate;
7268
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-ggwnrdqz.js";import{Hm as Oq,Hp as P,Wo as Bq,bo as l,eo as Hq,er as n}from"./chunk-rsxmjfxq.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-whm6bybj.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-gecmqs6p.js";import"./chunk-7m4yhzhb.js";import{Tm as Oq,_p as P,np as Bq,ro as l,uo as Hq,xr as n}from"./chunk-fg0nf7cv.js";import"./chunk-2h94c5hm.js";import"./chunk-8jam44my.js";import"./chunk-t51mwjyq.js";import"./chunk-wfffa8zm.js";import{_t as Xq}from"./chunk-mv5fdcwc.js";import"./chunk-4evbx7sz.js";import"./chunk-jxxv18a0.js";import{mu as d}from"./chunk-c131k3mt.js";import"./chunk-9nf3hgvq.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-95t0k8cz.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-95t0k8cz.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-k23r03qj.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-k23r03qj.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