@stacksjs/stx 0.2.755 → 0.2.759

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 (223) hide show
  1. package/dist/{chunk-0dsykna3.js → chunk-00ns0516.js} +5 -5
  2. package/dist/chunk-055v5qz2.js +2 -0
  3. package/dist/{chunk-kjfzkac7.js → chunk-06zn167b.js} +7 -7
  4. package/dist/{chunk-024m1xmd.js → chunk-0dkd26t4.js} +5 -5
  5. package/dist/{chunk-gzbmfwxr.js → chunk-0e9xdrzx.js} +4 -4
  6. package/dist/chunk-0j7e56zm.js +2 -0
  7. package/dist/{chunk-8wbgq43c.js → chunk-0jn79fkt.js} +3 -3
  8. package/dist/chunk-0y44f9rk.js +2 -0
  9. package/dist/{chunk-d73hh5ar.js → chunk-11kejz35.js} +1 -1
  10. package/dist/{chunk-p33w8zst.js → chunk-1mfj2j5g.js} +3 -3
  11. package/dist/{chunk-vc4jww9y.js → chunk-2x112fxs.js} +13 -13
  12. package/dist/{chunk-6ywa41tr.js → chunk-3ajnrfa2.js} +2 -2
  13. package/dist/{chunk-3z38swhv.js → chunk-3cn9y08d.js} +7 -7
  14. package/dist/chunk-3h2yz805.js +2 -0
  15. package/dist/chunk-3jfes9b0.js +2 -0
  16. package/dist/{chunk-nsjkmpjf.js → chunk-3kfbs0mw.js} +1 -1
  17. package/dist/{chunk-z5kdmget.js → chunk-3nxe5xmy.js} +3 -3
  18. package/dist/{chunk-p2v0r96k.js → chunk-42hcspws.js} +2 -2
  19. package/dist/{chunk-0tgrqhkr.js → chunk-465resq9.js} +11 -11
  20. package/dist/{chunk-m0shnhth.js → chunk-4m8bexrn.js} +3 -3
  21. package/dist/{chunk-8wbcy0cn.js → chunk-4npabwne.js} +3 -3
  22. package/dist/{chunk-xrzghjvy.js → chunk-4s9kytdz.js} +2 -2
  23. package/dist/chunk-4tz00fkp.js +2 -0
  24. package/dist/{chunk-dvakr9p9.js → chunk-4zw118tn.js} +4 -4
  25. package/dist/chunk-52q8184e.js +2 -0
  26. package/dist/chunk-59ytzyp1.js +2 -0
  27. package/dist/chunk-5ffdtfwg.js +2 -0
  28. package/dist/{chunk-g223zsce.js → chunk-5ge5h2y3.js} +3 -3
  29. package/dist/chunk-5q551m4w.js +2 -0
  30. package/dist/{chunk-cb4ybh7g.js → chunk-5q9ss7ty.js} +4 -4
  31. package/dist/{chunk-txgd0sj1.js → chunk-6n195hvc.js} +5 -5
  32. package/dist/chunk-6xt3kvq1.js +2 -0
  33. package/dist/chunk-75r09rqt.js +2 -0
  34. package/dist/{chunk-90gx5qxn.js → chunk-76fcwbe1.js} +4 -4
  35. package/dist/chunk-79y41h1d.js +2 -0
  36. package/dist/{chunk-9r3ehqtx.js → chunk-7g9vd5fv.js} +2 -2
  37. package/dist/chunk-7h5d35bf.js +2 -0
  38. package/dist/{chunk-73b6sst8.js → chunk-7r7j7vwt.js} +3 -3
  39. package/dist/chunk-82ybmdqk.js +2 -0
  40. package/dist/{chunk-g22absm0.js → chunk-83ezv8yz.js} +2 -2
  41. package/dist/chunk-8frs2dtp.js +2 -0
  42. package/dist/chunk-8n2gj4q2.js +11 -0
  43. package/dist/chunk-8prq9t3b.js +2 -0
  44. package/dist/chunk-8sxngenk.js +2 -0
  45. package/dist/chunk-90er677t.js +2 -0
  46. package/dist/{chunk-bkkwdh13.js → chunk-93j4atq9.js} +2 -2
  47. package/dist/{chunk-1a2cwee1.js → chunk-9s1qnf90.js} +2 -2
  48. package/dist/{chunk-j3d9zknp.js → chunk-a5d888es.js} +6 -6
  49. package/dist/chunk-aakkjjgr.js +2 -0
  50. package/dist/chunk-abs1k04e.js +2 -0
  51. package/dist/{chunk-0vvb78yj.js → chunk-asp7ett1.js} +5 -5
  52. package/dist/{chunk-7mm5mvg0.js → chunk-b6g24qj0.js} +2 -2
  53. package/dist/{chunk-7djnbbeb.js → chunk-bsq9zg9j.js} +6 -6
  54. package/dist/{chunk-7ycf8a8d.js → chunk-c05r0rzw.js} +2 -2
  55. package/dist/{chunk-g45p4y4v.js → chunk-cehjp06v.js} +3 -3
  56. package/dist/chunk-cpep999n.js +2 -0
  57. package/dist/chunk-cvwn6mga.js +2 -0
  58. package/dist/chunk-davr7z73.js +2 -0
  59. package/dist/{chunk-vpa4xzz3.js → chunk-dh9aagwm.js} +1 -1
  60. package/dist/chunk-dqs4bgec.js +2 -0
  61. package/dist/chunk-e30kgg28.js +2 -0
  62. package/dist/chunk-e3fkq9gb.js +2 -0
  63. package/dist/chunk-eab8na0z.js +2 -0
  64. package/dist/chunk-exg7ry7b.js +2 -0
  65. package/dist/chunk-f4mmk2cx.js +2 -0
  66. package/dist/chunk-fhwn8j9p.js +2 -0
  67. package/dist/chunk-fj105fff.js +2 -0
  68. package/dist/{chunk-cmaxdd8d.js → chunk-fjxhga6w.js} +2 -2
  69. package/dist/{chunk-thr1m7k7.js → chunk-fpagqrd1.js} +22 -22
  70. package/dist/chunk-g387j1qv.js +2 -0
  71. package/dist/{chunk-zqmvhg37.js → chunk-geb6zyxg.js} +10 -10
  72. package/dist/chunk-gefpzry6.js +2 -0
  73. package/dist/chunk-ghzycypz.js +2 -0
  74. package/dist/{chunk-sj2a5twe.js → chunk-gs373714.js} +2 -2
  75. package/dist/{chunk-nzy4set0.js → chunk-gs6wc7sr.js} +5 -5
  76. package/dist/chunk-gvaee1w0.js +170 -0
  77. package/dist/{chunk-5q2tfrcw.js → chunk-gz38jt5j.js} +2 -2
  78. package/dist/{chunk-pydmzvpq.js → chunk-h692k9xn.js} +1 -1
  79. package/dist/{chunk-81ysx0tc.js → chunk-hk98vptc.js} +2 -2
  80. package/dist/{chunk-xzz36k99.js → chunk-hmae7ha6.js} +2 -2
  81. package/dist/{chunk-qxrsm48h.js → chunk-hmydy949.js} +5 -5
  82. package/dist/{chunk-7r5vhqtz.js → chunk-j04v4rgf.js} +4 -4
  83. package/dist/{chunk-1tmq09ch.js → chunk-j4snweyz.js} +3 -3
  84. package/dist/{chunk-d2vsw1j7.js → chunk-jb1dk0w7.js} +2 -2
  85. package/dist/{chunk-5evgz54v.js → chunk-jevd16gq.js} +30 -30
  86. package/dist/{chunk-41sq06t2.js → chunk-jt28zh50.js} +2 -2
  87. package/dist/chunk-k37472gm.js +2 -0
  88. package/dist/chunk-k3wnmpt3.js +2 -0
  89. package/dist/chunk-kfqdx75m.js +2 -0
  90. package/dist/{chunk-9q1kkfv1.js → chunk-kpr09x3g.js} +6 -6
  91. package/dist/{chunk-3ap06zzx.js → chunk-m00c7sh0.js} +1 -1
  92. package/dist/{chunk-8w0cwcvk.js → chunk-m5fjhrpd.js} +62 -62
  93. package/dist/{chunk-mpmx0n3q.js → chunk-mcynmrbe.js} +26 -26
  94. package/dist/chunk-mgx71bfg.js +2 -0
  95. package/dist/chunk-mmhbn7xt.js +2 -0
  96. package/dist/{chunk-0md73jp8.js → chunk-myynywry.js} +2 -2
  97. package/dist/chunk-mzcbfra0.js +2 -0
  98. package/dist/{chunk-j5p191zq.js → chunk-nv9dy71x.js} +7 -7
  99. package/dist/chunk-ny2qzraq.js +2 -0
  100. package/dist/{chunk-q0f28539.js → chunk-pes27snj.js} +2 -2
  101. package/dist/chunk-pg15tx9c.js +2 -0
  102. package/dist/chunk-ppc5s12t.js +2 -0
  103. package/dist/{chunk-0dt7ax79.js → chunk-prej5pk6.js} +2 -2
  104. package/dist/chunk-ptzzpf97.js +2 -0
  105. package/dist/{chunk-df8cbgf0.js → chunk-pwmkhs7z.js} +2 -2
  106. package/dist/chunk-qgsrxyh9.js +2 -0
  107. package/dist/chunk-qmxcs806.js +2 -0
  108. package/dist/chunk-qn4gt8sx.js +3 -0
  109. package/dist/chunk-qryg0hgn.js +2 -0
  110. package/dist/chunk-qt17792g.js +2 -0
  111. package/dist/{chunk-236bdf7y.js → chunk-qwds327k.js} +2 -2
  112. package/dist/{chunk-c3dphs36.js → chunk-qwsgc5rc.js} +1 -1
  113. package/dist/chunk-qz9fzz5k.js +2 -0
  114. package/dist/{chunk-5wcgg5t4.js → chunk-r4sawwmp.js} +1 -1
  115. package/dist/chunk-r5jytt0f.js +20 -0
  116. package/dist/chunk-rh90yh1c.js +2 -0
  117. package/dist/chunk-rvc0pb16.js +2 -0
  118. package/dist/{chunk-fxftc455.js → chunk-s4y26fk6.js} +2 -2
  119. package/dist/{chunk-v0s52tmv.js → chunk-sgm6tg8h.js} +2 -2
  120. package/dist/chunk-sj5t0tnv.js +2 -0
  121. package/dist/{chunk-yd2nj0rv.js → chunk-spjpdymh.js} +1 -1
  122. package/dist/{chunk-nmy72s6r.js → chunk-t4mpq6t0.js} +2 -2
  123. package/dist/{chunk-np8knskz.js → chunk-t5gabs4x.js} +1 -1
  124. package/dist/{chunk-4zta7ay1.js → chunk-t6qn1374.js} +2 -2
  125. package/dist/{chunk-4fc8zs15.js → chunk-tb56j1zt.js} +5 -5
  126. package/dist/chunk-tb6jcr2v.js +2 -0
  127. package/dist/chunk-v20cwjgz.js +17 -0
  128. package/dist/{chunk-k9m36nyw.js → chunk-v2egd4zh.js} +5 -5
  129. package/dist/{chunk-0fweckq5.js → chunk-vh1d5eqk.js} +6 -6
  130. package/dist/{chunk-fa3ygt8c.js → chunk-w8p1y4c0.js} +4 -4
  131. package/dist/{chunk-j2hm8v8b.js → chunk-wp9y6x33.js} +4 -4
  132. package/dist/{chunk-g5sctfwa.js → chunk-x1q2ape8.js} +10 -10
  133. package/dist/{chunk-x5sy0tym.js → chunk-x9haxcsj.js} +6 -6
  134. package/dist/chunk-xcq41ah8.js +2 -0
  135. package/dist/chunk-y3jbkk7a.js +2 -0
  136. package/dist/{chunk-fmxtnva8.js → chunk-yftw25sa.js} +2 -2
  137. package/dist/chunk-yme43vbp.js +2 -0
  138. package/dist/{chunk-m6w75sq2.js → chunk-yp6w740k.js} +2 -2
  139. package/dist/chunk-yv8jeqdn.js +2 -0
  140. package/dist/{chunk-k4dn3ry6.js → chunk-z8k3fx4r.js} +4 -4
  141. package/dist/chunk-zq7g0687.js +2 -0
  142. package/dist/{chunk-c85j39f7.js → chunk-ztdjdxjt.js} +3 -3
  143. package/dist/cli.js +19 -19
  144. package/dist/client-module-registry.d.ts +56 -0
  145. package/dist/client-module-registry.js +249 -9
  146. package/dist/client-script-bundler.d.ts +17 -0
  147. package/dist/client-script-bundler.js +58 -11
  148. package/dist/craft-entry.js +2 -2
  149. package/dist/craft.js +2 -2
  150. package/dist/native/compiler/bundle.d.ts +1 -0
  151. package/dist/native/compiler/bundle.js +102 -11
  152. package/dist/native/compiler/render-screen.js +13 -6
  153. package/dist/native/compiler/setup-script.d.ts +1 -0
  154. package/dist/native/compiler/shared-scripts.d.ts +12 -0
  155. package/dist/native/compiler/shared-scripts.js +83 -0
  156. package/dist/pwa.js +3 -3
  157. package/dist/ssg.js +4 -4
  158. package/dist/store-loader.d.ts +23 -0
  159. package/dist/store-loader.js +93 -19
  160. package/package.json +5 -5
  161. package/dist/chunk-1gan06yr.js +0 -2
  162. package/dist/chunk-1menbxwb.js +0 -2
  163. package/dist/chunk-1n2d3cy5.js +0 -2
  164. package/dist/chunk-2vc2pkyz.js +0 -2
  165. package/dist/chunk-33bp9m4c.js +0 -2
  166. package/dist/chunk-361yezje.js +0 -2
  167. package/dist/chunk-45cvagp1.js +0 -2
  168. package/dist/chunk-5f0wwwmw.js +0 -2
  169. package/dist/chunk-5h71xbzk.js +0 -2
  170. package/dist/chunk-5z9a1vzw.js +0 -2
  171. package/dist/chunk-67jf2e8x.js +0 -2
  172. package/dist/chunk-6b7je8dc.js +0 -2
  173. package/dist/chunk-6fxjs3ay.js +0 -3
  174. package/dist/chunk-6n5jnd97.js +0 -2
  175. package/dist/chunk-6wvnfdqq.js +0 -2
  176. package/dist/chunk-78jkbaz3.js +0 -2
  177. package/dist/chunk-7e9hfrtb.js +0 -2
  178. package/dist/chunk-7tc5fj96.js +0 -2
  179. package/dist/chunk-82q0fy52.js +0 -2
  180. package/dist/chunk-8q5ec4s1.js +0 -2
  181. package/dist/chunk-8ysk095d.js +0 -2
  182. package/dist/chunk-9vbrj55v.js +0 -2
  183. package/dist/chunk-bcefawtc.js +0 -2
  184. package/dist/chunk-bd6s91p9.js +0 -2
  185. package/dist/chunk-bhkqzz91.js +0 -2
  186. package/dist/chunk-bx1mjwhb.js +0 -2
  187. package/dist/chunk-dw0m259e.js +0 -2
  188. package/dist/chunk-dx4g2ec9.js +0 -2
  189. package/dist/chunk-evdskc25.js +0 -2
  190. package/dist/chunk-gppv6fez.js +0 -2
  191. package/dist/chunk-grjr8shp.js +0 -2
  192. package/dist/chunk-gz1w4cpp.js +0 -2
  193. package/dist/chunk-h0qtmmq3.js +0 -2
  194. package/dist/chunk-h6sewvt2.js +0 -20
  195. package/dist/chunk-hb34m4pp.js +0 -2
  196. package/dist/chunk-hwvtpx3p.js +0 -2
  197. package/dist/chunk-k3kav39s.js +0 -2
  198. package/dist/chunk-k46j2maz.js +0 -2
  199. package/dist/chunk-ka2f844k.js +0 -2
  200. package/dist/chunk-kh4dr6gd.js +0 -2
  201. package/dist/chunk-myd82d80.js +0 -2
  202. package/dist/chunk-nek0q523.js +0 -130
  203. package/dist/chunk-nvbjcgzd.js +0 -2
  204. package/dist/chunk-p13dxvaj.js +0 -2
  205. package/dist/chunk-pht5z7wa.js +0 -2
  206. package/dist/chunk-ppvdbstz.js +0 -11
  207. package/dist/chunk-pwdk7jbx.js +0 -2
  208. package/dist/chunk-qekyxjy6.js +0 -2
  209. package/dist/chunk-r10eadgn.js +0 -2
  210. package/dist/chunk-r8184e10.js +0 -2
  211. package/dist/chunk-rshaz0df.js +0 -4
  212. package/dist/chunk-tcrpa52j.js +0 -2
  213. package/dist/chunk-vp1p250v.js +0 -2
  214. package/dist/chunk-vqrg5j83.js +0 -2
  215. package/dist/chunk-vzdfq3b5.js +0 -2
  216. package/dist/chunk-wzh4ene8.js +0 -2
  217. package/dist/chunk-x5vwkccx.js +0 -2
  218. package/dist/chunk-x6cmj5sa.js +0 -2
  219. package/dist/chunk-xnrfz4c3.js +0 -2
  220. package/dist/chunk-yaabhcss.js +0 -2
  221. package/dist/chunk-yazqtmq4.js +0 -2
  222. package/dist/chunk-zygpvm1x.js +0 -2
  223. package/dist/chunk-zz247c1r.js +0 -2
@@ -5,6 +5,8 @@ import { nativeStyleConfigFrom, withNativeStyleConfig } from "./style-config.js"
5
5
  import { NATIVE_APP_ROUTE } from "../runtime/shared-screen.js";
6
6
  import { generateSignalsRuntime } from "../../signals.js";
7
7
  import { withModuleSubstitutes } from "../../client-script-bundler.js";
8
+ import { shareComponentScripts } from "./shared-scripts.js";
9
+ import { buildSharedModuleRegistries, registeredModuleIdsIn, registeredModuleNamesIn } from "../../client-module-registry.js";
8
10
  export async function projectStyleConfig(root) {
9
11
  try {
10
12
  const { loadCssEngineConfig } = await import("../../dev-server/ts-css.js");
@@ -107,6 +109,45 @@ function runtimeDocument(document, root) {
107
109
  meta: { ...document.meta, source, compiledAt: 0 }
108
110
  };
109
111
  }
112
+ function sharedStylesheets(documents) {
113
+ const seen = new Map, sheets = documents.flatMap(({ name, document }) => {
114
+ const { _stylesheetRules: rules, _stylesheetTheme: theme } = document.root;
115
+ return rules === void 0 && theme === void 0 ? [] : [{ name, rules: rules ?? {}, theme }];
116
+ });
117
+ for (const { rules } of sheets)
118
+ for (const [rule, value] of Object.entries(rules)) {
119
+ const json = JSON.stringify(value), values = seen.get(rule) ?? new Map, known = values.get(json);
120
+ if (known)
121
+ known.count++;
122
+ else
123
+ values.set(json, { value, count: 1 });
124
+ seen.set(rule, values);
125
+ }
126
+ const shared = {}, sharedJson = new Map;
127
+ for (const [rule, values] of seen) {
128
+ const [json, best] = [...values].sort(([, a], [, b]) => b.count - a.count)[0];
129
+ shared[rule] = best.value;
130
+ sharedJson.set(rule, json);
131
+ }
132
+ const themes = {}, screens = new Map;
133
+ for (const { name, rules, theme } of sheets) {
134
+ const own = {};
135
+ for (const [rule, value] of Object.entries(rules))
136
+ if (JSON.stringify(value) !== sharedJson.get(rule))
137
+ own[rule] = value;
138
+ let key = null;
139
+ if (theme !== void 0) {
140
+ key = Bun.hash(JSON.stringify(theme)).toString(36);
141
+ themes[key] = theme;
142
+ }
143
+ screens.set(name, { order: Object.keys(rules), own, theme: key });
144
+ }
145
+ return { rules: shared, themes, screens };
146
+ }
147
+ function withoutStylesheet(document) {
148
+ const { _stylesheetRules, _stylesheetTheme, ...root } = document.root;
149
+ return { ...document, root };
150
+ }
110
151
  export async function compileNativeBundle(options) {
111
152
  const names = Object.keys(options.screens);
112
153
  if (names.length === 0)
@@ -145,18 +186,35 @@ export async function compileNativeBundle(options) {
145
186
  const signalsRuntime = generateSignalsRuntime();
146
187
  if (browser && options.routesDir)
147
188
  throw Error("A browser screen is one route; routesDir is for device hosts");
148
- const entry = (bundled, withApp, runtimeVersion) => {
189
+ const dependencies = new Set(compiledScreens.flatMap(({ compiled }) => compiled.dependencies));
190
+ let sharedModules = null;
191
+ if (options.routesDir && options.sharedRuntime && options.shareModules !== !1 && process.env.STX_NATIVE_SHARE_MODULES !== "0") {
192
+ const moduleInputs = [], routes = compiledScreens.map(({ name, compiled }) => {
193
+ const sources = compiled.scripts.filter((script) => !script.registry).map((script) => script.code);
194
+ return { name, ids: registeredModuleIdsIn(...sources), names: registeredModuleNamesIn(...sources) };
195
+ }), share = () => buildSharedModuleRegistries(routes, { collectInputs: moduleInputs });
196
+ sharedModules = await (stubs ? withModuleSubstitutes(stubs, share) : share());
197
+ if (sharedModules)
198
+ for (const input of moduleInputs)
199
+ dependencies.add(input);
200
+ }
201
+ const shared = sharedModules, sharedScripts = options.routesDir && options.sharedRuntime && options.shareModules !== !1 && process.env.STX_NATIVE_SHARE_MODULES !== "0" ? shareComponentScripts(compiledScreens.map(({ name, compiled }) => ({ name, scripts: compiled.scripts }))) : null, sharedSheets = sharedStylesheets(compiledScreens.map(({ name, compiled }) => ({ name, document: compiled.document }))), entry = (bundled, withApp, runtimeVersion) => {
149
202
  const route = routed ? `var routeName = g.__stxNativeRoute || ${JSON.stringify(initialScreen)};
150
203
  var isApp = ${appFile ? `routeName === ${JSON.stringify(NATIVE_APP_ROUTE)}` : "false"};
151
204
  if (!isApp && routeNames.indexOf(routeName) === -1) throw new Error(['Unknown native screen:', routeName].join(' '));
152
205
  if (isApp ? ${!withApp} : ${JSON.stringify(bundled.map(({ name }) => name))}.indexOf(routeName) === -1) throw new Error(['This bundle does not hold the native screen', routeName].join(' '));` : `var routeName = 'main';
153
- var isApp = false;`, selections = bundled.map(({ name, compiled }, index) => `${index === 0 ? "if" : "else if"} (routeName === ${JSON.stringify(routed ? name : "main")}) {
154
- nativeDocument = ${JSON.stringify(runtimeDocument(compiled.document, root))};
206
+ var isApp = false;`, selections = bundled.map(({ name, compiled }, index) => {
207
+ const sheet = runtimeVersion ? sharedSheets.screens.get(name) : void 0, document = runtimeDocument(sheet ? withoutStylesheet(compiled.document) : compiled.document, root);
208
+ return `${index === 0 ? "if" : "else if"} (routeName === ${JSON.stringify(routed ? name : "main")}) {
209
+ nativeDocument = ${JSON.stringify(document)};${sheet ? `
210
+ nativeDocument.root._stylesheetRules = runtime.stylesheetRules(${JSON.stringify(sheet.order)}, ${JSON.stringify(sheet.own)});${sheet.theme ? `
211
+ nativeDocument.root._stylesheetTheme = runtime.themes[${JSON.stringify(sheet.theme)}];` : ""}` : ""}
155
212
  manifest = ${JSON.stringify(compiled.manifest)};
156
- }`).join(`
213
+ }`;
214
+ }).join(`
157
215
  `), setups = bundled.map(({ name, compiled }, index) => `${index === 0 ? "if" : "else if"} (routeName === ${JSON.stringify(routed ? name : "main")}) {
158
216
  g.__stx_latestSetup = null;
159
- ${compiled.scripts.map((script) => script.owner ? ` g.__stx_componentSetups = g.__stx_componentSetups || {};
217
+ ${(runtimeVersion && sharedScripts?.screens.get(name) || compiled.scripts).map((script) => runtimeVersion && script.registry && shared?.routes.has(name) ? shared.routes.get(name) : script.owner ? ` g.__stx_componentSetups = g.__stx_componentSetups || {};
160
218
  // Kept by id as well as run once: a :for or :if clone of this component
161
219
  // has no script to copy, and is set up from this (component hydration).
162
220
  g.__stx_componentSetups[${JSON.stringify(script.owner)}] = function() {
@@ -181,14 +239,14 @@ ${app ? `import * as nativeAppModule from ${JSON.stringify(appFile)};` : "var na
181
239
  ${browser ? "(async function() {" : ""}
182
240
  var g = globalThis;
183
241
  installJSCGlobals(g);
184
- g.__stxNativeStyleConfig = ${JSON.stringify(styleConfig)};
242
+ g.__stxNativeStyleConfig = ${runtimeVersion ? "runtime.styleConfig" : JSON.stringify(styleConfig)};
185
243
  ${browser ? `var browserPlatform = await createBrowserPlatform(${JSON.stringify(browser.platformOptions ?? {})});
186
244
  var browserBridge = createBrowserScreenBridge(browserPlatform, ${JSON.stringify(browser)});
187
245
  var bridge = browserBridge;
188
246
  g.__stxNativeRoute = ${JSON.stringify(initialScreen)};` : "var bridge = g.__stxNativeBridge;"}
189
247
  if (!bridge) throw new Error('Missing __stxNativeBridge');
190
- var routeNames = ${JSON.stringify(routed ? names : ["main"])};
191
- var shareStorage = ${JSON.stringify(options.shareStorage ?? {})};
248
+ var routeNames = ${runtimeVersion ? "runtime.routeNames" : JSON.stringify(routed ? names : ["main"])};
249
+ var shareStorage = ${runtimeVersion ? "runtime.shareStorage" : JSON.stringify(options.shareStorage ?? {})};
192
250
  ${route}
193
251
  g.__stxNativeRoute = routeName;
194
252
  var nativeDocument;
@@ -232,7 +290,7 @@ g.addEventListener('pagehide', function(event) { if (!event.persisted) g.__stxNa
232
290
  builder.onResolve({ filter: /^stx:native-shared-screens$/ }, () => ({ path: "entry", namespace: "stx-native-shared-screens" }));
233
291
  builder.onLoad({ filter: /.*/, namespace: "stx-native-shared-screens" }, () => ({ contents, loader: "js" }));
234
292
  }
235
- }), dependencies = new Set(compiledScreens.flatMap(({ compiled }) => compiled.dependencies)), diagnostics = compiledScreens.flatMap(({ compiled }) => compiled.diagnostics).map((diagnostic) => ({
293
+ }), diagnostics = compiledScreens.flatMap(({ compiled }) => compiled.diagnostics).map((diagnostic) => ({
236
294
  level: "warning",
237
295
  message: [diagnostic.kind, diagnostic.tag, diagnostic.name].filter(Boolean).join(": ")
238
296
  })), chromed = compiledScreens.filter(({ compiled }) => compiled.document.chrome), chrome = chromed.length ? { chrome: Object.fromEntries(chromed.map(({ name, compiled }) => [name, compiled.document.chrome])) } : {}, minify = options.minify ?? !1;
@@ -245,6 +303,34 @@ import { installJSCGlobals } from ${JSON.stringify(runtimeGlobals)};
245
303
  import { prepareNativeApp, prepareSharedNativeScreen } from ${JSON.stringify(sharedScreen)};
246
304
  globalThis.__stxNativeRuntime = {
247
305
  version: '__STX_NATIVE_RUNTIME_VERSION__',
306
+ // What every route of this build shares, held once instead of in each
307
+ // route file: the app's style vocabulary, its route names and shared
308
+ // storage keys, and the rules and themes of the stylesheets its screens carry.
309
+ styleConfig: ${JSON.stringify(styleConfig)},
310
+ routeNames: ${JSON.stringify(routed ? names : ["main"])},
311
+ shareStorage: ${JSON.stringify(options.shareStorage ?? {})},
312
+ stylesheetRules: function(order, own) {
313
+ var rules = {};
314
+ var shared = this.rules;
315
+ for (var i = 0; i < order.length; i++) rules[order[i]] = Object.prototype.hasOwnProperty.call(own, order[i]) ? own[order[i]] : shared[order[i]];
316
+ return rules;
317
+ },
318
+ rules: ${JSON.stringify(sharedSheets.rules)},
319
+ themes: ${JSON.stringify(sharedSheets.themes)},
320
+ // The modules more than one route reaches (client-module-registry.ts),
321
+ // each run the first time a route asks for it, and once.
322
+ chunks: {${shared ? [...shared.chunks].map(([name, code]) => `
323
+ ${JSON.stringify(name)}: ${code}`).join(",") : ""}},
324
+ // The component code the routes have in common: the functions that set up
325
+ // a component, by content, which a route's factories and calls name.
326
+ components: {${sharedScripts ? [...sharedScripts.bodies].sort(([a], [b]) => a < b ? -1 : 1).map(([hash, body]) => `
327
+ ${JSON.stringify(hash)}: ${body}`).join(",") : ""}},
328
+ chunk: function(name) {
329
+ var loaded = this.loaded || (this.loaded = {});
330
+ if (Object.prototype.hasOwnProperty.call(loaded, name)) return loaded[name];
331
+ var runtime = this;
332
+ return (loaded[name] = this.chunks[name](function(chunk) { return runtime.chunk(chunk); }));
333
+ },
248
334
  installJSCGlobals: installJSCGlobals,
249
335
  prepareNativeApp: prepareNativeApp,
250
336
  prepareSharedNativeScreen: prepareSharedNativeScreen,
@@ -306,8 +392,13 @@ ${signalsRuntime}
306
392
  const file = path.join(dir, `${target.name}.js`), code = await build("stx:native-shared-screens", [plugin(entry(target.screens, target.app, runtimeVersion))], minify, dependencies, stubs ?? void 0);
307
393
  await Bun.write(file, code);
308
394
  routes[target.name] = file;
309
- if (messages)
310
- routeAreas[target.name] = areasRead(code);
395
+ if (messages) {
396
+ const areas = new Set(areasRead(code));
397
+ for (const chunk of shared?.reads.get(target.name) ?? [])
398
+ for (const area of areasRead(shared?.chunks.get(chunk) ?? ""))
399
+ areas.add(area);
400
+ routeAreas[target.name] = [...areas].sort();
401
+ }
311
402
  }));
312
403
  if (messages) {
313
404
  for (const [language, areas] of messages.data)
@@ -55,24 +55,31 @@ export async function compileScreenSource(source, filePath, options = {}) {
55
55
  if (forcedSetup && !scripts.some((script) => script.code === forcedSetup.code))
56
56
  scripts.push({ code: forcedSetup.code });
57
57
  }
58
- const { buildModuleRegistryScript, registeredModuleIdsIn } = await import("../../client-module-registry.js"), registry = async () => {
59
- const inputs = [], code = await buildModuleRegistryScript(registeredModuleIdsIn(...scripts.map((script) => script.code)), { collectInputs: inputs });
58
+ const { buildModuleRegistryScript, registeredModuleIdsIn, registeredModuleNamesIn } = await import("../../client-module-registry.js"), registry = async () => {
59
+ const inputs = [], sources = scripts.map((script) => script.code), code = await buildModuleRegistryScript(registeredModuleIdsIn(...sources), { collectInputs: inputs, names: registeredModuleNamesIn(...sources) });
60
60
  for (const input of inputs)
61
61
  dependencies.add(input);
62
62
  return code;
63
63
  };
64
64
  let modules = await registry();
65
65
  if ([...scripts.map((script) => script.code), modules ?? ""].some((code) => /\buseStore\s*\(/.test(code)) && /<script\b[^>]*\bdata-stx-stores\b/i.test(html)) {
66
- const { getStoreScript } = await import("../../store-loader.js"), stores = await getStoreScript(config.storesDir);
67
- if (stores) {
68
- scripts.unshift({ code: stores });
66
+ const { getStoreScriptFor } = await import("../../store-loader.js"), own = [...scripts];
67
+ let kept = "";
68
+ for (let round = 0;round < 8; round++) {
69
+ const stores = await getStoreScriptFor(config.storesDir, [...own.map((script) => script.code), modules], { sharedModules: !0 });
70
+ if (!stores)
71
+ break;
72
+ if (stores.stores.join() === kept)
73
+ break;
74
+ kept = stores.stores.join();
75
+ scripts.splice(0, scripts.length, { code: stores.code }, ...own);
69
76
  for (const file of new Bun.Glob("*.ts").scanSync({ cwd: config.storesDir, absolute: !0 }))
70
77
  dependencies.add(file);
71
78
  modules = await registry();
72
79
  }
73
80
  }
74
81
  if (modules)
75
- scripts.unshift({ code: modules });
82
+ scripts.unshift({ code: modules, registry: !0 });
76
83
  return { document, manifest, setup, scripts, diagnostics, html, dependencies: [...dependencies] };
77
84
  }
78
85
  function enterTemplatedBindings(root, manifest) {
@@ -10,4 +10,5 @@ export declare interface GeneratedSetupScript {
10
10
  export declare interface NativeClientScript {
11
11
  code: string
12
12
  owner?: string
13
+ registry?: boolean
13
14
  }
@@ -0,0 +1,12 @@
1
+ import type { NativeClientScript } from './setup-script';
2
+ /**
3
+ * Pull the code more than one screen has out of every screen's scripts. What
4
+ * only one screen has stays in it: the runtime is read by every screen. A
5
+ * factory and a component drawn once are the same function when they are the
6
+ * same component, so both are counted by content.
7
+ */
8
+ export declare function shareComponentScripts(screens: Array<{ name: string, scripts: NativeClientScript[] }>): SharedScripts;
9
+ export declare interface SharedScripts {
10
+ bodies: Map<string, string>
11
+ screens: Map<string, NativeClientScript[]>
12
+ }
@@ -0,0 +1,83 @@
1
+ const bodyHash = (body) => Bun.hash(body).toString(36), FACTORIES_SCRIPT = `(function() {
2
+ const factories = window.__stxComponentFactories = window.__stxComponentFactories || {};
3
+ `, FACTORY_START = /^ {2}try \{ factories\[("[0-9a-f]+")\] = factories\[\1\] \|\| /gm, COMPONENT_BODY = /^\(function\(__scopeId\) \{([\s\S]*)\}\)\("([^"\\]+)"\);\s*$/;
4
+ function factoryDefinitions(code) {
5
+ if (!code.startsWith(FACTORIES_SCRIPT) || !code.endsWith(`
6
+ })();`))
7
+ return null;
8
+ const starts = [...code.matchAll(FACTORY_START)];
9
+ if (starts.length === 0)
10
+ return null;
11
+ const definitions = [];
12
+ let cursor = FACTORIES_SCRIPT.length;
13
+ for (const [at, start] of starts.entries()) {
14
+ if (start.index !== cursor)
15
+ return null;
16
+ const id = JSON.parse(start[1]), from = start.index + start[0].length, tail = `; }
17
+ catch (e) { console.error('[stx] component factory ' + ${JSON.stringify(id)} + ' failed to register; instances of it will not hydrate.', e); }`, end = code.indexOf(tail, from);
18
+ if (end < 0 || !code.slice(from, end).startsWith("function(__scopeId) {") && !code.slice(from, end).startsWith("function (__scopeId) {"))
19
+ return null;
20
+ const next = starts[at + 1];
21
+ cursor = end + tail.length;
22
+ if (next ? code[cursor] !== `
23
+ ` || next.index !== cursor + 1 : code.slice(cursor) !== `
24
+ })();`)
25
+ return null;
26
+ definitions.push({ id, body: code.slice(from, end), text: code.slice(start.index, end + tail.length) });
27
+ cursor = next ? cursor + 1 : cursor;
28
+ }
29
+ return definitions;
30
+ }
31
+ export function shareComponentScripts(screens) {
32
+ const factoryIds = new Map;
33
+ for (const { scripts } of screens)
34
+ for (const script of scripts)
35
+ for (const definition of (script.registry || script.owner ? null : factoryDefinitions(script.code)) ?? [])
36
+ factoryIds.set(definition.body, definition.id);
37
+ const keyOf = (body) => factoryIds.get(body) ?? bodyHash(body), used = new Map, componentOf = (script) => {
38
+ const match = script.owner ? COMPONENT_BODY.exec(script.code) : null;
39
+ return match ? { body: `function(__scopeId) {${match[1]}}`, scope: match[2] } : null;
40
+ }, count = (screen, body) => {
41
+ const key = keyOf(body), known = used.get(key) ?? new Set;
42
+ known.add(screen);
43
+ used.set(key, known);
44
+ }, common = (body) => (used.get(keyOf(body))?.size ?? 0) > 1;
45
+ for (const { name, scripts } of screens)
46
+ for (const script of scripts) {
47
+ if (script.registry)
48
+ continue;
49
+ for (const definition of (script.owner ? null : factoryDefinitions(script.code)) ?? [])
50
+ count(name, definition.body);
51
+ const component = componentOf(script);
52
+ if (component)
53
+ count(name, component.body);
54
+ }
55
+ const bodies = new Map, result = new Map;
56
+ for (const { name, scripts } of screens)
57
+ result.set(name, scripts.map((script) => {
58
+ if (script.registry)
59
+ return script;
60
+ const definitions = script.owner ? null : factoryDefinitions(script.code);
61
+ if (definitions) {
62
+ const inCommon = definitions.filter((definition) => common(definition.body));
63
+ if (inCommon.length === 0)
64
+ return script;
65
+ for (const { body } of inCommon)
66
+ bodies.set(keyOf(body), body);
67
+ const own = definitions.filter((definition) => !inCommon.includes(definition)), ids = inCommon.map((definition) => JSON.stringify(definition.id)).join(", ");
68
+ return {
69
+ ...script,
70
+ code: `${FACTORIES_SCRIPT}${own.map((definition) => `${definition.text}
71
+ `).join("")} [${ids}].forEach(function (id) { factories[id] = factories[id] || runtime.components[id]; });
72
+ })();`
73
+ };
74
+ }
75
+ const component = componentOf(script);
76
+ if (component && common(component.body)) {
77
+ bodies.set(keyOf(component.body), component.body);
78
+ return { ...script, code: `runtime.components[${JSON.stringify(keyOf(component.body))}](${JSON.stringify(component.scope)});` };
79
+ }
80
+ return script;
81
+ }));
82
+ return { bodies, screens: result };
83
+ }
package/dist/pwa.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{qs,Ft,ul,pg}from"./chunk-dvakr9p9.js";import{Ws,Si,lg,ug,dg}from"./chunk-9q1kkfv1.js";import{al,cl,ll,ag,cg}from"./chunk-1a2cwee1.js";import{Ve,Cn,ki}from"./chunk-g22absm0.js";import{fg,gg,mg,hg,Ks,Hh}from"./chunk-xrzghjvy.js";import B from"fs";import w from"path";import O from"fs";import u from"path";var v=[72,96,128,144,152,192,384,512],S=[120,152,167,180],P=[16,32];async function M(n,t){let e={success:!0,generatedFiles:[],errors:[],warnings:[]},r=n.pwa?.icons;if(!r?.src)return e.errors.push("No source icon specified in pwa.icons.src"),e.success=!1,e;let o=u.isAbsolute(r.src)?r.src:u.resolve(process.cwd(),r.src);if(!await Bun.file(o).exists())return e.errors.push(`Source icon not found: ${o}`),e.success=!1,e;let a=u.resolve(t,r.outputDir||"pwa-icons");try{O.mkdirSync(a,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${a}`),e.success=!1,e}let s=r.sizes||v,l=r.generateWebP??!0,p=r.generateAppleIcons??!0;try{let c;try{c=await import("sharp")}catch{return e.errors.push(`sharp is not installed. Install it with: bun add sharp
3
- Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-33bp9m4c.js"),o=await Bun.file(e).text();return await r(o,{},e,n,new Set)}catch(r){console.warn(`[PWA] Failed to process custom offline page: ${r}`)}else console.warn(`[PWA] Custom offline page not found: ${e}`)}return E(n)}function E(n){let t=n.pwa?.offline,e=n.pwa?.manifest,r=t?.fallbackTitle||"You are offline",o=t?.fallbackMessage||"Please check your internet connection and try again.",a=e?.themeColor||"#4f46e5",s=e?.shortName||e?.name||"App";return`<!DOCTYPE html>
2
+ import{Gs,Ft,ml,yg}from"./chunk-4zw118tn.js";import{Ks,Ci,gg,mg,hg}from"./chunk-kpr09x3g.js";import{pl,fl,gl,pg,fg}from"./chunk-9s1qnf90.js";import{Ve,Cn,Ei}from"./chunk-83ezv8yz.js";import{bg,vg,wg,xg,Xs,Jh}from"./chunk-4s9kytdz.js";import B from"fs";import w from"path";import O from"fs";import u from"path";var v=[72,96,128,144,152,192,384,512],S=[120,152,167,180],P=[16,32];async function M(n,t){let e={success:!0,generatedFiles:[],errors:[],warnings:[]},r=n.pwa?.icons;if(!r?.src)return e.errors.push("No source icon specified in pwa.icons.src"),e.success=!1,e;let o=u.isAbsolute(r.src)?r.src:u.resolve(process.cwd(),r.src);if(!await Bun.file(o).exists())return e.errors.push(`Source icon not found: ${o}`),e.success=!1,e;let a=u.resolve(t,r.outputDir||"pwa-icons");try{O.mkdirSync(a,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${a}`),e.success=!1,e}let s=r.sizes||v,l=r.generateWebP??!0,p=r.generateAppleIcons??!0;try{let c;try{c=await import("sharp")}catch{return e.errors.push(`sharp is not installed. Install it with: bun add sharp
3
+ Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-f4mmk2cx.js"),o=await Bun.file(e).text();return await r(o,{},e,n,new Set)}catch(r){console.warn(`[PWA] Failed to process custom offline page: ${r}`)}else console.warn(`[PWA] Custom offline page not found: ${e}`)}return E(n)}function E(n){let t=n.pwa?.offline,e=n.pwa?.manifest,r=t?.fallbackTitle||"You are offline",o=t?.fallbackMessage||"Please check your internet connection and try again.",a=e?.themeColor||"#4f46e5",s=e?.shortName||e?.name||"App";return`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">
@@ -233,4 +233,4 @@ Icon generation requires the sharp package for image processing.`),e.success=!1,
233
233
  }, 5000);
234
234
  </script>
235
235
  </body>
236
- </html>`}function b(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}async function re(n,t){let e={success:!0,files:{icons:[]},errors:[],warnings:[]},r=n.pwa;if(!r?.enabled)return e;try{B.mkdirSync(t,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${t}`),e.success=!1,e}try{let a=_(n);if(a){let s=w.join(t,"manifest.json");await Bun.write(s,a),e.files.manifest=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate manifest.json: ${s}`),e.success=!1}if(r.icons?.src)if(await I()){let s=await M(n,t);if(e.files.icons=s.generatedFiles,e.warnings.push(...s.warnings),!s.success)e.errors.push(...s.errors),e.success=!1}else e.warnings.push("sharp is not installed. Skipping icon generation. Install with: bun add sharp");if(r.offline?.enabled)try{let a=await F(n);if(a){let s=w.join(t,"offline.html");await Bun.write(s,a),e.files.offlinePage=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate offline page: ${s}`),e.success=!1}let o;if(r.precache?.enabled){let a=Ve(t,n);o={fileCount:a.fileCount,totalSize:a.totalSize},e.precacheStats=o}try{let a=qs(n,t);if(a){let s=Ft(n),l=w.join(t,s);await Bun.write(l,a),e.files.serviceWorker=l}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate service worker: ${s}`),e.success=!1}return e}function ae(n,t){return Si(n,t)}function se(n){return n.pwa?.enabled===!0}export{S as APPLE_TOUCH_ICON_SIZES,v as DEFAULT_ICON_SIZES,P as FAVICON_SIZES,cl as auditBuildOutput,al as auditConfig,re as buildPwaAssets,ll as calculateAuditResult,cg as formatAuditResult,ki as formatSize,j as generateManifest,_ as generateManifestJson,ug as generateManifestLink,F as generateOfflinePage,Ve as generatePrecacheManifest,Cn as generatePrecacheManifestJs,M as generatePwaIcons,Ws as generatePwaTags,qs as generateServiceWorker,pg as generateServiceWorkerAuto,lg as generateSwRegistrationScript,dg as generateThemeColorMeta,N as getExpectedIconPaths,Ft as getServiceWorkerFileName,Si as injectPwaTags,se as isPwaEnabled,I as isSharpAvailable,ul as isWorkboxEnabled,q as mergeManifestConfig,ae as processPwaHtml,Ks as pwaDirectives,fg as pwaInstallDirective,mg as pwaOfflineDirective,hg as pwaPushDirective,gg as pwaUpdateDirective,Hh as registerPwaDirectives,ag as runPwaAudit,D as validateManifest};
236
+ </html>`}function b(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}async function re(n,t){let e={success:!0,files:{icons:[]},errors:[],warnings:[]},r=n.pwa;if(!r?.enabled)return e;try{B.mkdirSync(t,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${t}`),e.success=!1,e}try{let a=_(n);if(a){let s=w.join(t,"manifest.json");await Bun.write(s,a),e.files.manifest=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate manifest.json: ${s}`),e.success=!1}if(r.icons?.src)if(await I()){let s=await M(n,t);if(e.files.icons=s.generatedFiles,e.warnings.push(...s.warnings),!s.success)e.errors.push(...s.errors),e.success=!1}else e.warnings.push("sharp is not installed. Skipping icon generation. Install with: bun add sharp");if(r.offline?.enabled)try{let a=await F(n);if(a){let s=w.join(t,"offline.html");await Bun.write(s,a),e.files.offlinePage=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate offline page: ${s}`),e.success=!1}let o;if(r.precache?.enabled){let a=Ve(t,n);o={fileCount:a.fileCount,totalSize:a.totalSize},e.precacheStats=o}try{let a=Gs(n,t);if(a){let s=Ft(n),l=w.join(t,s);await Bun.write(l,a),e.files.serviceWorker=l}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate service worker: ${s}`),e.success=!1}return e}function ae(n,t){return Ci(n,t)}function se(n){return n.pwa?.enabled===!0}export{S as APPLE_TOUCH_ICON_SIZES,v as DEFAULT_ICON_SIZES,P as FAVICON_SIZES,fl as auditBuildOutput,pl as auditConfig,re as buildPwaAssets,gl as calculateAuditResult,fg as formatAuditResult,Ei as formatSize,j as generateManifest,_ as generateManifestJson,mg as generateManifestLink,F as generateOfflinePage,Ve as generatePrecacheManifest,Cn as generatePrecacheManifestJs,M as generatePwaIcons,Ks as generatePwaTags,Gs as generateServiceWorker,yg as generateServiceWorkerAuto,gg as generateSwRegistrationScript,hg as generateThemeColorMeta,N as getExpectedIconPaths,Ft as getServiceWorkerFileName,Ci as injectPwaTags,se as isPwaEnabled,I as isSharpAvailable,ml as isWorkboxEnabled,q as mergeManifestConfig,ae as processPwaHtml,Xs as pwaDirectives,bg as pwaInstallDirective,wg as pwaOfflineDirective,xg as pwaPushDirective,vg as pwaUpdateDirective,Jh as registerPwaDirectives,pg as runPwaAudit,D as validateManifest};
package/dist/ssg.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import"./chunk-19safa6y.js";import{b,Wc}from"./chunk-0tgrqhkr.js";import"./chunk-236bdf7y.js";import"./chunk-89h4snzd.js";import{Tt,S}from"./chunk-8w0cwcvk.js";import"./chunk-sj2a5twe.js";import"./chunk-7mm5mvg0.js";import"./chunk-m6w75sq2.js";import{xt,St,kt,_t,Ct,Et}from"./chunk-k4dn3ry6.js";import{a}from"./chunk-g5sctfwa.js";import{bs}from"./chunk-3z38swhv.js";import"./chunk-cb4ybh7g.js";import"./chunk-txgd0sj1.js";import{Te,Zt,Qt}from"./chunk-h6sewvt2.js";import"./chunk-xzz36k99.js";import{y}from"./chunk-x5sy0tym.js";import{mt,i}from"./chunk-thr1m7k7.js";import"./chunk-gzbmfwxr.js";import"./chunk-j5p191zq.js";import{os}from"./chunk-kjfzkac7.js";import"./chunk-8wbgq43c.js";import"./chunk-41sq06t2.js";import{za,Ha,Va}from"./chunk-z5kdmget.js";import{Jt,Xn,Jn}from"./chunk-tn40nh9e.js";import{Yt}from"./chunk-np8knskz.js";import"./chunk-6fxjs3ay.js";import"./chunk-v0s52tmv.js";import{G,be}from"./chunk-024m1xmd.js";import"./chunk-nsjkmpjf.js";import"./chunk-p33w8zst.js";import{l}from"./chunk-7ycf8a8d.js";import{s,ge}from"./chunk-g45p4y4v.js";import D from"fs";import f from"path";import{createHash as $t}from"crypto";function Dt(t){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(t).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return t}}var Rt=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function It(t){return Bun.hash(t).toString(16)}function ot(t,r={}){if(!t.includes('type="stx/island"'))return{html:t,chunks:[]};let n=new Map,o=t.replace(Rt,(e,u,g,v)=>{let w=v.trim();if(!w)return e;if(/\bdata-stx-src=/.test(g))return e;if(r.minify)w=Dt(w);let p=It(w);if(!n.has(p))n.set(p,w);let P=r.integrity?` data-stx-integrity="sha384-${$t("sha384").update(w).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${u}" data-stx-src="/_stx/islands/${p}.js"${P}${g}></script>`}),c=Array.from(n,([e,u])=>({hash:e,code:u}));return{html:o,chunks:c}}var Bt=new Set(["visible","idle"]);function ct(t){if(!t.includes("data-stx-src="))return t;let r=new Map,n=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,o;while((o=n.exec(t))!==null)r.set(o[1],o[2]);let c=new Set,e=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,u;while((u=e.exec(t))!==null)if(Bt.has(r.get(u[1])||""))c.add(u[2]);let g=/<\/head\s*>/iy,v=S(t,(p,P)=>(g.lastIndex=P,g.exec(p)?g.lastIndex:-1))[0]?.start??-1;if(c.size===0||v===-1)return t;let w=Array.from(c).filter((p)=>!t.includes(`rel="prefetch" href="${p}"`)).map((p)=>`<link rel="prefetch" href="${p}" as="script">`).join("");if(!w)return t;return t.slice(0,v)+w+t.slice(v)}var jt=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function X(t){let r=t.trim();if(!r)return null;let n=/^https?:\/\//i.test(r)?r:`https://${r}`;try{return new URL(n).origin+new URL(n).pathname.replace(/\/$/,"")}catch{return null}}function Ft(t){for(let r of jt){let n=t[r];if(!n)continue;let o=X(n);if(o)return{url:o,source:"env",via:r}}return null}function lt(t){if(!t||typeof t!=="object")return null;let r=t,n=r.site?.url??r.url??r.app?.url;return typeof n==="string"?X(n):null}async function At(t){let{existsSync:r}=await import("fs"),n=await import("path");for(let o of["site.config.ts","site.config.js",".config/site.config.ts"]){let c=n.resolve(t,o);if(!r(c))continue;try{let e=await import(c),u=lt(e.default??e);if(u)return u}catch{}}return null}async function ut(t={}){let r=t.cwd??process.cwd(),n=t.env??process.env;if(t.explicit){let u=X(t.explicit);if(u)return{url:u,source:"option"}}let o=lt(t.stxConfig);if(o)return{url:o,source:"stx.config",via:"site.url"};let c=await At(r);if(c)return{url:c,source:"site.config",via:"url"};let e=Ft(n);if(e)return e;return{url:"http://localhost",source:"fallback"}}function dt(){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
- `)}function J(t){return async()=>({paths:await t(),fallback:!1})}var Ot;function Lt(t){let r=s(t),{depths:n}=ge(r),o=/\b(?:async\s+)?function\s+getStaticPaths\s*\(/g,c;while((c=o.exec(r))!==null){if(n[c.index]!==0)continue;let u=b(r,"(",")",o.lastIndex-1),g=r.indexOf("{",u+1),v=b(r,"{","}",g);if(u<0||g<0||v<0)break;return t.slice(c.index,v+1)}let e=/\b(?:const|let|var)\s+getStaticPaths\s*=/g;while((c=e.exec(r))!==null){if(n[c.index]!==0)continue;let u=Wc(r,e.lastIndex).endPos;return t.slice(e.lastIndex,u).trim()}throw SyntaxError("Could not extract getStaticPaths; use a top-level function or const declaration")}async function gt(t){let r="read";try{let n=await Bun.file(t).text();r="parse";let o=Yt(n),c=[...o.server,...o.client,...o.signals].filter((e)=>/(?:^|\s)server(?:\s|=|$)/i.test(s(e.attrs))).sort((e,u)=>n.indexOf(e.fullTag)-n.indexOf(u.fullTag));for(let e of c){if(!/\bgetStaticPaths\b/.test(s(e.content)))continue;let u=(Ot??=new Bun.Transpiler({loader:"ts",target:"bun"})).transformSync(e.content);if(!/\bgetStaticPaths\b/.test(s(u)))continue;let g=Lt(u);if(/\bdefineStaticPaths\b/.test(s(g))&&Tt(u,"defineStaticPaths"))throw SyntaxError("Cannot evaluate a module-local defineStaticPaths binding during isolated hook extraction");r="execute";let v=Function("defineStaticPaths",`return (${g})`)(J);if(typeof v!=="function")throw TypeError("getStaticPaths must be a function");let w=await v();r="result";let p=Array.isArray(w)?{paths:w}:w;if(!p||typeof p!=="object"||!("paths"in p)||!Array.isArray(p.paths))throw TypeError("getStaticPaths must return { paths: [...] } or an array of paths");for(let P of p.paths)if(!P||typeof P!=="object"||!P.params||typeof P.params!=="object"||Array.isArray(P.params))throw TypeError("Each getStaticPaths path must contain a params object");return{kind:"ok",value:p}}return{kind:"absent"}}catch(n){return{kind:"error",phase:r,error:n instanceof Error?n:Error(String(n))}}}class pt{cacheDir;cache=new Map;loaded=!1;salt;constructor(t,r=""){this.cacheDir=t,this.salt=r}async load(){if(this.loaded)return;let t=f.join(this.cacheDir,"build-cache.json");if(await Bun.file(t).exists())try{let r=JSON.parse(await Bun.file(t).text());for(let[n,o]of Object.entries(r))this.cache.set(n,o)}catch{}this.loaded=!0}async save(){await D.promises.mkdir(this.cacheDir,{recursive:!0});let t=f.join(this.cacheDir,"build-cache.json"),r={};for(let[n,o]of this.cache)r[n]=o;await Bun.write(t,JSON.stringify(r))}getHash(t,r){let n=D.statSync(t),o=`${this.salt}|${t}:${n.mtimeMs}`;for(let e of r)if(D.existsSync(e)){let u=D.statSync(e);o+=`:${e}:${u.mtimeMs}`}let c=0;for(let e=0;e<o.length;e++){let u=o.charCodeAt(e);c=(c<<5)-c+u,c=c&c}return Math.abs(c).toString(36)}get(t,r){let n=this.cache.get(t);if(!n)return null;let o=ft(r).some((u)=>D.existsSync(u)),c=[r,...n.dependencies??[]].some((u)=>u.endsWith(".stx")&&D.existsSync(u)&&os(D.readFileSync(u,"utf8")).some((g)=>/\bserver\b/.test(g.attrs)));if(o||c)return this.cache.delete(t),null;let e=this.getHash(r,n.dependencies??[]);if(n.hash!==e)return this.cache.delete(t),null;return n.html}set(t,r,n,o){let c=this.getHash(r,n);this.cache.set(t,{hash:c,html:o,generatedAt:Date.now(),dependencies:n})}}class ht{cacheDir;constructor(t){this.cacheDir=t}getFilePath(t){let r=t.replace(/[^a-zA-Z0-9]/g,"_")+".json";return f.join(this.cacheDir,"isr",r)}async get(t){let r=this.getFilePath(t);if(!await Bun.file(r).exists())return null;try{return JSON.parse(await Bun.file(r).text())}catch{return null}}async set(t,r){let n=this.getFilePath(t);await D.promises.mkdir(f.dirname(n),{recursive:!0}),await Bun.write(n,JSON.stringify(r))}async invalidate(t){let r=this.getFilePath(t);if(await Bun.file(r).exists())await D.promises.unlink(r)}async invalidatePattern(t){let r=f.join(this.cacheDir,"isr");if(!D.existsSync(r))return;let n=await D.promises.readdir(r);for(let o of n){let c=o.replace(/_/g,"/").replace(".json","");if(t.test(c))await D.promises.unlink(f.join(r,o))}}async needsRevalidation(t){let r=await this.get(t);if(!r)return!0;return Date.now()>r.revalidateAfter}}async function Ut(t){let r=[];if(!t.isDynamic)r.push({url:t.pattern,params:{}});else{let n=await gt(t.filePath);if(n.kind==="error")throw Error(`getStaticPaths ${n.phase} failed for ${t.pattern} (${t.filePath}): ${n.error.message}`,{cause:n.error});if(n.kind==="absent")return console.warn(`Warning: Dynamic route ${t.pattern} (${t.filePath}) has no getStaticPaths`),r;let o=n.value;if(o.paths.length===0)return console.info(`getStaticPaths returned no paths for dynamic route ${t.pattern} (${t.filePath})`),r;for(let c of o.paths){let e=t.pattern;for(let[u,g]of Object.entries(c.params))e=e.replace(`:${u}`,g).replace(`:${u}*`,g);r.push({url:e,params:c.params,props:c.props,revalidate:c.revalidate})}}return r}function ft(t){return[t.replace(/\.stx$/,".data.ts"),t.replace(/\.stx$/,".data.js"),t+".data.ts",t+".data.js"]}async function Mt(t){for(let r of ft(t))if(await Bun.file(r).exists())try{let n=await import(r);if(typeof n.default==="function")return await n.default();else if(typeof n.default==="object")return n.default;else if(typeof n.getData==="function")return await n.getData();else{let{default:o,...c}=n;return c}}catch(n){console.error(`Error loading data file ${r}:`,n)}return null}async function Gt(t,r,n){let o=t.match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return null;let c=o[1];if(!c.includes("getStaticProps"))return null;try{let e=c.match(/(?:export\s+)?(?:async\s+)?function\s+getStaticProps\s*\([^)]*\)\s*\{([\s\S]*?)\n\}/);if(!e)return null;return await Function("params",`
2
+ import"./chunk-19safa6y.js";import{b,Jc}from"./chunk-465resq9.js";import"./chunk-qwds327k.js";import"./chunk-89h4snzd.js";import{Tt,S}from"./chunk-m5fjhrpd.js";import"./chunk-gs373714.js";import"./chunk-b6g24qj0.js";import"./chunk-yp6w740k.js";import{xt,St,kt,_t,Ct,Et}from"./chunk-z8k3fx4r.js";import{a}from"./chunk-x1q2ape8.js";import{ws}from"./chunk-3cn9y08d.js";import"./chunk-5q9ss7ty.js";import"./chunk-6n195hvc.js";import{Te,Zt,Qt}from"./chunk-r5jytt0f.js";import"./chunk-hmae7ha6.js";import{y}from"./chunk-x9haxcsj.js";import{mt,i}from"./chunk-fpagqrd1.js";import"./chunk-0e9xdrzx.js";import"./chunk-nv9dy71x.js";import{as}from"./chunk-06zn167b.js";import"./chunk-0jn79fkt.js";import"./chunk-jt28zh50.js";import{Wa,qa,Ka}from"./chunk-3nxe5xmy.js";import{Jt,Xn,Jn}from"./chunk-tn40nh9e.js";import{Yt}from"./chunk-t5gabs4x.js";import"./chunk-qn4gt8sx.js";import"./chunk-sgm6tg8h.js";import{G,be}from"./chunk-0dkd26t4.js";import"./chunk-3kfbs0mw.js";import"./chunk-1mfj2j5g.js";import{l}from"./chunk-c05r0rzw.js";import{s,ge}from"./chunk-cehjp06v.js";import D from"fs";import f from"path";import{createHash as $t}from"crypto";function Dt(t){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(t).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return t}}var Rt=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function It(t){return Bun.hash(t).toString(16)}function ot(t,r={}){if(!t.includes('type="stx/island"'))return{html:t,chunks:[]};let n=new Map,o=t.replace(Rt,(e,u,g,v)=>{let w=v.trim();if(!w)return e;if(/\bdata-stx-src=/.test(g))return e;if(r.minify)w=Dt(w);let p=It(w);if(!n.has(p))n.set(p,w);let P=r.integrity?` data-stx-integrity="sha384-${$t("sha384").update(w).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${u}" data-stx-src="/_stx/islands/${p}.js"${P}${g}></script>`}),c=Array.from(n,([e,u])=>({hash:e,code:u}));return{html:o,chunks:c}}var Bt=new Set(["visible","idle"]);function ct(t){if(!t.includes("data-stx-src="))return t;let r=new Map,n=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,o;while((o=n.exec(t))!==null)r.set(o[1],o[2]);let c=new Set,e=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,u;while((u=e.exec(t))!==null)if(Bt.has(r.get(u[1])||""))c.add(u[2]);let g=/<\/head\s*>/iy,v=S(t,(p,P)=>(g.lastIndex=P,g.exec(p)?g.lastIndex:-1))[0]?.start??-1;if(c.size===0||v===-1)return t;let w=Array.from(c).filter((p)=>!t.includes(`rel="prefetch" href="${p}"`)).map((p)=>`<link rel="prefetch" href="${p}" as="script">`).join("");if(!w)return t;return t.slice(0,v)+w+t.slice(v)}var jt=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function X(t){let r=t.trim();if(!r)return null;let n=/^https?:\/\//i.test(r)?r:`https://${r}`;try{return new URL(n).origin+new URL(n).pathname.replace(/\/$/,"")}catch{return null}}function Ft(t){for(let r of jt){let n=t[r];if(!n)continue;let o=X(n);if(o)return{url:o,source:"env",via:r}}return null}function lt(t){if(!t||typeof t!=="object")return null;let r=t,n=r.site?.url??r.url??r.app?.url;return typeof n==="string"?X(n):null}async function At(t){let{existsSync:r}=await import("fs"),n=await import("path");for(let o of["site.config.ts","site.config.js",".config/site.config.ts"]){let c=n.resolve(t,o);if(!r(c))continue;try{let e=await import(c),u=lt(e.default??e);if(u)return u}catch{}}return null}async function ut(t={}){let r=t.cwd??process.cwd(),n=t.env??process.env;if(t.explicit){let u=X(t.explicit);if(u)return{url:u,source:"option"}}let o=lt(t.stxConfig);if(o)return{url:o,source:"stx.config",via:"site.url"};let c=await At(r);if(c)return{url:c,source:"site.config",via:"url"};let e=Ft(n);if(e)return e;return{url:"http://localhost",source:"fallback"}}function dt(){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
+ `)}function J(t){return async()=>({paths:await t(),fallback:!1})}var Ot;function Lt(t){let r=s(t),{depths:n}=ge(r),o=/\b(?:async\s+)?function\s+getStaticPaths\s*\(/g,c;while((c=o.exec(r))!==null){if(n[c.index]!==0)continue;let u=b(r,"(",")",o.lastIndex-1),g=r.indexOf("{",u+1),v=b(r,"{","}",g);if(u<0||g<0||v<0)break;return t.slice(c.index,v+1)}let e=/\b(?:const|let|var)\s+getStaticPaths\s*=/g;while((c=e.exec(r))!==null){if(n[c.index]!==0)continue;let u=Jc(r,e.lastIndex).endPos;return t.slice(e.lastIndex,u).trim()}throw SyntaxError("Could not extract getStaticPaths; use a top-level function or const declaration")}async function gt(t){let r="read";try{let n=await Bun.file(t).text();r="parse";let o=Yt(n),c=[...o.server,...o.client,...o.signals].filter((e)=>/(?:^|\s)server(?:\s|=|$)/i.test(s(e.attrs))).sort((e,u)=>n.indexOf(e.fullTag)-n.indexOf(u.fullTag));for(let e of c){if(!/\bgetStaticPaths\b/.test(s(e.content)))continue;let u=(Ot??=new Bun.Transpiler({loader:"ts",target:"bun"})).transformSync(e.content);if(!/\bgetStaticPaths\b/.test(s(u)))continue;let g=Lt(u);if(/\bdefineStaticPaths\b/.test(s(g))&&Tt(u,"defineStaticPaths"))throw SyntaxError("Cannot evaluate a module-local defineStaticPaths binding during isolated hook extraction");r="execute";let v=Function("defineStaticPaths",`return (${g})`)(J);if(typeof v!=="function")throw TypeError("getStaticPaths must be a function");let w=await v();r="result";let p=Array.isArray(w)?{paths:w}:w;if(!p||typeof p!=="object"||!("paths"in p)||!Array.isArray(p.paths))throw TypeError("getStaticPaths must return { paths: [...] } or an array of paths");for(let P of p.paths)if(!P||typeof P!=="object"||!P.params||typeof P.params!=="object"||Array.isArray(P.params))throw TypeError("Each getStaticPaths path must contain a params object");return{kind:"ok",value:p}}return{kind:"absent"}}catch(n){return{kind:"error",phase:r,error:n instanceof Error?n:Error(String(n))}}}class pt{cacheDir;cache=new Map;loaded=!1;salt;constructor(t,r=""){this.cacheDir=t,this.salt=r}async load(){if(this.loaded)return;let t=f.join(this.cacheDir,"build-cache.json");if(await Bun.file(t).exists())try{let r=JSON.parse(await Bun.file(t).text());for(let[n,o]of Object.entries(r))this.cache.set(n,o)}catch{}this.loaded=!0}async save(){await D.promises.mkdir(this.cacheDir,{recursive:!0});let t=f.join(this.cacheDir,"build-cache.json"),r={};for(let[n,o]of this.cache)r[n]=o;await Bun.write(t,JSON.stringify(r))}getHash(t,r){let n=D.statSync(t),o=`${this.salt}|${t}:${n.mtimeMs}`;for(let e of r)if(D.existsSync(e)){let u=D.statSync(e);o+=`:${e}:${u.mtimeMs}`}let c=0;for(let e=0;e<o.length;e++){let u=o.charCodeAt(e);c=(c<<5)-c+u,c=c&c}return Math.abs(c).toString(36)}get(t,r){let n=this.cache.get(t);if(!n)return null;let o=ft(r).some((u)=>D.existsSync(u)),c=[r,...n.dependencies??[]].some((u)=>u.endsWith(".stx")&&D.existsSync(u)&&as(D.readFileSync(u,"utf8")).some((g)=>/\bserver\b/.test(g.attrs)));if(o||c)return this.cache.delete(t),null;let e=this.getHash(r,n.dependencies??[]);if(n.hash!==e)return this.cache.delete(t),null;return n.html}set(t,r,n,o){let c=this.getHash(r,n);this.cache.set(t,{hash:c,html:o,generatedAt:Date.now(),dependencies:n})}}class ht{cacheDir;constructor(t){this.cacheDir=t}getFilePath(t){let r=t.replace(/[^a-zA-Z0-9]/g,"_")+".json";return f.join(this.cacheDir,"isr",r)}async get(t){let r=this.getFilePath(t);if(!await Bun.file(r).exists())return null;try{return JSON.parse(await Bun.file(r).text())}catch{return null}}async set(t,r){let n=this.getFilePath(t);await D.promises.mkdir(f.dirname(n),{recursive:!0}),await Bun.write(n,JSON.stringify(r))}async invalidate(t){let r=this.getFilePath(t);if(await Bun.file(r).exists())await D.promises.unlink(r)}async invalidatePattern(t){let r=f.join(this.cacheDir,"isr");if(!D.existsSync(r))return;let n=await D.promises.readdir(r);for(let o of n){let c=o.replace(/_/g,"/").replace(".json","");if(t.test(c))await D.promises.unlink(f.join(r,o))}}async needsRevalidation(t){let r=await this.get(t);if(!r)return!0;return Date.now()>r.revalidateAfter}}async function Ut(t){let r=[];if(!t.isDynamic)r.push({url:t.pattern,params:{}});else{let n=await gt(t.filePath);if(n.kind==="error")throw Error(`getStaticPaths ${n.phase} failed for ${t.pattern} (${t.filePath}): ${n.error.message}`,{cause:n.error});if(n.kind==="absent")return console.warn(`Warning: Dynamic route ${t.pattern} (${t.filePath}) has no getStaticPaths`),r;let o=n.value;if(o.paths.length===0)return console.info(`getStaticPaths returned no paths for dynamic route ${t.pattern} (${t.filePath})`),r;for(let c of o.paths){let e=t.pattern;for(let[u,g]of Object.entries(c.params))e=e.replace(`:${u}`,g).replace(`:${u}*`,g);r.push({url:e,params:c.params,props:c.props,revalidate:c.revalidate})}}return r}function ft(t){return[t.replace(/\.stx$/,".data.ts"),t.replace(/\.stx$/,".data.js"),t+".data.ts",t+".data.js"]}async function Mt(t){for(let r of ft(t))if(await Bun.file(r).exists())try{let n=await import(r);if(typeof n.default==="function")return await n.default();else if(typeof n.default==="object")return n.default;else if(typeof n.getData==="function")return await n.getData();else{let{default:o,...c}=n;return c}}catch(n){console.error(`Error loading data file ${r}:`,n)}return null}async function Gt(t,r,n){let o=t.match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return null;let c=o[1];if(!c.includes("getStaticProps"))return null;try{let e=c.match(/(?:export\s+)?(?:async\s+)?function\s+getStaticProps\s*\([^)]*\)\s*\{([\s\S]*?)\n\}/);if(!e)return null;return await Function("params",`
4
4
  return (async function getStaticProps() {
5
5
  ${e[1]}
6
6
  })()
@@ -37,7 +37,7 @@ ${t.map((o)=>{let c=new URL(o.loc,r).href,e=` <url>
37
37
  ${n.join(`
38
38
  `)}
39
39
  </channel>
40
- </rss>`}async function Kt(t={}){let r=Date.now();Qt();let n=await a(process.cwd()),o=n.build||{},c=await ut({explicit:t.domain||o.domain,stxConfig:n});if(c.source==="fallback"&&(t.sitemap??o.sitemap??!0))console.warn(dt());let e={router:t.router??n?.router??{},pagesDir:t.pagesDir||o.pagesDir||"pages",outputDir:t.outputDir||o.outputDir||"dist",baseUrl:t.baseUrl||o.baseUrl||"/",domain:c.url,revalidate:t.revalidate??o.revalidate??!1,sitemap:t.sitemap??o.sitemap??!0,sitemapExclude:t.sitemapExclude||o.sitemapExclude||[],robots:t.robots??o.robots??!0,rss:t.rss??o.rss??!1,concurrency:t.concurrency||o.concurrency||10,cache:t.cache??o.cache??!0,cacheDir:t.cacheDir||o.cacheDir||l(process.cwd(),"ssg-cache"),contentLoaders:t.contentLoaders||[],hooks:t.hooks||{},minify:t.minify??o.minify??!0,generate404:t.generate404??o.generate404??!0,publicDir:t.publicDir||o.publicDir||"public",trailingSlash:t.trailingSlash??o.trailingSlash??!1,cleanOutput:t.cleanOutput??o.cleanOutput??!0,cacheSalt:t.cacheSalt??"",partialsDir:t.partialsDir||n?.partialsDir||"",componentsDir:t.componentsDir||n?.componentsDir||"",failOnIncludeError:t.failOnIncludeError??!0,failOnServerScriptError:t.failOnServerScriptError??!0,chunkIslands:t.chunkIslands===!0,prefetchIslands:t.prefetchIslands===!0,integrityIslands:t.integrityIslands===!0},u={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},g=new Set,v=0,w={},p={};await e.hooks.onBuildStart?.();try{if(e.cleanOutput&&D.existsSync(e.outputDir))await D.promises.rm(e.outputDir,{recursive:!0});await D.promises.mkdir(e.outputDir,{recursive:!0});let E=e.cacheSalt;if(!E){let{resolveUserCssConfig:d,fingerprintConfig:m}=await import("./chunk-yazqtmq4.js");try{E=m(await d(process.cwd()))}catch{}}let{prepareImageDelivery:x}=await import("./chunk-x6cmj5sa.js"),R=await x(e.publicDir,e.outputDir);if(R.count>0)console.log(`Optimized ${R.count} image(s) for responsive delivery`),E=[E,R.fingerprint].filter(Boolean).join(":");let T=new pt(e.cacheDir,E);if(e.cache)await T.load();try{let{generateCss:d}=await import("./chunk-yazqtmq4.js");await d('<div class="bg-black"></div>')}catch{}xt();let yt=n?.routeMiddleware?.dir||"middleware";await kt(process.cwd(),yt);let V=St();if(V.length>0)console.log(`Loaded ${V.length} middleware: ${V.join(", ")}`);let bt=n?.routeMiddleware?.global||[];Va(n?.layoutsDir,l(process.cwd()));let Z=G(".",{pagesDir:e.pagesDir,pagesDirs:n?._layerPageDirs});console.log(`Found ${Z.length} routes`);let M=[];for(let d of Z)try{let m=await Ut(d);for(let k of m)M.push({route:d,url:k.url,params:k.params,props:k.props,revalidate:k.revalidate??e.revalidate})}catch(m){let k=m instanceof Error?m:Error(String(m));u.failedCount++,u.errors.push({route:d.pattern,error:k}),await e.hooks.onError?.(k,d.pattern),console.error(`Error discovering paths for ${d.pattern}:`,k)}u.totalPages=M.length+u.failedCount,console.log(`Generating ${M.length} pages...`);let _=[],Q=[];for(let d=0;d<M.length;d+=e.concurrency)Q.push(M.slice(d,d+e.concurrency));for(let d of Q)await Promise.all(d.map(async(m)=>{let{route:k,url:h,params:N,props:vt,revalidate:rt}=m;try{await e.hooks.onPageStart?.(h);let A=await Bun.file(k.filePath).text(),O=ee(A),Pt=O?.middleware?Array.isArray(O.middleware)?O.middleware:[O.middleware]:[],nt=[...bt,...Pt];if(nt.length>0){let B=_t(h,N,O||{}),L=Ct(B,null,void 0,{isServer:!0}),j=await Et(nt,L);if(j.redirect){let C=typeof j.redirect==="string"?j.redirect:j.redirect.path||j.redirect,z=re(String(C),h),U=ne(h,e);await D.promises.mkdir(f.dirname(U),{recursive:!0}),await Bun.write(U,z),u.successCount++,u.pages.push({route:h,outputPath:U,size:Buffer.byteLength(z),cached:!1}),_.push({loc:h,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${h} \u2192 redirect to ${C}`);return}if(j.abort){let C=typeof j.abort==="string"?j.abort:j.abort?.error?.message||"aborted";console.warn(` \u21B3 ${h} \u2014 middleware aborted: ${C}`);return}}let it=A.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(it)try{if(!await Function("route",`
40
+ </rss>`}async function Kt(t={}){let r=Date.now();Qt();let n=await a(process.cwd()),o=n.build||{},c=await ut({explicit:t.domain||o.domain,stxConfig:n});if(c.source==="fallback"&&(t.sitemap??o.sitemap??!0))console.warn(dt());let e={router:t.router??n?.router??{},pagesDir:t.pagesDir||o.pagesDir||"pages",outputDir:t.outputDir||o.outputDir||"dist",baseUrl:t.baseUrl||o.baseUrl||"/",domain:c.url,revalidate:t.revalidate??o.revalidate??!1,sitemap:t.sitemap??o.sitemap??!0,sitemapExclude:t.sitemapExclude||o.sitemapExclude||[],robots:t.robots??o.robots??!0,rss:t.rss??o.rss??!1,concurrency:t.concurrency||o.concurrency||10,cache:t.cache??o.cache??!0,cacheDir:t.cacheDir||o.cacheDir||l(process.cwd(),"ssg-cache"),contentLoaders:t.contentLoaders||[],hooks:t.hooks||{},minify:t.minify??o.minify??!0,generate404:t.generate404??o.generate404??!0,publicDir:t.publicDir||o.publicDir||"public",trailingSlash:t.trailingSlash??o.trailingSlash??!1,cleanOutput:t.cleanOutput??o.cleanOutput??!0,cacheSalt:t.cacheSalt??"",partialsDir:t.partialsDir||n?.partialsDir||"",componentsDir:t.componentsDir||n?.componentsDir||"",failOnIncludeError:t.failOnIncludeError??!0,failOnServerScriptError:t.failOnServerScriptError??!0,chunkIslands:t.chunkIslands===!0,prefetchIslands:t.prefetchIslands===!0,integrityIslands:t.integrityIslands===!0},u={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},g=new Set,v=0,w={},p={};await e.hooks.onBuildStart?.();try{if(e.cleanOutput&&D.existsSync(e.outputDir))await D.promises.rm(e.outputDir,{recursive:!0});await D.promises.mkdir(e.outputDir,{recursive:!0});let E=e.cacheSalt;if(!E){let{resolveUserCssConfig:d,fingerprintConfig:m}=await import("./chunk-davr7z73.js");try{E=m(await d(process.cwd()))}catch{}}let{prepareImageDelivery:x}=await import("./chunk-6xt3kvq1.js"),R=await x(e.publicDir,e.outputDir);if(R.count>0)console.log(`Optimized ${R.count} image(s) for responsive delivery`),E=[E,R.fingerprint].filter(Boolean).join(":");let T=new pt(e.cacheDir,E);if(e.cache)await T.load();try{let{generateCss:d}=await import("./chunk-davr7z73.js");await d('<div class="bg-black"></div>')}catch{}xt();let yt=n?.routeMiddleware?.dir||"middleware";await kt(process.cwd(),yt);let V=St();if(V.length>0)console.log(`Loaded ${V.length} middleware: ${V.join(", ")}`);let bt=n?.routeMiddleware?.global||[];Ka(n?.layoutsDir,l(process.cwd()));let Z=G(".",{pagesDir:e.pagesDir,pagesDirs:n?._layerPageDirs});console.log(`Found ${Z.length} routes`);let M=[];for(let d of Z)try{let m=await Ut(d);for(let k of m)M.push({route:d,url:k.url,params:k.params,props:k.props,revalidate:k.revalidate??e.revalidate})}catch(m){let k=m instanceof Error?m:Error(String(m));u.failedCount++,u.errors.push({route:d.pattern,error:k}),await e.hooks.onError?.(k,d.pattern),console.error(`Error discovering paths for ${d.pattern}:`,k)}u.totalPages=M.length+u.failedCount,console.log(`Generating ${M.length} pages...`);let _=[],Q=[];for(let d=0;d<M.length;d+=e.concurrency)Q.push(M.slice(d,d+e.concurrency));for(let d of Q)await Promise.all(d.map(async(m)=>{let{route:k,url:h,params:N,props:vt,revalidate:rt}=m;try{await e.hooks.onPageStart?.(h);let A=await Bun.file(k.filePath).text(),O=ee(A),Pt=O?.middleware?Array.isArray(O.middleware)?O.middleware:[O.middleware]:[],nt=[...bt,...Pt];if(nt.length>0){let B=_t(h,N,O||{}),L=Ct(B,null,void 0,{isServer:!0}),j=await Et(nt,L);if(j.redirect){let C=typeof j.redirect==="string"?j.redirect:j.redirect.path||j.redirect,z=re(String(C),h),U=ne(h,e);await D.promises.mkdir(f.dirname(U),{recursive:!0}),await Bun.write(U,z),u.successCount++,u.pages.push({route:h,outputPath:U,size:Buffer.byteLength(z),cached:!1}),_.push({loc:h,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${h} \u2192 redirect to ${C}`);return}if(j.abort){let C=typeof j.abort==="string"?j.abort:j.abort?.error?.message||"aborted";console.warn(` \u21B3 ${h} \u2014 middleware aborted: ${C}`);return}}let it=A.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(it)try{if(!await Function("route",`
41
41
  const validate = ${it[1]};
42
42
  return validate(route);
43
43
  `)({params:N})){console.warn(`Validation failed for ${h}, skipping...`);return}}catch{}let I=null,st=!1;if(e.cache){if(I=T.get(h,k.filePath),I)st=!0,u.cachedCount++}if(!I){let B=await wt(k,N,vt,e,n);if(I=B.html,e.failOnIncludeError&&B.includeFailures.length>0)throw Error(`${B.includeFailures.length} include(s) failed to resolve, so this page would have shipped with an error banner where the markup should be:
@@ -69,7 +69,7 @@ ${d}`)}if(e.cache)await T.save();if(e.generate404){let d=f.join(e.pagesDir,"404.
69
69
  <a href="/">Go home</a>
70
70
  </div>
71
71
  </body>
72
- </html>`)}for(let d of[500]){let m=f.join(e.pagesDir,`${d}.stx`);if(await Bun.file(m).exists()){let k=new Set,h={...n,minifyClient:!0,debug:!1,cache:!1},N=await i(await Bun.file(m).text(),{},m,h,k);await Bun.write(f.join(e.outputDir,`${d}.html`),N)}}let K=f.join(e.pagesDir,"error.stx");if(await Bun.file(K).exists()){let d=new Set,m={...n,minifyClient:!0,debug:!1,cache:!1},k=await i(await Bun.file(K).text(),{},K,m,d);await Bun.write(f.join(e.outputDir,"error.html"),k)}if(e.sitemap&&_.length>0){let d=qt(_,e.domain),m=f.join(e.outputDir,"sitemap.xml");await Bun.write(m,d),u.sitemapPath=m,console.log(`Generated sitemap.xml with ${_.length} URLs`)}if(e.robots!==!1){let d=typeof e.robots==="object"?e.robots:{},m=[...e.sitemapExclude.filter((h)=>typeof h==="string"),...d.disallow||[]],k=bs({rules:[{userAgent:d.userAgent||"*",allow:d.allow||["/"],...m.length>0?{disallow:m}:{}}],...d.sitemap!==!1&&u.sitemapPath?{sitemap:new URL("/sitemap.xml",e.domain).href}:{}});await Bun.write(f.join(e.outputDir,"robots.txt"),k),console.log("Generated robots.txt")}if(e.rss){let d=typeof e.rss==="object"?e.rss:{title:"Site Feed",description:"Latest updates",link:e.domain},m=[];if(d.getItems)m=await d.getItems();let k=Vt(d,m),h=f.join(e.outputDir,"rss.xml");await Bun.write(h,k),u.rssPath=h,console.log(`Generated rss.xml with ${m.length} items`)}let W=za(e.outputDir);if(W.assets>0)console.log(`Externalized ${W.assets} asset(s) from ${W.pages} page(s) (${(W.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);let q=Ha(e.outputDir);if(q.assets>0)console.log(`Externalized ${q.assets} repeated asset(s) from ${q.pages} page(s) (${(q.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);if(e.publicDir&&D.existsSync(e.publicDir))await Y(e.publicDir,e.outputDir),console.log(`Copied public assets from ${e.publicDir}`);let et=Jn();if(et)await Y(et,f.join(e.outputDir,Xn)),console.log(`Copied assets from ${Jt}`)}catch(E){throw await e.hooks.onError?.(E),E}if(u.buildTime=Date.now()-r,g.size>0){u.islandChunks={count:g.size,totalBytes:v};let E={generatedChunks:g.size,totalBytes:v,chunks:w,pages:p};await Bun.write(f.join(e.outputDir,"_stx","islands-manifest.json"),JSON.stringify(E,null,2))}await e.hooks.onBuildEnd?.(u);let P=u.islandChunks?`
72
+ </html>`)}for(let d of[500]){let m=f.join(e.pagesDir,`${d}.stx`);if(await Bun.file(m).exists()){let k=new Set,h={...n,minifyClient:!0,debug:!1,cache:!1},N=await i(await Bun.file(m).text(),{},m,h,k);await Bun.write(f.join(e.outputDir,`${d}.html`),N)}}let K=f.join(e.pagesDir,"error.stx");if(await Bun.file(K).exists()){let d=new Set,m={...n,minifyClient:!0,debug:!1,cache:!1},k=await i(await Bun.file(K).text(),{},K,m,d);await Bun.write(f.join(e.outputDir,"error.html"),k)}if(e.sitemap&&_.length>0){let d=qt(_,e.domain),m=f.join(e.outputDir,"sitemap.xml");await Bun.write(m,d),u.sitemapPath=m,console.log(`Generated sitemap.xml with ${_.length} URLs`)}if(e.robots!==!1){let d=typeof e.robots==="object"?e.robots:{},m=[...e.sitemapExclude.filter((h)=>typeof h==="string"),...d.disallow||[]],k=ws({rules:[{userAgent:d.userAgent||"*",allow:d.allow||["/"],...m.length>0?{disallow:m}:{}}],...d.sitemap!==!1&&u.sitemapPath?{sitemap:new URL("/sitemap.xml",e.domain).href}:{}});await Bun.write(f.join(e.outputDir,"robots.txt"),k),console.log("Generated robots.txt")}if(e.rss){let d=typeof e.rss==="object"?e.rss:{title:"Site Feed",description:"Latest updates",link:e.domain},m=[];if(d.getItems)m=await d.getItems();let k=Vt(d,m),h=f.join(e.outputDir,"rss.xml");await Bun.write(h,k),u.rssPath=h,console.log(`Generated rss.xml with ${m.length} items`)}let W=Wa(e.outputDir);if(W.assets>0)console.log(`Externalized ${W.assets} asset(s) from ${W.pages} page(s) (${(W.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);let q=qa(e.outputDir);if(q.assets>0)console.log(`Externalized ${q.assets} repeated asset(s) from ${q.pages} page(s) (${(q.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);if(e.publicDir&&D.existsSync(e.publicDir))await Y(e.publicDir,e.outputDir),console.log(`Copied public assets from ${e.publicDir}`);let et=Jn();if(et)await Y(et,f.join(e.outputDir,Xn)),console.log(`Copied assets from ${Jt}`)}catch(E){throw await e.hooks.onError?.(E),E}if(u.buildTime=Date.now()-r,g.size>0){u.islandChunks={count:g.size,totalBytes:v};let E={generatedChunks:g.size,totalBytes:v,chunks:w,pages:p};await Bun.write(f.join(e.outputDir,"_stx","islands-manifest.json"),JSON.stringify(E,null,2))}await e.hooks.onBuildEnd?.(u);let P=u.islandChunks?`
73
73
  Island chunks: ${u.islandChunks.count} (${(u.islandChunks.totalBytes/1024).toFixed(1)} KB lifted out of inline HTML)`:"";return console.log(`
74
74
  Build complete!
75
75
  Total: ${u.totalPages} pages
@@ -1,4 +1,27 @@
1
1
  export declare function getStoreScript(storesDir?: string): Promise<string | null>;
2
+ /**
3
+ * Every store a piece of code reads by name: `useStore("auth")`.
4
+ *
5
+ * `all` is set when it cannot tell: a call whose name is not a literal, or a
6
+ * look into the registry itself. Such code may read any store.
7
+ */
8
+ export declare function storesRead(...sources: Array<string | null | undefined>): { names: Set<string>, all: boolean };
9
+ /**
10
+ * The store script for code that reads only some of the stores: those it names
11
+ * with `useStore("…")`, and those the stores it names read in turn. A page
12
+ * that loads every store defines thirty of them (HQ's phone screens: ~140 KB of
13
+ * every route), each running its setup, for one or two it uses.
14
+ *
15
+ * `usedBy` is all the code that will run beside the stores (the page's
16
+ * scripts, its modules). With code that may read any store, or a store file
17
+ * whose ids cannot be read, every store is kept. `stores` names the files
18
+ * kept, for the caller to rebuild what depends on them.
19
+ *
20
+ * `sharedModules`: the stores' imports are left to the page's module registry
21
+ * (what production does) instead of inlined in each store. Defaults to
22
+ * production's.
23
+ */
24
+ export declare function getStoreScriptFor(storesDir: string | undefined, usedBy: Array<string | null | undefined>, options?: { sharedModules?: boolean }): Promise<{ code: string, stores: string[] } | null>;
2
25
  /**
3
26
  * Clear the cached store script (for dev mode hot reload).
4
27
  */