@stacksjs/stx 0.2.218 → 0.2.220

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 (184) hide show
  1. package/dist/app-shell.js +2 -1
  2. package/dist/{chunk-3twce5kp.js → chunk-02k0pg5s.js} +1 -1
  3. package/dist/{chunk-53ajah3v.js → chunk-06f65jz3.js} +2 -2
  4. package/dist/{chunk-crmk2jzf.js → chunk-08031d2g.js} +1 -1
  5. package/dist/chunk-0k12epgy.js +2 -0
  6. package/dist/{chunk-3fwn9edg.js → chunk-135mme4g.js} +1 -1
  7. package/dist/{chunk-c7pvwvse.js → chunk-1gy7fa09.js} +1 -1
  8. package/dist/{chunk-bsr7yrxh.js → chunk-1rka3ffx.js} +1 -1
  9. package/dist/chunk-1y3kc7mb.js +2 -0
  10. package/dist/chunk-20wgmax7.js +2 -0
  11. package/dist/chunk-25jkkv9d.js +2 -0
  12. package/dist/{chunk-wbq7cp57.js → chunk-2bxgan9p.js} +1 -1
  13. package/dist/{chunk-cqt6ry1e.js → chunk-2v1cj2qp.js} +1 -1
  14. package/dist/chunk-2y8ss8b3.js +2 -0
  15. package/dist/chunk-38zpyb7q.js +2 -0
  16. package/dist/{chunk-yk1smsev.js → chunk-3s3zyq5q.js} +1 -1
  17. package/dist/chunk-3zhhytkd.js +2 -0
  18. package/dist/chunk-4k5f40bb.js +2 -0
  19. package/dist/{chunk-gvm4dw6p.js → chunk-4svjne4w.js} +2 -2
  20. package/dist/{chunk-z2sp0k8d.js → chunk-4tmw4kjm.js} +1 -1
  21. package/dist/{chunk-ne8sygmy.js → chunk-4vhxtfkw.js} +1 -1
  22. package/dist/{chunk-mxqp7x07.js → chunk-4wdbmjmg.js} +2 -2
  23. package/dist/{chunk-hyrjade7.js → chunk-572ttrsj.js} +1 -1
  24. package/dist/{chunk-fvpaf9v5.js → chunk-5a5efazd.js} +2 -2
  25. package/dist/chunk-5fz9n4wq.js +3 -0
  26. package/dist/{chunk-css1sfnr.js → chunk-5y731xe9.js} +1 -1
  27. package/dist/chunk-67b47fez.js +2 -0
  28. package/dist/{chunk-8anh6d36.js → chunk-6b0xz02h.js} +1 -1
  29. package/dist/{chunk-74gc1x9x.js → chunk-6qjzx44j.js} +2 -2
  30. package/dist/{chunk-weajy31v.js → chunk-6sm1vr9h.js} +2 -2
  31. package/dist/{chunk-x8b16v5q.js → chunk-6vdn3qy0.js} +1 -1
  32. package/dist/{chunk-x13f5bbe.js → chunk-72w4hhbq.js} +1 -1
  33. package/dist/chunk-735atsqq.js +2 -0
  34. package/dist/{chunk-n8zpm7xb.js → chunk-74pjj8d0.js} +1 -1
  35. package/dist/chunk-7cq5b6zp.js +2 -0
  36. package/dist/chunk-7jhtvcy5.js +2 -0
  37. package/dist/{chunk-whxregkn.js → chunk-7ryqex47.js} +1 -1
  38. package/dist/{chunk-1nnpwrqj.js → chunk-7s3wrtpb.js} +2 -2
  39. package/dist/chunk-7x3nd6r4.js +2 -0
  40. package/dist/{chunk-m2mhtpwy.js → chunk-80qre9zp.js} +1 -1
  41. package/dist/{chunk-c0p9kf53.js → chunk-8awfakrk.js} +1 -1
  42. package/dist/{chunk-st5qggks.js → chunk-8ha8h3s1.js} +1 -1
  43. package/dist/{chunk-trtm887x.js → chunk-8rn5e39c.js} +1 -1
  44. package/dist/chunk-9ktvkzcc.js +2 -0
  45. package/dist/chunk-a4329ma8.js +30 -0
  46. package/dist/{chunk-y4hkqsgw.js → chunk-a6nnbnmb.js} +2 -2
  47. package/dist/{chunk-j3njy10j.js → chunk-ad84gwgv.js} +2 -2
  48. package/dist/{chunk-xwc4pg5w.js → chunk-anenwsj3.js} +2 -2
  49. package/dist/{chunk-khrtzbxd.js → chunk-arnse15r.js} +1 -1
  50. package/dist/chunk-bgb5a3q6.js +4 -0
  51. package/dist/chunk-bj25jvsn.js +2 -0
  52. package/dist/{chunk-fnkxbnka.js → chunk-bx766t25.js} +1 -1
  53. package/dist/{chunk-msjzqne1.js → chunk-bz9z4pfr.js} +1 -1
  54. package/dist/{chunk-yckd6ks5.js → chunk-c0n802j1.js} +1 -1
  55. package/dist/{chunk-b6jhznkh.js → chunk-cq6fsp6j.js} +1 -1
  56. package/dist/chunk-cw0352e8.js +2 -0
  57. package/dist/{chunk-q4se9rtw.js → chunk-dykhpgyx.js} +1 -1
  58. package/dist/{chunk-7md45k52.js → chunk-e890s5em.js} +2 -2
  59. package/dist/{chunk-ht51fz7w.js → chunk-efr3ejqt.js} +1 -1
  60. package/dist/{chunk-1306tswx.js → chunk-efrv1yp5.js} +1 -1
  61. package/dist/{chunk-jmnftb29.js → chunk-ejspksxd.js} +2 -2
  62. package/dist/chunk-et555kdz.js +2 -0
  63. package/dist/{chunk-7mst8kqm.js → chunk-ewdn7s6r.js} +1 -1
  64. package/dist/{chunk-hncp9gz6.js → chunk-f5cw54q3.js} +1 -1
  65. package/dist/chunk-fw5d1aev.js +18 -0
  66. package/dist/chunk-g3rg8afc.js +2 -0
  67. package/dist/{chunk-9b82d4g5.js → chunk-gnmft4dz.js} +1 -1
  68. package/dist/chunk-h7xtn6j0.js +2 -0
  69. package/dist/{chunk-rczpw37w.js → chunk-hcqzbhc1.js} +1 -1
  70. package/dist/{chunk-7zk48rd8.js → chunk-hg2ja2gj.js} +1 -1
  71. package/dist/chunk-hh2r7hrb.js +2 -0
  72. package/dist/chunk-hysfnyh4.js +2 -0
  73. package/dist/chunk-j3mw2vpt.js +2 -0
  74. package/dist/{chunk-q8szpd6w.js → chunk-jw1besrt.js} +1 -1
  75. package/dist/{chunk-3es366z4.js → chunk-k6b7gpk2.js} +1 -1
  76. package/dist/{chunk-z47tw39z.js → chunk-kdpy5rgk.js} +2 -2
  77. package/dist/{chunk-j0tfxbns.js → chunk-kvz7rg2x.js} +2 -2
  78. package/dist/{chunk-tryt2h85.js → chunk-m6damb1f.js} +1 -1
  79. package/dist/{chunk-1bvstnz4.js → chunk-mcz70xms.js} +2 -2
  80. package/dist/{chunk-y2jr10y8.js → chunk-mt4cdgz3.js} +2 -2
  81. package/dist/chunk-n1b7b20f.js +2 -0
  82. package/dist/{chunk-zgvga8rc.js → chunk-ncvd7673.js} +1 -1
  83. package/dist/{chunk-47pge5gz.js → chunk-nnw1ka45.js} +1 -1
  84. package/dist/{chunk-808qy9cq.js → chunk-pscdy0gn.js} +197 -197
  85. package/dist/{chunk-zat2ndst.js → chunk-pzcf36xm.js} +347 -347
  86. package/dist/{chunk-dmb6t0qj.js → chunk-q5w0fqd5.js} +2 -2
  87. package/dist/{chunk-pezxve4a.js → chunk-qfsktf7s.js} +3 -3
  88. package/dist/{chunk-a2rj5ce0.js → chunk-qr90ng3a.js} +2 -2
  89. package/dist/{chunk-rg6v68ya.js → chunk-rbnmbeda.js} +1 -1
  90. package/dist/chunk-rmrnnv87.js +2 -0
  91. package/dist/{chunk-j5vyt8wd.js → chunk-rpyck7kn.js} +1 -1
  92. package/dist/chunk-rq20qvkk.js +2 -0
  93. package/dist/{chunk-1nm2xrvq.js → chunk-ry86fd41.js} +1 -1
  94. package/dist/{chunk-9xh78snm.js → chunk-s6yn1mbm.js} +1 -1
  95. package/dist/{chunk-vgk5v31k.js → chunk-s88yt309.js} +1 -1
  96. package/dist/{chunk-ymccpdg6.js → chunk-snktca7b.js} +1 -1
  97. package/dist/{chunk-fvjh7rx0.js → chunk-swy03mg9.js} +1 -1
  98. package/dist/chunk-tc2d9en8.js +2 -0
  99. package/dist/{chunk-9064gyt5.js → chunk-tgaddq21.js} +2 -2
  100. package/dist/chunk-th7snpq2.js +2 -0
  101. package/dist/{chunk-f6jm4hy3.js → chunk-txre2e2m.js} +1 -1
  102. package/dist/chunk-v7ggp28p.js +2 -0
  103. package/dist/{chunk-zxb128xa.js → chunk-vaa8tk98.js} +2 -2
  104. package/dist/chunk-vg0kzfcy.js +2 -0
  105. package/dist/{chunk-p8pyqr7p.js → chunk-vgf945mj.js} +1 -1
  106. package/dist/{chunk-xkd164zg.js → chunk-w7ped5p5.js} +1 -1
  107. package/dist/{chunk-yf3bmmkk.js → chunk-wvc7t11n.js} +1 -1
  108. package/dist/{chunk-3wd9kfyz.js → chunk-x0bcc9sj.js} +1 -1
  109. package/dist/chunk-x0f34a44.js +2 -0
  110. package/dist/{chunk-aw9z3m10.js → chunk-xqnwy1t6.js} +1 -1
  111. package/dist/{chunk-pdh79z63.js → chunk-xrnqz76v.js} +1 -1
  112. package/dist/{chunk-p7qqbw2k.js → chunk-ydk1n77q.js} +2 -2
  113. package/dist/chunk-yk45219d.js +2 -0
  114. package/dist/{chunk-s7dqawk0.js → chunk-yppz6dgg.js} +2 -2
  115. package/dist/{chunk-w0ng9e1m.js → chunk-z6ev72qj.js} +1 -1
  116. package/dist/{chunk-6xg3j487.js → chunk-z794cdmn.js} +1 -1
  117. package/dist/{chunk-96kpqgh3.js → chunk-zg5mq1cj.js} +1 -1
  118. package/dist/chunk-zh75hc6a.js +2 -0
  119. package/dist/{chunk-zj44h5kk.js → chunk-zhfdf2h5.js} +1 -1
  120. package/dist/chunk-zpskp2xb.js +2 -0
  121. package/dist/cli.js +14 -14
  122. package/dist/craft-entry.js +1 -1
  123. package/dist/craft.js +1 -1
  124. package/dist/database.js +1 -1
  125. package/dist/dev-server/serve-app.js +33 -8
  126. package/dist/dev-server/serve-multi.js +5 -2
  127. package/dist/index.d.ts +1 -0
  128. package/dist/index.js +1 -0
  129. package/dist/page-response.d.ts +113 -0
  130. package/dist/page-response.js +106 -1
  131. package/dist/process.js +2 -0
  132. package/dist/production-server.js +13 -5
  133. package/dist/pwa.js +2 -2
  134. package/dist/render.d.ts +14 -0
  135. package/dist/render.js +3 -19
  136. package/dist/serve.js +19 -10
  137. package/dist/spa-nav.d.ts +49 -0
  138. package/dist/spa-nav.js +12 -0
  139. package/dist/ssg.js +2 -2
  140. package/dist/template-compiler.d.ts +1 -0
  141. package/dist/template-compiler.js +2 -0
  142. package/dist/template-hydrator.d.ts +1 -1
  143. package/dist/template-hydrator.js +4 -3
  144. package/dist/variable-extractor.d.ts +1 -1
  145. package/dist/variable-extractor.js +6 -2
  146. package/dist/visual-testing.js +1 -1
  147. package/package.json +5 -5
  148. package/dist/chunk-10yft4b7.js +0 -2
  149. package/dist/chunk-17atrbv2.js +0 -2
  150. package/dist/chunk-23vxz3hp.js +0 -2
  151. package/dist/chunk-2me28xee.js +0 -2
  152. package/dist/chunk-2w5d5tw1.js +0 -2
  153. package/dist/chunk-2xeq5xnf.js +0 -2
  154. package/dist/chunk-2z6k7gsa.js +0 -2
  155. package/dist/chunk-3fxcwk6a.js +0 -2
  156. package/dist/chunk-4vwxgmg0.js +0 -2
  157. package/dist/chunk-5gr4vv7m.js +0 -2
  158. package/dist/chunk-775fabj4.js +0 -2
  159. package/dist/chunk-8cyv5316.js +0 -2
  160. package/dist/chunk-8xtvmwpr.js +0 -2
  161. package/dist/chunk-9db2f09j.js +0 -2
  162. package/dist/chunk-9h908knr.js +0 -2
  163. package/dist/chunk-a1ydhf5t.js +0 -3
  164. package/dist/chunk-ba18hn7n.js +0 -2
  165. package/dist/chunk-bd0yv6a0.js +0 -2
  166. package/dist/chunk-cr7s8q08.js +0 -2
  167. package/dist/chunk-d48tzd8c.js +0 -2
  168. package/dist/chunk-dcy8hg45.js +0 -2
  169. package/dist/chunk-e6377wfq.js +0 -4
  170. package/dist/chunk-jnjxf5t2.js +0 -2
  171. package/dist/chunk-n4smz31k.js +0 -18
  172. package/dist/chunk-njkv35c3.js +0 -2
  173. package/dist/chunk-q3ea7q6t.js +0 -2
  174. package/dist/chunk-qd1nadff.js +0 -30
  175. package/dist/chunk-qwzfdq8q.js +0 -2
  176. package/dist/chunk-r153ybwd.js +0 -2
  177. package/dist/chunk-tg0w29j1.js +0 -2
  178. package/dist/chunk-tqhwzjj7.js +0 -2
  179. package/dist/chunk-vgr8kykv.js +0 -2
  180. package/dist/chunk-w670sde5.js +0 -2
  181. package/dist/chunk-x9bsft57.js +0 -2
  182. package/dist/chunk-y05vd24g.js +0 -2
  183. package/dist/chunk-yrqnsd3a.js +0 -2
  184. package/dist/chunk-z0hkt5sk.js +0 -2
@@ -1,3 +1,43 @@
1
+ /**
2
+ * The HTTP status and headers a page decides for its own response.
3
+ *
4
+ * Three shapes reach the same place, so a host reads one key and gets all
5
+ * three:
6
+ *
7
+ * - `definePageMeta({ status })` — read statically out of the source, before
8
+ * anything runs. Right for a page that is *always* an error page.
9
+ * - `@status(expr)` — a template directive, evaluated where the rest of the
10
+ * template is. It sits inside the branch it belongs to, so a page says
11
+ * `@if (!feature) @status(404) @endif` next to the markup that explains it.
12
+ * - `setResponseStatus(code)` / `notFound()` / `setResponseHeader(n, v)` —
13
+ * callable from `<script server>`, for a decision that needs the lookup's
14
+ * result.
15
+ *
16
+ * The last two record on the render context under `__stxResponseStatus` and
17
+ * `__stxResponseHeaders`. Every host that renders a view — the dev/production
18
+ * serve in `bun-plugin`, `stx`'s own `serve`, the app dev server, the
19
+ * precompiled production server — reads them back with `readResponseStatus`
20
+ * and answers with what it finds.
21
+ *
22
+ * That read-back is the whole point. Recording without it is the failure this
23
+ * module exists to prevent: a page that says 404 renders its not-found body
24
+ * under a 200, which tells a crawler, a cache and an uptime check that the URL
25
+ * is a real page.
26
+ *
27
+ * @module page-response
28
+ */
29
+ /** Context key holding the status a render asked for. */
30
+ export declare const RESPONSE_STATUS_KEY = "__stxResponseStatus";
31
+ /** Context key holding the headers a render asked for. */
32
+ export declare const RESPONSE_HEADERS_KEY = "__stxResponseHeaders";
33
+ /**
34
+ * Is this a status a response can actually carry?
35
+ *
36
+ * Out of range is ignored rather than thrown everywhere below. A status is not
37
+ * worth failing an already-rendered page over, and the range check is what
38
+ * stops a typo becoming a 500 from whichever host reads it back.
39
+ */
40
+ export declare function isHttpStatus(value: unknown): value is number;
1
41
  /**
2
42
  * Read the static HTTP status declared by `definePageMeta`.
3
43
  *
@@ -5,3 +45,76 @@
5
45
  * pages and other non-200 documents carry the correct response semantics.
6
46
  */
7
47
  export declare function extractPageResponseStatus(source: string): number | undefined;
48
+ /**
49
+ * Record a status on the render context, if it is one.
50
+ *
51
+ * Last call wins, so a page can look, decide, then change its mind — the
52
+ * lookup that finds the record after all must be able to take the 404 back.
53
+ * Returns whether the status was accepted, so a caller can warn about one that
54
+ * was not.
55
+ */
56
+ export declare function recordResponseStatus(context: Record<string, any> | undefined, status: unknown): boolean;
57
+ /**
58
+ * Record a response header on the render context.
59
+ *
60
+ * The pair is not optional: a page that works out mid-render that a handle has
61
+ * moved can say 301 and, without this, cannot say where to — so the response
62
+ * it produces is a redirect with no destination, which is worse than the 404
63
+ * it replaced.
64
+ */
65
+ export declare function recordResponseHeader(context: Record<string, any> | undefined, name: unknown, value: unknown): void;
66
+ /** The status a finished render asked for, or `undefined` if it asked for none. */
67
+ export declare function readResponseStatus(context: Record<string, any> | undefined | null): number | undefined;
68
+ /** The headers a finished render asked for, or `undefined` if it asked for none. */
69
+ export declare function readResponseHeaders(context: Record<string, any> | undefined | null): Record<string, string> | undefined;
70
+ /**
71
+ * Move a recorded status/headers from one context object onto another.
72
+ *
73
+ * Renderers build a fresh internal context from the caller's — so a page that
74
+ * records a status records it on an object nobody outside can read. This is
75
+ * how the intent gets back out: call it with the internal context and the
76
+ * caller's, after the render.
77
+ *
78
+ * Only copies what is there. A render that asked for nothing leaves the target
79
+ * untouched rather than stamping it with a 200, so a caller can tell "the page
80
+ * said 200" from "the page said nothing" — the second is what lets an outer
81
+ * status (an error page's `definePageMeta`) survive.
82
+ */
83
+ export declare function syncRecordedResponse(from: Record<string, any> | undefined | null, to: Record<string, any> | undefined | null): void;
84
+ /**
85
+ * The `<script server>` bindings for deciding a response, bound to one context.
86
+ *
87
+ * Handed to every server script by `extractVariables`, so no host can render a
88
+ * view and leave them out. A host that wants the calls to go somewhere of its
89
+ * own — the dev serve puts them straight on its per-request context — overrides
90
+ * them through the render context, which is appended after these and wins.
91
+ */
92
+ export declare function responseBindings(context: Record<string, any>): {
93
+ setResponseStatus: (status: number) => void;
94
+ setResponseHeader: (name: string, value: string) => void;
95
+ notFound: (status?: number) => void;
96
+ };
97
+ /**
98
+ * `@status(expr)` — the template-side spelling.
99
+ *
100
+ * Runs after `processConditionals`, so a `@status` in a branch that lost is
101
+ * already gone from the template and never fires. That ordering is the feature:
102
+ * it lets the status live beside the markup that justifies it,
103
+ *
104
+ * @if (!feature)
105
+ * @status(404)
106
+ * <h1>No feature by that name.</h1>
107
+ * @endif
108
+ *
109
+ * rather than being re-derived from a flag at the top of the server block.
110
+ *
111
+ * A literal is taken as written; anything else goes through `safeEvaluate`
112
+ * against the render context. An argument that evaluates to a non-status is
113
+ * ignored — see `isHttpStatus` — but *is* warned about, because unlike a
114
+ * runtime call this one was typed out in the template and a silent no-op there
115
+ * reads as the feature not existing.
116
+ */
117
+ export declare function processStatusDirective(template: string, context: Record<string, any>, options?: {
118
+ filePath?: string;
119
+ buildMode?: string;
120
+ }): string;
@@ -1,12 +1,117 @@
1
+ import { safeEvaluate } from "./safe-evaluator.js";
1
2
  const MIN_HTTP_STATUS = 100, MAX_HTTP_STATUS = 599;
3
+ export const RESPONSE_STATUS_KEY = "__stxResponseStatus", RESPONSE_HEADERS_KEY = "__stxResponseHeaders";
4
+ export function isHttpStatus(value) {
5
+ return typeof value === "number" && Number.isInteger(value) && value >= MIN_HTTP_STATUS && value <= MAX_HTTP_STATUS;
6
+ }
2
7
  export function extractPageResponseStatus(source) {
3
8
  for (const call of source.matchAll(/\bdefinePageMeta\s*\(\s*\{([\s\S]*?)\}\s*\)/g)) {
4
9
  const match = call[1].match(/(?:^|,)\s*status\s*:\s*(\d{3})(?=\s*(?:,|$))/);
5
10
  if (!match)
6
11
  continue;
7
12
  const status = Number(match[1]);
8
- if (Number.isInteger(status) && status >= MIN_HTTP_STATUS && status <= MAX_HTTP_STATUS)
13
+ if (isHttpStatus(status))
9
14
  return status;
10
15
  }
11
16
  return;
12
17
  }
18
+ export function recordResponseStatus(context, status) {
19
+ if (!context || typeof context !== "object")
20
+ return !1;
21
+ const code = typeof status === "string" && /^\d+$/.test(status.trim()) ? Number(status.trim()) : status;
22
+ if (!isHttpStatus(code))
23
+ return !1;
24
+ context[RESPONSE_STATUS_KEY] = code;
25
+ return !0;
26
+ }
27
+ export function recordResponseHeader(context, name, value) {
28
+ if (!context || typeof context !== "object")
29
+ return;
30
+ const header = String(name ?? "").trim();
31
+ if (!header)
32
+ return;
33
+ context[RESPONSE_HEADERS_KEY] = { ...context[RESPONSE_HEADERS_KEY], [header]: String(value) };
34
+ }
35
+ export function readResponseStatus(context) {
36
+ const status = context?.[RESPONSE_STATUS_KEY];
37
+ return isHttpStatus(status) ? status : void 0;
38
+ }
39
+ export function readResponseHeaders(context) {
40
+ const headers = context?.[RESPONSE_HEADERS_KEY];
41
+ if (!headers || typeof headers !== "object")
42
+ return;
43
+ const entries = Object.entries(headers).map(([k, v]) => [k, String(v)]);
44
+ return entries.length > 0 ? Object.fromEntries(entries) : void 0;
45
+ }
46
+ export function syncRecordedResponse(from, to) {
47
+ if (!from || !to || from === to || typeof to !== "object")
48
+ return;
49
+ const status = readResponseStatus(from);
50
+ if (status !== void 0)
51
+ to[RESPONSE_STATUS_KEY] = status;
52
+ const headers = readResponseHeaders(from);
53
+ if (headers)
54
+ to[RESPONSE_HEADERS_KEY] = { ...to[RESPONSE_HEADERS_KEY], ...headers };
55
+ }
56
+ export function responseBindings(context) {
57
+ return {
58
+ setResponseStatus: (status) => {
59
+ recordResponseStatus(context, status);
60
+ },
61
+ notFound: (status = 404) => {
62
+ const code = isHttpStatus(status) && status >= 400 ? status : 404;
63
+ recordResponseStatus(context, code);
64
+ },
65
+ setResponseHeader: (name, value) => {
66
+ recordResponseHeader(context, name, value);
67
+ }
68
+ };
69
+ }
70
+ export function processStatusDirective(template, context, options = {}) {
71
+ if (!template.includes("@status"))
72
+ return template;
73
+ const { filePath, buildMode } = options, precompiling = buildMode === "compile";
74
+ let result = "", cursor = 0;
75
+ const pattern = /@status\s*\(/g;
76
+ let match;
77
+ while ((match = pattern.exec(template)) !== null) {
78
+ const close = closingParen(template, match.index + match[0].length - 1);
79
+ if (close < 0)
80
+ break;
81
+ const arg = template.slice(match.index + match[0].length, close).trim(), value = /^\d+$/.test(arg) ? Number(arg) : safeEvaluate(arg, context), where = filePath ? ` in ${filePath}` : "";
82
+ if (precompiling)
83
+ console.warn(`[stx] @status(${arg})${where} is skipped when precompiling: the build has no request, so the branch it sits in is not the one a visitor will get. Call notFound() or setResponseStatus(${arg}) from <script server> instead \u2014 that runs per request.`);
84
+ else if (!recordResponseStatus(context, value))
85
+ console.warn(`[stx] @status(${arg})${where} is not an HTTP status (100-599) \u2014 ignoring it.`);
86
+ result += template.slice(cursor, match.index);
87
+ cursor = close + 1 + (template.slice(close + 1).match(/^[^\S\n]*\n?/)?.[0].length ?? 0);
88
+ pattern.lastIndex = cursor;
89
+ }
90
+ return cursor === 0 ? template : result + template.slice(cursor);
91
+ }
92
+ function closingParen(source, open) {
93
+ let depth = 1, quote = null, escaped = !1;
94
+ for (let i = open + 1;i < source.length; i++) {
95
+ const char = source[i];
96
+ if (escaped) {
97
+ escaped = !1;
98
+ continue;
99
+ }
100
+ if (quote) {
101
+ if (char === "\\")
102
+ escaped = !0;
103
+ else if (char === quote)
104
+ quote = null;
105
+ continue;
106
+ }
107
+ if (char === '"' || char === "'" || char === "`") {
108
+ quote = char;
109
+ continue;
110
+ }
111
+ if (char === "(")
112
+ depth++;
113
+ else if (char === ")" && --depth === 0)
114
+ return i;
115
+ }
116
+ return -1;
117
+ }
package/dist/process.js CHANGED
@@ -12,6 +12,7 @@ import { processAnimationDirectives } from "./animation.js";
12
12
  import { generateRuntimeScript, processEventDirectives } from "./events.js";
13
13
  import { extractBridgeData, processClientScript } from "./client-script.js";
14
14
  import { extractPageMetaFromSource, pageMetaLayout } from "./page-meta.js";
15
+ import { processStatusDirective } from "./page-response.js";
15
16
  import { processReactiveDirectives } from "./reactive.js";
16
17
  import { processMarkdownFileDirectives } from "./assets.js";
17
18
  import { processAuthDirectives, processConditionals, processEnvDirective, processIssetEmptyDirectives } from "./conditionals.js";
@@ -694,6 +695,7 @@ async function processOtherDirectives(template, context, filePath, options, depe
694
695
  output = output.replace(/@push\s*\(\s*['"][^'"]+['"]\s*\)[\s\S]*?@endpush/g, "");
695
696
  output = processRefAttributes(output);
696
697
  output = processConditionals(output, context, filePath);
698
+ output = processStatusDirective(output, context, { filePath, buildMode: opts.buildMode });
697
699
  output = processIssetEmptyDirectives(output, context);
698
700
  output = processEnvDirective(output, context);
699
701
  output = processBasicFormDirectives(output, context);
@@ -8,6 +8,7 @@ import { pageShipsSignalsRuntime } from "./runtime-injection.js";
8
8
  import { patternToRegex } from "stx-router";
9
9
  import { compressResponse } from "./compression.js";
10
10
  import { actionRedirectResponse, isActionableMethod } from "./page-action.js";
11
+ import { FRAGMENT_CACHE_CONTROL, isSpaNavRequest, spaNavVaryHeaders } from "./spa-nav.js";
11
12
  const MIME_TYPES = {
12
13
  ".js": "application/javascript",
13
14
  ".mjs": "application/javascript",
@@ -100,7 +101,7 @@ export async function startProductionServer(options = {}) {
100
101
  } catch {}
101
102
  }
102
103
  }
103
- const isSpaNav = request.headers.get("X-STX-Router") === "true";
104
+ const isSpaNav = isSpaNavRequest(request);
104
105
  let matchedRoute = null, params = {};
105
106
  matchedRoute = exactRoutes.get(pathname) || null;
106
107
  if (!matchedRoute)
@@ -139,7 +140,8 @@ export async function startProductionServer(options = {}) {
139
140
  "X-STX-Layout": layoutMetadata.layout,
140
141
  "X-STX-Layout-Group": layoutMetadata.group
141
142
  } : {},
142
- "Cache-Control": "no-cache"
143
+ ...spaNavVaryHeaders(),
144
+ "Cache-Control": FRAGMENT_CACHE_CONTROL
143
145
  }
144
146
  });
145
147
  }
@@ -159,13 +161,15 @@ export async function startProductionServer(options = {}) {
159
161
  }
160
162
  if (!isMutating && !compiled.hasServerScripts && Object.keys(compiled.placeholders).length === 0)
161
163
  return new Response(compiled.html, {
164
+ status: compiled.status ?? 200,
162
165
  headers: {
163
166
  "Content-Type": "text/html",
167
+ ...spaNavVaryHeaders(),
164
168
  "Cache-Control": "public, max-age=60"
165
169
  }
166
170
  });
167
171
  try {
168
- const { html, boundaries, redirect, cookies } = await hydrateTemplateStream(compiled, {
172
+ const { html, boundaries, redirect, cookies, status, headers: pageHeaders } = await hydrateTemplateStream(compiled, {
169
173
  params,
170
174
  request,
171
175
  method: request.method
@@ -175,16 +179,20 @@ export async function startProductionServer(options = {}) {
175
179
  if (boundaries && boundaries.length > 0) {
176
180
  const { renderStreamingPage, streamToResponse } = await import("./streaming.js");
177
181
  return streamToResponse(renderStreamingPage(html, boundaries, { timeoutMs: 30000 }), {
178
- headers: { "Cache-Control": "no-cache" }
182
+ status: status ?? compiled.status ?? 200,
183
+ headers: { "Cache-Control": "no-cache", ...pageHeaders }
179
184
  });
180
185
  }
181
186
  const headers = new Headers({
182
187
  "Content-Type": "text/html",
188
+ ...spaNavVaryHeaders(),
183
189
  "Cache-Control": "no-cache"
184
190
  });
185
191
  for (const cookie of cookies ?? [])
186
192
  headers.append("Set-Cookie", cookie);
187
- return new Response(html, { headers });
193
+ for (const [name, value] of Object.entries(pageHeaders ?? {}))
194
+ headers.set(name, value);
195
+ return new Response(html, { status: status ?? compiled.status ?? 200, headers });
188
196
  } catch (error) {
189
197
  console.error(`[stx] Hydration error for ${pathname}:`, error);
190
198
  return new Response(compiled.html, {
package/dist/pwa.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{Bk as wq,Ck as dq,Dk as Cq,Ek as mq,Fk as gq}from"./chunk-yf3bmmkk.js";import{Gk as S,Hk as Tq,Ik as _q,Jk as z,Kk as D,Lk as P,Mk as kq,Nk as vq,Ok as w,Pk as Iq,Qk as d,Rk as Hq,Sk as Oq,Tk as Mq}from"./chunk-53ajah3v.js";import{$t as Aq,au as bq,bu as Sq,cu as zq,du as Dq,eu as Pq}from"./chunk-3wd9kfyz.js";import{iu as N}from"./chunk-trtm887x.js";import p from"fs";import E from"path";import C from"fs";import L from"path";var k=[72,96,128,144,152,192,384,512],v=[120,152,167,180],I=[16,32];async function H(G,B){let q={success:!0,generatedFiles:[],errors:[],warnings:[]},K=G.pwa?.icons;if(!K?.src)return q.errors.push("No source icon specified in pwa.icons.src"),q.success=!1,q;let Y=L.isAbsolute(K.src)?K.src:L.resolve(process.cwd(),K.src);if(!await Bun.file(Y).exists())return q.errors.push(`Source icon not found: ${Y}`),q.success=!1,q;let Q=L.resolve(B,K.outputDir||"pwa-icons");try{C.mkdirSync(Q,{recursive:!0})}catch{return q.errors.push(`Failed to create output directory: ${Q}`),q.success=!1,q}let X=K.sizes||k,j=K.generateWebP??!0,J=K.generateAppleIcons??!0;try{let y;try{y=await import("sharp")}catch{return q.errors.push(`sharp is not installed. Install it with: bun add sharp
3
- Icon generation requires the sharp package for image processing.`),q.success=!1,q}let R=await y.default(Y).metadata();if(R.width&&R.width<512)q.warnings.push(`Source icon is ${R.width}x${R.height}. Recommend using at least 512x512 for best quality.`);for(let $ of X){let x=L.join(Q,`icon-${$}x${$}.png`);if(await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(x),q.generatedFiles.push(x),j){let F=L.join(Q,`icon-${$}x${$}.webp`);await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(F),q.generatedFiles.push(F)}}if(J){for(let x of v){let F=L.join(Q,`apple-touch-icon-${x}x${x}.png`);await y.default(Y).resize(x,x,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(F),q.generatedFiles.push(F)}let $=L.join(Q,"apple-touch-icon.png");await y.default(Y).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile($),q.generatedFiles.push($)}for(let $ of I){let x=L.join(Q,`favicon-${$}x${$}.png`);await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(x),q.generatedFiles.push(x)}let U=512,T=L.join(Q,`icon-maskable-${U}x${U}.png`),Z=Math.floor(U*0.1),_=U-Z*2;await y.default(Y).resize(_,_,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:Z,bottom:Z,left:Z,right:Z,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(T),q.generatedFiles.push(T)}catch(y){let V=y instanceof Error?y.message:String(y);q.errors.push(`Icon generation failed: ${V}`),q.success=!1}return q}function n(G){let B=G.sizes||k,q=G.outputDir?`/${G.outputDir}`:"/pwa-icons",K=G.generateWebP??!0,Y=G.generateAppleIcons??!0,Q=[];for(let X of B)if(Q.push(`${q}/icon-${X}x${X}.png`),K)Q.push(`${q}/icon-${X}x${X}.webp`);if(Y){Q.push(`${q}/apple-touch-icon.png`);for(let X of v)Q.push(`${q}/apple-touch-icon-${X}x${X}.png`)}for(let X of I)Q.push(`${q}/favicon-${X}x${X}.png`);return Q.push(`${q}/icon-maskable-512x512.png`),Q}async function O(){try{return await import("sharp"),!0}catch{return!1}}function m(G,B,q,K){let Y=[],Q=K.join(" ");for(let X of G)if(Y.push({src:`${B}/icon-${X}x${X}.png`,sizes:`${X}x${X}`,type:"image/png",purpose:Q}),q)Y.push({src:`${B}/icon-${X}x${X}.webp`,sizes:`${X}x${X}`,type:"image/webp",purpose:Q});return Y}function g(G){return G.map((B)=>({name:B.name,short_name:B.shortName,description:B.description,url:B.url,icons:B.icons?.map((q)=>({src:q.src,sizes:q.sizes,type:q.type}))}))}function h(G){let B=G.pwa?.shareTarget;if(!B?.enabled)return;let q={action:B.action||"/share",method:B.method||"POST",enctype:B.enctype||"multipart/form-data",params:{title:B.params?.title||"title",text:B.params?.text||"text",url:B.params?.url||"url"}};if(B.acceptFiles&&B.acceptFiles.length>0)q.params.files=B.acceptFiles.map((K)=>({name:K.name,accept:K.accept}));return q}function c(G){let B=G.pwa?.fileHandlers;if(!B?.enabled||!B.accept)return;let q=[{action:B.action||"/",accept:B.accept,launch_type:B.launchType||"single-client"}];if(B.icons)q[0].icons=B.icons.map((K)=>({src:K.src,sizes:K.sizes,type:K.type}));return q}function l(G){let B=G.pwa?.protocolHandlers;if(!B||B.length===0)return;return B.map((q)=>({protocol:q.protocol,url:q.url}))}function u(G){let B=G.pwa;if(!B?.enabled||!B.manifest)return null;let{manifest:q,icons:K}=B,Y=K?.sizes||[72,96,128,144,152,192,384,512],Q=K?.outputDir?`/${K.outputDir}`:"/pwa-icons",X=K?.generateWebP??!0,j=K?.purpose||["any","maskable"],J={name:q.name,short_name:q.shortName||q.name,description:q.description,start_url:q.startUrl||"/",display:q.display||"standalone",display_override:q.displayOverride,orientation:q.orientation,theme_color:q.themeColor,background_color:q.backgroundColor,scope:q.scope||"/",lang:q.lang,dir:q.dir,id:q.id,categories:q.categories,icons:m(Y,Q,X,j)};if(q.shortcuts&&q.shortcuts.length>0)J.shortcuts=g(q.shortcuts);if(q.screenshots&&q.screenshots.length>0)J.screenshots=q.screenshots.map((U)=>({src:U.src,sizes:U.sizes,type:U.type,label:U.label,form_factor:U.platform}));let y=h(G);if(y)J.share_target=y;let V=c(G);if(V)J.file_handlers=V;let R=l(G);if(R)J.protocol_handlers=R;if(q.launchHandler)J.launch_handler={client_mode:q.launchHandler};if(q.handleLinks)J.handle_links=q.handleLinks;if(q.edgeSidePanel?.enabled)J.edge_side_panel={preferred_width:q.edgeSidePanel.preferredWidth};return J}function M(G){let B=u(G);if(!B)return"";let q=JSON.parse(JSON.stringify(B));return JSON.stringify(q,null,2)}function i(G,B){return{...B,...G,shortcuts:G.shortcuts||B.shortcuts,screenshots:G.screenshots||B.screenshots,categories:G.categories||B.categories}}function s(G){let B=[],q=G.pwa;if(!q?.enabled)return B;let K=q.manifest;if(!K)return B.push("PWA manifest configuration is missing"),B;if(!K.name)B.push("Manifest name is required");let Y=["fullscreen","standalone","minimal-ui","browser"];if(K.display&&!Y.includes(K.display))B.push(`Invalid display mode: ${K.display}. Must be one of: ${Y.join(", ")}`);let Q=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(K.orientation&&!Q.includes(K.orientation))B.push(`Invalid orientation: ${K.orientation}`);let X=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(K.themeColor&&!X.test(K.themeColor))B.push(`Invalid theme color: ${K.themeColor}. Must be a valid hex color.`);if(K.backgroundColor&&!X.test(K.backgroundColor))B.push(`Invalid background color: ${K.backgroundColor}. Must be a valid hex color.`);if(q.shareTarget?.enabled){if(!q.shareTarget.action)B.push("Share target action URL is required")}if(q.fileHandlers?.enabled){if(!q.fileHandlers.accept||Object.keys(q.fileHandlers.accept).length===0)B.push("File handlers must specify accepted MIME types")}if(q.protocolHandlers)for(let j of q.protocolHandlers){if(!j.protocol)B.push("Protocol handler missing protocol");if(!j.url||!j.url.includes("%s"))B.push(`Protocol handler URL must contain %s placeholder: ${j.protocol}`)}return B}import A from"path";async function b(G){let B=G.pwa?.offline;if(!B?.enabled)return"";if(B.page){let q=A.isAbsolute(B.page)?B.page:A.resolve(process.cwd(),B.page);if(await Bun.file(q).exists())try{let{processDirectives:K}=await import("./chunk-17atrbv2.js"),Y=await Bun.file(q).text();return await K(Y,{},q,G,new Set)}catch(K){console.warn(`[PWA] Failed to process custom offline page: ${K}`)}else console.warn(`[PWA] Custom offline page not found: ${q}`)}return f(G)}function f(G){let B=G.pwa?.offline,q=G.pwa?.manifest,K=B?.fallbackTitle||"You are offline",Y=B?.fallbackMessage||"Please check your internet connection and try again.",Q=q?.themeColor||"#4f46e5",X=q?.shortName||q?.name||"App";return`<!DOCTYPE html>
2
+ import{Fk as wq,Gk as dq,Hk as Cq,Ik as mq,Jk as gq}from"./chunk-wvc7t11n.js";import{Kk as S,Lk as Tq,Mk as _q,Nk as z,Ok as D,Pk as P,Qk as kq,Rk as vq,Sk as w,Tk as Iq,Uk as d,Vk as Hq,Wk as Oq,Xk as Mq}from"./chunk-06f65jz3.js";import{ou as Aq,pu as bq,qu as Sq,ru as zq,su as Dq,tu as Pq}from"./chunk-x0bcc9sj.js";import{xu as N}from"./chunk-8rn5e39c.js";import p from"fs";import E from"path";import C from"fs";import L from"path";var k=[72,96,128,144,152,192,384,512],v=[120,152,167,180],I=[16,32];async function H(G,B){let q={success:!0,generatedFiles:[],errors:[],warnings:[]},K=G.pwa?.icons;if(!K?.src)return q.errors.push("No source icon specified in pwa.icons.src"),q.success=!1,q;let Y=L.isAbsolute(K.src)?K.src:L.resolve(process.cwd(),K.src);if(!await Bun.file(Y).exists())return q.errors.push(`Source icon not found: ${Y}`),q.success=!1,q;let Q=L.resolve(B,K.outputDir||"pwa-icons");try{C.mkdirSync(Q,{recursive:!0})}catch{return q.errors.push(`Failed to create output directory: ${Q}`),q.success=!1,q}let X=K.sizes||k,j=K.generateWebP??!0,J=K.generateAppleIcons??!0;try{let y;try{y=await import("sharp")}catch{return q.errors.push(`sharp is not installed. Install it with: bun add sharp
3
+ Icon generation requires the sharp package for image processing.`),q.success=!1,q}let R=await y.default(Y).metadata();if(R.width&&R.width<512)q.warnings.push(`Source icon is ${R.width}x${R.height}. Recommend using at least 512x512 for best quality.`);for(let $ of X){let x=L.join(Q,`icon-${$}x${$}.png`);if(await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(x),q.generatedFiles.push(x),j){let F=L.join(Q,`icon-${$}x${$}.webp`);await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(F),q.generatedFiles.push(F)}}if(J){for(let x of v){let F=L.join(Q,`apple-touch-icon-${x}x${x}.png`);await y.default(Y).resize(x,x,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(F),q.generatedFiles.push(F)}let $=L.join(Q,"apple-touch-icon.png");await y.default(Y).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile($),q.generatedFiles.push($)}for(let $ of I){let x=L.join(Q,`favicon-${$}x${$}.png`);await y.default(Y).resize($,$,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(x),q.generatedFiles.push(x)}let U=512,T=L.join(Q,`icon-maskable-${U}x${U}.png`),Z=Math.floor(U*0.1),_=U-Z*2;await y.default(Y).resize(_,_,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:Z,bottom:Z,left:Z,right:Z,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(T),q.generatedFiles.push(T)}catch(y){let V=y instanceof Error?y.message:String(y);q.errors.push(`Icon generation failed: ${V}`),q.success=!1}return q}function n(G){let B=G.sizes||k,q=G.outputDir?`/${G.outputDir}`:"/pwa-icons",K=G.generateWebP??!0,Y=G.generateAppleIcons??!0,Q=[];for(let X of B)if(Q.push(`${q}/icon-${X}x${X}.png`),K)Q.push(`${q}/icon-${X}x${X}.webp`);if(Y){Q.push(`${q}/apple-touch-icon.png`);for(let X of v)Q.push(`${q}/apple-touch-icon-${X}x${X}.png`)}for(let X of I)Q.push(`${q}/favicon-${X}x${X}.png`);return Q.push(`${q}/icon-maskable-512x512.png`),Q}async function O(){try{return await import("sharp"),!0}catch{return!1}}function m(G,B,q,K){let Y=[],Q=K.join(" ");for(let X of G)if(Y.push({src:`${B}/icon-${X}x${X}.png`,sizes:`${X}x${X}`,type:"image/png",purpose:Q}),q)Y.push({src:`${B}/icon-${X}x${X}.webp`,sizes:`${X}x${X}`,type:"image/webp",purpose:Q});return Y}function g(G){return G.map((B)=>({name:B.name,short_name:B.shortName,description:B.description,url:B.url,icons:B.icons?.map((q)=>({src:q.src,sizes:q.sizes,type:q.type}))}))}function h(G){let B=G.pwa?.shareTarget;if(!B?.enabled)return;let q={action:B.action||"/share",method:B.method||"POST",enctype:B.enctype||"multipart/form-data",params:{title:B.params?.title||"title",text:B.params?.text||"text",url:B.params?.url||"url"}};if(B.acceptFiles&&B.acceptFiles.length>0)q.params.files=B.acceptFiles.map((K)=>({name:K.name,accept:K.accept}));return q}function c(G){let B=G.pwa?.fileHandlers;if(!B?.enabled||!B.accept)return;let q=[{action:B.action||"/",accept:B.accept,launch_type:B.launchType||"single-client"}];if(B.icons)q[0].icons=B.icons.map((K)=>({src:K.src,sizes:K.sizes,type:K.type}));return q}function l(G){let B=G.pwa?.protocolHandlers;if(!B||B.length===0)return;return B.map((q)=>({protocol:q.protocol,url:q.url}))}function u(G){let B=G.pwa;if(!B?.enabled||!B.manifest)return null;let{manifest:q,icons:K}=B,Y=K?.sizes||[72,96,128,144,152,192,384,512],Q=K?.outputDir?`/${K.outputDir}`:"/pwa-icons",X=K?.generateWebP??!0,j=K?.purpose||["any","maskable"],J={name:q.name,short_name:q.shortName||q.name,description:q.description,start_url:q.startUrl||"/",display:q.display||"standalone",display_override:q.displayOverride,orientation:q.orientation,theme_color:q.themeColor,background_color:q.backgroundColor,scope:q.scope||"/",lang:q.lang,dir:q.dir,id:q.id,categories:q.categories,icons:m(Y,Q,X,j)};if(q.shortcuts&&q.shortcuts.length>0)J.shortcuts=g(q.shortcuts);if(q.screenshots&&q.screenshots.length>0)J.screenshots=q.screenshots.map((U)=>({src:U.src,sizes:U.sizes,type:U.type,label:U.label,form_factor:U.platform}));let y=h(G);if(y)J.share_target=y;let V=c(G);if(V)J.file_handlers=V;let R=l(G);if(R)J.protocol_handlers=R;if(q.launchHandler)J.launch_handler={client_mode:q.launchHandler};if(q.handleLinks)J.handle_links=q.handleLinks;if(q.edgeSidePanel?.enabled)J.edge_side_panel={preferred_width:q.edgeSidePanel.preferredWidth};return J}function M(G){let B=u(G);if(!B)return"";let q=JSON.parse(JSON.stringify(B));return JSON.stringify(q,null,2)}function i(G,B){return{...B,...G,shortcuts:G.shortcuts||B.shortcuts,screenshots:G.screenshots||B.screenshots,categories:G.categories||B.categories}}function s(G){let B=[],q=G.pwa;if(!q?.enabled)return B;let K=q.manifest;if(!K)return B.push("PWA manifest configuration is missing"),B;if(!K.name)B.push("Manifest name is required");let Y=["fullscreen","standalone","minimal-ui","browser"];if(K.display&&!Y.includes(K.display))B.push(`Invalid display mode: ${K.display}. Must be one of: ${Y.join(", ")}`);let Q=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(K.orientation&&!Q.includes(K.orientation))B.push(`Invalid orientation: ${K.orientation}`);let X=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(K.themeColor&&!X.test(K.themeColor))B.push(`Invalid theme color: ${K.themeColor}. Must be a valid hex color.`);if(K.backgroundColor&&!X.test(K.backgroundColor))B.push(`Invalid background color: ${K.backgroundColor}. Must be a valid hex color.`);if(q.shareTarget?.enabled){if(!q.shareTarget.action)B.push("Share target action URL is required")}if(q.fileHandlers?.enabled){if(!q.fileHandlers.accept||Object.keys(q.fileHandlers.accept).length===0)B.push("File handlers must specify accepted MIME types")}if(q.protocolHandlers)for(let j of q.protocolHandlers){if(!j.protocol)B.push("Protocol handler missing protocol");if(!j.url||!j.url.includes("%s"))B.push(`Protocol handler URL must contain %s placeholder: ${j.protocol}`)}return B}import A from"path";async function b(G){let B=G.pwa?.offline;if(!B?.enabled)return"";if(B.page){let q=A.isAbsolute(B.page)?B.page:A.resolve(process.cwd(),B.page);if(await Bun.file(q).exists())try{let{processDirectives:K}=await import("./chunk-3zhhytkd.js"),Y=await Bun.file(q).text();return await K(Y,{},q,G,new Set)}catch(K){console.warn(`[PWA] Failed to process custom offline page: ${K}`)}else console.warn(`[PWA] Custom offline page not found: ${q}`)}return f(G)}function f(G){let B=G.pwa?.offline,q=G.pwa?.manifest,K=B?.fallbackTitle||"You are offline",Y=B?.fallbackMessage||"Please check your internet connection and try again.",Q=q?.themeColor||"#4f46e5",X=q?.shortName||q?.name||"App";return`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">
package/dist/render.d.ts CHANGED
@@ -1,4 +1,18 @@
1
1
  import type { StxOptions } from './types';
2
+ /**
3
+ * Render a .stx template file to an HTML string.
4
+ *
5
+ * This is the primary rendering API. It:
6
+ * 1. Reads the template file
7
+ * 2. Extracts and executes server-side scripts
8
+ * 3. Processes all stx directives (conditionals, loops, expressions, etc.)
9
+ * 4. Injects client-side scripts
10
+ * 5. Returns the final HTML string
11
+ *
12
+ * @param filePath - Path to the .stx template file
13
+ * @param renderOptions - Additional rendering options
14
+ * @returns The rendered HTML string
15
+ */
2
16
  export declare function renderTemplate(filePath: string, renderOptions?: RenderOptions): Promise<string>;
3
17
  /**
4
18
  * Render an inline stx template string to HTML.
package/dist/render.js CHANGED
@@ -5,6 +5,7 @@ import { injectRouterScript, processDirectives } from "./process.js";
5
5
  import { extractBridgeData, processClientScript } from "./client-script.js";
6
6
  import { findSfcTemplateBlock } from "./sfc-template.js";
7
7
  import { isMarkdownPath, renderMarkdownView } from "./markdown-view.js";
8
+ import { responseBindings, syncRecordedResponse } from "./page-response.js";
8
9
  function parseTemplate(content) {
9
10
  let workingContent = content;
10
11
  const templateBlock = findSfcTemplateBlock(content);
@@ -53,10 +54,6 @@ ${html}
53
54
  </body>
54
55
  </html>`;
55
56
  }
56
- function recordOn(target, key, value) {
57
- if (target && typeof target === "object")
58
- target[key] = value;
59
- }
60
57
  export async function renderTemplate(filePath, renderOptions = {}) {
61
58
  const resolvedPath = resolve(filePath), file = Bun.file(resolvedPath);
62
59
  if (!await file.exists())
@@ -103,21 +100,7 @@ export async function renderTemplateString(content, filePath, renderOptions = {}
103
100
  __stx_sfc_mode: !0,
104
101
  __stx_inject_css: renderOptions.injectCSS === !0,
105
102
  __stxServeContext: void 0,
106
- setResponseStatus: (status) => {
107
- if (Number.isInteger(status) && status >= 100 && status <= 599)
108
- recordOn(renderOptions.context, "__stxResponseStatus", status);
109
- },
110
- notFound: (status = 404) => {
111
- const code = Number.isInteger(status) && status >= 400 && status <= 599 ? status : 404;
112
- recordOn(renderOptions.context, "__stxResponseStatus", code);
113
- },
114
- setResponseHeader: (name, value) => {
115
- if (!name)
116
- return;
117
- const headers = renderOptions.context?.__stxResponseHeaders || {};
118
- headers[String(name)] = String(value);
119
- recordOn(renderOptions.context, "__stxResponseHeaders", headers);
120
- },
103
+ ...responseBindings(renderOptions.context ?? {}),
121
104
  definePageMeta: () => {},
122
105
  ...renderOptions.context || {}
123
106
  };
@@ -126,6 +109,7 @@ export async function renderTemplateString(content, filePath, renderOptions = {}
126
109
  const dependencies = new Set;
127
110
  let output = templateContent;
128
111
  output = await processDirectives(output, context, filePath, options, dependencies);
112
+ syncRecordedResponse(context, renderOptions.context);
129
113
  if (renderOptions.templateOnly) {
130
114
  output = output.replace(/<script data-stx-scoped>[\s\S]*?<\/script>\s*/gi, "");
131
115
  output = output.replace(/<!-- stx SEO Tags -->[\s\S]*?(?=<)/i, "");
package/dist/serve.js CHANGED
@@ -6,6 +6,7 @@ import { readMarkdownFile } from "./assets.js";
6
6
  import { processDirectives } from "./process.js";
7
7
  import { extractVariables } from "./utils.js";
8
8
  import { compressResponse } from "./compression.js";
9
+ import { readResponseHeaders, readResponseStatus } from "./page-response.js";
9
10
  export function htmlResponse(html, status = 200, headers = {}) {
10
11
  return new Response(html, {
11
12
  status,
@@ -33,7 +34,7 @@ export async function serve(options = {}) {
33
34
  async function processStxFile(filePath) {
34
35
  const stats = fs.statSync(filePath), cacheKey = `${filePath}:${stats.mtimeMs}`, cached = fileCache.get(cacheKey);
35
36
  if (cached)
36
- return cached.content;
37
+ return { content: cached.content, status: cached.status, headers: cached.headers };
37
38
  for (const key of fileCache.keys())
38
39
  if (key.startsWith(`${filePath}:`) && key !== cacheKey)
39
40
  fileCache.delete(key);
@@ -76,8 +77,9 @@ $1`);
76
77
  output += `
77
78
  ${scriptsHtml}`;
78
79
  }
79
- fileCache.set(cacheKey, { content: output, mtime: stats.mtimeMs });
80
- return output;
80
+ const status = readResponseStatus(context), headers = readResponseHeaders(context);
81
+ fileCache.set(cacheKey, { content: output, mtime: stats.mtimeMs, status, headers });
82
+ return { content: output, status, headers };
81
83
  }
82
84
  async function processMarkdownFile(filePath) {
83
85
  const stats = fs.statSync(filePath), cacheKey = `${filePath}:${stats.mtimeMs}`, cached = fileCache.get(cacheKey);
@@ -121,10 +123,13 @@ ${scriptsHtml}`;
121
123
  return new Response("Not Found", { status: 404 });
122
124
  }
123
125
  try {
124
- let content, contentType = "text/html";
125
- if (filePath.endsWith(".stx"))
126
- content = await processStxFile(filePath);
127
- else if (filePath.endsWith(".md"))
126
+ let content, contentType = "text/html", pageStatus, pageHeaders;
127
+ if (filePath.endsWith(".stx")) {
128
+ const page = await processStxFile(filePath);
129
+ content = page.content;
130
+ pageStatus = page.status;
131
+ pageHeaders = page.headers;
132
+ } else if (filePath.endsWith(".md"))
128
133
  content = await processMarkdownFile(filePath);
129
134
  else if (filePath.endsWith(".html"))
130
135
  content = await Bun.file(filePath).text();
@@ -140,7 +145,8 @@ ${scriptsHtml}`;
140
145
  } else
141
146
  return new Response(Bun.file(filePath));
142
147
  return new Response(content, {
143
- headers: { "Content-Type": contentType }
148
+ status: pageStatus ?? 200,
149
+ headers: { "Content-Type": contentType, ...pageHeaders }
144
150
  });
145
151
  } catch (error) {
146
152
  if (onError)
@@ -192,7 +198,7 @@ export async function serveFile(filePath, options = {}) {
192
198
  root: path.dirname(absolutePath),
193
199
  routes: {
194
200
  "/": async () => {
195
- let content;
201
+ let content, status = 200, headers;
196
202
  if (isMarkdown) {
197
203
  const { content: md } = await readMarkdownFile(absolutePath, stxOptions);
198
204
  content = md;
@@ -207,9 +213,12 @@ export async function serveFile(filePath, options = {}) {
207
213
  if (scriptContent.trim())
208
214
  await extractVariables(scriptContent, context, absolutePath);
209
215
  content = await processDirectives(templateContent, context, absolutePath, stxOptions, new Set);
216
+ status = readResponseStatus(context) ?? 200;
217
+ headers = readResponseHeaders(context);
210
218
  }
211
219
  return new Response(content, {
212
- headers: { "Content-Type": "text/html" }
220
+ status,
221
+ headers: { "Content-Type": "text/html", ...headers }
213
222
  });
214
223
  },
215
224
  ...options.routes
@@ -0,0 +1,49 @@
1
+ /** Whether this request is the SPA router asking for a fragment. */
2
+ export declare function isSpaNavRequest(request: { headers: { get: (name: string) => string | null } }): boolean;
3
+ /**
4
+ * `vary` with `field` appended, or `field` alone when there was nothing there.
5
+ *
6
+ * Appends only when the field is not already listed: `Vary: X-STX-Router,
7
+ * X-STX-Router` is legal, pointless, and confusing to read in a response.
8
+ */
9
+ export declare function appendVary(vary: string | null | undefined, field: string): string;
10
+ /**
11
+ * The header bag a route serves when it answers both representations.
12
+ *
13
+ * Spread into BOTH the fragment and the document response. Declaring it on only
14
+ * the fragment fixes nothing: a cache that stored the document first would go
15
+ * on serving that document to the router, which then swaps a whole `<html>`
16
+ * tree inside the container. `Vary` describes the url, not one answer for it.
17
+ */
18
+ export declare function spaNavVaryHeaders(existing?: string | null): { Vary: string };
19
+ /**
20
+ * The request header that asks for a page fragment instead of a document, and
21
+ * the cache correctness that has to travel with it.
22
+ *
23
+ * The SPA router fetches the SAME url the browser would navigate to and tells
24
+ * the server which representation it wants with `X-STX-Router: true`. Two very
25
+ * different bodies therefore share one url: a full `<html>` document, and the
26
+ * inner content of the router container with no `<head>` at all.
27
+ *
28
+ * That is legal HTTP only while the server says so. A response whose body
29
+ * depends on a request header MUST list that header in `Vary`, or any shared
30
+ * cache between the origin and the browser is entitled to store whichever
31
+ * representation it saw first and serve it to everyone. When the stored one is
32
+ * the fragment, every visitor gets a headless page — no doctype, no stylesheet,
33
+ * no nav — until the entry expires. It is invisible from the origin, which is
34
+ * still answering both requests perfectly, and it lasts as long as the cache's
35
+ * TTL rather than as long as the mistake.
36
+ *
37
+ * @module spa-nav
38
+ */
39
+ /** Request header the SPA router sends to ask for a fragment. */
40
+ export declare const SPA_NAV_HEADER: 'X-STX-Router';
41
+ /**
42
+ * `Cache-Control` for a fragment response.
43
+ *
44
+ * `private` is the half that matters: a fragment is only ever meaningful to the
45
+ * router instance that asked for it, so no shared cache should hold it under
46
+ * any circumstances. `no-store` then keeps it out of the browser's cache too,
47
+ * where it would otherwise be replayed into a fresh document load.
48
+ */
49
+ export declare const FRAGMENT_CACHE_CONTROL: 'private, no-store';
@@ -0,0 +1,12 @@
1
+ export const SPA_NAV_HEADER = "X-STX-Router", FRAGMENT_CACHE_CONTROL = "private, no-store";
2
+ export function isSpaNavRequest(request) {
3
+ return request.headers.get(SPA_NAV_HEADER) === "true";
4
+ }
5
+ export function appendVary(vary, field) {
6
+ if (!vary)
7
+ return field;
8
+ return vary.split(",").some((entry) => entry.trim().toLowerCase() === field.toLowerCase()) ? vary : `${vary}, ${field}`;
9
+ }
10
+ export function spaNavVaryHeaders(existing) {
11
+ return { Vary: appendVary(existing, SPA_NAV_HEADER) };
12
+ }
package/dist/ssg.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{sk as Bq,tk as Hq,xk as Tq}from"./chunk-1nnpwrqj.js";import{Ak as Eq,yk as Uq,zk as Iq}from"./chunk-yckd6ks5.js";import{Wk as Nq,Xk as _q}from"./chunk-dmb6t0qj.js";import"./chunk-zgvga8rc.js";import{Cm as Aq,Lr as l,Wp as c,Zp as Oq,lp as Xq,mq as x}from"./chunk-zat2ndst.js";import"./chunk-j0tfxbns.js";import"./chunk-khrtzbxd.js";import"./chunk-8anh6d36.js";import"./chunk-3fwn9edg.js";import{Hs as zq}from"./chunk-pezxve4a.js";import{Ms as f}from"./chunk-m2mhtpwy.js";import"./chunk-6xg3j487.js";import"./chunk-q4se9rtw.js";import"./chunk-1nm2xrvq.js";import{Pt as Wq,Qt as Yq,Rt as Vq,St as jq,Tt as Gq,Ut as Lq}from"./chunk-z47tw39z.js";import"./chunk-3wd9kfyz.js";import{iu as g}from"./chunk-trtm887x.js";import O from"fs";import j from"path";import{createHash as kq}from"crypto";function Sq(q){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(q).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return q}}var vq=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function xq(q){return Bun.hash(q).toString(16)}function Jq(q,Z={}){if(!q.includes('type="stx/island"'))return{html:q,chunks:[]};let $=new Map,Q=q.replace(vq,(J,W,z,A)=>{let N=A.trim();if(!N)return J;if(/\bdata-stx-src=/.test(z))return J;if(Z.minify)N=Sq(N);let X=xq(N);if(!$.has(X))$.set(X,N);let H=Z.integrity?` data-stx-integrity="sha384-${kq("sha384").update(N).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${W}" data-stx-src="/_stx/islands/${X}.js"${H}${z}></script>`}),K=Array.from($,([J,W])=>({hash:J,code:W}));return{html:Q,chunks:K}}var yq=new Set(["visible","idle"]);function Qq(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(yq.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((N)=>!q.includes(`rel="prefetch" href="${N}"`)).map((N)=>`<link rel="prefetch" href="${N}" as="script">`).join("");if(!A)return q;return q.slice(0,z)+A+q.slice(z)}var Pq=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function u(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 Cq(q){for(let Z of Pq){let $=q[Z];if(!$)continue;let Q=u($);if(Q)return{url:Q,source:"env",via:Z}}return null}function Zq(q){if(!q||typeof q!=="object")return null;let Z=q,$=Z.site?.url??Z.url??Z.app?.url;return typeof $==="string"?u($):null}async function gq(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=Zq(J.default??J);if(W)return W}catch{}}return null}async function $q(q={}){let Z=q.cwd??process.cwd(),$=q.env??process.env;if(q.explicit){let W=u(q.explicit);if(W)return{url:W,source:"option"}}let Q=Zq(q.stxConfig);if(Q)return{url:Q,source:"stx.config",via:"site.url"};let K=await gq(Z);if(K)return{url:K,source:"site.config",via:"url"};let J=Cq($);if(J)return J;return{url:"http://localhost",source:"fallback"}}function Kq(){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{Bk as Tq,wk as Bq,xk as Hq}from"./chunk-7s3wrtpb.js";import{Ck as Uq,Dk as Iq,Ek as Eq}from"./chunk-c0n802j1.js";import{$k as _q,_k as Nq}from"./chunk-q5w0fqd5.js";import"./chunk-ncvd7673.js";import{Ap as Xq,Bq as x,Gm as Aq,_r as l,jq as c,mq as Oq}from"./chunk-pzcf36xm.js";import"./chunk-kvz7rg2x.js";import"./chunk-arnse15r.js";import"./chunk-6b0xz02h.js";import"./chunk-135mme4g.js";import{Ws as zq}from"./chunk-qfsktf7s.js";import{$s as f}from"./chunk-80qre9zp.js";import"./chunk-z794cdmn.js";import"./chunk-dykhpgyx.js";import"./chunk-ry86fd41.js";import{cu as Wq,du as Yq,eu as Vq,fu as jq,gu as Gq,hu as Lq}from"./chunk-kdpy5rgk.js";import"./chunk-x0bcc9sj.js";import{xu as g}from"./chunk-8rn5e39c.js";import O from"fs";import j from"path";import{createHash as kq}from"crypto";function Sq(q){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(q).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return q}}var vq=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function xq(q){return Bun.hash(q).toString(16)}function Jq(q,Z={}){if(!q.includes('type="stx/island"'))return{html:q,chunks:[]};let $=new Map,Q=q.replace(vq,(J,W,z,A)=>{let N=A.trim();if(!N)return J;if(/\bdata-stx-src=/.test(z))return J;if(Z.minify)N=Sq(N);let X=xq(N);if(!$.has(X))$.set(X,N);let H=Z.integrity?` data-stx-integrity="sha384-${kq("sha384").update(N).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${W}" data-stx-src="/_stx/islands/${X}.js"${H}${z}></script>`}),K=Array.from($,([J,W])=>({hash:J,code:W}));return{html:Q,chunks:K}}var yq=new Set(["visible","idle"]);function Qq(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(yq.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((N)=>!q.includes(`rel="prefetch" href="${N}"`)).map((N)=>`<link rel="prefetch" href="${N}" as="script">`).join("");if(!A)return q;return q.slice(0,z)+A+q.slice(z)}var Pq=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function u(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 Cq(q){for(let Z of Pq){let $=q[Z];if(!$)continue;let Q=u($);if(Q)return{url:Q,source:"env",via:Z}}return null}function Zq(q){if(!q||typeof q!=="object")return null;let Z=q,$=Z.site?.url??Z.url??Z.app?.url;return typeof $==="string"?u($):null}async function gq(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=Zq(J.default??J);if(W)return W}catch{}}return null}async function $q(q={}){let Z=q.cwd??process.cwd(),$=q.env??process.env;if(q.explicit){let W=u(q.explicit);if(W)return{url:W,source:"option"}}let Q=Zq(q.stxConfig);if(Q)return{url:Q,source:"stx.config",via:"site.url"};let K=await gq(Z);if(K)return{url:K,source:"site.config",via:"url"};let J=Cq($);if(J)return J;return{url:"http://localhost",source:"fallback"}}function Kq(){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 Dq{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 Fq{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 fq(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 sq(q={}){let Z=Date.now();_q();let $=await l(process.cwd()),Q=$.build||{},K=await $q({explicit:q.domain||Q.domain,stxConfig:$});if(K.source==="fallback"&&(q.sitemap??Q.sitemap??!0))console.warn(Kq());let J={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||f(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,N={},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 _=J.cacheSalt;if(!_){let{resolveUserCrosswindConfig:Y,fingerprintConfig:L}=await import("./chunk-css1sfnr.js");try{_=L(await Y(process.cwd()))}catch{}}let G=new Dq(J.cacheDir,_);if(J.cache)await G.load();try{let{generateCrosswindCSS:Y}=await import("./chunk-css1sfnr.js");await Y('<div class="bg-black"></div>')}catch{}Wq();let m=$?.routeMiddleware?.dir||"middleware";await Vq(process.cwd(),m);let d=Yq();if(d.length>0)console.log(`Loaded ${d.length} middleware: ${d.join(", ")}`);let Mq=$?.routeMiddleware?.global||[];Tq($?.layoutsDir,f(process.cwd()));let n=c(".",{pagesDir:J.pagesDir});console.log(`Found ${n.length} routes`);let y=[];for(let Y of n){let L=await mq(Y);for(let B of L)y.push({route:Y,url:B.url,params:B.params,props:B.props,revalidate:B.revalidate??J.revalidate})}W.totalPages=y.length,console.log(`Generating ${W.totalPages} pages...`);let b=[],i=[];for(let Y=0;Y<y.length;Y+=J.concurrency)i.push(y.slice(Y,Y+J.concurrency));for(let Y of i)await Promise.all(Y.map(async(L)=>{let{route:B,url:V,params:k,props:wq,revalidate:a}=L;try{await J.hooks.onPageStart?.(V);let F=await Bun.file(B.filePath).text(),R=tq(F),bq=R?.middleware?Array.isArray(R.middleware)?R.middleware:[R.middleware]:[],r=[...Mq,...bq];if(r.length>0){let D=jq(V,k,R||{}),M=Gq(D,null,void 0,{isServer:!0}),E=await Lq(r,M);if(E.redirect){let U=typeof E.redirect==="string"?E.redirect:E.redirect.path||E.redirect,v=eq(String(U),V),w=qJ(V,J);await O.promises.mkdir(j.dirname(w),{recursive:!0}),await Bun.write(w,v),W.successCount++,W.pages.push({route:V,outputPath:w,size:Buffer.byteLength(v),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 t=F.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(t)try{if(!await Function("route",`
44
+ </rss>`}async function sq(q={}){let Z=Date.now();_q();let $=await l(process.cwd()),Q=$.build||{},K=await $q({explicit:q.domain||Q.domain,stxConfig:$});if(K.source==="fallback"&&(q.sitemap??Q.sitemap??!0))console.warn(Kq());let J={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||f(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,N={},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 _=J.cacheSalt;if(!_){let{resolveUserCrosswindConfig:Y,fingerprintConfig:L}=await import("./chunk-5y731xe9.js");try{_=L(await Y(process.cwd()))}catch{}}let G=new Dq(J.cacheDir,_);if(J.cache)await G.load();try{let{generateCrosswindCSS:Y}=await import("./chunk-5y731xe9.js");await Y('<div class="bg-black"></div>')}catch{}Wq();let m=$?.routeMiddleware?.dir||"middleware";await Vq(process.cwd(),m);let d=Yq();if(d.length>0)console.log(`Loaded ${d.length} middleware: ${d.join(", ")}`);let Mq=$?.routeMiddleware?.global||[];Tq($?.layoutsDir,f(process.cwd()));let n=c(".",{pagesDir:J.pagesDir});console.log(`Found ${n.length} routes`);let y=[];for(let Y of n){let L=await mq(Y);for(let B of L)y.push({route:Y,url:B.url,params:B.params,props:B.props,revalidate:B.revalidate??J.revalidate})}W.totalPages=y.length,console.log(`Generating ${W.totalPages} pages...`);let b=[],i=[];for(let Y=0;Y<y.length;Y+=J.concurrency)i.push(y.slice(Y,Y+J.concurrency));for(let Y of i)await Promise.all(Y.map(async(L)=>{let{route:B,url:V,params:k,props:wq,revalidate:a}=L;try{await J.hooks.onPageStart?.(V);let F=await Bun.file(B.filePath).text(),R=tq(F),bq=R?.middleware?Array.isArray(R.middleware)?R.middleware:[R.middleware]:[],r=[...Mq,...bq];if(r.length>0){let D=jq(V,k,R||{}),M=Gq(D,null,void 0,{isServer:!0}),E=await Lq(r,M);if(E.redirect){let U=typeof E.redirect==="string"?E.redirect:E.redirect.path||E.redirect,v=eq(String(U),V),w=qJ(V,J);await O.promises.mkdir(j.dirname(w),{recursive:!0}),await Bun.write(w,v),W.successCount++,W.pages.push({route:V,outputPath:w,size:Buffer.byteLength(v),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 t=F.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(t)try{if(!await Function("route",`
45
45
  const validate = ${t[1]};
46
46
  return validate(route);
47
47
  `)({params:k})){console.warn(`Validation failed for ${V}, skipping...`);return}}catch{}let I=null,e=!1;if(J.cache){if(I=G.get(V,B.filePath),I)e=!0,W.cachedCount++}if(!I){let D=await Rq(B,k,wq,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:
@@ -28,5 +28,6 @@ export declare interface CompiledTemplate {
28
28
  serverScriptContent: string[]
29
29
  dependencies: string[]
30
30
  contentHash: string
31
+ status?: number
31
32
  streamTemplates?: Record<string, string>
32
33
  }