@stacksjs/stx 0.2.814 → 0.2.816

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 (143) hide show
  1. package/dist/{chunk-4rny8rf5.js → chunk-0h99mrb0.js} +3 -3
  2. package/dist/chunk-0j8qrqke.js +2 -0
  3. package/dist/chunk-0yjm4j26.js +2 -0
  4. package/dist/{chunk-kvz01wzc.js → chunk-17wb2x3z.js} +2 -2
  5. package/dist/{chunk-bmkm1c8s.js → chunk-1bgv727x.js} +37 -5
  6. package/dist/{chunk-3efaf8v0.js → chunk-24354nk5.js} +2 -2
  7. package/dist/{chunk-he9zzsh4.js → chunk-2v7qvj69.js} +2 -2
  8. package/dist/{chunk-33x11khy.js → chunk-314zqrv0.js} +1 -1
  9. package/dist/{chunk-w5xq1217.js → chunk-3jd5ak8h.js} +1 -1
  10. package/dist/chunk-45gv3akm.js +2 -0
  11. package/dist/{chunk-9bt479pb.js → chunk-4vxbcf4a.js} +2 -2
  12. package/dist/{chunk-et8n16k2.js → chunk-4ypwqrj2.js} +1 -1
  13. package/dist/chunk-5b6tsg13.js +2 -0
  14. package/dist/{chunk-cfbpvm5e.js → chunk-5efv1fhk.js} +2 -2
  15. package/dist/{chunk-ethnqap6.js → chunk-5wcgqr21.js} +7 -7
  16. package/dist/{chunk-k86573fe.js → chunk-6cw072n5.js} +1 -1
  17. package/dist/{chunk-v0kn4q29.js → chunk-7bfsvkvd.js} +6 -6
  18. package/dist/{chunk-7aqdqfwf.js → chunk-7r5efkbz.js} +1 -1
  19. package/dist/{chunk-gebb12ak.js → chunk-7rk7wfm6.js} +6 -6
  20. package/dist/{chunk-ayq07qrz.js → chunk-8ca33v3s.js} +1 -1
  21. package/dist/{chunk-ewzdsksb.js → chunk-8g8h2xwz.js} +1 -1
  22. package/dist/{chunk-bejj0gra.js → chunk-8h3jv8dd.js} +1 -1
  23. package/dist/chunk-956zq9b7.js +2 -0
  24. package/dist/{chunk-t4j2rw91.js → chunk-981z8va1.js} +2 -2
  25. package/dist/{chunk-aqnfzse9.js → chunk-9avsdbz5.js} +2 -2
  26. package/dist/{chunk-ajg7tvn1.js → chunk-9d79afs9.js} +6 -6
  27. package/dist/{chunk-kf96nks9.js → chunk-9mnr9x0d.js} +2 -2
  28. package/dist/{chunk-qckgv0vz.js → chunk-9mtw71xy.js} +1 -1
  29. package/dist/{chunk-5za58geh.js → chunk-9t9qf38k.js} +20 -20
  30. package/dist/chunk-9yc4fw7e.js +2 -0
  31. package/dist/{chunk-x2hc3zth.js → chunk-a350jjd3.js} +1 -1
  32. package/dist/chunk-ar7w1kx0.js +2 -0
  33. package/dist/{chunk-hvdmhzad.js → chunk-atdn8n6b.js} +7 -7
  34. package/dist/{chunk-nsph6c12.js → chunk-azg5e5ts.js} +5 -5
  35. package/dist/chunk-b7vfs0cq.js +2 -0
  36. package/dist/{chunk-pr6nrg6x.js → chunk-b9ntt41z.js} +1 -1
  37. package/dist/{chunk-vyad54bv.js → chunk-be2stv5x.js} +1 -1
  38. package/dist/{chunk-x94q5ptn.js → chunk-bxtwbkc1.js} +1 -1
  39. package/dist/{chunk-9jdqxsna.js → chunk-c6w39fdb.js} +4 -4
  40. package/dist/chunk-c8vhjxm9.js +2 -0
  41. package/dist/{chunk-m5q50ct0.js → chunk-d3d5s0va.js} +1 -1
  42. package/dist/{chunk-49r48cjj.js → chunk-e2855m6w.js} +1 -1
  43. package/dist/{chunk-8zexecar.js → chunk-e58g2n9k.js} +1 -1
  44. package/dist/{chunk-1carv1dw.js → chunk-f54t0qar.js} +1 -1
  45. package/dist/{chunk-v6p8tf1x.js → chunk-f8zs50z0.js} +1 -1
  46. package/dist/{chunk-0dm38zt6.js → chunk-g74r0edp.js} +3 -3
  47. package/dist/chunk-geyvz4ae.js +2 -0
  48. package/dist/chunk-gqe0hnbb.js +2 -0
  49. package/dist/{chunk-1d6ef8g9.js → chunk-h5c786jf.js} +20 -20
  50. package/dist/{chunk-3z0e637x.js → chunk-jg9f5nqf.js} +5 -5
  51. package/dist/chunk-jham85mf.js +2 -0
  52. package/dist/{chunk-b682cfc9.js → chunk-jrjd02kf.js} +4 -4
  53. package/dist/{chunk-vgpnjrq4.js → chunk-k4xkbk2z.js} +1 -1
  54. package/dist/{chunk-qfqv3fjm.js → chunk-kq40yvdh.js} +1 -1
  55. package/dist/{chunk-dvbd5fxe.js → chunk-kvhsdyfg.js} +1 -1
  56. package/dist/{chunk-y7sf7aj0.js → chunk-m0x96g8e.js} +1 -1
  57. package/dist/{chunk-cbx7qght.js → chunk-mkr46mzz.js} +1 -1
  58. package/dist/{chunk-ycr9bkww.js → chunk-mmyrdbxx.js} +1 -1
  59. package/dist/{chunk-ybjfr7e8.js → chunk-n761hp6d.js} +2 -2
  60. package/dist/chunk-nctnc7tn.js +2 -0
  61. package/dist/{chunk-cxsxb3bc.js → chunk-nkb214z1.js} +8 -8
  62. package/dist/{chunk-rx5ak659.js → chunk-nqcqench.js} +102 -101
  63. package/dist/chunk-nr58sedd.js +2 -0
  64. package/dist/{chunk-bfm5cedw.js → chunk-ntn6bnjv.js} +2 -2
  65. package/dist/{chunk-p0qf405e.js → chunk-p0fp7p7x.js} +1 -1
  66. package/dist/chunk-p7tg362f.js +2 -0
  67. package/dist/{chunk-91re9xtj.js → chunk-pkjza0vv.js} +3 -3
  68. package/dist/{chunk-3pz8yag9.js → chunk-ps3t15gp.js} +1 -1
  69. package/dist/{chunk-mmh2k7ab.js → chunk-pyytr30r.js} +5 -5
  70. package/dist/chunk-qffx1nqg.js +2 -0
  71. package/dist/chunk-qn6y53v0.js +2 -0
  72. package/dist/chunk-qyxr6kq1.js +20 -0
  73. package/dist/{chunk-jj5b4h6f.js → chunk-qz8bz1f2.js} +1 -1
  74. package/dist/chunk-r4kdwpbh.js +2 -0
  75. package/dist/{chunk-r1vkk7qp.js → chunk-r5nt1bcx.js} +1 -1
  76. package/dist/{chunk-3ec6jf9b.js → chunk-r6dtrd7y.js} +3 -3
  77. package/dist/chunk-sj4vw93g.js +2 -0
  78. package/dist/chunk-spgf7r7h.js +2 -0
  79. package/dist/chunk-sxhya0hd.js +2 -0
  80. package/dist/{chunk-vbc8a8fh.js → chunk-t2sg2tp2.js} +2 -2
  81. package/dist/chunk-tnjzhbkc.js +2 -0
  82. package/dist/{chunk-vshskj73.js → chunk-tvc5n28s.js} +1 -1
  83. package/dist/chunk-veh49fc5.js +2 -0
  84. package/dist/chunk-vft84x6s.js +2 -0
  85. package/dist/{chunk-fzzfy1yh.js → chunk-vn6jxchy.js} +1 -1
  86. package/dist/chunk-wbkca2se.js +2 -0
  87. package/dist/{chunk-ta1yzmz8.js → chunk-wbzgtf5c.js} +1 -1
  88. package/dist/{chunk-46vd0375.js → chunk-wrygfmhf.js} +1 -1
  89. package/dist/{chunk-86vcmh2x.js → chunk-x6fpj9hh.js} +1 -1
  90. package/dist/{chunk-dcc0ejtd.js → chunk-y4xcym3k.js} +2 -2
  91. package/dist/{chunk-gb3tv53p.js → chunk-yts2b9d8.js} +2 -2
  92. package/dist/{chunk-40zwjmta.js → chunk-z87g05z5.js} +1 -1
  93. package/dist/{chunk-p6g80v4p.js → chunk-zcb34wfr.js} +1 -1
  94. package/dist/chunk-zjw5gm1n.js +2 -0
  95. package/dist/chunk-zkzp1ckd.js +3 -0
  96. package/dist/cli.js +12 -12
  97. package/dist/component-resolution.d.ts +33 -0
  98. package/dist/component-resolution.js +30 -0
  99. package/dist/craft-entry.js +2 -2
  100. package/dist/craft.js +2 -2
  101. package/dist/media/client/upload-fetch.d.ts +6 -0
  102. package/dist/media/client/upload-fetch.js +62 -0
  103. package/dist/native/bridge/protocol.d.ts +2 -1
  104. package/dist/native/bridge/protocol.js +27 -4
  105. package/dist/native/runtime/craft-bridge.js +29 -7
  106. package/dist/native/runtime/craft.d.ts +1 -0
  107. package/dist/pwa.js +1 -1
  108. package/dist/runtime-injection.js +2 -0
  109. package/dist/ssg.js +4 -4
  110. package/dist/stx-virtual-ts.d.ts +26 -5
  111. package/dist/stx-virtual-ts.js +67 -11
  112. package/dist/typecheck.js +6 -4
  113. package/dist/types/config-types.d.ts +1 -0
  114. package/dist/utils.js +6 -3
  115. package/package.json +5 -5
  116. package/dist/chunk-0gf0ny6y.js +0 -2
  117. package/dist/chunk-1ydz2w3t.js +0 -2
  118. package/dist/chunk-2a4dhkdw.js +0 -2
  119. package/dist/chunk-2m60sqvs.js +0 -2
  120. package/dist/chunk-526n626z.js +0 -2
  121. package/dist/chunk-54w0epxq.js +0 -2
  122. package/dist/chunk-6dcc4ezx.js +0 -2
  123. package/dist/chunk-7kj3g9bx.js +0 -2
  124. package/dist/chunk-85w7kf2j.js +0 -2
  125. package/dist/chunk-88ftnhm9.js +0 -2
  126. package/dist/chunk-9107scv6.js +0 -2
  127. package/dist/chunk-9fhgy5y5.js +0 -2
  128. package/dist/chunk-9gyy6z1d.js +0 -2
  129. package/dist/chunk-bkq60hpn.js +0 -2
  130. package/dist/chunk-e8zf4fqg.js +0 -2
  131. package/dist/chunk-h7257fsm.js +0 -2
  132. package/dist/chunk-hhahbv6g.js +0 -2
  133. package/dist/chunk-jt6k606s.js +0 -2
  134. package/dist/chunk-mmy3h4ye.js +0 -2
  135. package/dist/chunk-nq8bw7cm.js +0 -2
  136. package/dist/chunk-nz0cgrt9.js +0 -2
  137. package/dist/chunk-pjv91e8z.js +0 -20
  138. package/dist/chunk-pnbh9fgm.js +0 -2
  139. package/dist/chunk-qsepyy1p.js +0 -2
  140. package/dist/chunk-skjwswd8.js +0 -3
  141. package/dist/chunk-tdcgskyy.js +0 -2
  142. package/dist/chunk-w717cyka.js +0 -2
  143. package/dist/chunk-z27n1z4f.js +0 -2
@@ -0,0 +1,62 @@
1
+ function cancelled(signal) {
2
+ if (signal?.reason instanceof Error)
3
+ return signal.reason;
4
+ return typeof DOMException === "function" ? new DOMException("The upload was aborted", "AbortError") : Object.assign(Error("The upload was aborted"), { name: "AbortError" });
5
+ }
6
+ export function uploadFetch(url, init = {}) {
7
+ if (init.signal?.aborted)
8
+ return Promise.reject(cancelled(init.signal));
9
+ if (!init.onUploadProgress || typeof XMLHttpRequest > "u")
10
+ return fetch(url, init);
11
+ return new Promise((resolve, reject) => {
12
+ const xhr = new XMLHttpRequest;
13
+ let settled = !1;
14
+ const finish = (error) => {
15
+ if (settled)
16
+ return;
17
+ settled = !0;
18
+ init.signal?.removeEventListener("abort", abort);
19
+ if (error) {
20
+ reject(error);
21
+ return;
22
+ }
23
+ try {
24
+ if (xhr.status < 100 || xhr.status > 599)
25
+ throw TypeError("Upload received no HTTP response");
26
+ const headers = new Headers;
27
+ for (const line of xhr.getAllResponseHeaders().trim().split(/[\r\n]+/)) {
28
+ const colon = line.indexOf(":");
29
+ if (colon > 0)
30
+ headers.append(line.slice(0, colon).trim(), line.slice(colon + 1).trim());
31
+ }
32
+ resolve(new Response(xhr.status === 204 || xhr.status === 304 ? null : xhr.responseText, { status: xhr.status, statusText: xhr.statusText, headers }));
33
+ } catch (cause) {
34
+ reject(cause);
35
+ }
36
+ }, abort = () => {
37
+ xhr.abort();
38
+ finish(cancelled(init.signal));
39
+ };
40
+ xhr.open(init.method || "POST", url, !0);
41
+ xhr.timeout = init.timeoutMs ?? 600000;
42
+ xhr.withCredentials = init.credentials === "include";
43
+ new Headers(init.headers).forEach((value, name) => xhr.setRequestHeader(name, value));
44
+ xhr.upload.onprogress = (event) => {
45
+ if (settled || !event.lengthComputable || event.total <= 0)
46
+ return;
47
+ try {
48
+ init.onUploadProgress?.({ loaded: event.loaded, total: event.total });
49
+ } catch {}
50
+ };
51
+ xhr.onload = () => finish();
52
+ xhr.onerror = () => finish(TypeError("Upload network request failed"));
53
+ xhr.ontimeout = () => finish(Object.assign(Error("Upload timed out"), { name: "TimeoutError" }));
54
+ xhr.onabort = () => finish(cancelled(init.signal));
55
+ init.signal?.addEventListener("abort", abort, { once: !0 });
56
+ try {
57
+ xhr.send(init.body);
58
+ } catch (error) {
59
+ finish(error instanceof Error ? error : Error(String(error)));
60
+ }
61
+ });
62
+ }
@@ -300,6 +300,7 @@ export type BridgeMessageType = | 'RENDER' // Render a new componen
300
300
  | 'PUSH_TOKEN' // A new push device token
301
301
  | 'SOUND_EVENT' // A craft.audio sound ended or failed
302
302
  | 'NETWORK_STREAM' // A piece, the end or the failure of a streaming fetch
303
+ | 'NETWORK_UPLOAD_PROGRESS' // Bytes sent by the screen's own upload task
303
304
  | 'CRAFT_EVENT' // A host event in the page's name (craftLocationUpdate)
304
305
  | 'MEMORY_WARNING' // Low memory warning
305
306
 
@@ -342,7 +343,7 @@ export declare class NativeCapabilityError extends Error {
342
343
  export declare class STXBridge {
343
344
  initialize(nativeBridge: NativeBridgeInterface): void;
344
345
  send<T>(type: BridgeMessageType, payload: T): string;
345
- request<T, R>(type: BridgeMessageType, payload: T, timeout?: number | null): Promise<R>;
346
+ request<T, R>(type: BridgeMessageType, payload: T, timeout?: number | null, signal?: AbortSignal): Promise<R>;
346
347
  on<T>(type: BridgeMessageType, handler: MessageHandler<T>): () => void;
347
348
  once<T>(type: BridgeMessageType, handler: MessageHandler<T>): () => void;
348
349
  dispose(reason?: ApiCancelPayload['reason']): void;
@@ -32,11 +32,27 @@ export class STXBridge {
32
32
  this.postToNative(message);
33
33
  return message.id;
34
34
  }
35
- async request(type, payload, timeout = this.defaultTimeout) {
35
+ async request(type, payload, timeout = this.defaultTimeout, signal) {
36
36
  const message = this.createMessage(type, payload);
37
37
  return new Promise((resolve, reject) => {
38
- const scheduleTimeout = timeout !== null && typeof globalThis.setTimeout === "function" ? globalThis.setTimeout.bind(globalThis) : null, timeoutId = scheduleTimeout && timeout !== null ? scheduleTimeout(() => {
38
+ if (signal?.aborted) {
39
+ reject(new NativeCapabilityError("CANCELLED", "The native request was aborted"));
40
+ return;
41
+ }
42
+ const cleanup = () => signal?.removeEventListener("abort", cancel), cancel = () => {
43
+ const pending = this.pendingRequests.get(message.id);
44
+ if (!pending)
45
+ return;
46
+ this.pendingRequests.delete(message.id);
47
+ if (pending.timeout !== null)
48
+ globalThis.clearTimeout?.(pending.timeout);
49
+ if (type === "API_REQUEST")
50
+ this.postToNative(this.createMessage("API_CANCEL", { version: 1, requestId: message.id, reason: "aborted" }));
51
+ cleanup();
52
+ reject(new NativeCapabilityError("CANCELLED", "The native request was aborted"));
53
+ }, scheduleTimeout = timeout !== null && typeof globalThis.setTimeout === "function" ? globalThis.setTimeout.bind(globalThis) : null, timeoutId = scheduleTimeout && timeout !== null ? scheduleTimeout(() => {
39
54
  this.pendingRequests.delete(message.id);
55
+ cleanup();
40
56
  if (type === "API_REQUEST")
41
57
  this.postToNative(this.createMessage("API_CANCEL", {
42
58
  version: 1,
@@ -46,10 +62,17 @@ export class STXBridge {
46
62
  reject(new NativeCapabilityError("TIMEOUT", `Request ${message.id} timed out after ${timeout}ms`));
47
63
  }, timeout) : null;
48
64
  this.pendingRequests.set(message.id, {
49
- resolve,
50
- reject,
65
+ resolve: (value) => {
66
+ cleanup();
67
+ resolve(value);
68
+ },
69
+ reject: (error) => {
70
+ cleanup();
71
+ reject(error);
72
+ },
51
73
  timeout: timeoutId
52
74
  });
75
+ signal?.addEventListener("abort", cancel, { once: !0 });
53
76
  this.postToNative(message);
54
77
  });
55
78
  }
@@ -58,6 +58,7 @@ function capabilityFlags(capabilities) {
58
58
  network: capabilities.has("network"),
59
59
  deviceInfo: capabilities.has("device"),
60
60
  fetch: capabilities.has("fetch"),
61
+ uploadProgress: capabilities.has("uploadProgress"),
61
62
  badge: capabilities.has("badge"),
62
63
  wallet: capabilities.has("wallet"),
63
64
  passkeys: capabilities.has("passkeys"),
@@ -1073,7 +1074,16 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
1073
1074
  });
1074
1075
  });
1075
1076
  };
1076
- if (capabilities.has("fetch") && typeof target.fetch !== "function")
1077
+ if (capabilities.has("fetch") && typeof target.fetch !== "function") {
1078
+ const uploads = new Map;
1079
+ let nextUpload = 0;
1080
+ protocol.on("NETWORK_UPLOAD_PROGRESS", ({ payload }) => {
1081
+ if (!Number.isFinite(payload?.loaded) || !Number.isFinite(payload?.total) || payload.loaded < 0 || payload.total <= 0)
1082
+ return;
1083
+ try {
1084
+ uploads.get(payload.id)?.({ loaded: Math.min(payload.loaded, payload.total), total: payload.total });
1085
+ } catch {}
1086
+ });
1077
1087
  target.fetch = (input, init = {}) => {
1078
1088
  const source = input && typeof input === "object" ? input : {}, url = typeof input === "string" ? input : String(source.url || input), method = String(init.method || source.method || "GET").toUpperCase(), headers = {}, inputHeaders = init.headers || source.headers, addHeader = (name, value) => {
1079
1089
  headers[String(name).toLowerCase()] = String(value);
@@ -1101,9 +1111,17 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
1101
1111
  const signal = init.signal || source.signal;
1102
1112
  if (signal?.aborted)
1103
1113
  return Promise.reject(abortError(signal.reason));
1114
+ if (typeof init.onUploadProgress === "function" && !capabilities.has("uploadProgress"))
1115
+ return Promise.reject(Object.assign(Error("This app build cannot report upload progress"), { code: "UPLOAD_PROGRESS_UNSUPPORTED" }));
1104
1116
  if (streaming && !form && /text\/event-stream/i.test(headers.accept || ""))
1105
1117
  return streamingFetch(url, method, headers, body == null ? null : body, signal);
1106
- const answer = (form ? ask : request)("Network", "fetch", [{ url, method, headers, body: body == null ? null : body, ...form ? { form } : {} }]).then((data) => {
1118
+ const uploadProgressId = typeof init.onUploadProgress === "function" ? `upload-${++nextUpload}` : "";
1119
+ if (uploadProgressId)
1120
+ uploads.set(uploadProgressId, (value) => {
1121
+ if (!signal?.aborted)
1122
+ init.onUploadProgress(value);
1123
+ });
1124
+ return protocol.request("API_REQUEST", { version: 1, module: "Network", method: "fetch", args: [{ url, method, headers, body: body == null ? null : body, ...form ? { form } : {}, ...uploadProgressId ? { uploadProgressId } : {} }], ...form ? { untimed: !0 } : {} }, form ? null : void 0, signal).then((data) => {
1107
1125
  const responseBody = data?.body == null ? "" : String(data.body);
1108
1126
  let bodyUsed = !1;
1109
1127
  return response(data, { get bodyUsed() {
@@ -1114,16 +1132,20 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
1114
1132
  bodyUsed = !0;
1115
1133
  return Promise.resolve(responseBody);
1116
1134
  } });
1117
- }, networkFailure);
1118
- return signal ? Promise.race([answer, aborted(signal)]) : answer;
1135
+ }, (error) => {
1136
+ if (signal?.aborted)
1137
+ throw abortError(signal.reason);
1138
+ return networkFailure(error);
1139
+ }).finally(() => {
1140
+ if (uploadProgressId)
1141
+ uploads.delete(uploadProgressId);
1142
+ });
1119
1143
  };
1144
+ }
1120
1145
  if (streaming && typeof target.fetch === "function" && typeof target.EventSource !== "function")
1121
1146
  target.EventSource = createEventSourceClass(target);
1122
1147
  return craft;
1123
1148
  }
1124
- function aborted(signal) {
1125
- return new Promise((_, reject) => signal.addEventListener?.("abort", () => reject(abortError(signal.reason))));
1126
- }
1127
1149
  function networkFailure(error) {
1128
1150
  if (error?.code === "INVALID_ARGUMENT")
1129
1151
  throw error;
@@ -40,6 +40,7 @@ export declare interface NativeTabItemOptions {
40
40
  }
41
41
  export declare interface NativeNavigationOptions {
42
42
  title?: string
43
+ titleColor?: string | null
43
44
  largeTitle?: boolean
44
45
  hidden?: boolean
45
46
  tabBarHidden?: boolean
package/dist/pwa.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
2
  import{eo,Ht,xl,Cg}from"./chunk-0svj1nfa.js";import{Qs,Pi,Sg,kg,_g}from"./chunk-e39nkbt4.js";import{bl,wl,vl,vg,xg}from"./chunk-d47m4qat.js";import{Ue,Tn,Ii}from"./chunk-7xs45trj.js";import{Eg,Tg,$g,Rg,to,dy}from"./chunk-gqjb1y7c.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-2m60sqvs.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>
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-5b6tsg13.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">
@@ -149,6 +149,8 @@ export async function injectRouterScript(template, options) {
149
149
  configObj.prefetchVisible = routerConfig.prefetchVisible;
150
150
  if (routerConfig.prefetchVisibleMax !== void 0)
151
151
  configObj.prefetchVisibleMax = routerConfig.prefetchVisibleMax;
152
+ if (routerConfig.prefetchBudgetBytes !== void 0)
153
+ configObj.prefetchBudgetBytes = routerConfig.prefetchBudgetBytes;
152
154
  if (routerConfig.keepOpening !== void 0)
153
155
  configObj.keepOpening = routerConfig.keepOpening;
154
156
  }
package/dist/ssg.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import"./chunk-7sh9fa3q.js";import{w,nl}from"./chunk-gebb12ak.js";import"./chunk-ybjfr7e8.js";import"./chunk-r9e0r6jx.js";import{Rt,S}from"./chunk-rx5ak659.js";import"./chunk-m7hfcxt3.js";import"./chunk-qfqv3fjm.js";import"./chunk-2ws2qe1k.js";import{kt,_t,Ct,Et,Tt,$t}from"./chunk-bmkm1c8s.js";import{a}from"./chunk-hvdmhzad.js";import{Ts}from"./chunk-3z0e637x.js";import"./chunk-vbc8a8fh.js";import"./chunk-9bt479pb.js";import{he,en,tn}from"./chunk-aqnfzse9.js";import"./chunk-3efaf8v0.js";import{y}from"./chunk-he9zzsh4.js";import{yt,i}from"./chunk-1d6ef8g9.js";import"./chunk-91re9xtj.js";import"./chunk-ethnqap6.js";import{gs}from"./chunk-v0kn4q29.js";import"./chunk-0dm38zt6.js";import"./chunk-c84pxd2k.js";import{Ya,Za,Qa}from"./chunk-hwcfgs3e.js";import{Zt,Yn,Zn}from"./chunk-ndjmt3vg.js";import{Qt}from"./chunk-3pz8yag9.js";import"./chunk-skjwswd8.js";import"./chunk-y7sf7aj0.js";import{X,we}from"./chunk-ajg7tvn1.js";import"./chunk-1carv1dw.js";import"./chunk-jj5b4h6f.js";import{c}from"./chunk-0rjcbqk3.js";import{r,ge}from"./chunk-3vpgr6nk.js";import D from"fs";import f from"path";import{createHash as vt}from"crypto";function Pt(t){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(t).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return t}}var Dt=/<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,n={}){if(!t.includes('type="stx/island"'))return{html:t,chunks:[]};let s=new Map,o=t.replace(Dt,(e,u,g,v)=>{let x=v.trim();if(!x)return e;if(/\bdata-stx-src=/.test(g))return e;if(n.minify)x=Pt(x);let p=It(x);if(!s.has(p))s.set(p,x);let P=n.integrity?` data-stx-integrity="sha384-${vt("sha384").update(x).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${u}" data-stx-src="/_stx/islands/${p}.js"${P}${g}></script>`}),l=Array.from(s,([e,u])=>({hash:e,code:u}));return{html:o,chunks:l}}var Bt=new Set(["visible","idle"]);function ct(t){if(!t.includes("data-stx-src="))return t;let n=new Map,s=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,o;while((o=s.exec(t))!==null)n.set(o[1],o[2]);let l=new Set,e=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,u;while((u=e.exec(t))!==null)if(Bt.has(n.get(u[1])||""))l.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(l.size===0||v===-1)return t;let x=Array.from(l).filter((p)=>!t.includes(`rel="prefetch" href="${p}"`)).map((p)=>`<link rel="prefetch" href="${p}" as="script">`).join("");if(!x)return t;return t.slice(0,v)+x+t.slice(v)}var jt=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function K(t){let n=t.trim();if(!n)return null;let s=/^https?:\/\//i.test(n)?n:`https://${n}`;try{return new URL(s).origin+new URL(s).pathname.replace(/\/$/,"")}catch{return null}}function Ft(t){for(let n of jt){let s=t[n];if(!s)continue;let o=K(s);if(o)return{url:o,source:"env",via:n}}return null}function lt(t){if(!t||typeof t!=="object")return null;let n=t,s=n.site?.url??n.url??n.app?.url;return typeof s==="string"?K(s):null}async function At(t){let{existsSync:n}=await import("fs"),s=await import("path");for(let o of["site.config.ts","site.config.js",".config/site.config.ts"]){let l=s.resolve(t,o);if(!n(l))continue;try{let e=await import(l),u=lt(e.default??e);if(u)return u}catch{}}return null}async function ut(t={}){let n=t.cwd??process.cwd(),s=t.env??process.env;if(t.explicit){let u=K(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 l=await At(n);if(l)return{url:l,source:"site.config",via:"url"};let e=Ft(s);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 q(t){return async()=>({paths:await t(),fallback:!1})}var Ot;function Lt(t){let n=r(t),{depths:s}=ge(n),o=/\b(?:async\s+)?function\s+getStaticPaths\s*\(/g,l;while((l=o.exec(n))!==null){if(s[l.index]!==0)continue;let u=w(n,"(",")",o.lastIndex-1),g=n.indexOf("{",u+1),v=w(n,"{","}",g);if(u<0||g<0||v<0)break;return t.slice(l.index,v+1)}let e=/\b(?:const|let|var)\s+getStaticPaths\s*=/g;while((l=e.exec(n))!==null){if(s[l.index]!==0)continue;let u=nl(n,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 n="read";try{let s=await Bun.file(t).text();n="parse";let o=Qt(s),l=[...o.server,...o.client,...o.signals].filter((e)=>/(?:^|\s)server(?:\s|=|$)/i.test(r(e.attrs))).sort((e,u)=>s.indexOf(e.fullTag)-s.indexOf(u.fullTag));for(let e of l){if(!/\bgetStaticPaths\b/.test(r(e.content)))continue;let u=(Ot??=new Bun.Transpiler({loader:"ts",target:"bun"})).transformSync(e.content);if(!/\bgetStaticPaths\b/.test(r(u)))continue;let g=Lt(u);if(/\bdefineStaticPaths\b/.test(r(g))&&Rt(u,"defineStaticPaths"))throw SyntaxError("Cannot evaluate a module-local defineStaticPaths binding during isolated hook extraction");n="execute";let v=Function("defineStaticPaths",`return (${g})`)(q);if(typeof v!=="function")throw TypeError("getStaticPaths must be a function");let x=await v();n="result";let p=Array.isArray(x)?{paths:x}:x;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(s){return{kind:"error",phase:n,error:s instanceof Error?s:Error(String(s))}}}class pt{cacheDir;cache=new Map;loaded=!1;salt;constructor(t,n=""){this.cacheDir=t,this.salt=n}async load(){if(this.loaded)return;let t=f.join(this.cacheDir,"build-cache.json");if(await Bun.file(t).exists())try{let n=JSON.parse(await Bun.file(t).text());for(let[s,o]of Object.entries(n))this.cache.set(s,o)}catch{}this.loaded=!0}async save(){await D.promises.mkdir(this.cacheDir,{recursive:!0});let t=f.join(this.cacheDir,"build-cache.json"),n={};for(let[s,o]of this.cache)n[s]=o;await Bun.write(t,JSON.stringify(n))}getHash(t,n){let s=D.statSync(t),o=`${this.salt}|${t}:${s.mtimeMs}`;for(let e of n)if(D.existsSync(e)){let u=D.statSync(e);o+=`:${e}:${u.mtimeMs}`}let l=0;for(let e=0;e<o.length;e++){let u=o.charCodeAt(e);l=(l<<5)-l+u,l=l&l}return Math.abs(l).toString(36)}get(t,n){let s=this.cache.get(t);if(!s)return null;let o=ft(n).some((u)=>D.existsSync(u)),l=[n,...s.dependencies??[]].some((u)=>u.endsWith(".stx")&&D.existsSync(u)&&gs(D.readFileSync(u,"utf8")).some((g)=>/\bserver\b/.test(g.attrs)));if(o||l)return this.cache.delete(t),null;let e=this.getHash(n,s.dependencies??[]);if(s.hash!==e)return this.cache.delete(t),null;return s.html}set(t,n,s,o){let l=this.getHash(n,s);this.cache.set(t,{hash:l,html:o,generatedAt:Date.now(),dependencies:s})}}class ht{cacheDir;constructor(t){this.cacheDir=t}getFilePath(t){let n=t.replace(/[^a-zA-Z0-9]/g,"_")+".json";return f.join(this.cacheDir,"isr",n)}async get(t){let n=this.getFilePath(t);if(!await Bun.file(n).exists())return null;try{return JSON.parse(await Bun.file(n).text())}catch{return null}}async set(t,n){let s=this.getFilePath(t);await D.promises.mkdir(f.dirname(s),{recursive:!0}),await Bun.write(s,JSON.stringify(n))}async invalidate(t){let n=this.getFilePath(t);if(await Bun.file(n).exists())await D.promises.unlink(n)}async invalidatePattern(t){let n=f.join(this.cacheDir,"isr");if(!D.existsSync(n))return;let s=await D.promises.readdir(n);for(let o of s){let l=o.replace(/_/g,"/").replace(".json","");if(t.test(l))await D.promises.unlink(f.join(n,o))}}async needsRevalidation(t){let n=await this.get(t);if(!n)return!0;return Date.now()>n.revalidateAfter}}async function Ut(t){let n=[];if(!t.isDynamic)n.push({url:t.pattern,params:{}});else{let s=await gt(t.filePath);if(s.kind==="error")throw Error(`getStaticPaths ${s.phase} failed for ${t.pattern} (${t.filePath}): ${s.error.message}`,{cause:s.error});if(s.kind==="absent")return console.warn(`Warning: Dynamic route ${t.pattern} (${t.filePath}) has no getStaticPaths`),n;let o=s.value;if(o.paths.length===0)return console.info(`getStaticPaths returned no paths for dynamic route ${t.pattern} (${t.filePath})`),n;for(let l of o.paths){let e=t.pattern;for(let[u,g]of Object.entries(l.params))e=e.replace(`:${u}`,g).replace(`:${u}*`,g);n.push({url:e,params:l.params,props:l.props,revalidate:l.revalidate})}}return n}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 n of ft(t))if(await Bun.file(n).exists())try{let s=await import(n);if(typeof s.default==="function")return await s.default();else if(typeof s.default==="object")return s.default;else if(typeof s.getData==="function")return await s.getData();else{let{default:o,...l}=s;return l}}catch(s){console.error(`Error loading data file ${n}:`,s)}return null}async function Gt(t,n,s){let o=t.match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return null;let l=o[1];if(!l.includes("getStaticProps"))return null;try{let e=l.match(/(?:export\s+)?(?:async\s+)?function\s+getStaticProps\s*\([^)]*\)\s*\{([\s\S]*?)\n\}/);if(!e)return null;return await Function("params",`
2
+ import"./chunk-7sh9fa3q.js";import{w,nl}from"./chunk-7rk7wfm6.js";import"./chunk-n761hp6d.js";import"./chunk-r9e0r6jx.js";import{Rt,S}from"./chunk-nqcqench.js";import"./chunk-m7hfcxt3.js";import"./chunk-kq40yvdh.js";import"./chunk-2ws2qe1k.js";import{kt,_t,Ct,Et,Tt,$t}from"./chunk-1bgv727x.js";import{a}from"./chunk-atdn8n6b.js";import{Es}from"./chunk-jg9f5nqf.js";import"./chunk-t2sg2tp2.js";import"./chunk-4vxbcf4a.js";import{he,en,tn}from"./chunk-9avsdbz5.js";import"./chunk-24354nk5.js";import{y}from"./chunk-2v7qvj69.js";import{yt,i}from"./chunk-h5c786jf.js";import"./chunk-pkjza0vv.js";import"./chunk-5wcgqr21.js";import{ps}from"./chunk-7bfsvkvd.js";import"./chunk-g74r0edp.js";import"./chunk-c84pxd2k.js";import{Ya,Za,Qa}from"./chunk-hwcfgs3e.js";import{Zt,Yn,Zn}from"./chunk-ndjmt3vg.js";import{Qt}from"./chunk-ps3t15gp.js";import"./chunk-zkzp1ckd.js";import"./chunk-m0x96g8e.js";import{X,we}from"./chunk-9d79afs9.js";import"./chunk-f54t0qar.js";import"./chunk-qz8bz1f2.js";import{c}from"./chunk-0rjcbqk3.js";import{r,ge}from"./chunk-3vpgr6nk.js";import D from"fs";import f from"path";import{createHash as vt}from"crypto";function Pt(t){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(t).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return t}}var Dt=/<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,n={}){if(!t.includes('type="stx/island"'))return{html:t,chunks:[]};let s=new Map,o=t.replace(Dt,(e,u,g,v)=>{let x=v.trim();if(!x)return e;if(/\bdata-stx-src=/.test(g))return e;if(n.minify)x=Pt(x);let p=It(x);if(!s.has(p))s.set(p,x);let P=n.integrity?` data-stx-integrity="sha384-${vt("sha384").update(x).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${u}" data-stx-src="/_stx/islands/${p}.js"${P}${g}></script>`}),l=Array.from(s,([e,u])=>({hash:e,code:u}));return{html:o,chunks:l}}var Bt=new Set(["visible","idle"]);function ct(t){if(!t.includes("data-stx-src="))return t;let n=new Map,s=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,o;while((o=s.exec(t))!==null)n.set(o[1],o[2]);let l=new Set,e=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,u;while((u=e.exec(t))!==null)if(Bt.has(n.get(u[1])||""))l.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(l.size===0||v===-1)return t;let x=Array.from(l).filter((p)=>!t.includes(`rel="prefetch" href="${p}"`)).map((p)=>`<link rel="prefetch" href="${p}" as="script">`).join("");if(!x)return t;return t.slice(0,v)+x+t.slice(v)}var jt=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function K(t){let n=t.trim();if(!n)return null;let s=/^https?:\/\//i.test(n)?n:`https://${n}`;try{return new URL(s).origin+new URL(s).pathname.replace(/\/$/,"")}catch{return null}}function Ft(t){for(let n of jt){let s=t[n];if(!s)continue;let o=K(s);if(o)return{url:o,source:"env",via:n}}return null}function lt(t){if(!t||typeof t!=="object")return null;let n=t,s=n.site?.url??n.url??n.app?.url;return typeof s==="string"?K(s):null}async function At(t){let{existsSync:n}=await import("fs"),s=await import("path");for(let o of["site.config.ts","site.config.js",".config/site.config.ts"]){let l=s.resolve(t,o);if(!n(l))continue;try{let e=await import(l),u=lt(e.default??e);if(u)return u}catch{}}return null}async function ut(t={}){let n=t.cwd??process.cwd(),s=t.env??process.env;if(t.explicit){let u=K(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 l=await At(n);if(l)return{url:l,source:"site.config",via:"url"};let e=Ft(s);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 q(t){return async()=>({paths:await t(),fallback:!1})}var Ot;function Lt(t){let n=r(t),{depths:s}=ge(n),o=/\b(?:async\s+)?function\s+getStaticPaths\s*\(/g,l;while((l=o.exec(n))!==null){if(s[l.index]!==0)continue;let u=w(n,"(",")",o.lastIndex-1),g=n.indexOf("{",u+1),v=w(n,"{","}",g);if(u<0||g<0||v<0)break;return t.slice(l.index,v+1)}let e=/\b(?:const|let|var)\s+getStaticPaths\s*=/g;while((l=e.exec(n))!==null){if(s[l.index]!==0)continue;let u=nl(n,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 n="read";try{let s=await Bun.file(t).text();n="parse";let o=Qt(s),l=[...o.server,...o.client,...o.signals].filter((e)=>/(?:^|\s)server(?:\s|=|$)/i.test(r(e.attrs))).sort((e,u)=>s.indexOf(e.fullTag)-s.indexOf(u.fullTag));for(let e of l){if(!/\bgetStaticPaths\b/.test(r(e.content)))continue;let u=(Ot??=new Bun.Transpiler({loader:"ts",target:"bun"})).transformSync(e.content);if(!/\bgetStaticPaths\b/.test(r(u)))continue;let g=Lt(u);if(/\bdefineStaticPaths\b/.test(r(g))&&Rt(u,"defineStaticPaths"))throw SyntaxError("Cannot evaluate a module-local defineStaticPaths binding during isolated hook extraction");n="execute";let v=Function("defineStaticPaths",`return (${g})`)(q);if(typeof v!=="function")throw TypeError("getStaticPaths must be a function");let x=await v();n="result";let p=Array.isArray(x)?{paths:x}:x;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(s){return{kind:"error",phase:n,error:s instanceof Error?s:Error(String(s))}}}class pt{cacheDir;cache=new Map;loaded=!1;salt;constructor(t,n=""){this.cacheDir=t,this.salt=n}async load(){if(this.loaded)return;let t=f.join(this.cacheDir,"build-cache.json");if(await Bun.file(t).exists())try{let n=JSON.parse(await Bun.file(t).text());for(let[s,o]of Object.entries(n))this.cache.set(s,o)}catch{}this.loaded=!0}async save(){await D.promises.mkdir(this.cacheDir,{recursive:!0});let t=f.join(this.cacheDir,"build-cache.json"),n={};for(let[s,o]of this.cache)n[s]=o;await Bun.write(t,JSON.stringify(n))}getHash(t,n){let s=D.statSync(t),o=`${this.salt}|${t}:${s.mtimeMs}`;for(let e of n)if(D.existsSync(e)){let u=D.statSync(e);o+=`:${e}:${u.mtimeMs}`}let l=0;for(let e=0;e<o.length;e++){let u=o.charCodeAt(e);l=(l<<5)-l+u,l=l&l}return Math.abs(l).toString(36)}get(t,n){let s=this.cache.get(t);if(!s)return null;let o=ft(n).some((u)=>D.existsSync(u)),l=[n,...s.dependencies??[]].some((u)=>u.endsWith(".stx")&&D.existsSync(u)&&ps(D.readFileSync(u,"utf8")).some((g)=>/\bserver\b/.test(g.attrs)));if(o||l)return this.cache.delete(t),null;let e=this.getHash(n,s.dependencies??[]);if(s.hash!==e)return this.cache.delete(t),null;return s.html}set(t,n,s,o){let l=this.getHash(n,s);this.cache.set(t,{hash:l,html:o,generatedAt:Date.now(),dependencies:s})}}class ht{cacheDir;constructor(t){this.cacheDir=t}getFilePath(t){let n=t.replace(/[^a-zA-Z0-9]/g,"_")+".json";return f.join(this.cacheDir,"isr",n)}async get(t){let n=this.getFilePath(t);if(!await Bun.file(n).exists())return null;try{return JSON.parse(await Bun.file(n).text())}catch{return null}}async set(t,n){let s=this.getFilePath(t);await D.promises.mkdir(f.dirname(s),{recursive:!0}),await Bun.write(s,JSON.stringify(n))}async invalidate(t){let n=this.getFilePath(t);if(await Bun.file(n).exists())await D.promises.unlink(n)}async invalidatePattern(t){let n=f.join(this.cacheDir,"isr");if(!D.existsSync(n))return;let s=await D.promises.readdir(n);for(let o of s){let l=o.replace(/_/g,"/").replace(".json","");if(t.test(l))await D.promises.unlink(f.join(n,o))}}async needsRevalidation(t){let n=await this.get(t);if(!n)return!0;return Date.now()>n.revalidateAfter}}async function Ut(t){let n=[];if(!t.isDynamic)n.push({url:t.pattern,params:{}});else{let s=await gt(t.filePath);if(s.kind==="error")throw Error(`getStaticPaths ${s.phase} failed for ${t.pattern} (${t.filePath}): ${s.error.message}`,{cause:s.error});if(s.kind==="absent")return console.warn(`Warning: Dynamic route ${t.pattern} (${t.filePath}) has no getStaticPaths`),n;let o=s.value;if(o.paths.length===0)return console.info(`getStaticPaths returned no paths for dynamic route ${t.pattern} (${t.filePath})`),n;for(let l of o.paths){let e=t.pattern;for(let[u,g]of Object.entries(l.params))e=e.replace(`:${u}`,g).replace(`:${u}*`,g);n.push({url:e,params:l.params,props:l.props,revalidate:l.revalidate})}}return n}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 n of ft(t))if(await Bun.file(n).exists())try{let s=await import(n);if(typeof s.default==="function")return await s.default();else if(typeof s.default==="object")return s.default;else if(typeof s.getData==="function")return await s.getData();else{let{default:o,...l}=s;return l}}catch(s){console.error(`Error loading data file ${n}:`,s)}return null}async function Gt(t,n,s){let o=t.match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return null;let l=o[1];if(!l.includes("getStaticProps"))return null;try{let e=l.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 l=new URL(o.loc,n).href,e=` <url>
37
37
  ${s.join(`
38
38
  `)}
39
39
  </channel>
40
- </rss>`}async function Vt(t={}){let n=Date.now();tn();let s=await a(process.cwd()),o=s.build||{},l=await ut({explicit:t.domain||o.domain,stxConfig:s});if(l.source==="fallback"&&(t.sitemap??o.sitemap??!0))console.warn(dt());let e={router:t.router??s?.router??{},pagesDir:t.pagesDir||o.pagesDir||"pages",outputDir:t.outputDir||o.outputDir||"dist",baseUrl:t.baseUrl||o.baseUrl||"/",domain:l.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||c(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||s?.partialsDir||"",componentsDir:t.componentsDir||s?.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,x={},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-nq8bw7cm.js");try{E=m(await d(process.cwd()))}catch{}}let{prepareImageDelivery:b}=await import("./chunk-vyad54bv.js"),R=await b(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-nq8bw7cm.js");await d('<div class="bg-black"></div>')}catch{}kt();let wt=s?.routeMiddleware?.dir||"middleware";await Ct(process.cwd(),wt);let J=_t();if(J.length>0)console.log(`Loaded ${J.length} middleware: ${J.join(", ")}`);let St=s?.routeMiddleware?.global||[];Qa(s?.layoutsDir,c(process.cwd()));let Z=X(".",{pagesDir:e.pagesDir,pagesDirs:s?._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:G,props:xt,revalidate:rt}=m;try{await e.hooks.onPageStart?.(h);let A=await Bun.file(k.filePath).text(),O=Yt(A),bt=O?.middleware?Array.isArray(O.middleware)?O.middleware:[O.middleware]:[],nt=[...St,...bt];if(nt.length>0){let B=Et(h,G,O||{}),L=Tt(B,null,void 0,{isServer:!0}),j=await $t(nt,L);if(j.redirect){let C=typeof j.redirect==="string"?j.redirect:j.redirect.path||j.redirect,H=te(String(C),h),U=ee(h,e);await D.promises.mkdir(f.dirname(U),{recursive:!0}),await Bun.write(U,H),u.successCount++,u.pages.push({route:h,outputPath:U,size:Buffer.byteLength(H),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 Vt(t={}){let n=Date.now();tn();let s=await a(process.cwd()),o=s.build||{},l=await ut({explicit:t.domain||o.domain,stxConfig:s});if(l.source==="fallback"&&(t.sitemap??o.sitemap??!0))console.warn(dt());let e={router:t.router??s?.router??{},pagesDir:t.pagesDir||o.pagesDir||"pages",outputDir:t.outputDir||o.outputDir||"dist",baseUrl:t.baseUrl||o.baseUrl||"/",domain:l.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||c(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||s?.partialsDir||"",componentsDir:t.componentsDir||s?.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,x={},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-nr58sedd.js");try{E=m(await d(process.cwd()))}catch{}}let{prepareImageDelivery:b}=await import("./chunk-be2stv5x.js"),R=await b(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-nr58sedd.js");await d('<div class="bg-black"></div>')}catch{}kt();let wt=s?.routeMiddleware?.dir||"middleware";await Ct(process.cwd(),wt);let J=_t();if(J.length>0)console.log(`Loaded ${J.length} middleware: ${J.join(", ")}`);let St=s?.routeMiddleware?.global||[];Qa(s?.layoutsDir,c(process.cwd()));let Z=X(".",{pagesDir:e.pagesDir,pagesDirs:s?._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:G,props:xt,revalidate:rt}=m;try{await e.hooks.onPageStart?.(h);let A=await Bun.file(k.filePath).text(),O=Yt(A),bt=O?.middleware?Array.isArray(O.middleware)?O.middleware:[O.middleware]:[],nt=[...St,...bt];if(nt.length>0){let B=Et(h,G,O||{}),L=Tt(B,null,void 0,{isServer:!0}),j=await $t(nt,L);if(j.redirect){let C=typeof j.redirect==="string"?j.redirect:j.redirect.path||j.redirect,H=te(String(C),h),U=ee(h,e);await D.promises.mkdir(f.dirname(U),{recursive:!0}),await Bun.write(U,H),u.successCount++,u.pages.push({route:h,outputPath:U,size:Buffer.byteLength(H),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:G})){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 mt(k,G,xt,e,s);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={...s,minifyClient:!0,debug:!1,cache:!1},G=await i(await Bun.file(m).text(),{},m,h,k);await Bun.write(f.join(e.outputDir,`${d}.html`),G)}}let V=f.join(e.pagesDir,"error.stx");if(await Bun.file(V).exists()){let d=new Set,m={...s,minifyClient:!0,debug:!1,cache:!1},k=await i(await Bun.file(V).text(),{},V,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=Ts({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=Jt(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 z=Ya(e.outputDir);if(z.assets>0)console.log(`Externalized ${z.assets} asset(s) from ${z.pages} page(s) (${(z.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);let W=Za(e.outputDir);if(W.assets>0)console.log(`Externalized ${W.assets} repeated asset(s) from ${W.pages} page(s) (${(W.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=Zn();if(et)await Y(et,f.join(e.outputDir,Yn)),console.log(`Copied assets from ${Zt}`)}catch(E){throw await e.hooks.onError?.(E),E}if(u.buildTime=Date.now()-n,g.size>0){u.islandChunks={count:g.size,totalBytes:v};let E={generatedChunks:g.size,totalBytes:v,chunks:x,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={...s,minifyClient:!0,debug:!1,cache:!1},G=await i(await Bun.file(m).text(),{},m,h,k);await Bun.write(f.join(e.outputDir,`${d}.html`),G)}}let V=f.join(e.pagesDir,"error.stx");if(await Bun.file(V).exists()){let d=new Set,m={...s,minifyClient:!0,debug:!1,cache:!1},k=await i(await Bun.file(V).text(),{},V,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=Es({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=Jt(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 z=Ya(e.outputDir);if(z.assets>0)console.log(`Externalized ${z.assets} asset(s) from ${z.pages} page(s) (${(z.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);let W=Za(e.outputDir);if(W.assets>0)console.log(`Externalized ${W.assets} repeated asset(s) from ${W.pages} page(s) (${(W.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=Zn();if(et)await Y(et,f.join(e.outputDir,Yn)),console.log(`Copied assets from ${Zt}`)}catch(E){throw await e.hooks.onError?.(E),E}if(u.buildTime=Date.now()-n,g.size>0){u.islandChunks={count:g.size,totalBytes:v};let E={generatedChunks:g.size,totalBytes:v,chunks:x,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
@@ -46,11 +46,6 @@ export declare function substituteInterpolations(value: string): string;
46
46
  * fit and would shift the line.
47
47
  */
48
48
  export declare function substituteInterpolationsInPlace(code: string): string;
49
- /**
50
- * Infer interpolations inside the server's lexical scope, never by running it.
51
- * A long generated identifier may not fit in `{{a}}`; keep newlines in place
52
- * and record the changed columns instead of fabricating a short numeric value.
53
- */
54
49
  export declare function projectScriptInterpolations(code: string, serverCode: string, key?: string): ScriptProjection;
55
50
  /** Map a generated script column back across all preceding edits on its line. */
56
51
  export declare function resolveScriptColumn(edits: readonly ScriptColumnEdit[], column: number): number;
@@ -294,6 +289,31 @@ export declare function expressionStatement(expression: TemplateExpression): { t
294
289
  * change a line count, so every diagnostic still lands on the author's line.
295
290
  */
296
291
  export declare function absolutizeRelativeSpecifiers(code: string, originDir: string): string;
292
+ /**
293
+ * The same rewrite, reporting the columns it moved.
294
+ *
295
+ * The comment above is right that this cannot change a line COUNT, so every
296
+ * diagnostic lands on the author's line. It says nothing about columns, and
297
+ * that was the gap: `'./numeric'` becoming an absolute path widens its line by
298
+ * however deep the project sits on disk, so anything after the import on that
299
+ * line is reported far to the right of where it was written -- column 170 for
300
+ * something authored at column 42 (stacksjs/stx#2154).
301
+ *
302
+ * The edits are shaped exactly like the interpolation ones so both can be
303
+ * undone by the same walker; see resolveVirtualColumn for the ordering.
304
+ */
305
+ export declare function rewriteRelativeSpecifiers(code: string, originDir: string): { code: string, columns: Map<number, ScriptColumnEdit[]> };
306
+ /**
307
+ * Undo both column projections, newest edit first.
308
+ *
309
+ * A line is written, then interpolations are projected into it, then its
310
+ * relative specifiers are absolutized. Walking back from a generated column
311
+ * therefore undoes the specifier rewrite before the interpolation one; doing
312
+ * it in the other order reads the second map in coordinates it never used.
313
+ */
314
+ export declare function resolveVirtualColumn(virtual: Pick<VirtualFile, 'scriptColumns' | 'importColumns'>, line: number, column: number): number;
315
+ /** The inverse, in pipeline order, for editor hover and completions. */
316
+ export declare function projectVirtualColumn(virtual: Pick<VirtualFile, 'scriptColumns' | 'importColumns'>, line: number, column: number): number;
297
317
  /**
298
318
  * Spaces that put a block's first line at the column it occupies in the file.
299
319
  *
@@ -415,6 +435,7 @@ export declare interface VirtualFile {
415
435
  lineMap: Map<number, MappedLine>
416
436
  sourceLineCount: number
417
437
  scriptColumns?: Map<number, ScriptColumnEdit[]>
438
+ importColumns?: Map<number, ScriptColumnEdit[]>
418
439
  }
419
440
  /** A width-changing edit on one script line; untouched columns keep their offset. */
420
441
  export declare interface ScriptColumnEdit {
@@ -112,14 +112,39 @@ export function substituteInterpolationsInPlace(code) {
112
112
  `.repeat(newlines)}`;
113
113
  });
114
114
  }
115
+ function findInterpolationEnd(text, start, close) {
116
+ let depth = 0;
117
+ for (let i = start;i < text.length; i++) {
118
+ const char = text[i];
119
+ if (char === "{") {
120
+ depth++;
121
+ continue;
122
+ }
123
+ if (char !== "}" && char !== "!")
124
+ continue;
125
+ if (text.startsWith(close, i) && depth === 0)
126
+ return i;
127
+ if (char === "}" && depth > 0)
128
+ depth--;
129
+ }
130
+ return -1;
131
+ }
115
132
  export function projectScriptInterpolations(code, serverCode, key = "0") {
116
133
  let prefix = `__stxScript${key}`;
117
134
  while ((code + serverCode).includes(prefix))
118
135
  prefix += "_";
119
136
  const columns = new Map, declarations = [], expressions = [], searchable = stripCommentsAndLiterals(code), starts = lineStarts(code), chunks = [];
120
137
  let cursor = 0;
121
- for (const found of searchable.matchAll(/\{\{([\s\S]*?)\}\}|\{!!([\s\S]*?)!!\}/g)) {
122
- const offset = found.index, match = code.slice(offset, offset + found[0].length), escaped = found[1] !== void 0, expression = match.slice(escaped ? 2 : 3, escaped ? -2 : -3), index = expressions.length, position = offsetToPosition(starts, offset), origin = offsetToPosition(starts, offset + (escaped ? 2 : 3));
138
+ for (let scan = 0;scan < searchable.length; scan++) {
139
+ const escaped = searchable.startsWith("{{", scan);
140
+ if (!escaped && !searchable.startsWith("{!!", scan))
141
+ continue;
142
+ const open = escaped ? 2 : 3, close = escaped ? "}}" : "!!}", end = findInterpolationEnd(searchable, scan + open, close);
143
+ if (end < 0)
144
+ continue;
145
+ const offset = scan, match = code.slice(offset, end + close.length), expression = match.slice(open, -close.length);
146
+ scan = end + close.length - 1;
147
+ const index = expressions.length, position = offsetToPosition(starts, offset), origin = offsetToPosition(starts, offset + (escaped ? 2 : 3));
123
148
  expressions.push({ code: stripFilterChain(expression), ...origin });
124
149
  const name = `${prefix}_${index}`, pieces = match.split(`
125
150
  `), firstWidth = pieces[0].length;
@@ -748,12 +773,40 @@ export function expressionStatement(expression) {
748
773
  }
749
774
  const RELATIVE_SPECIFIER_RE = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)(['"])(\.{1,2}\/[^'"\n]*)\2/g;
750
775
  export function absolutizeRelativeSpecifiers(code, originDir) {
776
+ return rewriteRelativeSpecifiers(code, originDir).code;
777
+ }
778
+ export function rewriteRelativeSpecifiers(code, originDir) {
779
+ const columns = new Map;
751
780
  if (!originDir)
752
- return code;
753
- return code.replace(RELATIVE_SPECIFIER_RE, (_whole, prefix, quote, specifier) => {
754
- const absolute = path.resolve(originDir, specifier).replace(/\\/g, "/");
755
- return `${prefix}${quote}${absolute}${quote}`;
756
- });
781
+ return { code, columns };
782
+ const starts = lineStarts(code), chunks = [];
783
+ let cursor = 0;
784
+ for (const found of code.matchAll(RELATIVE_SPECIFIER_RE)) {
785
+ const offset = found.index, [whole, prefix, quote, specifier] = found, absolute = path.resolve(originDir, specifier).replace(/\\/g, "/"), replacement = `${prefix}${quote}${absolute}${quote}`;
786
+ chunks.push(code.slice(cursor, offset), replacement);
787
+ cursor = offset + whole.length;
788
+ if (whole.includes(`
789
+ `))
790
+ continue;
791
+ const position = offsetToPosition(starts, offset), edits = columns.get(position.line) ?? [], previous = edits.at(-1), generatedStart = position.column + (previous ? previous.generatedEnd - previous.sourceEnd : 0);
792
+ edits.push({
793
+ sourceStart: position.column,
794
+ sourceEnd: position.column + whole.length,
795
+ generatedStart,
796
+ generatedEnd: generatedStart + replacement.length
797
+ });
798
+ columns.set(position.line, edits);
799
+ }
800
+ chunks.push(code.slice(cursor));
801
+ return { code: chunks.join(""), columns };
802
+ }
803
+ export function resolveVirtualColumn(virtual, line, column) {
804
+ const projected = resolveScriptColumn(virtual.importColumns?.get(line) ?? [], column);
805
+ return resolveScriptColumn(virtual.scriptColumns?.get(line) ?? [], projected);
806
+ }
807
+ export function projectVirtualColumn(virtual, line, column) {
808
+ const projected = projectScriptColumn(virtual.scriptColumns?.get(line) ?? [], column);
809
+ return projectScriptColumn(virtual.importColumns?.get(line) ?? [], projected);
757
810
  }
758
811
  export function firstLinePadding(block) {
759
812
  return " ".repeat(Math.max(0, (block.startColumn ?? 1) - 1));
@@ -778,7 +831,7 @@ export function collectImportedNames(code) {
778
831
  }
779
832
  export function buildVirtualTypeScript(source, options = {}) {
780
833
  const blocks = extractScriptBlocks(source), sourceLines = source.split(`
781
- `), lines = Array.from({ length: sourceLines.length }, () => ""), lineMap = new Map, scriptColumns = new Map, scriptDeclarations = [], serverCode = blocks.filter((block) => block.kind === "server").map((block) => block.code).join(`
834
+ `), lines = Array.from({ length: sourceLines.length }, () => ""), lineMap = new Map, scriptColumns = new Map, importColumns = new Map, scriptDeclarations = [], serverCode = blocks.filter((block) => block.kind === "server").map((block) => block.code).join(`
782
835
  `), components = options.filePath && options.templateExpressions !== !1 ? componentContractChecks(source, maskNonTemplateRegions(source), {
783
836
  filePath: options.filePath,
784
837
  componentsDir: options.componentsDir,
@@ -796,7 +849,10 @@ export function buildVirtualTypeScript(source, options = {}) {
796
849
  text: absolutizeRelativeSpecifiers(declaration.text, options.originDir ?? ""),
797
850
  origin: declaration.origin ? { ...declaration.origin, line: declaration.origin.line + block.startLine - 1 } : void 0
798
851
  });
799
- const code = blankScriptDirectives(projection.code), bodyLines = absolutizeRelativeSpecifiers(code, options.originDir ?? "").split(`
852
+ const code = blankScriptDirectives(projection.code), rewritten = rewriteRelativeSpecifiers(code, options.originDir ?? "");
853
+ for (const [line, edits] of rewritten.columns)
854
+ importColumns.set(block.startLine + line - 1, edits);
855
+ const bodyLines = rewritten.code.split(`
800
856
  `);
801
857
  bodyLines.forEach((text, i) => {
802
858
  const index = block.startLine - 1 + i;
@@ -909,7 +965,7 @@ export function buildVirtualTypeScript(source, options = {}) {
909
965
  }
910
966
  append("export {}");
911
967
  return { text: lines.join(`
912
- `), lineMap, sourceLineCount: sourceLines.length, componentDependencies: components?.dependencies, referenced, scriptColumns };
968
+ `), lineMap, sourceLineCount: sourceLines.length, componentDependencies: components?.dependencies, referenced, scriptColumns, importColumns };
913
969
  }
914
970
  export function lineStarts(text) {
915
971
  const starts = [0];
@@ -941,7 +997,7 @@ export function isTemplateArtefact(position, code) {
941
997
  export function resolvePosition(virtual, line, column) {
942
998
  const mapped = virtual.lineMap.get(line);
943
999
  if (!mapped)
944
- return line <= virtual.sourceLineCount ? { line, column: resolveScriptColumn(virtual.scriptColumns?.get(line) ?? [], column) } : null;
1000
+ return line <= virtual.sourceLineCount ? { line, column: resolveVirtualColumn(virtual, line, column) } : null;
945
1001
  const within = mapped.expression?.anchor ? 0 : Math.max(0, column - 1 - (mapped.prefixLength ?? 0));
946
1002
  return {
947
1003
  line: mapped.line,
package/dist/typecheck.js CHANGED
@@ -6,7 +6,7 @@ import { STX_RUNTIME_GLOBALS } from "./runtime-globals.js";
6
6
  import { stateDir } from "./state-dir.js";
7
7
  import { loadStxConfig } from "./config.js";
8
8
  import {
9
- absolutizeRelativeSpecifiers,
9
+ rewriteRelativeSpecifiers,
10
10
  buildVirtualTypeScript,
11
11
  extractScriptBlocks,
12
12
  resolvePosition,
@@ -37,12 +37,14 @@ export function buildScriptVirtualFile(block, serverCode = "", originDir = "") {
37
37
  lineMap.set(lines.length, { ...declaration.origin, line: block.startLine + declaration.origin.line - 1 + index, column: index === 0 ? declaration.origin.column : 1 });
38
38
  }
39
39
  lines.push(payload, "export {}", "");
40
+ const rewritten = rewriteRelativeSpecifiers(lines.join(`
41
+ `), originDir);
40
42
  return {
41
- text: absolutizeRelativeSpecifiers(lines.join(`
42
- `), originDir),
43
+ text: rewritten.code,
43
44
  sourceLineCount,
44
45
  lineMap,
45
- scriptColumns: new Map([...projection.columns].map(([line, edits]) => [line + block.startLine - 1, edits]))
46
+ scriptColumns: new Map([...projection.columns].map(([line, edits]) => [line + block.startLine - 1, edits])),
47
+ importColumns: rewritten.columns
46
48
  };
47
49
  }
48
50
  export function buildVirtualSource(block, serverCode = "", originDir = "") {
@@ -392,6 +392,7 @@ export declare interface StxConfig {
392
392
  progressHeight?: string
393
393
  prefetchVisible?: boolean
394
394
  prefetchVisibleMax?: number
395
+ prefetchBudgetBytes?: number
395
396
  keepOpening?: boolean
396
397
  }
397
398
  apiRouter?: { handleRequest: (request: Request) => Response | Promise<Response> }
package/dist/utils.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { extractExports as scopeExports, scopePropertyDescriptor } from "./client-scope-bindings.js";
2
- import { pascalToKebab } from "./component-resolution.js";
2
+ import { packageComponentDirs, pascalToKebab } from "./component-resolution.js";
3
3
  import { usesSharedImageApi } from "./component-image-usage.js";
4
4
  import fs from "node:fs";
5
5
  import path from "node:path";
@@ -563,7 +563,10 @@ export async function userComponentFileExists(componentPath, componentsDir, pare
563
563
  const variants = [...new Set([`${baseName}.stx`, `${kebabToPascal(baseName)}.stx`, `${pascalToKebab(baseName)}.stx`])], configuredRoot = typeof options.root === "string" ? path.resolve(options.root) : void 0, resolveBase = configuredRoot ?? path.dirname(parentFilePath), searchDirs = [], push = (dir) => {
564
564
  if (dir && !searchDirs.includes(dir))
565
565
  searchDirs.push(dir);
566
- }, originalFilePath = parentContext.__originalFilePath;
566
+ };
567
+ for (const dir of packageComponentDirs(parentFilePath, configuredRoot))
568
+ push(dir);
569
+ const originalFilePath = parentContext.__originalFilePath;
567
570
  if (originalFilePath)
568
571
  push(path.join(path.dirname(originalFilePath), "components"));
569
572
  if (isInsideFrameworkComponentsDir(componentsDir, options))
@@ -738,7 +741,7 @@ export async function renderComponentWithSlot(componentPath, props, slotContent,
738
741
  for (const dir of options.additionalComponentsDirs ?? [])
739
742
  if (dir && !searchDirs.includes(dir))
740
743
  searchDirs.push(dir);
741
- const checkedControl = options._nativeHostAttrs && /^(?:checkbox|switch)$/i.test(baseName), eventNames = (renderMetadata?.events ?? []).map((name) => name.replace(/^@/, "").split(".")[0].toLowerCase().replace(/-/g, "")), usesChecked = Object.hasOwn(props, "checked") || Boolean(renderMetadata?.reactiveProps?.includes("checked")), usesValue = Object.hasOwn(props, "value") || Boolean(renderMetadata?.reactiveProps?.includes("value")), sharedCheckedUsage = !eventNames.includes("valuechange") && (usesChecked || eventNames.includes("change") && !usesValue), textInput = options._nativeHostAttrs && /^textinput$/i.test(baseName), sharedTextInputUsage = eventNames.includes("update:value") && !eventNames.includes("input"), video = options._nativeHostAttrs && /^video$/i.test(baseName), image = options._nativeHostAttrs && /^image$/i.test(baseName), sharedImageUsage = usesSharedImageApi([...Object.keys(props), ...renderMetadata?.reactiveProps ?? []], renderMetadata?.events, props), usesSrc = Object.hasOwn(props, "src") || Boolean(renderMetadata?.reactiveProps?.includes("src")), usesSource = Object.hasOwn(props, "source") || Boolean(renderMetadata?.reactiveProps?.includes("source")), sharedVideoUsage = video && usesSrc && !usesSource && (renderMetadata?.events ?? []).every((event) => /^(?:play|pause|ended|timeupdate|loadedmetadata|loadstart|error)$/.test(event.replace(/^@/, "").split(".")[0])), hasProp = (name) => Object.hasOwn(props, name) || Boolean(renderMetadata?.reactiveProps?.includes(name)), nativeButtonUsage = options._nativeHostAttrs && /^button$/i.test(baseName) && (hasProp("symbol") || hasProp("iconOnly") || hasProp("title") && !hasProp("label") && !slotContent.trim()), targetIsFallback = options._targetComponentFallbackNames?.some((name) => name.toLowerCase() === baseName.toLowerCase()) && (!checkedControl || sharedCheckedUsage) && (!textInput || sharedTextInputUsage) && (!video || sharedVideoUsage) && (!image || sharedImageUsage) && !nativeButtonUsage;
744
+ const checkedControl = options._nativeHostAttrs && /^(?:checkbox|switch)$/i.test(baseName), eventNames = (renderMetadata?.events ?? []).map((name) => name.replace(/^@/, "").split(".")[0].toLowerCase().replace(/-/g, "")), usesChecked = Object.hasOwn(props, "checked") || Boolean(renderMetadata?.reactiveProps?.includes("checked")), usesValue = Object.hasOwn(props, "value") || Boolean(renderMetadata?.reactiveProps?.includes("value")), sharedCheckedUsage = !eventNames.includes("valuechange") && (usesChecked || eventNames.includes("change") && !usesValue), textInput = options._nativeHostAttrs && /^textinput$/i.test(baseName), sharedTextInputUsage = eventNames.includes("update:value") && !eventNames.includes("input"), video = options._nativeHostAttrs && /^video$/i.test(baseName), image = options._nativeHostAttrs && /^image$/i.test(baseName), sharedImageUsage = usesSharedImageApi([...Object.keys(props), ...renderMetadata?.reactiveProps ?? []], renderMetadata?.events, props), usesSrc = Object.hasOwn(props, "src") || Boolean(renderMetadata?.reactiveProps?.includes("src")), usesSource = Object.hasOwn(props, "source") || Boolean(renderMetadata?.reactiveProps?.includes("source")), sharedVideoUsage = video && usesSrc && !usesSource && (renderMetadata?.events ?? []).every((event) => /^(?:play|pause|ended|timeupdate|loadedmetadata|loadstart|error)$/.test(event.replace(/^@/, "").split(".")[0])), sharedButtonVariants = new Set(["", "primary", "secondary", "outline", "ghost", "danger"]), buttonVariant = typeof props.variant === "string" ? props.variant.trim().toLowerCase() : "", nativeButtonUsage = options._nativeHostAttrs && /^button$/i.test(baseName) && !sharedButtonVariants.has(buttonVariant), targetIsFallback = options._targetComponentFallbackNames?.some((name) => name.toLowerCase() === baseName.toLowerCase()) && (!checkedControl || sharedCheckedUsage) && (!textInput || sharedTextInputUsage) && (!video || sharedVideoUsage) && (!image || sharedImageUsage) && !nativeButtonUsage;
742
745
  for (const dir of targetIsFallback ? [] : options._targetComponentDirs ?? [])
743
746
  if (dir && !searchDirs.includes(dir))
744
747
  searchDirs.push(dir);