@thexjs/core 0.1.4 → 0.1.7

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.
package/dist/index.js CHANGED
@@ -300,7 +300,7 @@ var CLIENT_NAV_SCRIPT = `
300
300
  if (url.origin !== location.origin) return null;
301
301
  var here = new URL(location.href);
302
302
  if (url.pathname === here.pathname && url.search === here.search && url.hash) return null;
303
- return url;
303
+ return anchor;
304
304
  }
305
305
 
306
306
  function setLoading(on) {
@@ -447,7 +447,7 @@ function renderPage(node, options = {}) {
447
447
  const body = renderToString(node);
448
448
  const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
449
449
  const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
450
- const islandScriptsHtml = islandScripts?.map((src) => `<script type="module" data-island-script src="${escapeHtml(src)}"></script>`).join("\n ");
450
+ const islandScriptsHtml = islandScripts?.map((src) => `<script data-island-script src="${escapeHtml(src)}"></script>`).join("\n ");
451
451
  return htmlShell(
452
452
  title,
453
453
  buildHeadExtras(options.stylesheet),
@@ -464,7 +464,7 @@ function renderStaticPage(node, options = {}) {
464
464
  const body = renderToStaticMarkup(node);
465
465
  const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
466
466
  const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
467
- const islandScriptsHtml = islandScripts?.map((src) => `<script type="module" data-island-script src="${escapeHtml(src)}"></script>`).join("\n ");
467
+ const islandScriptsHtml = islandScripts?.map((src) => `<script data-island-script src="${escapeHtml(src)}"></script>`).join("\n ");
468
468
  return htmlShell(
469
469
  title,
470
470
  buildHeadExtras(options.stylesheet),
@@ -480,7 +480,7 @@ async function renderStreamingPage(node, options = {}) {
480
480
  const title = escapeHtml(options.title ?? "x app");
481
481
  const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
482
482
  const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json">${propsJson}</script>` : "";
483
- const islandScriptsHtml = islandScripts?.map((src) => `<script type="module" data-island-script src="${escapeHtml(src)}"></script>`).join("\n ");
483
+ const islandScriptsHtml = islandScripts?.map((src) => `<script data-island-script src="${escapeHtml(src)}"></script>`).join("\n ");
484
484
  const navScriptTag = buildNavScriptTag(options.clientNav);
485
485
  const liveReloadTag = buildLiveReloadTag(options.liveReload);
486
486
  const headExtras = buildHeadExtras(options.stylesheet);
@@ -538,7 +538,7 @@ ${liveReloadTag} </body>
538
538
 
539
539
  // src/createApp.ts
540
540
  import { existsSync, watch } from "fs";
541
- import { join as join4, resolve, sep as sep3 } from "path";
541
+ import { join as join5, resolve, sep as sep3 } from "path";
542
542
  import { createElement } from "react";
543
543
 
544
544
  // src/content.ts
@@ -753,111 +753,153 @@ function renderErrorOverlay(error) {
753
753
  </html>`;
754
754
  }
755
755
 
756
- // src/middleware.ts
757
- function composeMiddleware(fns, handler) {
758
- return async (ctx, _next) => {
759
- let index = -1;
760
- const dispatch = async (i) => {
761
- if (i <= index) throw new Error("next() called multiple times");
762
- index = i;
763
- const fn = fns[i];
764
- if (fn) {
765
- return fn(ctx, () => dispatch(i + 1));
766
- }
767
- return handler(ctx);
768
- };
769
- return dispatch(0);
770
- };
771
- }
772
-
773
- // src/observability/health.ts
774
- async function runChecks(checks) {
775
- const results = {};
776
- let allOk = true;
777
- await Promise.all(
778
- Object.entries(checks).map(async ([name, check]) => {
779
- try {
780
- const ok = await check();
781
- results[name] = ok ? "ok" : "error";
782
- if (!ok) allOk = false;
783
- } catch {
784
- results[name] = "error";
785
- allOk = false;
786
- }
787
- })
788
- );
789
- return { status: allOk ? "ok" : "error", checks: results };
790
- }
791
- function createHealthCheckHandler(options = {}) {
792
- const checks = options.checks ?? {};
756
+ // src/images/proxy.ts
757
+ var ALLOWED_CONTENT_TYPES = /* @__PURE__ */ new Set([
758
+ "image/png",
759
+ "image/jpeg",
760
+ "image/gif",
761
+ "image/webp",
762
+ "image/svg+xml",
763
+ "image/avif",
764
+ "image/x-icon"
765
+ ]);
766
+ function createImageProxyHandler(options = {}) {
767
+ const allowedHosts = new Set(options.remoteHosts ?? []);
793
768
  return async (req) => {
794
- const pathname = new URL(req.url).pathname;
795
- if (pathname === "/healthz") {
796
- return Response.json({ status: "ok" }, { status: 200 });
769
+ const reqUrl = new URL(req.url);
770
+ if (reqUrl.pathname !== "/_x/image") return null;
771
+ if (req.method !== "GET" && req.method !== "HEAD") return null;
772
+ const target = reqUrl.searchParams.get("url");
773
+ if (!target) return new Response("missing url param", { status: 400 });
774
+ let parsed;
775
+ try {
776
+ parsed = new URL(target);
777
+ } catch {
778
+ return new Response("invalid url param", { status: 400 });
797
779
  }
798
- if (pathname === "/readyz") {
799
- const result = await runChecks(checks);
800
- return Response.json(result, { status: result.status === "ok" ? 200 : 503 });
780
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:" || !allowedHosts.has(parsed.hostname)) {
781
+ return new Response("host not allow-listed for image proxy", { status: 403 });
801
782
  }
802
- return null;
783
+ let upstream;
784
+ try {
785
+ upstream = await fetch(parsed);
786
+ } catch (err) {
787
+ return new Response(`upstream fetch failed: ${String(err)}`, { status: 502 });
788
+ }
789
+ if (!upstream.ok) {
790
+ return new Response("upstream error", { status: 502 });
791
+ }
792
+ const contentType = upstream.headers.get("content-type") ?? "";
793
+ const baseContentType = (contentType.split(";")[0] ?? "").trim();
794
+ if (!ALLOWED_CONTENT_TYPES.has(baseContentType)) {
795
+ return new Response("upstream did not return an image", { status: 502 });
796
+ }
797
+ return new Response(upstream.body, {
798
+ status: 200,
799
+ headers: {
800
+ "Content-Type": contentType,
801
+ // Cache aggressively client + edge side — the proxied URL is the
802
+ // cache key, and remote asset URLs like this one are typically
803
+ // content-hashed by the origin already.
804
+ "Cache-Control": "public, max-age=86400, immutable"
805
+ }
806
+ });
803
807
  };
804
808
  }
805
809
 
806
- // src/observability/logger.ts
807
- function write(level, message, fields) {
808
- const entry = {
809
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
810
- level,
811
- message,
812
- ...fields
813
- };
814
- const line = JSON.stringify(entry);
815
- if (level === "error") {
816
- console.error(line);
817
- } else if (level === "warn") {
818
- console.warn(line);
819
- } else {
820
- console.log(line);
810
+ // src/island.tsx
811
+ import { createContext, useContext } from "react";
812
+ import { jsx as jsx2 } from "react/jsx-runtime";
813
+ function createIslandRegistry() {
814
+ return { entries: [] };
815
+ }
816
+ var IslandContext = createContext(null);
817
+ function IslandProvider({
818
+ registry,
819
+ children
820
+ }) {
821
+ return /* @__PURE__ */ jsx2(IslandContext.Provider, { value: registry, children });
822
+ }
823
+ var islandCounter = 0;
824
+ function Island({
825
+ name,
826
+ client = "idle",
827
+ children
828
+ }) {
829
+ const registry = useContext(IslandContext);
830
+ const id = `x-island-${islandCounter++}`;
831
+ if (registry) {
832
+ registry.entries.push({ name, id });
821
833
  }
834
+ return /* @__PURE__ */ jsx2("div", { "data-island": name, "data-island-id": id, "data-island-client": client, children });
822
835
  }
823
- var logger = {
824
- info: (message, fields) => write("info", message, fields),
825
- warn: (message, fields) => write("warn", message, fields),
826
- error: (message, fields) => write("error", message, fields)
827
- };
828
- function withRequestLogging(handler) {
829
- return async (req) => {
830
- const start = performance.now();
831
- const requestId = req.headers.get("x-request-id") ?? crypto.randomUUID();
832
- const route = new URL(req.url).pathname;
833
- try {
834
- const res = await handler(req);
835
- write("info", "request completed", {
836
- requestId,
837
- route,
838
- method: req.method,
839
- status: res.status,
840
- durationMs: Math.round(performance.now() - start)
841
- });
842
- if (!res.headers.has("x-request-id")) {
843
- const headers = new Headers(res.headers);
844
- headers.set("x-request-id", requestId);
845
- return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
836
+
837
+ // src/island-bundle.ts
838
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync as writeFileSync3 } from "fs";
839
+ import { basename, join as join4 } from "path";
840
+
841
+ // src/security/env-isolation.ts
842
+ var PUBLIC_ENV_PREFIX = "THEXJS_PUBLIC_";
843
+ var ENV_ACCESS_PATTERNS = [
844
+ /\bprocess\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
845
+ /\bprocess\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g,
846
+ /\bBun\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
847
+ /\bBun\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g,
848
+ /\bimport\.meta\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
849
+ /\bimport\.meta\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g
850
+ ];
851
+ var SUSPICIOUS_ENV_PATTERNS = [
852
+ {
853
+ re: /\b(?:process|Bun|import\.meta)\.env\s*\[[^"'`]/g,
854
+ label: "dynamic env key access"
855
+ },
856
+ {
857
+ re: /\b(?:process|Bun|import\.meta)\.env\[["'][^"']*["']\s*\+/g,
858
+ label: "concatenated env key access"
859
+ },
860
+ {
861
+ re: /\b(?:process|Bun)\.env\b(?!\s*(?:\.|\[))/g,
862
+ label: "bare process.env access (aliasing/mutation)"
863
+ }
864
+ ];
865
+ function findLeakedEnvKeys(code) {
866
+ const found = /* @__PURE__ */ new Set();
867
+ for (const pattern of ENV_ACCESS_PATTERNS) {
868
+ for (const match of code.matchAll(pattern)) {
869
+ const key = match[1];
870
+ if (key && !key.startsWith(PUBLIC_ENV_PREFIX)) {
871
+ found.add(key);
846
872
  }
847
- return res;
848
- } catch (err) {
849
- write("error", "request failed", {
850
- requestId,
851
- route,
852
- method: req.method,
853
- status: 500,
854
- durationMs: Math.round(performance.now() - start),
855
- error: err instanceof Error ? err.message : String(err)
856
- });
857
- throw err;
858
873
  }
859
- };
874
+ }
875
+ for (const { re, label } of SUSPICIOUS_ENV_PATTERNS) {
876
+ re.lastIndex = 0;
877
+ if (re.test(code)) found.add(`process.env (${label})`);
878
+ }
879
+ return [...found];
860
880
  }
881
+ var EnvLeakageError = class extends Error {
882
+ constructor(file, keys) {
883
+ super(
884
+ `[x] server-only environment variable(s) leaked into client bundle "${file}": ${keys.join(", ")}. Only "${PUBLIC_ENV_PREFIX}*" variables may be referenced in client-shipped code \u2014 move this access into a loader, server function, or API route.`
885
+ );
886
+ this.file = file;
887
+ this.keys = keys;
888
+ this.name = "EnvLeakageError";
889
+ }
890
+ file;
891
+ keys;
892
+ };
893
+ function assertNoEnvLeakage(code, file) {
894
+ const leaked = findLeakedEnvKeys(code);
895
+ if (leaked.length > 0) {
896
+ throw new EnvLeakageError(file, leaked);
897
+ }
898
+ }
899
+
900
+ // src/server-functions.ts
901
+ import { writeFileSync as writeFileSync2 } from "fs";
902
+ import { join as join3 } from "path";
861
903
 
862
904
  // src/observability/monitoring.ts
863
905
  var noopReporter = {
@@ -919,91 +961,11 @@ function combineReporters(...reporters) {
919
961
  };
920
962
  }
921
963
 
922
- // src/security/headers.ts
923
- var DEFAULT_CSP = "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'";
924
- function buildSecurityHeaders(options = {}) {
925
- const headers = new Headers();
926
- const csp = options.contentSecurityPolicy ?? DEFAULT_CSP;
927
- if (csp !== false) headers.set("Content-Security-Policy", csp);
928
- const hstsMaxAge = options.hstsMaxAge ?? 15552e3;
929
- if (hstsMaxAge !== false) {
930
- const includeSub = options.hstsIncludeSubDomains ?? true;
931
- headers.set(
932
- "Strict-Transport-Security",
933
- `max-age=${hstsMaxAge}${includeSub ? "; includeSubDomains" : ""}`
934
- );
935
- }
936
- const frameOptions = options.frameOptions ?? "DENY";
937
- if (frameOptions !== false) headers.set("X-Frame-Options", frameOptions);
938
- const contentTypeOptions = options.contentTypeOptions ?? "nosniff";
939
- if (contentTypeOptions !== false) headers.set("X-Content-Type-Options", contentTypeOptions);
940
- const referrerPolicy = options.referrerPolicy ?? "strict-origin-when-cross-origin";
941
- if (referrerPolicy !== false) headers.set("Referrer-Policy", referrerPolicy);
942
- return headers;
943
- }
944
- function applySecurityHeaders(res, options = {}) {
945
- const extra = buildSecurityHeaders(options);
946
- const headers = new Headers(res.headers);
947
- for (const [key, value] of extra.entries()) {
948
- if (!headers.has(key)) headers.set(key, value);
949
- }
950
- return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
951
- }
952
-
953
- // src/security/rate-limit.ts
954
- function defaultKeyFn(req) {
955
- const headers = req.headers;
956
- const forwarded = headers.get("x-forwarded-for");
957
- if (forwarded) return forwarded.split(",")[0]?.trim() ?? "unknown";
958
- return headers.get("x-real-ip") ?? "unknown";
959
- }
960
- function createRateLimiter(options = {}) {
961
- const limit = options.limit ?? 60;
962
- const windowMs = options.windowMs ?? 6e4;
963
- const keyFn = options.keyFn ?? defaultKeyFn;
964
- const buckets = /* @__PURE__ */ new Map();
965
- function check(req) {
966
- const key = keyFn(req);
967
- const now = Date.now();
968
- let bucket = buckets.get(key);
969
- if (!bucket || bucket.resetAt <= now) {
970
- bucket = { count: 0, resetAt: now + windowMs };
971
- buckets.set(key, bucket);
972
- }
973
- bucket.count += 1;
974
- const ok = bucket.count <= limit;
975
- return { ok, limit, remaining: Math.max(0, limit - bucket.count), resetAt: bucket.resetAt };
976
- }
977
- function sweep() {
978
- const now = Date.now();
979
- for (const [key, bucket] of buckets) {
980
- if (bucket.resetAt <= now) buckets.delete(key);
981
- }
982
- }
983
- return { check, sweep, buckets };
984
- }
985
- function rateLimitMiddleware(limiter, req) {
986
- const result = limiter.check(req);
987
- if (result.ok) return null;
988
- const retryAfterSeconds = Math.max(1, Math.ceil((result.resetAt - Date.now()) / 1e3));
989
- return new Response("Too Many Requests", {
990
- status: 429,
991
- headers: {
992
- "Retry-After": String(retryAfterSeconds),
993
- "X-RateLimit-Limit": String(result.limit),
994
- "X-RateLimit-Remaining": String(result.remaining)
995
- }
996
- });
997
- }
998
-
999
- // src/server-functions.ts
1000
- import { writeFileSync as writeFileSync2 } from "fs";
1001
- import { join as join3 } from "path";
1002
-
1003
964
  // src/security/csrf.ts
1004
965
  var CSRF_COOKIE_NAME = "x_csrf_token";
1005
966
  var CSRF_HEADER_NAME = "x-csrf-token";
1006
967
  var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
968
+ var SECURE_COOKIE_FLAG = process.env.NODE_ENV === "production" ? "; Secure" : "";
1007
969
  function originFromHeader(value) {
1008
970
  if (!value) return null;
1009
971
  try {
@@ -1058,7 +1020,10 @@ function withCsrfCookie(req, res) {
1058
1020
  if (readCookie(req, CSRF_COOKIE_NAME)) return res;
1059
1021
  const token = generateCsrfToken();
1060
1022
  const headers = new Headers(res.headers);
1061
- headers.append("Set-Cookie", `${CSRF_COOKIE_NAME}=${token}; Path=/; SameSite=Lax`);
1023
+ headers.append(
1024
+ "Set-Cookie",
1025
+ `${CSRF_COOKIE_NAME}=${token}; Path=/; SameSite=Lax${SECURE_COOKIE_FLAG}`
1026
+ );
1062
1027
  return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
1063
1028
  }
1064
1029
  function checkCsrf(req, options = {}) {
@@ -1103,68 +1068,403 @@ function registerServerFunctions(routePath, paramNames, fns) {
1103
1068
  for (const [name, fn] of fnMap) {
1104
1069
  existing.fns.set(name, fn);
1105
1070
  }
1106
- } else {
1107
- ACTION_ROUTES.push({ routePath, paramNames, fns: fnMap });
1071
+ } else {
1072
+ ACTION_ROUTES.push({ routePath, paramNames, fns: fnMap });
1073
+ }
1074
+ }
1075
+ function getServerFunctionHandler(csrfOptions) {
1076
+ return async (req) => {
1077
+ if (req.method !== "POST") return null;
1078
+ const url = new URL(req.url);
1079
+ if (!url.pathname.startsWith("/__x/actions/")) return null;
1080
+ const csrfResult = checkCsrf(req, csrfOptions);
1081
+ if (!csrfResult.ok) {
1082
+ return new Response(`Forbidden: ${csrfResult.reason}`, { status: 403 });
1083
+ }
1084
+ const parts = url.pathname.replace("/__x/actions/", "").split("/");
1085
+ if (parts.length < 1) return null;
1086
+ const actionName = parts.pop();
1087
+ if (!actionName) return null;
1088
+ const concretePath = `/${parts.join("/")}`;
1089
+ for (const entry of ACTION_ROUTES) {
1090
+ const params = extractActionParams(entry.routePath, entry.paramNames, concretePath);
1091
+ if (params === null) continue;
1092
+ const fn = entry.fns.get(actionName);
1093
+ if (!fn) return new Response("Function not found", { status: 404 });
1094
+ let args = [];
1095
+ try {
1096
+ const body = await req.json();
1097
+ args = Array.isArray(body) ? body : [body];
1098
+ } catch {
1099
+ return new Response("Invalid request body", { status: 400 });
1100
+ }
1101
+ try {
1102
+ const result = await fn(...args);
1103
+ return Response.json(result);
1104
+ } catch (err) {
1105
+ reportException(err, { route: concretePath, phase: "action" });
1106
+ const message = err instanceof Error ? err.message : "Internal error";
1107
+ return new Response(message, { status: 500 });
1108
+ }
1109
+ }
1110
+ return new Response("Not found", { status: 404 });
1111
+ };
1112
+ }
1113
+ function extractActionParams(routePath, paramNames, url) {
1114
+ const regex = routePatternToRegex(routePath);
1115
+ const match = url.match(regex);
1116
+ if (!match) return null;
1117
+ const params = {};
1118
+ let idx = 1;
1119
+ for (const name of paramNames) {
1120
+ const value = match[idx];
1121
+ if (value !== void 0) {
1122
+ params[name] = value;
1123
+ }
1124
+ idx++;
1125
+ }
1126
+ return params;
1127
+ }
1128
+
1129
+ // src/island-bundle.ts
1130
+ function actionsRewritePlugin(actionModules) {
1131
+ return {
1132
+ name: "x-actions-rewrite",
1133
+ setup(build2) {
1134
+ if (actionModules.size === 0) return;
1135
+ build2.onLoad({ filter: /\.(ts|tsx)$/ }, (args) => {
1136
+ const info = actionModules.get(args.path);
1137
+ if (!info) return void 0;
1138
+ const endpointBase = info.parentPath === "/" ? "/__x/actions" : `/__x/actions${info.parentPath}`;
1139
+ const contents = generateServerFunctionClient(args.path, info.fnNames, endpointBase);
1140
+ return { contents, loader: "ts" };
1141
+ });
1142
+ }
1143
+ };
1144
+ }
1145
+ function generateHydrateEntry(routeAbsPath, layoutAbsPaths = []) {
1146
+ const layoutImports = layoutAbsPaths.map((p, i) => `import * as Layout${i} from "${p}";`).join("\n");
1147
+ const lookupParts = ["Route.islands?.[name]"];
1148
+ for (let i = 0; i < layoutAbsPaths.length; i++) {
1149
+ lookupParts.push(`Layout${i}.islands?.[name]`);
1150
+ }
1151
+ const lookup = lookupParts.join(" ?? ");
1152
+ return `import React from "react";
1153
+ import { hydrateRoot } from "react-dom/client";
1154
+ import * as Route from "${routeAbsPath}";
1155
+ ${layoutImports}
1156
+
1157
+ function resolveIsland(name: string) {
1158
+ return ${lookup};
1159
+ }
1160
+
1161
+ // Islands whose render is non-deterministic (e.g. \`useState(() => ...)\` with
1162
+ // Math.random) can't be hydrated against their SSR output. React recovers by
1163
+ // re-rendering client-side, so the island is still fully interactive -- the
1164
+ // mismatch is benign, so swallow the recovery so it doesn't spam the console
1165
+ // or cascade into React's event system.
1166
+ function onRecoverableError() {}
1167
+
1168
+ document.querySelectorAll("[data-island]").forEach((el) => {
1169
+ const name = el.getAttribute("data-island");
1170
+ if (!name) return;
1171
+ const Component = resolveIsland(name);
1172
+ if (!Component) return;
1173
+ hydrateRoot(el, React.createElement(Component), { onRecoverableError });
1174
+ });
1175
+ `;
1176
+ }
1177
+ function generateFallbackHydration(islandNames) {
1178
+ return `// x island hydration fallback \u2014 ${islandNames.join(", ")}
1179
+ document.querySelectorAll("[data-island]").forEach(function(el) {
1180
+ el.setAttribute("data-island-hydrated", "false");
1181
+ });
1182
+ `;
1183
+ }
1184
+ function hashId(str) {
1185
+ let h = 0;
1186
+ for (let i = 0; i < str.length; i++) {
1187
+ h = Math.imul(31, h) + str.charCodeAt(i) | 0;
1188
+ }
1189
+ return Math.abs(h).toString(36);
1190
+ }
1191
+ function islandEntryId(routeFilePath) {
1192
+ return `${basename(routeFilePath).replace(/\.(tsx|ts)$/, "")}-${hashId(routeFilePath)}`;
1193
+ }
1194
+ function wrapIslandBundle(code) {
1195
+ return `;(function () {
1196
+ ${code}
1197
+ })();
1198
+ `;
1199
+ }
1200
+ async function buildIslandBundleInMemory(routeFilePath, layoutFilePaths, islandNames, actionModules, projectRoot) {
1201
+ const entryId = islandEntryId(routeFilePath);
1202
+ const scratchRoot = join4(projectRoot, ".x", "islands-tmp");
1203
+ mkdirSync(scratchRoot, { recursive: true });
1204
+ const scratchDir = mkdtempSync(join4(scratchRoot, "x-islands-"));
1205
+ try {
1206
+ const entryPath = join4(scratchDir, `${entryId}.tsx`);
1207
+ writeFileSync3(entryPath, generateHydrateEntry(routeFilePath, layoutFilePaths), "utf-8");
1208
+ const result = await Bun.build({
1209
+ entrypoints: [entryPath],
1210
+ target: "browser",
1211
+ plugins: [actionsRewritePlugin(actionModules)]
1212
+ });
1213
+ if (!result.success) {
1214
+ for (const log of result.logs) {
1215
+ console.warn(` [islands] build error: ${log.message}`);
1216
+ }
1217
+ return wrapIslandBundle(generateFallbackHydration(islandNames));
1218
+ }
1219
+ const outputs = result.outputs.filter((o) => o.kind === "entry-point");
1220
+ const built = outputs[0] ?? result.outputs[0];
1221
+ if (!built) return wrapIslandBundle(generateFallbackHydration(islandNames));
1222
+ const code = await built.text();
1223
+ assertNoEnvLeakage(code, entryPath);
1224
+ return wrapIslandBundle(code);
1225
+ } catch (err) {
1226
+ console.warn(` [islands] build failed for ${routeFilePath}:`, err);
1227
+ return wrapIslandBundle(generateFallbackHydration(islandNames));
1228
+ } finally {
1229
+ rmSync(scratchDir, { recursive: true, force: true });
1230
+ }
1231
+ }
1232
+
1233
+ // src/middleware.ts
1234
+ function composeMiddleware(fns, handler) {
1235
+ return async (ctx, _next) => {
1236
+ let index = -1;
1237
+ const dispatch = async (i) => {
1238
+ if (i <= index) throw new Error("next() called multiple times");
1239
+ index = i;
1240
+ const fn = fns[i];
1241
+ if (fn) {
1242
+ return fn(ctx, () => dispatch(i + 1));
1243
+ }
1244
+ return handler(ctx);
1245
+ };
1246
+ return dispatch(0);
1247
+ };
1248
+ }
1249
+
1250
+ // src/observability/health.ts
1251
+ async function runChecks(checks) {
1252
+ const results = {};
1253
+ let allOk = true;
1254
+ await Promise.all(
1255
+ Object.entries(checks).map(async ([name, check]) => {
1256
+ try {
1257
+ const ok = await check();
1258
+ results[name] = ok ? "ok" : "error";
1259
+ if (!ok) allOk = false;
1260
+ } catch {
1261
+ results[name] = "error";
1262
+ allOk = false;
1263
+ }
1264
+ })
1265
+ );
1266
+ return { status: allOk ? "ok" : "error", checks: results };
1267
+ }
1268
+ function createHealthCheckHandler(options = {}) {
1269
+ const checks = options.checks ?? {};
1270
+ return async (req) => {
1271
+ const pathname = new URL(req.url).pathname;
1272
+ if (pathname === "/healthz") {
1273
+ return Response.json({ status: "ok" }, { status: 200 });
1274
+ }
1275
+ if (pathname === "/readyz") {
1276
+ const result = await runChecks(checks);
1277
+ return Response.json(result, { status: result.status === "ok" ? 200 : 503 });
1278
+ }
1279
+ return null;
1280
+ };
1281
+ }
1282
+
1283
+ // src/observability/logger.ts
1284
+ function write(level, message, fields) {
1285
+ const entry = {
1286
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1287
+ level,
1288
+ message,
1289
+ ...fields
1290
+ };
1291
+ const line = JSON.stringify(entry);
1292
+ if (level === "error") {
1293
+ console.error(line);
1294
+ } else if (level === "warn") {
1295
+ console.warn(line);
1296
+ } else {
1297
+ console.log(line);
1298
+ }
1299
+ }
1300
+ var logger = {
1301
+ info: (message, fields) => write("info", message, fields),
1302
+ warn: (message, fields) => write("warn", message, fields),
1303
+ error: (message, fields) => write("error", message, fields)
1304
+ };
1305
+ function withRequestLogging(handler) {
1306
+ return async (req) => {
1307
+ const start = performance.now();
1308
+ const requestId = req.headers.get("x-request-id") ?? crypto.randomUUID();
1309
+ const route = new URL(req.url).pathname;
1310
+ try {
1311
+ const res = await handler(req);
1312
+ const isStream = res.headers.get("content-type")?.includes("text/event-stream");
1313
+ console.log(
1314
+ `[x][request] ${req.method} ${route} -> ${res.status}${isStream ? " (stream opened, not closed)" : ""}`
1315
+ );
1316
+ write("info", isStream ? "stream opened" : "request completed", {
1317
+ requestId,
1318
+ route,
1319
+ method: req.method,
1320
+ status: res.status,
1321
+ durationMs: Math.round(performance.now() - start)
1322
+ });
1323
+ if (!res.headers.has("x-request-id")) {
1324
+ res.headers.set("x-request-id", requestId);
1325
+ }
1326
+ return res;
1327
+ } catch (err) {
1328
+ write("error", "request failed", {
1329
+ requestId,
1330
+ route,
1331
+ method: req.method,
1332
+ status: 500,
1333
+ durationMs: Math.round(performance.now() - start),
1334
+ error: err instanceof Error ? err.message : String(err)
1335
+ });
1336
+ throw err;
1337
+ }
1338
+ };
1339
+ }
1340
+
1341
+ // src/security/headers.ts
1342
+ var DEFAULT_CSP = "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'";
1343
+ function buildSecurityHeaders(options = {}) {
1344
+ const headers = new Headers();
1345
+ const csp = options.contentSecurityPolicy ?? DEFAULT_CSP;
1346
+ if (csp !== false) headers.set("Content-Security-Policy", csp);
1347
+ const hstsMaxAge = options.hstsMaxAge ?? 15552e3;
1348
+ if (hstsMaxAge !== false) {
1349
+ const includeSub = options.hstsIncludeSubDomains ?? true;
1350
+ headers.set(
1351
+ "Strict-Transport-Security",
1352
+ `max-age=${hstsMaxAge}${includeSub ? "; includeSubDomains" : ""}`
1353
+ );
1354
+ }
1355
+ const frameOptions = options.frameOptions ?? "DENY";
1356
+ if (frameOptions !== false) headers.set("X-Frame-Options", frameOptions);
1357
+ const contentTypeOptions = options.contentTypeOptions ?? "nosniff";
1358
+ if (contentTypeOptions !== false) headers.set("X-Content-Type-Options", contentTypeOptions);
1359
+ const referrerPolicy = options.referrerPolicy ?? "strict-origin-when-cross-origin";
1360
+ if (referrerPolicy !== false) headers.set("Referrer-Policy", referrerPolicy);
1361
+ return headers;
1362
+ }
1363
+ function applySecurityHeaders(res, options = {}) {
1364
+ const extra = buildSecurityHeaders(options);
1365
+ for (const [key, value] of extra.entries()) {
1366
+ if (!res.headers.has(key)) {
1367
+ res.headers.set(key, value);
1368
+ }
1369
+ }
1370
+ return res;
1371
+ }
1372
+
1373
+ // src/security/rate-limit.ts
1374
+ function defaultKeyFn(req) {
1375
+ const headers = req.headers;
1376
+ const forwarded = headers.get("x-forwarded-for");
1377
+ if (forwarded) return forwarded.split(",")[0]?.trim() ?? "unknown";
1378
+ return headers.get("x-real-ip") ?? "unknown";
1379
+ }
1380
+ function createRateLimiter(options = {}) {
1381
+ const limit = options.limit ?? 60;
1382
+ const windowMs = options.windowMs ?? 6e4;
1383
+ const keyFn = options.keyFn ?? defaultKeyFn;
1384
+ const store = options.store;
1385
+ const buckets = /* @__PURE__ */ new Map();
1386
+ async function check(req) {
1387
+ const key = keyFn(req);
1388
+ if (store) {
1389
+ const { count, resetAt } = await store.incr(key, windowMs);
1390
+ return { ok: count <= limit, limit, remaining: Math.max(0, limit - count), resetAt };
1391
+ }
1392
+ const now = Date.now();
1393
+ let bucket = buckets.get(key);
1394
+ if (!bucket || bucket.resetAt <= now) {
1395
+ bucket = { count: 0, resetAt: now + windowMs };
1396
+ buckets.set(key, bucket);
1397
+ }
1398
+ bucket.count += 1;
1399
+ const ok = bucket.count <= limit;
1400
+ return { ok, limit, remaining: Math.max(0, limit - bucket.count), resetAt: bucket.resetAt };
1401
+ }
1402
+ function sweep() {
1403
+ const now = Date.now();
1404
+ for (const [key, bucket] of buckets) {
1405
+ if (bucket.resetAt <= now) buckets.delete(key);
1406
+ }
1108
1407
  }
1408
+ const timer = setInterval(sweep, Math.max(windowMs, 1e3));
1409
+ timer.unref?.();
1410
+ return { check, sweep, buckets, dispose: () => clearInterval(timer) };
1109
1411
  }
1110
- function getServerFunctionHandler(csrfOptions) {
1111
- return async (req) => {
1112
- if (req.method !== "POST") return null;
1113
- const url = new URL(req.url);
1114
- if (!url.pathname.startsWith("/__x/actions/")) return null;
1115
- const csrfResult = checkCsrf(req, csrfOptions);
1116
- if (!csrfResult.ok) {
1117
- return new Response(`Forbidden: ${csrfResult.reason}`, { status: 403 });
1118
- }
1119
- const parts = url.pathname.replace("/__x/actions/", "").split("/");
1120
- if (parts.length < 2) return null;
1121
- const actionName = parts.pop();
1122
- if (!actionName) return null;
1123
- const concretePath = `/${parts.join("/")}`;
1124
- for (const entry of ACTION_ROUTES) {
1125
- const params = extractActionParams(entry.routePath, entry.paramNames, concretePath);
1126
- if (params === null) continue;
1127
- const fn = entry.fns.get(actionName);
1128
- if (!fn) return new Response("Function not found", { status: 404 });
1129
- let args = [];
1130
- try {
1131
- const body = await req.json();
1132
- args = Array.isArray(body) ? body : [body];
1133
- } catch {
1134
- return new Response("Invalid request body", { status: 400 });
1135
- }
1136
- try {
1137
- const result = await fn(...args);
1138
- return Response.json(result);
1139
- } catch (err) {
1140
- reportException(err, { route: concretePath, phase: "action" });
1141
- const message = err instanceof Error ? err.message : "Internal error";
1142
- return new Response(message, { status: 500 });
1143
- }
1412
+ async function rateLimitMiddleware(limiter, req) {
1413
+ const result = await limiter.check(req);
1414
+ if (result.ok) return null;
1415
+ const retryAfterSeconds = Math.max(1, Math.ceil((result.resetAt - Date.now()) / 1e3));
1416
+ return new Response("Too Many Requests", {
1417
+ status: 429,
1418
+ headers: {
1419
+ "Retry-After": String(retryAfterSeconds),
1420
+ "X-RateLimit-Limit": String(result.limit),
1421
+ "X-RateLimit-Remaining": String(result.remaining)
1144
1422
  }
1145
- return new Response("Not found", { status: 404 });
1146
- };
1423
+ });
1147
1424
  }
1148
- function extractActionParams(routePath, paramNames, url) {
1149
- const regex = routePatternToRegex(routePath);
1150
- const match = url.match(regex);
1151
- if (!match) return null;
1152
- const params = {};
1153
- let idx = 1;
1154
- for (const name of paramNames) {
1155
- const value = match[idx];
1156
- if (value !== void 0) {
1157
- params[name] = value;
1425
+ function createRedisRateLimitStore(options = {}) {
1426
+ let client = null;
1427
+ let connecting = null;
1428
+ async function connect() {
1429
+ const require2 = import.meta.require;
1430
+ const mod = require2("bun:redis");
1431
+ const instance = options.url ? new mod.RedisClient({ url: options.url }) : new mod.RedisClient();
1432
+ await instance.connect();
1433
+ return instance;
1434
+ }
1435
+ function getClient() {
1436
+ if (client) return Promise.resolve(client);
1437
+ if (!connecting) {
1438
+ connecting = connect().then(
1439
+ (c) => {
1440
+ client = c;
1441
+ return c;
1442
+ },
1443
+ (err) => {
1444
+ connecting = null;
1445
+ throw err;
1446
+ }
1447
+ );
1158
1448
  }
1159
- idx++;
1449
+ return connecting;
1160
1450
  }
1161
- return params;
1451
+ return {
1452
+ async incr(key, windowMs) {
1453
+ const c = await getClient();
1454
+ const redisKey = `x:ratelimit:${key}`;
1455
+ const ttlSeconds = Math.max(1, Math.ceil(windowMs / 1e3));
1456
+ const count = Number(await c.sendCommand("INCR", redisKey));
1457
+ if (count === 1) {
1458
+ await c.sendCommand("EXPIRE", redisKey, String(ttlSeconds));
1459
+ }
1460
+ return { count, resetAt: Date.now() + windowMs };
1461
+ }
1462
+ };
1162
1463
  }
1163
1464
 
1164
1465
  // src/createApp.ts
1165
- var HTTP_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
1166
1466
  function projectRootFromRoutesDir(routesDir) {
1167
- return join4(routesDir, "..", "..");
1467
+ return join5(routesDir, "..", "..");
1168
1468
  }
1169
1469
  function resolvePublicAsset(publicDir, pathname) {
1170
1470
  let decoded;
@@ -1173,7 +1473,7 @@ function resolvePublicAsset(publicDir, pathname) {
1173
1473
  } catch {
1174
1474
  return null;
1175
1475
  }
1176
- const target = resolve(join4(publicDir, decoded));
1476
+ const target = resolve(join5(publicDir, decoded));
1177
1477
  const root = resolve(publicDir);
1178
1478
  if (target !== root && !target.startsWith(root + sep3)) return null;
1179
1479
  return target;
@@ -1185,7 +1485,9 @@ async function serveStaticAsset(publicDir, req) {
1185
1485
  if (pathname === "/" || pathname.endsWith("/")) return null;
1186
1486
  const filePath = resolvePublicAsset(publicDir, pathname);
1187
1487
  if (!filePath) return null;
1188
- const file = Bun.file(filePath);
1488
+ const bun = globalThis.Bun;
1489
+ if (!bun) return null;
1490
+ const file = bun.file(filePath);
1189
1491
  if (!await file.exists()) return null;
1190
1492
  return new Response(file);
1191
1493
  }
@@ -1222,6 +1524,8 @@ function importDev(path, dev) {
1222
1524
  async function createApp(options) {
1223
1525
  const dev = options.development ?? false;
1224
1526
  const primaryDir = options.pagesDir || options.routesDir || "src/pages";
1527
+ const projectRoot = projectRootFromRoutesDir(primaryDir);
1528
+ const resolvedActionsDir = options.actionsDir ?? (existsSync(join5(projectRoot, "src", "actions")) ? join5(projectRoot, "src", "actions") : void 0);
1225
1529
  let handlers = [];
1226
1530
  let contentHandlers = [];
1227
1531
  let publicDir = null;
@@ -1230,6 +1534,39 @@ async function createApp(options) {
1230
1534
  let notFoundLayout;
1231
1535
  const serverFnHandler = getServerFunctionHandler(options.security?.csrf);
1232
1536
  const staticCache = /* @__PURE__ */ new Map();
1537
+ let actionModules = /* @__PURE__ */ new Map();
1538
+ const islandBundleCache = /* @__PURE__ */ new Map();
1539
+ const islandFileCache = /* @__PURE__ */ new Map();
1540
+ async function resolveIslandScripts(routeFilePath, layoutFilePaths, entries) {
1541
+ if (entries.length === 0) return [];
1542
+ const uniqueNames = [...new Set(entries.map((e) => e.name))].sort();
1543
+ const cacheKey = `${routeFilePath}::${layoutFilePaths.join("|")}::${uniqueNames.join(",")}`;
1544
+ const cached = islandBundleCache.get(cacheKey);
1545
+ if (cached) return cached;
1546
+ const code = await buildIslandBundleInMemory(
1547
+ routeFilePath,
1548
+ layoutFilePaths,
1549
+ uniqueNames,
1550
+ actionModules,
1551
+ projectRoot
1552
+ );
1553
+ const entryId = islandEntryId(routeFilePath);
1554
+ const url = `/_islands/${entryId}/${entryId}.js`;
1555
+ islandFileCache.set(url, code);
1556
+ const scripts = [url];
1557
+ islandBundleCache.set(cacheKey, scripts);
1558
+ return scripts;
1559
+ }
1560
+ function serveIslandBundle(req) {
1561
+ if (req.method !== "GET" && req.method !== "HEAD") return null;
1562
+ const pathname = new URL(req.url).pathname;
1563
+ if (!pathname.startsWith("/_islands/")) return null;
1564
+ const code = islandFileCache.get(pathname);
1565
+ if (code === void 0) return null;
1566
+ return new Response(code, {
1567
+ headers: { "Content-Type": "application/javascript; charset=utf-8" }
1568
+ });
1569
+ }
1233
1570
  if (options.observability?.errorReporter) {
1234
1571
  setErrorReporter(options.observability.errorReporter);
1235
1572
  }
@@ -1237,6 +1574,7 @@ async function createApp(options) {
1237
1574
  const rateLimiter = options.security?.rateLimit === false ? null : createRateLimiter(options.security?.rateLimit ?? {});
1238
1575
  const securityHeadersOptions = options.security?.headers;
1239
1576
  const loggingEnabled = options.observability?.logging ?? true;
1577
+ const imageProxyHandler = createImageProxyHandler(options.images);
1240
1578
  function withResponseHardening(res) {
1241
1579
  return securityHeadersOptions === false ? res : applySecurityHeaders(res, securityHeadersOptions);
1242
1580
  }
@@ -1252,8 +1590,183 @@ async function createApp(options) {
1252
1590
  headers: { "Content-Type": "text/html; charset=utf-8" }
1253
1591
  });
1254
1592
  }
1593
+ const makeApiHandler = (route, module) => async (req) => {
1594
+ try {
1595
+ const method = req.method;
1596
+ const handlerFn = module[method];
1597
+ if (typeof handlerFn === "function") {
1598
+ const result = await handlerFn(req);
1599
+ if (result instanceof Response) return result;
1600
+ if (result === void 0 || result === null) {
1601
+ return new Response("OK", { status: 200 });
1602
+ }
1603
+ return Response.json(result);
1604
+ }
1605
+ return new Response(`Method ${method} not allowed`, { status: 405 });
1606
+ } catch (err) {
1607
+ reportException(err, { route: route.routePath, phase: "api" });
1608
+ console.error("[x] API handler error:", err);
1609
+ if (dev) {
1610
+ return new Response(renderErrorOverlay(err), {
1611
+ status: 500,
1612
+ headers: { "Content-Type": "text/html; charset=utf-8" }
1613
+ });
1614
+ }
1615
+ return new Response("Internal server error", { status: 500 });
1616
+ }
1617
+ };
1618
+ const makePageHandler = (opts) => {
1619
+ const {
1620
+ route,
1621
+ mode,
1622
+ revalidate,
1623
+ loader,
1624
+ Component,
1625
+ layoutModules,
1626
+ layoutFilePaths,
1627
+ middlewareModules,
1628
+ islandScripts
1629
+ } = opts;
1630
+ return async (req) => {
1631
+ try {
1632
+ const params = extractParams(route.routePath, route.paramNames, new URL(req.url).pathname) ?? {};
1633
+ const baseHandler = async (ctx) => {
1634
+ let loaderData = {};
1635
+ if (loader) {
1636
+ const result = await loader(ctx);
1637
+ if (result instanceof Response) return result;
1638
+ loaderData = result;
1639
+ }
1640
+ if (mode === "server") {
1641
+ const registry2 = createIslandRegistry();
1642
+ const content2 = createElement(
1643
+ IslandProvider,
1644
+ { registry: registry2 },
1645
+ wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
1646
+ );
1647
+ let scripts2 = islandScripts;
1648
+ if (scripts2 === void 0) {
1649
+ renderPage(content2, { stylesheet: stylesheetHref, liveReload: dev });
1650
+ scripts2 = await resolveIslandScripts(
1651
+ route.filePath,
1652
+ layoutFilePaths,
1653
+ registry2.entries
1654
+ );
1655
+ }
1656
+ const stream = await renderStreamingPage(content2, {
1657
+ stylesheet: stylesheetHref,
1658
+ liveReload: dev,
1659
+ islandScripts: scripts2
1660
+ });
1661
+ return new Response(stream, {
1662
+ headers: { "Content-Type": "text/html; charset=utf-8" }
1663
+ });
1664
+ }
1665
+ const cached = staticCache.get(route.routePath);
1666
+ const revalidateSeconds = revalidate ?? 0;
1667
+ if (revalidateSeconds > 0 && cached && Date.now() - cached.timestamp < revalidateSeconds * 1e3) {
1668
+ return new Response(cached.html, {
1669
+ headers: { "Content-Type": "text/html; charset=utf-8", "X-Revalidated": "hit" }
1670
+ });
1671
+ }
1672
+ const registry = createIslandRegistry();
1673
+ const content = createElement(
1674
+ IslandProvider,
1675
+ { registry },
1676
+ wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
1677
+ );
1678
+ let scripts = islandScripts;
1679
+ if (scripts === void 0) {
1680
+ renderPage(content, { stylesheet: stylesheetHref, liveReload: dev });
1681
+ scripts = await resolveIslandScripts(route.filePath, layoutFilePaths, registry.entries);
1682
+ }
1683
+ const html = renderPage(content, {
1684
+ stylesheet: stylesheetHref,
1685
+ liveReload: dev,
1686
+ islandScripts: scripts
1687
+ });
1688
+ if (revalidateSeconds > 0) {
1689
+ staticCache.set(route.routePath, { html, timestamp: Date.now() });
1690
+ }
1691
+ return new Response(html, {
1692
+ headers: {
1693
+ "Content-Type": "text/html; charset=utf-8",
1694
+ "X-Revalidated": revalidateSeconds > 0 ? "miss" : "none"
1695
+ }
1696
+ });
1697
+ };
1698
+ if (middlewareModules.length > 0) {
1699
+ const composed = composeMiddleware(middlewareModules, baseHandler);
1700
+ return composed(
1701
+ { params, request: req },
1702
+ async () => new Response("Not found", { status: 404 })
1703
+ );
1704
+ }
1705
+ return baseHandler({ params, request: req });
1706
+ } catch (err) {
1707
+ reportException(err, { route: route.routePath, phase: "ssr" });
1708
+ console.error("[x] route handler error:", err);
1709
+ if (dev) {
1710
+ return new Response(renderErrorOverlay(err), {
1711
+ status: 500,
1712
+ headers: { "Content-Type": "text/html; charset=utf-8" }
1713
+ });
1714
+ }
1715
+ return new Response("Internal server error", { status: 500 });
1716
+ }
1717
+ };
1718
+ };
1255
1719
  async function buildHandlers() {
1720
+ if (options.preloaded) {
1721
+ const preloaded = options.preloaded;
1722
+ const candidatePublicDir2 = join5(projectRoot, "public");
1723
+ publicDir = existsSync(candidatePublicDir2) ? candidatePublicDir2 : null;
1724
+ stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync(join5(publicDir, "styles.css")) ? "/styles.css" : void 0);
1725
+ if (preloaded.notFoundComponent) notFoundComponent = preloaded.notFoundComponent;
1726
+ if (preloaded.notFoundLayout) notFoundLayout = preloaded.notFoundLayout;
1727
+ const loaded2 = [];
1728
+ for (const p of preloaded.routes) {
1729
+ const actions = p.module.actions;
1730
+ if (actions) {
1731
+ registerServerFunctions(p.entry.routePath, p.entry.paramNames, actions);
1732
+ }
1733
+ if (p.entry.isApi) {
1734
+ loaded2.push({
1735
+ entry: p.entry,
1736
+ mode: p.mode,
1737
+ revalidate: void 0,
1738
+ handler: makeApiHandler(p.entry, p.module)
1739
+ });
1740
+ continue;
1741
+ }
1742
+ const Component = p.module.default;
1743
+ if (!Component) continue;
1744
+ const routeMiddleware = p.module.middleware;
1745
+ const middlewareModules = routeMiddleware ? [...p.middlewareModules, routeMiddleware] : p.middlewareModules;
1746
+ loaded2.push({
1747
+ entry: p.entry,
1748
+ mode: p.mode,
1749
+ revalidate: p.revalidate,
1750
+ handler: makePageHandler({
1751
+ route: p.entry,
1752
+ mode: p.mode,
1753
+ revalidate: p.revalidate,
1754
+ loader: p.module.loader,
1755
+ Component,
1756
+ layoutModules: p.layoutModules,
1757
+ layoutFilePaths: p.layoutFilePaths ?? [],
1758
+ middlewareModules,
1759
+ islandScripts: p.islandScripts
1760
+ })
1761
+ });
1762
+ }
1763
+ handlers = loaded2;
1764
+ return;
1765
+ }
1256
1766
  resetServerFunctions();
1767
+ actionModules = /* @__PURE__ */ new Map();
1768
+ islandBundleCache.clear();
1769
+ islandFileCache.clear();
1257
1770
  const pagesDir = primaryDir;
1258
1771
  const apiDir = options.apiDir;
1259
1772
  const layoutsDir = options.layoutsDir || pagesDir;
@@ -1262,7 +1775,7 @@ async function createApp(options) {
1262
1775
  if (apiDir && existsSync(apiDir)) {
1263
1776
  apiFound.push(...scanApiDir(apiDir));
1264
1777
  }
1265
- const legacyApiDir = join4(pagesDir, "api");
1778
+ const legacyApiDir = join5(pagesDir, "api");
1266
1779
  if (existsSync(legacyApiDir) && legacyApiDir !== apiDir) {
1267
1780
  apiFound.push(...scanApiDir(legacyApiDir));
1268
1781
  }
@@ -1272,29 +1785,34 @@ async function createApp(options) {
1272
1785
  const nestedLayouts = scanLayouts(pagesDir);
1273
1786
  const layouts = [...dedicatedLayouts, ...nestedLayouts];
1274
1787
  const middlewareEntries = scanMiddleware(pagesDir);
1275
- if (options.actionsDir) {
1276
- const actionFiles = scanRoutes(options.actionsDir);
1788
+ if (resolvedActionsDir) {
1789
+ const actionFiles = scanRoutes(resolvedActionsDir);
1277
1790
  for (const actionFile of actionFiles) {
1278
1791
  const mod = await importDev(actionFile.filePath, dev);
1279
1792
  const segments = actionFile.routePath.split("/").filter(Boolean);
1280
1793
  const fileName = segments[segments.length - 1] ?? "";
1281
1794
  const parentPath = fileName === "index" || !fileName ? actionFile.routePath : `/${segments.slice(0, -1).join("/")}`;
1282
1795
  const actions = mod.actions;
1796
+ const fnNames = [];
1283
1797
  if (actions) {
1284
1798
  registerServerFunctions(parentPath, actionFile.paramNames, actions);
1799
+ fnNames.push(...Object.keys(actions));
1285
1800
  }
1286
1801
  for (const [key, value] of Object.entries(mod)) {
1287
1802
  if (key === "default" || key === "actions" || typeof value !== "function") continue;
1288
1803
  registerServerFunctions(parentPath, actionFile.paramNames, {
1289
1804
  [key]: value
1290
1805
  });
1806
+ fnNames.push(key);
1807
+ }
1808
+ if (fnNames.length > 0) {
1809
+ actionModules.set(actionFile.filePath, { parentPath, fnNames });
1291
1810
  }
1292
1811
  }
1293
1812
  }
1294
- const projectRoot = projectRootFromRoutesDir(pagesDir);
1295
- const candidatePublicDir = join4(projectRoot, "public");
1813
+ const candidatePublicDir = join5(projectRoot, "public");
1296
1814
  publicDir = existsSync(candidatePublicDir) ? candidatePublicDir : null;
1297
- stylesheetHref = publicDir && existsSync(join4(publicDir, "styles.css")) ? "/styles.css" : void 0;
1815
+ stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync(join5(publicDir, "styles.css")) ? "/styles.css" : void 0);
1298
1816
  const notFoundEntry = scanNotFound(pagesDir);
1299
1817
  if (notFoundEntry) {
1300
1818
  const mod = await importDev(notFoundEntry.filePath, dev);
@@ -1316,12 +1834,6 @@ async function createApp(options) {
1316
1834
  for (const route of found) {
1317
1835
  const mod = await importDev(route.filePath, dev);
1318
1836
  if (route.isApi) {
1319
- const methodHandlers = {};
1320
- for (const method of HTTP_METHODS) {
1321
- if (typeof mod[method] === "function") {
1322
- methodHandlers[method] = mod[method];
1323
- }
1324
- }
1325
1837
  const actions2 = mod.actions;
1326
1838
  if (actions2) {
1327
1839
  registerServerFunctions(route.routePath, route.paramNames, actions2);
@@ -1330,31 +1842,7 @@ async function createApp(options) {
1330
1842
  entry: route,
1331
1843
  mode: "server",
1332
1844
  revalidate: void 0,
1333
- handler: async (req) => {
1334
- try {
1335
- const method = req.method;
1336
- const handlerFn = methodHandlers[method];
1337
- if (handlerFn) {
1338
- const result = await handlerFn(req);
1339
- if (result instanceof Response) return result;
1340
- if (result === void 0 || result === null) {
1341
- return new Response("OK", { status: 200 });
1342
- }
1343
- return Response.json(result);
1344
- }
1345
- return new Response(`Method ${method} not allowed`, { status: 405 });
1346
- } catch (err) {
1347
- reportException(err, { route: route.routePath, phase: "api" });
1348
- console.error("[x] API handler error:", err);
1349
- if (options.development) {
1350
- return new Response(renderErrorOverlay(err), {
1351
- status: 500,
1352
- headers: { "Content-Type": "text/html; charset=utf-8" }
1353
- });
1354
- }
1355
- return new Response("Internal server error", { status: 500 });
1356
- }
1357
- }
1845
+ handler: makeApiHandler(route, mod)
1358
1846
  });
1359
1847
  continue;
1360
1848
  }
@@ -1379,6 +1867,7 @@ async function createApp(options) {
1379
1867
  layoutChain.unshift(rootLayout2);
1380
1868
  }
1381
1869
  }
1870
+ const layoutFilePaths = layoutChain.map((l) => l.filePath);
1382
1871
  const layoutModules = [];
1383
1872
  for (const l of layoutChain) {
1384
1873
  const layoutMod = await importDev(l.filePath, dev);
@@ -1399,65 +1888,16 @@ async function createApp(options) {
1399
1888
  entry: route,
1400
1889
  mode,
1401
1890
  revalidate,
1402
- handler: async (req) => {
1403
- try {
1404
- const params = extractParams(route.routePath, route.paramNames, new URL(req.url).pathname) ?? {};
1405
- const baseHandler = async (ctx) => {
1406
- let loaderData = {};
1407
- if (loader) {
1408
- const result = await loader(ctx);
1409
- if (result instanceof Response) return result;
1410
- loaderData = result;
1411
- }
1412
- if (mode === "server") {
1413
- const content2 = wrapWithLayouts(Component, ctx.params, loaderData, layoutModules);
1414
- const stream = await renderStreamingPage(content2, {
1415
- stylesheet: stylesheetHref,
1416
- liveReload: dev
1417
- });
1418
- return new Response(stream, {
1419
- headers: { "Content-Type": "text/html; charset=utf-8" }
1420
- });
1421
- }
1422
- const cached = staticCache.get(route.routePath);
1423
- const revalidateSeconds = revalidate ?? 0;
1424
- if (revalidateSeconds > 0 && cached && Date.now() - cached.timestamp < revalidateSeconds * 1e3) {
1425
- return new Response(cached.html, {
1426
- headers: { "Content-Type": "text/html; charset=utf-8", "X-Revalidated": "hit" }
1427
- });
1428
- }
1429
- const content = wrapWithLayouts(Component, ctx.params, loaderData, layoutModules);
1430
- const html = renderPage(content, { stylesheet: stylesheetHref, liveReload: dev });
1431
- if (revalidateSeconds > 0) {
1432
- staticCache.set(route.routePath, { html, timestamp: Date.now() });
1433
- }
1434
- return new Response(html, {
1435
- headers: {
1436
- "Content-Type": "text/html; charset=utf-8",
1437
- "X-Revalidated": revalidateSeconds > 0 ? "miss" : "none"
1438
- }
1439
- });
1440
- };
1441
- if (middlewareModules.length > 0) {
1442
- const composed = composeMiddleware(middlewareModules, baseHandler);
1443
- return composed(
1444
- { params, request: req },
1445
- async () => new Response("Not found", { status: 404 })
1446
- );
1447
- }
1448
- return baseHandler({ params, request: req });
1449
- } catch (err) {
1450
- reportException(err, { route: route.routePath, phase: "ssr" });
1451
- console.error("[x] route handler error:", err);
1452
- if (options.development) {
1453
- return new Response(renderErrorOverlay(err), {
1454
- status: 500,
1455
- headers: { "Content-Type": "text/html; charset=utf-8" }
1456
- });
1457
- }
1458
- return new Response("Internal server error", { status: 500 });
1459
- }
1460
- }
1891
+ handler: makePageHandler({
1892
+ route,
1893
+ mode,
1894
+ revalidate,
1895
+ loader,
1896
+ Component,
1897
+ layoutModules,
1898
+ layoutFilePaths,
1899
+ middlewareModules
1900
+ })
1461
1901
  });
1462
1902
  }
1463
1903
  handlers = loaded;
@@ -1528,10 +1968,10 @@ async function createApp(options) {
1528
1968
  let rebuildTimeout = null;
1529
1969
  const sseClients = /* @__PURE__ */ new Set();
1530
1970
  try {
1531
- const srcDir = join4(primaryDir, "..", "..", "src");
1971
+ const srcDir = join5(primaryDir, "..", "..", "src");
1532
1972
  const watchDirs = [
1533
1973
  ...new Set(
1534
- [primaryDir, options.apiDir, options.layoutsDir, options.actionsDir, srcDir].filter(
1974
+ [primaryDir, options.apiDir, options.layoutsDir, resolvedActionsDir, srcDir].filter(
1535
1975
  Boolean
1536
1976
  )
1537
1977
  )
@@ -1554,7 +1994,7 @@ async function createApp(options) {
1554
1994
  const healthResult = await healthHandler(req);
1555
1995
  if (healthResult !== null) return healthResult;
1556
1996
  if (rateLimiter) {
1557
- const limited = rateLimitMiddleware(rateLimiter, req);
1997
+ const limited = await rateLimitMiddleware(rateLimiter, req);
1558
1998
  if (limited !== null) return limited;
1559
1999
  }
1560
2000
  if (url === "/__x/reload") {
@@ -1569,14 +2009,26 @@ data: ${data}
1569
2009
  `));
1570
2010
  };
1571
2011
  sseClients.add(send);
1572
- req.signal.addEventListener("abort", () => sseClients.delete(send));
2012
+ console.log(`[x][reload] client connected (${sseClients.size} total)`);
2013
+ const heartbeat = setInterval(() => {
2014
+ try {
2015
+ send("hb", "");
2016
+ } catch (err) {
2017
+ console.log(`[x][reload] heartbeat failed, clearing interval: ${String(err)}`);
2018
+ clearInterval(heartbeat);
2019
+ }
2020
+ }, 5e3);
2021
+ req.signal.addEventListener("abort", () => {
2022
+ clearInterval(heartbeat);
2023
+ sseClients.delete(send);
2024
+ console.log(`[x][reload] client disconnected (${sseClients.size} total)`);
2025
+ });
1573
2026
  }
1574
2027
  });
1575
2028
  return new Response(body, {
1576
2029
  headers: {
1577
2030
  "Content-Type": "text/event-stream",
1578
- "Cache-Control": "no-cache",
1579
- Connection: "keep-alive"
2031
+ "Cache-Control": "no-cache"
1580
2032
  }
1581
2033
  });
1582
2034
  }
@@ -1586,6 +2038,10 @@ data: ${data}
1586
2038
  if (serverFnResult !== null) return serverFnResult;
1587
2039
  const staticAsset = await serveStaticAsset(publicDir, req);
1588
2040
  if (staticAsset !== null) return staticAsset;
2041
+ const islandBundle = serveIslandBundle(req);
2042
+ if (islandBundle !== null) return islandBundle;
2043
+ const proxiedImage = await imageProxyHandler(req);
2044
+ if (proxiedImage !== null) return proxiedImage;
1589
2045
  for (const h of handlers) {
1590
2046
  const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
1591
2047
  if (params !== null) {
@@ -1613,7 +2069,7 @@ data: ${data}
1613
2069
  const healthResult = await healthHandler(req);
1614
2070
  if (healthResult !== null) return healthResult;
1615
2071
  if (rateLimiter) {
1616
- const limited = rateLimitMiddleware(rateLimiter, req);
2072
+ const limited = await rateLimitMiddleware(rateLimiter, req);
1617
2073
  if (limited !== null) return limited;
1618
2074
  }
1619
2075
  const revalidationResult = await handleRevalidation(req);
@@ -1622,6 +2078,10 @@ data: ${data}
1622
2078
  if (serverFnResult !== null) return serverFnResult;
1623
2079
  const staticAsset = await serveStaticAsset(publicDir, req);
1624
2080
  if (staticAsset !== null) return staticAsset;
2081
+ const islandBundle = serveIslandBundle(req);
2082
+ if (islandBundle !== null) return islandBundle;
2083
+ const proxiedImage = await imageProxyHandler(req);
2084
+ if (proxiedImage !== null) return proxiedImage;
1625
2085
  for (const h of handlers) {
1626
2086
  const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
1627
2087
  if (params !== null) {
@@ -1646,94 +2106,25 @@ data: ${data}
1646
2106
  }
1647
2107
 
1648
2108
  // src/build.ts
1649
- import { cpSync, existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "fs";
1650
- import { basename, join as join5, relative as relative3 } from "path";
2109
+ import { cpSync, existsSync as existsSync2, mkdirSync as mkdirSync2, writeFileSync as writeFileSync4 } from "fs";
2110
+ import { join as join6, relative as relative3 } from "path";
1651
2111
  import { createElement as createElement2 } from "react";
1652
-
1653
- // src/island.tsx
1654
- import { createContext, useContext } from "react";
1655
- import { jsx as jsx2 } from "react/jsx-runtime";
1656
- function createIslandRegistry() {
1657
- return { entries: [] };
1658
- }
1659
- var IslandContext = createContext(null);
1660
- function IslandProvider({
1661
- registry,
1662
- children
1663
- }) {
1664
- return /* @__PURE__ */ jsx2(IslandContext.Provider, { value: registry, children });
1665
- }
1666
- var islandCounter = 0;
1667
- function Island({
1668
- name,
1669
- client = "idle",
1670
- children
1671
- }) {
1672
- const registry = useContext(IslandContext);
1673
- const id = `x-island-${islandCounter++}`;
1674
- if (registry) {
1675
- registry.entries.push({ name, id });
1676
- }
1677
- return /* @__PURE__ */ jsx2("div", { "data-island": name, "data-island-id": id, "data-island-client": client, children });
1678
- }
1679
-
1680
- // src/security/env-isolation.ts
1681
- var PUBLIC_ENV_PREFIX = "THEXJS_PUBLIC_";
1682
- var ENV_ACCESS_PATTERNS = [
1683
- /\bprocess\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
1684
- /\bprocess\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g,
1685
- /\bBun\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
1686
- /\bBun\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g,
1687
- /\bimport\.meta\.env\.([A-Za-z_][A-Za-z0-9_]*)/g
1688
- ];
1689
- function findLeakedEnvKeys(code) {
1690
- const found = /* @__PURE__ */ new Set();
1691
- for (const pattern of ENV_ACCESS_PATTERNS) {
1692
- for (const match of code.matchAll(pattern)) {
1693
- const key = match[1];
1694
- if (key && !key.startsWith(PUBLIC_ENV_PREFIX)) {
1695
- found.add(key);
1696
- }
1697
- }
1698
- }
1699
- return [...found];
1700
- }
1701
- var EnvLeakageError = class extends Error {
1702
- constructor(file, keys) {
1703
- super(
1704
- `[x] server-only environment variable(s) leaked into client bundle "${file}": ${keys.join(", ")}. Only "${PUBLIC_ENV_PREFIX}*" variables may be referenced in client-shipped code \u2014 move this access into a loader, server function, or API route.`
1705
- );
1706
- this.file = file;
1707
- this.keys = keys;
1708
- this.name = "EnvLeakageError";
1709
- }
1710
- file;
1711
- keys;
1712
- };
1713
- function assertNoEnvLeakage(code, file) {
1714
- const leaked = findLeakedEnvKeys(code);
1715
- if (leaked.length > 0) {
1716
- throw new EnvLeakageError(file, leaked);
1717
- }
1718
- }
1719
-
1720
- // src/build.ts
1721
2112
  async function build(options) {
1722
- const outDir = options.outDir ?? join5(process.cwd(), ".x");
1723
- const clientDir = join5(outDir, "client");
1724
- const serverDir = join5(outDir, "server");
1725
- const islandsDir = join5(clientDir, "_islands");
1726
- mkdirSync(clientDir, { recursive: true });
1727
- mkdirSync(serverDir, { recursive: true });
1728
- mkdirSync(islandsDir, { recursive: true });
2113
+ const outDir = options.outDir ?? join6(process.cwd(), ".x");
2114
+ const clientDir = join6(outDir, "client");
2115
+ const serverDir = join6(outDir, "server");
2116
+ const islandsDir = join6(clientDir, "_islands");
2117
+ mkdirSync2(clientDir, { recursive: true });
2118
+ mkdirSync2(serverDir, { recursive: true });
2119
+ mkdirSync2(islandsDir, { recursive: true });
1729
2120
  const pagesDir = options.pagesDir ?? options.routesDir ?? "";
1730
2121
  const apiDir = options.apiDir;
1731
2122
  const actionsDir = options.actionsDir;
1732
2123
  const layoutsDir = options.layoutsDir ?? pagesDir;
1733
- const projectRoot = pagesDir ? join5(pagesDir, "..", "..") : process.cwd();
1734
- const publicDir = join5(projectRoot, "public");
2124
+ const projectRoot = pagesDir ? join6(pagesDir, "..", "..") : process.cwd();
2125
+ const publicDir = join6(projectRoot, "public");
1735
2126
  const hasPublicDir = existsSync2(publicDir);
1736
- const stylesheetHref = hasPublicDir && existsSync2(join5(publicDir, "styles.css")) ? "/styles.css" : void 0;
2127
+ const stylesheetHref = hasPublicDir && existsSync2(join6(publicDir, "styles.css")) ? "/styles.css" : void 0;
1737
2128
  if (hasPublicDir) {
1738
2129
  cpSync(publicDir, clientDir, { recursive: true });
1739
2130
  console.log(`[x] build: copied public/ -> ${relative3(process.cwd(), clientDir)}`);
@@ -1745,22 +2136,31 @@ async function build(options) {
1745
2136
  if (apiDir && existsSync2(apiDir)) {
1746
2137
  routeEntries.push(...scanApiDir(apiDir));
1747
2138
  }
1748
- const legacyApiDir = pagesDir ? join5(pagesDir, "api") : "";
2139
+ const legacyApiDir = pagesDir ? join6(pagesDir, "api") : "";
1749
2140
  if (legacyApiDir && existsSync2(legacyApiDir) && legacyApiDir !== apiDir) {
1750
2141
  routeEntries.push(...scanApiDir(legacyApiDir));
1751
2142
  }
2143
+ const actionModules = /* @__PURE__ */ new Map();
1752
2144
  if (actionsDir && existsSync2(actionsDir)) {
1753
2145
  for (const actionFile of scanRoutes(actionsDir)) {
1754
2146
  const mod = await import(actionFile.filePath);
1755
2147
  const segments = actionFile.routePath.split("/").filter(Boolean);
1756
2148
  const parentPath = `/${segments.slice(0, -1).join("/")}`;
2149
+ const fnNames = [];
1757
2150
  const actions = mod.actions;
1758
- if (actions) registerServerFunctions(parentPath, actionFile.paramNames, actions);
2151
+ if (actions) {
2152
+ registerServerFunctions(parentPath, actionFile.paramNames, actions);
2153
+ fnNames.push(...Object.keys(actions));
2154
+ }
1759
2155
  for (const [key, value] of Object.entries(mod)) {
1760
2156
  if (key === "default" || key === "actions" || typeof value !== "function") continue;
1761
2157
  registerServerFunctions(parentPath, actionFile.paramNames, {
1762
2158
  [key]: value
1763
2159
  });
2160
+ fnNames.push(key);
2161
+ }
2162
+ if (fnNames.length > 0) {
2163
+ actionModules.set(actionFile.filePath, { parentPath, fnNames });
1764
2164
  }
1765
2165
  }
1766
2166
  }
@@ -1793,7 +2193,14 @@ async function build(options) {
1793
2193
  const layoutMod = await import(l.filePath);
1794
2194
  if (layoutMod.default) layoutModules.push(layoutMod.default);
1795
2195
  }
1796
- const page = { entry, filePath: entry.filePath, mode, Component, layoutModules };
2196
+ const page = {
2197
+ entry,
2198
+ filePath: entry.filePath,
2199
+ mode,
2200
+ Component,
2201
+ layoutModules,
2202
+ layoutFilePaths: layoutChain.map((l) => l.filePath)
2203
+ };
1797
2204
  if (mode === "static") {
1798
2205
  staticPages.push(page);
1799
2206
  } else {
@@ -1815,8 +2222,8 @@ async function build(options) {
1815
2222
  const content = createElement2(IslandProvider, { registry }, pageContent);
1816
2223
  const html = renderStaticPage(content, { stylesheet: stylesheetHref });
1817
2224
  const outPath = page.entry.routePath === "/" ? "/index.html" : `${page.entry.routePath}/index.html`;
1818
- const fullPath = join5(clientDir, outPath);
1819
- mkdirSync(join5(fullPath, ".."), { recursive: true });
2225
+ const fullPath = join6(clientDir, outPath);
2226
+ mkdirSync2(join6(fullPath, ".."), { recursive: true });
1820
2227
  if (writtenPaths.has(outPath)) {
1821
2228
  console.warn(` [warn] collision: ${page.entry.routePath} overwrites existing output`);
1822
2229
  }
@@ -1824,13 +2231,19 @@ async function build(options) {
1824
2231
  let islandScripts = [];
1825
2232
  if (registry.entries.length > 0) {
1826
2233
  const uniqueNames = [...new Set(registry.entries.map((e) => e.name))];
1827
- islandScripts = await bundleRouteIslands(page.filePath, uniqueNames, islandsDir);
2234
+ islandScripts = await bundleRouteIslands(
2235
+ page.filePath,
2236
+ page.layoutFilePaths,
2237
+ uniqueNames,
2238
+ islandsDir,
2239
+ actionModules
2240
+ );
1828
2241
  console.log(
1829
2242
  ` [islands] ${uniqueNames.length} island(s) on ${page.entry.routePath} -> ${islandScripts.join(", ")}`
1830
2243
  );
1831
2244
  }
1832
2245
  const finalHtml = renderStaticPage(content, { islandScripts, stylesheet: stylesheetHref });
1833
- writeFileSync3(fullPath, finalHtml, "utf-8");
2246
+ writeFileSync4(fullPath, finalHtml, "utf-8");
1834
2247
  console.log(` [static] ${page.entry.routePath} -> ${outPath}`);
1835
2248
  }
1836
2249
  for (const content of contentEntries) {
@@ -1846,16 +2259,16 @@ async function build(options) {
1846
2259
  stylesheet: stylesheetHref
1847
2260
  });
1848
2261
  const outPath = content.routePath === "/" ? "/index.html" : `${content.routePath}/index.html`;
1849
- const fullPath = join5(clientDir, outPath);
1850
- mkdirSync(join5(fullPath, ".."), { recursive: true });
2262
+ const fullPath = join6(clientDir, outPath);
2263
+ mkdirSync2(join6(fullPath, ".."), { recursive: true });
1851
2264
  if (writtenPaths.has(outPath)) {
1852
2265
  console.warn(` [warn] collision: content ${content.routePath} overwrites existing output`);
1853
2266
  }
1854
2267
  writtenPaths.add(outPath);
1855
- writeFileSync3(fullPath, html, "utf-8");
2268
+ writeFileSync4(fullPath, html, "utf-8");
1856
2269
  console.log(` [content] ${content.routePath} -> ${outPath}`);
1857
2270
  }
1858
- if (serverPages.length > 0 || apiRoutes.length > 0) {
2271
+ if (pagesDir || options.routesDir || options.contentDir) {
1859
2272
  const srvOpts = {
1860
2273
  pagesDir: pagesDir || options.routesDir || ""
1861
2274
  };
@@ -1866,68 +2279,52 @@ async function build(options) {
1866
2279
  const configImportPath = options.configPath ? relativeImportPath(serverDir, options.configPath) : void 0;
1867
2280
  const serverEntry = buildServerEntry(
1868
2281
  srvOpts,
1869
- configImportPath
2282
+ configImportPath,
2283
+ stylesheetHref
1870
2284
  );
1871
- const serverEntryPath = join5(serverDir, "index.ts");
1872
- writeFileSync3(serverEntryPath, serverEntry, "utf-8");
2285
+ const serverEntryPath = join6(serverDir, "index.ts");
2286
+ writeFileSync4(serverEntryPath, serverEntry, "utf-8");
1873
2287
  console.log(
1874
2288
  ` [server] ${serverPages.length} page routes, ${apiRoutes.length} api routes -> server/index.ts`
1875
2289
  );
1876
2290
  }
1877
2291
  console.log(`[x] build complete -> ${outDir}`);
1878
2292
  }
1879
- async function bundleRouteIslands(routeFilePath, islandNames, islandsDir) {
1880
- const entryId = `${basename(routeFilePath).replace(/\.(tsx|ts)$/, "")}-${hash(routeFilePath)}`;
1881
- const outdir = join5(islandsDir, entryId);
1882
- mkdirSync(outdir, { recursive: true });
1883
- const bundlePath = join5(outdir, `${entryId}.js`);
1884
- const routeRel = join5(relative3(outdir, join5(routeFilePath, "..")), basename(routeFilePath));
1885
- const hydrateEntry = generateHydrateEntry(routeRel, islandNames);
1886
- const entryPath = join5(outdir, `${entryId}.tsx`);
1887
- writeFileSync3(entryPath, hydrateEntry, "utf-8");
1888
- const result = Bun.spawnSync([
1889
- "bun",
1890
- "build",
1891
- "--target=browser",
1892
- "--external",
1893
- "react",
1894
- "--external",
1895
- "react-dom",
1896
- "--outdir",
1897
- outdir,
1898
- entryPath
1899
- ]);
1900
- if (result.success) {
1901
- assertNoEnvLeakage(readFileSync2(bundlePath, "utf-8"), bundlePath);
1902
- return [`/_islands/${entryId}/${entryId}.js`];
1903
- }
1904
- writeFileSync3(bundlePath, generateFallbackHydration(islandNames), "utf-8");
2293
+ async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, islandsDir, actionModules) {
2294
+ const entryId = islandEntryId(routeFilePath);
2295
+ const outdir = join6(islandsDir, entryId);
2296
+ mkdirSync2(outdir, { recursive: true });
2297
+ const bundlePath = join6(outdir, `${entryId}.js`);
2298
+ const hydrateEntry = generateHydrateEntry(routeFilePath, layoutFilePaths);
2299
+ const entryPath = join6(outdir, `${entryId}.tsx`);
2300
+ writeFileSync4(entryPath, hydrateEntry, "utf-8");
2301
+ try {
2302
+ const result = await Bun.build({
2303
+ entrypoints: [entryPath],
2304
+ target: "browser",
2305
+ plugins: [actionsRewritePlugin(actionModules)]
2306
+ });
2307
+ if (result.success) {
2308
+ const outputs = result.outputs.filter((o) => o.kind === "entry-point");
2309
+ const built = outputs[0] ?? result.outputs[0];
2310
+ if (!built) throw new Error("bun build produced no output");
2311
+ const code = await built.text();
2312
+ assertNoEnvLeakage(code, bundlePath);
2313
+ writeFileSync4(bundlePath, wrapIslandBundle(code), "utf-8");
2314
+ return [`/_islands/${entryId}/${entryId}.js`];
2315
+ }
2316
+ for (const log of result.logs) {
2317
+ console.warn(` [islands] build error: ${log.message}`);
2318
+ }
2319
+ } catch (err) {
2320
+ console.warn(` [islands] build failed for ${routeFilePath}:`, err);
2321
+ }
2322
+ writeFileSync4(bundlePath, wrapIslandBundle(generateFallbackHydration(islandNames)), "utf-8");
1905
2323
  return [`/_islands/${entryId}/${entryId}.js`];
1906
2324
  }
1907
- function generateHydrateEntry(routeRelPath, _islandNames) {
1908
- return `import React from "react";
1909
- import { hydrateRoot } from "react-dom/client";
1910
- import * as Route from "${routeRelPath}";
1911
-
1912
- document.querySelectorAll("[data-island]").forEach((el) => {
1913
- const name = el.getAttribute("data-island");
1914
- if (!name) return;
1915
- const Component = Route.islands?.[name];
1916
- if (!Component) return;
1917
- hydrateRoot(el, React.createElement(Component));
1918
- });
1919
- `;
1920
- }
1921
- function generateFallbackHydration(islandNames) {
1922
- return `// x island hydration fallback \u2014 ${islandNames.join(", ")}
1923
- document.querySelectorAll("[data-island]").forEach(function(el) {
1924
- el.setAttribute("data-island-hydrated", "false");
1925
- });
1926
- `;
1927
- }
1928
2325
  function renderPageWithLayout(Component, params, layoutModules) {
1929
2326
  let content = createElement2(Component, { params });
1930
- for (const Layout of layoutModules) {
2327
+ for (const Layout of [...layoutModules].reverse()) {
1931
2328
  content = createElement2(Layout, null, content);
1932
2329
  }
1933
2330
  return content;
@@ -1946,7 +2343,7 @@ function StaticContentPage({
1946
2343
  })
1947
2344
  );
1948
2345
  }
1949
- function buildServerEntry(opts, configImportPath) {
2346
+ function buildServerEntry(opts, configImportPath, stylesheetHref) {
1950
2347
  const dirKeys = ["pagesDir", "apiDir", "layoutsDir", "actionsDir", "contentDir"];
1951
2348
  const lines = [
1952
2349
  "// Auto-generated by @thexjs/core build",
@@ -1967,19 +2364,40 @@ function buildServerEntry(opts, configImportPath) {
1967
2364
  const val = opts[key];
1968
2365
  if (val) lines.push(` ${key}: ${JSON.stringify(val)},`);
1969
2366
  }
2367
+ if (stylesheetHref) lines.push(` stylesheetHref: ${JSON.stringify(stylesheetHref)},`);
1970
2368
  lines.push(' port: parseInt(process.env.PORT || "3000", 10),', " development: false,");
1971
2369
  if (configImportPath) {
1972
2370
  lines.push(" ...(userConfig.security ? { security: userConfig.security } : {}),");
1973
2371
  lines.push(
1974
2372
  " ...(userConfig.observability ? { observability: userConfig.observability } : {}),"
1975
2373
  );
2374
+ lines.push(" ...(userConfig.images ? { images: userConfig.images } : {}),");
1976
2375
  }
1977
2376
  lines.push(
1978
2377
  "});",
1979
2378
  "",
1980
2379
  "const server = Bun.serve(app);",
1981
2380
  "",
1982
- "console.log(`[x] production server running at ${server.url}`);"
2381
+ "console.log(`[x] production server running at ${server.url}`);",
2382
+ "",
2383
+ "// Graceful shutdown: stop accepting new connections, flush the error",
2384
+ "// reporter, then exit after in-flight requests have a moment to drain.",
2385
+ "let shuttingDown = false;",
2386
+ "async function shutdown(signal: string): Promise<void> {",
2387
+ " if (shuttingDown) return;",
2388
+ " shuttingDown = true;",
2389
+ " console.log(`[x] received ${signal} - shutting down`);",
2390
+ " try {",
2391
+ ' const { getErrorReporter } = await import("@thexjs/core");',
2392
+ " await getErrorReporter().flush?.();",
2393
+ " } catch {}",
2394
+ " server.stop(true);",
2395
+ " const exit = () => process.exit(0);",
2396
+ " const drainTimer = setTimeout(exit, 3000);",
2397
+ " drainTimer.unref?.();",
2398
+ "}",
2399
+ 'process.on("SIGTERM", () => shutdown("SIGTERM"));',
2400
+ 'process.on("SIGINT", () => shutdown("SIGINT"));'
1983
2401
  );
1984
2402
  return lines.join("\n");
1985
2403
  }
@@ -1987,13 +2405,6 @@ function relativeImportPath(fromDir, toFile) {
1987
2405
  const rel = relative3(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
1988
2406
  return rel.startsWith(".") ? rel : `./${rel}`;
1989
2407
  }
1990
- function hash(str) {
1991
- let h = 0;
1992
- for (let i = 0; i < str.length; i++) {
1993
- h = Math.imul(31, h) + str.charCodeAt(i) | 0;
1994
- }
1995
- return Math.abs(h).toString(36);
1996
- }
1997
2408
 
1998
2409
  // src/link.tsx
1999
2410
  import { jsx as jsx3 } from "react/jsx-runtime";
@@ -2009,88 +2420,6 @@ function Link({ href, children, clientNav = true, prefetch = true, ...rest }) {
2009
2420
  }
2010
2421
  );
2011
2422
  }
2012
-
2013
- // src/data/sqlite.ts
2014
- import { Database } from "bun:sqlite";
2015
- function connectSQLite(options) {
2016
- const db = new Database(options?.path ?? "data/dev.db");
2017
- if (options?.wal !== false) {
2018
- db.run("PRAGMA journal_mode = WAL");
2019
- }
2020
- if (options?.foreignKeys !== false) {
2021
- db.run("PRAGMA foreign_keys = ON");
2022
- }
2023
- return db;
2024
- }
2025
-
2026
- // src/data/postgres.ts
2027
- function connectPostgres(options) {
2028
- const url = options?.url ?? process.env.DATABASE_URL;
2029
- if (!url) {
2030
- throw new Error(
2031
- "DATABASE_URL is required \u2014 set it via options.url or the DATABASE_URL environment variable"
2032
- );
2033
- }
2034
- return Bun.sql(url);
2035
- }
2036
-
2037
- // src/data/migrate.ts
2038
- import { readFileSync as readFileSync3, readdirSync as readdirSync3 } from "fs";
2039
- import { join as join6 } from "path";
2040
- function runSQLiteMigrations(db, migrationsDir) {
2041
- db.run(`CREATE TABLE IF NOT EXISTS _x_migrations (
2042
- name TEXT PRIMARY KEY,
2043
- applied_at TEXT DEFAULT (datetime('now'))
2044
- )`);
2045
- const stmt = db.prepare("SELECT name FROM _x_migrations");
2046
- const applied = new Set(stmt.all().map((r) => r.name));
2047
- let files;
2048
- try {
2049
- files = readdirSync3(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
2050
- } catch {
2051
- return { applied: [], skipped: [] };
2052
- }
2053
- const result = { applied: [], skipped: [] };
2054
- for (const file of files) {
2055
- if (applied.has(file)) {
2056
- result.skipped.push(file);
2057
- continue;
2058
- }
2059
- const sql = readFileSync3(join6(migrationsDir, file), "utf-8");
2060
- db.run(sql);
2061
- db.run("INSERT INTO _x_migrations (name) VALUES (?1)", [file]);
2062
- console.log(`[x] migration applied: ${file}`);
2063
- result.applied.push(file);
2064
- }
2065
- return result;
2066
- }
2067
- async function runPostgresMigrations(client, migrationsDir) {
2068
- await client.unsafe(`CREATE TABLE IF NOT EXISTS _x_migrations (
2069
- name TEXT PRIMARY KEY,
2070
- applied_at TIMESTAMP DEFAULT NOW()
2071
- )`);
2072
- const rows = await client.unsafe("SELECT name FROM _x_migrations");
2073
- const applied = new Set(rows.map((r) => r.name));
2074
- let files;
2075
- try {
2076
- files = readdirSync3(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
2077
- } catch {
2078
- return { applied: [], skipped: [] };
2079
- }
2080
- const result = { applied: [], skipped: [] };
2081
- for (const file of files) {
2082
- if (applied.has(file)) {
2083
- result.skipped.push(file);
2084
- continue;
2085
- }
2086
- const raw = readFileSync3(join6(migrationsDir, file), "utf-8");
2087
- await client.unsafe(raw);
2088
- await client.unsafe(`INSERT INTO _x_migrations (name) VALUES ('${file}')`);
2089
- console.log(`[x] migration applied: ${file}`);
2090
- result.applied.push(file);
2091
- }
2092
- return result;
2093
- }
2094
2423
  export {
2095
2424
  CLIENT_NAV_SCRIPT,
2096
2425
  DefaultNotFound,
@@ -2106,12 +2435,12 @@ export {
2106
2435
  checkCsrf,
2107
2436
  combineReporters,
2108
2437
  composeMiddleware,
2109
- connectPostgres,
2110
- connectSQLite,
2111
2438
  createApp,
2112
2439
  createHealthCheckHandler,
2440
+ createImageProxyHandler,
2113
2441
  createOtelReporter,
2114
2442
  createRateLimiter,
2443
+ createRedisRateLimitStore,
2115
2444
  createSentryReporter,
2116
2445
  defineConfig,
2117
2446
  escapeHtml2 as escapeHtml,
@@ -2134,8 +2463,6 @@ export {
2134
2463
  renderStreamingPage,
2135
2464
  reportException,
2136
2465
  resetServerFunctions,
2137
- runPostgresMigrations,
2138
- runSQLiteMigrations,
2139
2466
  scanApiDir,
2140
2467
  scanContent,
2141
2468
  scanLayouts,