@thexjs/core 0.1.5 → 1.0.0

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
@@ -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,112 +753,154 @@ 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];
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
+ }
860
898
  }
861
899
 
900
+ // src/server-functions.ts
901
+ import { writeFileSync as writeFileSync2 } from "fs";
902
+ import { join as join3 } from "path";
903
+
862
904
  // src/observability/monitoring.ts
863
905
  var noopReporter = {
864
906
  captureException: () => {
@@ -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,407 @@ 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 });
1108
- }
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, server) => {
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, server);
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, server) {
1375
+ if (server?.requestIP) {
1376
+ const ip = server.requestIP(req);
1377
+ if (ip) return ip.address;
1378
+ }
1379
+ const forwarded = req.headers.get("x-forwarded-for");
1380
+ if (forwarded) return forwarded.split(",")[0]?.trim() ?? "unknown";
1381
+ return req.headers.get("x-real-ip") ?? "unknown";
1382
+ }
1383
+ function createRateLimiter(options = {}) {
1384
+ const limit = options.limit ?? 60;
1385
+ const windowMs = options.windowMs ?? 6e4;
1386
+ const keyFn = options.keyFn ?? defaultKeyFn;
1387
+ const store = options.store;
1388
+ const buckets = /* @__PURE__ */ new Map();
1389
+ async function check(req, server) {
1390
+ const key = keyFn(req, server);
1391
+ if (store) {
1392
+ const { count, resetAt } = await store.incr(key, windowMs);
1393
+ return { ok: count <= limit, limit, remaining: Math.max(0, limit - count), resetAt };
1394
+ }
1395
+ const now = Date.now();
1396
+ let bucket = buckets.get(key);
1397
+ if (!bucket || bucket.resetAt <= now) {
1398
+ bucket = { count: 0, resetAt: now + windowMs };
1399
+ buckets.set(key, bucket);
1400
+ }
1401
+ bucket.count += 1;
1402
+ const ok = bucket.count <= limit;
1403
+ return { ok, limit, remaining: Math.max(0, limit - bucket.count), resetAt: bucket.resetAt };
1404
+ }
1405
+ function sweep() {
1406
+ const now = Date.now();
1407
+ for (const [key, bucket] of buckets) {
1408
+ if (bucket.resetAt <= now) buckets.delete(key);
1409
+ }
1410
+ }
1411
+ const timer = setInterval(sweep, Math.max(windowMs, 1e3));
1412
+ timer.unref?.();
1413
+ return { check, sweep, buckets, dispose: () => clearInterval(timer) };
1414
+ }
1415
+ async function rateLimitMiddleware(limiter, req, server) {
1416
+ const result = await limiter.check(req, server);
1417
+ if (result.ok) return null;
1418
+ const retryAfterSeconds = Math.max(1, Math.ceil((result.resetAt - Date.now()) / 1e3));
1419
+ return new Response("Too Many Requests", {
1420
+ status: 429,
1421
+ headers: {
1422
+ "Content-Type": "text/plain; charset=utf-8",
1423
+ "Retry-After": String(retryAfterSeconds),
1424
+ "X-RateLimit-Limit": String(result.limit),
1425
+ "X-RateLimit-Remaining": String(result.remaining)
1426
+ }
1427
+ });
1109
1428
  }
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 });
1429
+ function createRedisRateLimitStore(options = {}) {
1430
+ let client = null;
1431
+ let connecting = null;
1432
+ async function connect() {
1433
+ const require2 = import.meta.require;
1434
+ const mod = require2("bun:redis");
1435
+ const instance = options.url ? new mod.RedisClient({ url: options.url }) : new mod.RedisClient();
1436
+ await instance.connect();
1437
+ return instance;
1438
+ }
1439
+ function getClient() {
1440
+ if (client) return Promise.resolve(client);
1441
+ if (!connecting) {
1442
+ connecting = connect().then(
1443
+ (c) => {
1444
+ client = c;
1445
+ return c;
1446
+ },
1447
+ (err) => {
1448
+ connecting = null;
1449
+ throw err;
1450
+ }
1451
+ );
1118
1452
  }
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 });
1453
+ return connecting;
1454
+ }
1455
+ return {
1456
+ async incr(key, windowMs) {
1457
+ const c = await getClient();
1458
+ const redisKey = `x:ratelimit:${key}`;
1459
+ const ttlSeconds = Math.max(1, Math.ceil(windowMs / 1e3));
1460
+ const count = Number(await c.sendCommand("INCR", redisKey));
1461
+ if (count === 1) {
1462
+ await c.sendCommand("EXPIRE", redisKey, String(ttlSeconds));
1143
1463
  }
1464
+ return { count, resetAt: Date.now() + windowMs };
1144
1465
  }
1145
- return new Response("Not found", { status: 404 });
1146
1466
  };
1147
1467
  }
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;
1158
- }
1159
- idx++;
1160
- }
1161
- return params;
1162
- }
1163
1468
 
1164
1469
  // src/createApp.ts
1165
- var HTTP_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
1166
1470
  function projectRootFromRoutesDir(routesDir) {
1167
- return join4(routesDir, "..", "..");
1471
+ return join5(routesDir, "..", "..");
1168
1472
  }
1169
1473
  function resolvePublicAsset(publicDir, pathname) {
1170
1474
  let decoded;
@@ -1173,7 +1477,7 @@ function resolvePublicAsset(publicDir, pathname) {
1173
1477
  } catch {
1174
1478
  return null;
1175
1479
  }
1176
- const target = resolve(join4(publicDir, decoded));
1480
+ const target = resolve(join5(publicDir, decoded));
1177
1481
  const root = resolve(publicDir);
1178
1482
  if (target !== root && !target.startsWith(root + sep3)) return null;
1179
1483
  return target;
@@ -1185,7 +1489,9 @@ async function serveStaticAsset(publicDir, req) {
1185
1489
  if (pathname === "/" || pathname.endsWith("/")) return null;
1186
1490
  const filePath = resolvePublicAsset(publicDir, pathname);
1187
1491
  if (!filePath) return null;
1188
- const file = Bun.file(filePath);
1492
+ const bun = globalThis.Bun;
1493
+ if (!bun) return null;
1494
+ const file = bun.file(filePath);
1189
1495
  if (!await file.exists()) return null;
1190
1496
  return new Response(file);
1191
1497
  }
@@ -1222,6 +1528,8 @@ function importDev(path, dev) {
1222
1528
  async function createApp(options) {
1223
1529
  const dev = options.development ?? false;
1224
1530
  const primaryDir = options.pagesDir || options.routesDir || "src/pages";
1531
+ const projectRoot = projectRootFromRoutesDir(primaryDir);
1532
+ const resolvedActionsDir = options.actionsDir ?? (existsSync(join5(projectRoot, "src", "actions")) ? join5(projectRoot, "src", "actions") : void 0);
1225
1533
  let handlers = [];
1226
1534
  let contentHandlers = [];
1227
1535
  let publicDir = null;
@@ -1230,6 +1538,39 @@ async function createApp(options) {
1230
1538
  let notFoundLayout;
1231
1539
  const serverFnHandler = getServerFunctionHandler(options.security?.csrf);
1232
1540
  const staticCache = /* @__PURE__ */ new Map();
1541
+ let actionModules = /* @__PURE__ */ new Map();
1542
+ const islandBundleCache = /* @__PURE__ */ new Map();
1543
+ const islandFileCache = /* @__PURE__ */ new Map();
1544
+ async function resolveIslandScripts(routeFilePath, layoutFilePaths, entries) {
1545
+ if (entries.length === 0) return [];
1546
+ const uniqueNames = [...new Set(entries.map((e) => e.name))].sort();
1547
+ const cacheKey = `${routeFilePath}::${layoutFilePaths.join("|")}::${uniqueNames.join(",")}`;
1548
+ const cached = islandBundleCache.get(cacheKey);
1549
+ if (cached) return cached;
1550
+ const code = await buildIslandBundleInMemory(
1551
+ routeFilePath,
1552
+ layoutFilePaths,
1553
+ uniqueNames,
1554
+ actionModules,
1555
+ projectRoot
1556
+ );
1557
+ const entryId = islandEntryId(routeFilePath);
1558
+ const url = `/_islands/${entryId}/${entryId}.js`;
1559
+ islandFileCache.set(url, code);
1560
+ const scripts = [url];
1561
+ islandBundleCache.set(cacheKey, scripts);
1562
+ return scripts;
1563
+ }
1564
+ function serveIslandBundle(req) {
1565
+ if (req.method !== "GET" && req.method !== "HEAD") return null;
1566
+ const pathname = new URL(req.url).pathname;
1567
+ if (!pathname.startsWith("/_islands/")) return null;
1568
+ const code = islandFileCache.get(pathname);
1569
+ if (code === void 0) return null;
1570
+ return new Response(code, {
1571
+ headers: { "Content-Type": "application/javascript; charset=utf-8" }
1572
+ });
1573
+ }
1233
1574
  if (options.observability?.errorReporter) {
1234
1575
  setErrorReporter(options.observability.errorReporter);
1235
1576
  }
@@ -1237,6 +1578,7 @@ async function createApp(options) {
1237
1578
  const rateLimiter = options.security?.rateLimit === false ? null : createRateLimiter(options.security?.rateLimit ?? {});
1238
1579
  const securityHeadersOptions = options.security?.headers;
1239
1580
  const loggingEnabled = options.observability?.logging ?? true;
1581
+ const imageProxyHandler = createImageProxyHandler(options.images);
1240
1582
  function withResponseHardening(res) {
1241
1583
  return securityHeadersOptions === false ? res : applySecurityHeaders(res, securityHeadersOptions);
1242
1584
  }
@@ -1252,8 +1594,183 @@ async function createApp(options) {
1252
1594
  headers: { "Content-Type": "text/html; charset=utf-8" }
1253
1595
  });
1254
1596
  }
1597
+ const makeApiHandler = (route, module) => async (req) => {
1598
+ try {
1599
+ const method = req.method;
1600
+ const handlerFn = module[method];
1601
+ if (typeof handlerFn === "function") {
1602
+ const result = await handlerFn(req);
1603
+ if (result instanceof Response) return result;
1604
+ if (result === void 0 || result === null) {
1605
+ return new Response("OK", { status: 200 });
1606
+ }
1607
+ return Response.json(result);
1608
+ }
1609
+ return new Response(`Method ${method} not allowed`, { status: 405 });
1610
+ } catch (err) {
1611
+ reportException(err, { route: route.routePath, phase: "api" });
1612
+ console.error("[x] API handler error:", err);
1613
+ if (dev) {
1614
+ return new Response(renderErrorOverlay(err), {
1615
+ status: 500,
1616
+ headers: { "Content-Type": "text/html; charset=utf-8" }
1617
+ });
1618
+ }
1619
+ return new Response("Internal server error", { status: 500 });
1620
+ }
1621
+ };
1622
+ const makePageHandler = (opts) => {
1623
+ const {
1624
+ route,
1625
+ mode,
1626
+ revalidate,
1627
+ loader,
1628
+ Component,
1629
+ layoutModules,
1630
+ layoutFilePaths,
1631
+ middlewareModules,
1632
+ islandScripts
1633
+ } = opts;
1634
+ return async (req) => {
1635
+ try {
1636
+ const params = extractParams(route.routePath, route.paramNames, new URL(req.url).pathname) ?? {};
1637
+ const baseHandler = async (ctx) => {
1638
+ let loaderData = {};
1639
+ if (loader) {
1640
+ const result = await loader(ctx);
1641
+ if (result instanceof Response) return result;
1642
+ loaderData = result;
1643
+ }
1644
+ if (mode === "server") {
1645
+ const registry2 = createIslandRegistry();
1646
+ const content2 = createElement(
1647
+ IslandProvider,
1648
+ { registry: registry2 },
1649
+ wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
1650
+ );
1651
+ let scripts2 = islandScripts;
1652
+ if (scripts2 === void 0) {
1653
+ renderPage(content2, { stylesheet: stylesheetHref, liveReload: dev });
1654
+ scripts2 = await resolveIslandScripts(
1655
+ route.filePath,
1656
+ layoutFilePaths,
1657
+ registry2.entries
1658
+ );
1659
+ }
1660
+ const stream = await renderStreamingPage(content2, {
1661
+ stylesheet: stylesheetHref,
1662
+ liveReload: dev,
1663
+ islandScripts: scripts2
1664
+ });
1665
+ return new Response(stream, {
1666
+ headers: { "Content-Type": "text/html; charset=utf-8" }
1667
+ });
1668
+ }
1669
+ const cached = staticCache.get(route.routePath);
1670
+ const revalidateSeconds = revalidate ?? 0;
1671
+ if (revalidateSeconds > 0 && cached && Date.now() - cached.timestamp < revalidateSeconds * 1e3) {
1672
+ return new Response(cached.html, {
1673
+ headers: { "Content-Type": "text/html; charset=utf-8", "X-Revalidated": "hit" }
1674
+ });
1675
+ }
1676
+ const registry = createIslandRegistry();
1677
+ const content = createElement(
1678
+ IslandProvider,
1679
+ { registry },
1680
+ wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
1681
+ );
1682
+ let scripts = islandScripts;
1683
+ if (scripts === void 0) {
1684
+ renderPage(content, { stylesheet: stylesheetHref, liveReload: dev });
1685
+ scripts = await resolveIslandScripts(route.filePath, layoutFilePaths, registry.entries);
1686
+ }
1687
+ const html = renderPage(content, {
1688
+ stylesheet: stylesheetHref,
1689
+ liveReload: dev,
1690
+ islandScripts: scripts
1691
+ });
1692
+ if (revalidateSeconds > 0) {
1693
+ staticCache.set(route.routePath, { html, timestamp: Date.now() });
1694
+ }
1695
+ return new Response(html, {
1696
+ headers: {
1697
+ "Content-Type": "text/html; charset=utf-8",
1698
+ "X-Revalidated": revalidateSeconds > 0 ? "miss" : "none"
1699
+ }
1700
+ });
1701
+ };
1702
+ if (middlewareModules.length > 0) {
1703
+ const composed = composeMiddleware(middlewareModules, baseHandler);
1704
+ return composed(
1705
+ { params, request: req },
1706
+ async () => new Response("Not found", { status: 404 })
1707
+ );
1708
+ }
1709
+ return baseHandler({ params, request: req });
1710
+ } catch (err) {
1711
+ reportException(err, { route: route.routePath, phase: "ssr" });
1712
+ console.error("[x] route handler error:", err);
1713
+ if (dev) {
1714
+ return new Response(renderErrorOverlay(err), {
1715
+ status: 500,
1716
+ headers: { "Content-Type": "text/html; charset=utf-8" }
1717
+ });
1718
+ }
1719
+ return new Response("Internal server error", { status: 500 });
1720
+ }
1721
+ };
1722
+ };
1255
1723
  async function buildHandlers() {
1724
+ if (options.preloaded) {
1725
+ const preloaded = options.preloaded;
1726
+ const candidatePublicDir2 = join5(projectRoot, "public");
1727
+ publicDir = existsSync(candidatePublicDir2) ? candidatePublicDir2 : null;
1728
+ stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync(join5(publicDir, "styles.css")) ? "/styles.css" : void 0);
1729
+ if (preloaded.notFoundComponent) notFoundComponent = preloaded.notFoundComponent;
1730
+ if (preloaded.notFoundLayout) notFoundLayout = preloaded.notFoundLayout;
1731
+ const loaded2 = [];
1732
+ for (const p of preloaded.routes) {
1733
+ const actions = p.module.actions;
1734
+ if (actions) {
1735
+ registerServerFunctions(p.entry.routePath, p.entry.paramNames, actions);
1736
+ }
1737
+ if (p.entry.isApi) {
1738
+ loaded2.push({
1739
+ entry: p.entry,
1740
+ mode: p.mode,
1741
+ revalidate: void 0,
1742
+ handler: makeApiHandler(p.entry, p.module)
1743
+ });
1744
+ continue;
1745
+ }
1746
+ const Component = p.module.default;
1747
+ if (!Component) continue;
1748
+ const routeMiddleware = p.module.middleware;
1749
+ const middlewareModules = routeMiddleware ? [...p.middlewareModules, routeMiddleware] : p.middlewareModules;
1750
+ loaded2.push({
1751
+ entry: p.entry,
1752
+ mode: p.mode,
1753
+ revalidate: p.revalidate,
1754
+ handler: makePageHandler({
1755
+ route: p.entry,
1756
+ mode: p.mode,
1757
+ revalidate: p.revalidate,
1758
+ loader: p.module.loader,
1759
+ Component,
1760
+ layoutModules: p.layoutModules,
1761
+ layoutFilePaths: p.layoutFilePaths ?? [],
1762
+ middlewareModules,
1763
+ islandScripts: p.islandScripts
1764
+ })
1765
+ });
1766
+ }
1767
+ handlers = loaded2;
1768
+ return;
1769
+ }
1256
1770
  resetServerFunctions();
1771
+ actionModules = /* @__PURE__ */ new Map();
1772
+ islandBundleCache.clear();
1773
+ islandFileCache.clear();
1257
1774
  const pagesDir = primaryDir;
1258
1775
  const apiDir = options.apiDir;
1259
1776
  const layoutsDir = options.layoutsDir || pagesDir;
@@ -1262,7 +1779,7 @@ async function createApp(options) {
1262
1779
  if (apiDir && existsSync(apiDir)) {
1263
1780
  apiFound.push(...scanApiDir(apiDir));
1264
1781
  }
1265
- const legacyApiDir = join4(pagesDir, "api");
1782
+ const legacyApiDir = join5(pagesDir, "api");
1266
1783
  if (existsSync(legacyApiDir) && legacyApiDir !== apiDir) {
1267
1784
  apiFound.push(...scanApiDir(legacyApiDir));
1268
1785
  }
@@ -1272,29 +1789,34 @@ async function createApp(options) {
1272
1789
  const nestedLayouts = scanLayouts(pagesDir);
1273
1790
  const layouts = [...dedicatedLayouts, ...nestedLayouts];
1274
1791
  const middlewareEntries = scanMiddleware(pagesDir);
1275
- if (options.actionsDir) {
1276
- const actionFiles = scanRoutes(options.actionsDir);
1792
+ if (resolvedActionsDir) {
1793
+ const actionFiles = scanRoutes(resolvedActionsDir);
1277
1794
  for (const actionFile of actionFiles) {
1278
1795
  const mod = await importDev(actionFile.filePath, dev);
1279
1796
  const segments = actionFile.routePath.split("/").filter(Boolean);
1280
1797
  const fileName = segments[segments.length - 1] ?? "";
1281
1798
  const parentPath = fileName === "index" || !fileName ? actionFile.routePath : `/${segments.slice(0, -1).join("/")}`;
1282
1799
  const actions = mod.actions;
1800
+ const fnNames = [];
1283
1801
  if (actions) {
1284
1802
  registerServerFunctions(parentPath, actionFile.paramNames, actions);
1803
+ fnNames.push(...Object.keys(actions));
1285
1804
  }
1286
1805
  for (const [key, value] of Object.entries(mod)) {
1287
1806
  if (key === "default" || key === "actions" || typeof value !== "function") continue;
1288
1807
  registerServerFunctions(parentPath, actionFile.paramNames, {
1289
1808
  [key]: value
1290
1809
  });
1810
+ fnNames.push(key);
1811
+ }
1812
+ if (fnNames.length > 0) {
1813
+ actionModules.set(actionFile.filePath, { parentPath, fnNames });
1291
1814
  }
1292
1815
  }
1293
1816
  }
1294
- const projectRoot = projectRootFromRoutesDir(pagesDir);
1295
- const candidatePublicDir = join4(projectRoot, "public");
1817
+ const candidatePublicDir = join5(projectRoot, "public");
1296
1818
  publicDir = existsSync(candidatePublicDir) ? candidatePublicDir : null;
1297
- stylesheetHref = publicDir && existsSync(join4(publicDir, "styles.css")) ? "/styles.css" : void 0;
1819
+ stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync(join5(publicDir, "styles.css")) ? "/styles.css" : void 0);
1298
1820
  const notFoundEntry = scanNotFound(pagesDir);
1299
1821
  if (notFoundEntry) {
1300
1822
  const mod = await importDev(notFoundEntry.filePath, dev);
@@ -1316,12 +1838,6 @@ async function createApp(options) {
1316
1838
  for (const route of found) {
1317
1839
  const mod = await importDev(route.filePath, dev);
1318
1840
  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
1841
  const actions2 = mod.actions;
1326
1842
  if (actions2) {
1327
1843
  registerServerFunctions(route.routePath, route.paramNames, actions2);
@@ -1330,31 +1846,7 @@ async function createApp(options) {
1330
1846
  entry: route,
1331
1847
  mode: "server",
1332
1848
  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
- }
1849
+ handler: makeApiHandler(route, mod)
1358
1850
  });
1359
1851
  continue;
1360
1852
  }
@@ -1379,6 +1871,7 @@ async function createApp(options) {
1379
1871
  layoutChain.unshift(rootLayout2);
1380
1872
  }
1381
1873
  }
1874
+ const layoutFilePaths = layoutChain.map((l) => l.filePath);
1382
1875
  const layoutModules = [];
1383
1876
  for (const l of layoutChain) {
1384
1877
  const layoutMod = await importDev(l.filePath, dev);
@@ -1399,65 +1892,16 @@ async function createApp(options) {
1399
1892
  entry: route,
1400
1893
  mode,
1401
1894
  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
- }
1895
+ handler: makePageHandler({
1896
+ route,
1897
+ mode,
1898
+ revalidate,
1899
+ loader,
1900
+ Component,
1901
+ layoutModules,
1902
+ layoutFilePaths,
1903
+ middlewareModules
1904
+ })
1461
1905
  });
1462
1906
  }
1463
1907
  handlers = loaded;
@@ -1528,10 +1972,10 @@ async function createApp(options) {
1528
1972
  let rebuildTimeout = null;
1529
1973
  const sseClients = /* @__PURE__ */ new Set();
1530
1974
  try {
1531
- const srcDir = join4(primaryDir, "..", "..", "src");
1975
+ const srcDir = join5(primaryDir, "..", "..", "src");
1532
1976
  const watchDirs = [
1533
1977
  ...new Set(
1534
- [primaryDir, options.apiDir, options.layoutsDir, options.actionsDir, srcDir].filter(
1978
+ [primaryDir, options.apiDir, options.layoutsDir, resolvedActionsDir, srcDir].filter(
1535
1979
  Boolean
1536
1980
  )
1537
1981
  )
@@ -1549,12 +1993,12 @@ async function createApp(options) {
1549
1993
  } catch {
1550
1994
  console.warn("[x] file watching not available on this platform");
1551
1995
  }
1552
- const devFetchInner = async (req) => {
1996
+ const devFetchInner = async (req, server) => {
1553
1997
  const url = new URL(req.url).pathname;
1554
1998
  const healthResult = await healthHandler(req);
1555
1999
  if (healthResult !== null) return healthResult;
1556
2000
  if (rateLimiter) {
1557
- const limited = rateLimitMiddleware(rateLimiter, req);
2001
+ const limited = await rateLimitMiddleware(rateLimiter, req, server);
1558
2002
  if (limited !== null) return limited;
1559
2003
  }
1560
2004
  if (url === "/__x/reload") {
@@ -1569,14 +2013,26 @@ data: ${data}
1569
2013
  `));
1570
2014
  };
1571
2015
  sseClients.add(send);
1572
- req.signal.addEventListener("abort", () => sseClients.delete(send));
2016
+ console.log(`[x][reload] client connected (${sseClients.size} total)`);
2017
+ const heartbeat = setInterval(() => {
2018
+ try {
2019
+ send("hb", "");
2020
+ } catch (err) {
2021
+ console.log(`[x][reload] heartbeat failed, clearing interval: ${String(err)}`);
2022
+ clearInterval(heartbeat);
2023
+ }
2024
+ }, 5e3);
2025
+ req.signal.addEventListener("abort", () => {
2026
+ clearInterval(heartbeat);
2027
+ sseClients.delete(send);
2028
+ console.log(`[x][reload] client disconnected (${sseClients.size} total)`);
2029
+ });
1573
2030
  }
1574
2031
  });
1575
2032
  return new Response(body, {
1576
2033
  headers: {
1577
2034
  "Content-Type": "text/event-stream",
1578
- "Cache-Control": "no-cache",
1579
- Connection: "keep-alive"
2035
+ "Cache-Control": "no-cache"
1580
2036
  }
1581
2037
  });
1582
2038
  }
@@ -1586,6 +2042,10 @@ data: ${data}
1586
2042
  if (serverFnResult !== null) return serverFnResult;
1587
2043
  const staticAsset = await serveStaticAsset(publicDir, req);
1588
2044
  if (staticAsset !== null) return staticAsset;
2045
+ const islandBundle = serveIslandBundle(req);
2046
+ if (islandBundle !== null) return islandBundle;
2047
+ const proxiedImage = await imageProxyHandler(req);
2048
+ if (proxiedImage !== null) return proxiedImage;
1589
2049
  for (const h of handlers) {
1590
2050
  const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
1591
2051
  if (params !== null) {
@@ -1599,7 +2059,7 @@ data: ${data}
1599
2059
  }
1600
2060
  return renderNotFound(req);
1601
2061
  };
1602
- const devFetchHardened = async (req) => withResponseHardening(await devFetchInner(req));
2062
+ const devFetchHardened = async (req, server) => withResponseHardening(await devFetchInner(req, server));
1603
2063
  const devFetch = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
1604
2064
  return {
1605
2065
  routes: {},
@@ -1608,12 +2068,12 @@ data: ${data}
1608
2068
  fetch: devFetch
1609
2069
  };
1610
2070
  }
1611
- const prodFetchInner = async (req) => {
2071
+ const prodFetchInner = async (req, server) => {
1612
2072
  const url = new URL(req.url).pathname;
1613
2073
  const healthResult = await healthHandler(req);
1614
2074
  if (healthResult !== null) return healthResult;
1615
2075
  if (rateLimiter) {
1616
- const limited = rateLimitMiddleware(rateLimiter, req);
2076
+ const limited = await rateLimitMiddleware(rateLimiter, req, server);
1617
2077
  if (limited !== null) return limited;
1618
2078
  }
1619
2079
  const revalidationResult = await handleRevalidation(req);
@@ -1622,6 +2082,10 @@ data: ${data}
1622
2082
  if (serverFnResult !== null) return serverFnResult;
1623
2083
  const staticAsset = await serveStaticAsset(publicDir, req);
1624
2084
  if (staticAsset !== null) return staticAsset;
2085
+ const islandBundle = serveIslandBundle(req);
2086
+ if (islandBundle !== null) return islandBundle;
2087
+ const proxiedImage = await imageProxyHandler(req);
2088
+ if (proxiedImage !== null) return proxiedImage;
1625
2089
  for (const h of handlers) {
1626
2090
  const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
1627
2091
  if (params !== null) {
@@ -1635,7 +2099,7 @@ data: ${data}
1635
2099
  }
1636
2100
  return renderNotFound(req);
1637
2101
  };
1638
- const prodFetchHardened = async (req) => withResponseHardening(await prodFetchInner(req));
2102
+ const prodFetchHardened = async (req, server) => withResponseHardening(await prodFetchInner(req, server));
1639
2103
  const prodFetch = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
1640
2104
  return {
1641
2105
  routes: {},
@@ -1646,94 +2110,25 @@ data: ${data}
1646
2110
  }
1647
2111
 
1648
2112
  // src/build.ts
1649
- import { cpSync, existsSync as existsSync2, mkdirSync, writeFileSync as writeFileSync3 } from "fs";
1650
- import { basename, join as join5, relative as relative3 } from "path";
2113
+ import { cpSync, existsSync as existsSync2, mkdirSync as mkdirSync2, writeFileSync as writeFileSync4 } from "fs";
2114
+ import { join as join6, relative as relative3 } from "path";
1651
2115
  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
2116
  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 });
2117
+ const outDir = options.outDir ?? join6(process.cwd(), ".x");
2118
+ const clientDir = join6(outDir, "client");
2119
+ const serverDir = join6(outDir, "server");
2120
+ const islandsDir = join6(clientDir, "_islands");
2121
+ mkdirSync2(clientDir, { recursive: true });
2122
+ mkdirSync2(serverDir, { recursive: true });
2123
+ mkdirSync2(islandsDir, { recursive: true });
1729
2124
  const pagesDir = options.pagesDir ?? options.routesDir ?? "";
1730
2125
  const apiDir = options.apiDir;
1731
2126
  const actionsDir = options.actionsDir;
1732
2127
  const layoutsDir = options.layoutsDir ?? pagesDir;
1733
- const projectRoot = pagesDir ? join5(pagesDir, "..", "..") : process.cwd();
1734
- const publicDir = join5(projectRoot, "public");
2128
+ const projectRoot = pagesDir ? join6(pagesDir, "..", "..") : process.cwd();
2129
+ const publicDir = join6(projectRoot, "public");
1735
2130
  const hasPublicDir = existsSync2(publicDir);
1736
- const stylesheetHref = hasPublicDir && existsSync2(join5(publicDir, "styles.css")) ? "/styles.css" : void 0;
2131
+ const stylesheetHref = hasPublicDir && existsSync2(join6(publicDir, "styles.css")) ? "/styles.css" : void 0;
1737
2132
  if (hasPublicDir) {
1738
2133
  cpSync(publicDir, clientDir, { recursive: true });
1739
2134
  console.log(`[x] build: copied public/ -> ${relative3(process.cwd(), clientDir)}`);
@@ -1745,7 +2140,7 @@ async function build(options) {
1745
2140
  if (apiDir && existsSync2(apiDir)) {
1746
2141
  routeEntries.push(...scanApiDir(apiDir));
1747
2142
  }
1748
- const legacyApiDir = pagesDir ? join5(pagesDir, "api") : "";
2143
+ const legacyApiDir = pagesDir ? join6(pagesDir, "api") : "";
1749
2144
  if (legacyApiDir && existsSync2(legacyApiDir) && legacyApiDir !== apiDir) {
1750
2145
  routeEntries.push(...scanApiDir(legacyApiDir));
1751
2146
  }
@@ -1802,7 +2197,14 @@ async function build(options) {
1802
2197
  const layoutMod = await import(l.filePath);
1803
2198
  if (layoutMod.default) layoutModules.push(layoutMod.default);
1804
2199
  }
1805
- const page = { entry, filePath: entry.filePath, mode, Component, layoutModules };
2200
+ const page = {
2201
+ entry,
2202
+ filePath: entry.filePath,
2203
+ mode,
2204
+ Component,
2205
+ layoutModules,
2206
+ layoutFilePaths: layoutChain.map((l) => l.filePath)
2207
+ };
1806
2208
  if (mode === "static") {
1807
2209
  staticPages.push(page);
1808
2210
  } else {
@@ -1824,8 +2226,8 @@ async function build(options) {
1824
2226
  const content = createElement2(IslandProvider, { registry }, pageContent);
1825
2227
  const html = renderStaticPage(content, { stylesheet: stylesheetHref });
1826
2228
  const outPath = page.entry.routePath === "/" ? "/index.html" : `${page.entry.routePath}/index.html`;
1827
- const fullPath = join5(clientDir, outPath);
1828
- mkdirSync(join5(fullPath, ".."), { recursive: true });
2229
+ const fullPath = join6(clientDir, outPath);
2230
+ mkdirSync2(join6(fullPath, ".."), { recursive: true });
1829
2231
  if (writtenPaths.has(outPath)) {
1830
2232
  console.warn(` [warn] collision: ${page.entry.routePath} overwrites existing output`);
1831
2233
  }
@@ -1833,13 +2235,19 @@ async function build(options) {
1833
2235
  let islandScripts = [];
1834
2236
  if (registry.entries.length > 0) {
1835
2237
  const uniqueNames = [...new Set(registry.entries.map((e) => e.name))];
1836
- islandScripts = await bundleRouteIslands(page.filePath, uniqueNames, islandsDir, actionModules);
2238
+ islandScripts = await bundleRouteIslands(
2239
+ page.filePath,
2240
+ page.layoutFilePaths,
2241
+ uniqueNames,
2242
+ islandsDir,
2243
+ actionModules
2244
+ );
1837
2245
  console.log(
1838
2246
  ` [islands] ${uniqueNames.length} island(s) on ${page.entry.routePath} -> ${islandScripts.join(", ")}`
1839
2247
  );
1840
2248
  }
1841
2249
  const finalHtml = renderStaticPage(content, { islandScripts, stylesheet: stylesheetHref });
1842
- writeFileSync3(fullPath, finalHtml, "utf-8");
2250
+ writeFileSync4(fullPath, finalHtml, "utf-8");
1843
2251
  console.log(` [static] ${page.entry.routePath} -> ${outPath}`);
1844
2252
  }
1845
2253
  for (const content of contentEntries) {
@@ -1855,16 +2263,16 @@ async function build(options) {
1855
2263
  stylesheet: stylesheetHref
1856
2264
  });
1857
2265
  const outPath = content.routePath === "/" ? "/index.html" : `${content.routePath}/index.html`;
1858
- const fullPath = join5(clientDir, outPath);
1859
- mkdirSync(join5(fullPath, ".."), { recursive: true });
2266
+ const fullPath = join6(clientDir, outPath);
2267
+ mkdirSync2(join6(fullPath, ".."), { recursive: true });
1860
2268
  if (writtenPaths.has(outPath)) {
1861
2269
  console.warn(` [warn] collision: content ${content.routePath} overwrites existing output`);
1862
2270
  }
1863
2271
  writtenPaths.add(outPath);
1864
- writeFileSync3(fullPath, html, "utf-8");
2272
+ writeFileSync4(fullPath, html, "utf-8");
1865
2273
  console.log(` [content] ${content.routePath} -> ${outPath}`);
1866
2274
  }
1867
- if (serverPages.length > 0 || apiRoutes.length > 0) {
2275
+ if (pagesDir || options.routesDir || options.contentDir) {
1868
2276
  const srvOpts = {
1869
2277
  pagesDir: pagesDir || options.routesDir || ""
1870
2278
  };
@@ -1875,30 +2283,29 @@ async function build(options) {
1875
2283
  const configImportPath = options.configPath ? relativeImportPath(serverDir, options.configPath) : void 0;
1876
2284
  const serverEntry = buildServerEntry(
1877
2285
  srvOpts,
1878
- configImportPath
2286
+ configImportPath,
2287
+ stylesheetHref
1879
2288
  );
1880
- const serverEntryPath = join5(serverDir, "index.ts");
1881
- writeFileSync3(serverEntryPath, serverEntry, "utf-8");
2289
+ const serverEntryPath = join6(serverDir, "index.ts");
2290
+ writeFileSync4(serverEntryPath, serverEntry, "utf-8");
1882
2291
  console.log(
1883
2292
  ` [server] ${serverPages.length} page routes, ${apiRoutes.length} api routes -> server/index.ts`
1884
2293
  );
1885
2294
  }
1886
2295
  console.log(`[x] build complete -> ${outDir}`);
1887
2296
  }
1888
- async function bundleRouteIslands(routeFilePath, islandNames, islandsDir, actionModules) {
1889
- const entryId = `${basename(routeFilePath).replace(/\.(tsx|ts)$/, "")}-${hash(routeFilePath)}`;
1890
- const outdir = join5(islandsDir, entryId);
1891
- mkdirSync(outdir, { recursive: true });
1892
- const bundlePath = join5(outdir, `${entryId}.js`);
1893
- const routeRel = join5(relative3(outdir, join5(routeFilePath, "..")), basename(routeFilePath));
1894
- const hydrateEntry = generateHydrateEntry(routeRel, islandNames);
1895
- const entryPath = join5(outdir, `${entryId}.tsx`);
1896
- writeFileSync3(entryPath, hydrateEntry, "utf-8");
2297
+ async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, islandsDir, actionModules) {
2298
+ const entryId = islandEntryId(routeFilePath);
2299
+ const outdir = join6(islandsDir, entryId);
2300
+ mkdirSync2(outdir, { recursive: true });
2301
+ const bundlePath = join6(outdir, `${entryId}.js`);
2302
+ const hydrateEntry = generateHydrateEntry(routeFilePath, layoutFilePaths);
2303
+ const entryPath = join6(outdir, `${entryId}.tsx`);
2304
+ writeFileSync4(entryPath, hydrateEntry, "utf-8");
1897
2305
  try {
1898
2306
  const result = await Bun.build({
1899
2307
  entrypoints: [entryPath],
1900
2308
  target: "browser",
1901
- external: ["react", "react-dom"],
1902
2309
  plugins: [actionsRewritePlugin(actionModules)]
1903
2310
  });
1904
2311
  if (result.success) {
@@ -1907,7 +2314,7 @@ async function bundleRouteIslands(routeFilePath, islandNames, islandsDir, action
1907
2314
  if (!built) throw new Error("bun build produced no output");
1908
2315
  const code = await built.text();
1909
2316
  assertNoEnvLeakage(code, bundlePath);
1910
- writeFileSync3(bundlePath, code, "utf-8");
2317
+ writeFileSync4(bundlePath, wrapIslandBundle(code), "utf-8");
1911
2318
  return [`/_islands/${entryId}/${entryId}.js`];
1912
2319
  }
1913
2320
  for (const log of result.logs) {
@@ -1916,48 +2323,12 @@ async function bundleRouteIslands(routeFilePath, islandNames, islandsDir, action
1916
2323
  } catch (err) {
1917
2324
  console.warn(` [islands] build failed for ${routeFilePath}:`, err);
1918
2325
  }
1919
- writeFileSync3(bundlePath, generateFallbackHydration(islandNames), "utf-8");
2326
+ writeFileSync4(bundlePath, wrapIslandBundle(generateFallbackHydration(islandNames)), "utf-8");
1920
2327
  return [`/_islands/${entryId}/${entryId}.js`];
1921
2328
  }
1922
- function actionsRewritePlugin(actionModules) {
1923
- return {
1924
- name: "x-actions-rewrite",
1925
- setup(build2) {
1926
- if (actionModules.size === 0) return;
1927
- build2.onLoad({ filter: /\.(ts|tsx)$/ }, (args) => {
1928
- const info = actionModules.get(args.path);
1929
- if (!info) return void 0;
1930
- const endpointBase = info.parentPath === "/" ? "/__x/actions" : `/__x/actions${info.parentPath}`;
1931
- const contents = generateServerFunctionClient(args.path, info.fnNames, endpointBase);
1932
- return { contents, loader: "ts" };
1933
- });
1934
- }
1935
- };
1936
- }
1937
- function generateHydrateEntry(routeRelPath, _islandNames) {
1938
- return `import React from "react";
1939
- import { hydrateRoot } from "react-dom/client";
1940
- import * as Route from "${routeRelPath}";
1941
-
1942
- document.querySelectorAll("[data-island]").forEach((el) => {
1943
- const name = el.getAttribute("data-island");
1944
- if (!name) return;
1945
- const Component = Route.islands?.[name];
1946
- if (!Component) return;
1947
- hydrateRoot(el, React.createElement(Component));
1948
- });
1949
- `;
1950
- }
1951
- function generateFallbackHydration(islandNames) {
1952
- return `// x island hydration fallback \u2014 ${islandNames.join(", ")}
1953
- document.querySelectorAll("[data-island]").forEach(function(el) {
1954
- el.setAttribute("data-island-hydrated", "false");
1955
- });
1956
- `;
1957
- }
1958
2329
  function renderPageWithLayout(Component, params, layoutModules) {
1959
2330
  let content = createElement2(Component, { params });
1960
- for (const Layout of layoutModules) {
2331
+ for (const Layout of [...layoutModules].reverse()) {
1961
2332
  content = createElement2(Layout, null, content);
1962
2333
  }
1963
2334
  return content;
@@ -1976,7 +2347,7 @@ function StaticContentPage({
1976
2347
  })
1977
2348
  );
1978
2349
  }
1979
- function buildServerEntry(opts, configImportPath) {
2350
+ function buildServerEntry(opts, configImportPath, stylesheetHref) {
1980
2351
  const dirKeys = ["pagesDir", "apiDir", "layoutsDir", "actionsDir", "contentDir"];
1981
2352
  const lines = [
1982
2353
  "// Auto-generated by @thexjs/core build",
@@ -1997,19 +2368,40 @@ function buildServerEntry(opts, configImportPath) {
1997
2368
  const val = opts[key];
1998
2369
  if (val) lines.push(` ${key}: ${JSON.stringify(val)},`);
1999
2370
  }
2371
+ if (stylesheetHref) lines.push(` stylesheetHref: ${JSON.stringify(stylesheetHref)},`);
2000
2372
  lines.push(' port: parseInt(process.env.PORT || "3000", 10),', " development: false,");
2001
2373
  if (configImportPath) {
2002
2374
  lines.push(" ...(userConfig.security ? { security: userConfig.security } : {}),");
2003
2375
  lines.push(
2004
2376
  " ...(userConfig.observability ? { observability: userConfig.observability } : {}),"
2005
2377
  );
2378
+ lines.push(" ...(userConfig.images ? { images: userConfig.images } : {}),");
2006
2379
  }
2007
2380
  lines.push(
2008
2381
  "});",
2009
2382
  "",
2010
2383
  "const server = Bun.serve(app);",
2011
2384
  "",
2012
- "console.log(`[x] production server running at ${server.url}`);"
2385
+ "console.log(`[x] production server running at ${server.url}`);",
2386
+ "",
2387
+ "// Graceful shutdown: stop accepting new connections, flush the error",
2388
+ "// reporter, then exit after in-flight requests have a moment to drain.",
2389
+ "let shuttingDown = false;",
2390
+ "async function shutdown(signal: string): Promise<void> {",
2391
+ " if (shuttingDown) return;",
2392
+ " shuttingDown = true;",
2393
+ " console.log(`[x] received ${signal} - shutting down`);",
2394
+ " try {",
2395
+ ' const { getErrorReporter } = await import("@thexjs/core");',
2396
+ " await getErrorReporter().flush?.();",
2397
+ " } catch {}",
2398
+ " server.stop(true);",
2399
+ " const exit = () => process.exit(0);",
2400
+ " const drainTimer = setTimeout(exit, 3000);",
2401
+ " drainTimer.unref?.();",
2402
+ "}",
2403
+ 'process.on("SIGTERM", () => shutdown("SIGTERM"));',
2404
+ 'process.on("SIGINT", () => shutdown("SIGINT"));'
2013
2405
  );
2014
2406
  return lines.join("\n");
2015
2407
  }
@@ -2017,13 +2409,6 @@ function relativeImportPath(fromDir, toFile) {
2017
2409
  const rel = relative3(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
2018
2410
  return rel.startsWith(".") ? rel : `./${rel}`;
2019
2411
  }
2020
- function hash(str) {
2021
- let h = 0;
2022
- for (let i = 0; i < str.length; i++) {
2023
- h = Math.imul(31, h) + str.charCodeAt(i) | 0;
2024
- }
2025
- return Math.abs(h).toString(36);
2026
- }
2027
2412
 
2028
2413
  // src/link.tsx
2029
2414
  import { jsx as jsx3 } from "react/jsx-runtime";
@@ -2039,88 +2424,6 @@ function Link({ href, children, clientNav = true, prefetch = true, ...rest }) {
2039
2424
  }
2040
2425
  );
2041
2426
  }
2042
-
2043
- // src/data/sqlite.ts
2044
- import { Database } from "bun:sqlite";
2045
- function connectSQLite(options) {
2046
- const db = new Database(options?.path ?? "data/dev.db");
2047
- if (options?.wal !== false) {
2048
- db.run("PRAGMA journal_mode = WAL");
2049
- }
2050
- if (options?.foreignKeys !== false) {
2051
- db.run("PRAGMA foreign_keys = ON");
2052
- }
2053
- return db;
2054
- }
2055
-
2056
- // src/data/postgres.ts
2057
- function connectPostgres(options) {
2058
- const url = options?.url ?? process.env.DATABASE_URL;
2059
- if (!url) {
2060
- throw new Error(
2061
- "DATABASE_URL is required \u2014 set it via options.url or the DATABASE_URL environment variable"
2062
- );
2063
- }
2064
- return Bun.sql(url);
2065
- }
2066
-
2067
- // src/data/migrate.ts
2068
- import { readFileSync as readFileSync3, readdirSync as readdirSync3 } from "fs";
2069
- import { join as join6 } from "path";
2070
- function runSQLiteMigrations(db, migrationsDir) {
2071
- db.run(`CREATE TABLE IF NOT EXISTS _x_migrations (
2072
- name TEXT PRIMARY KEY,
2073
- applied_at TEXT DEFAULT (datetime('now'))
2074
- )`);
2075
- const stmt = db.prepare("SELECT name FROM _x_migrations");
2076
- const applied = new Set(stmt.all().map((r) => r.name));
2077
- let files;
2078
- try {
2079
- files = readdirSync3(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
2080
- } catch {
2081
- return { applied: [], skipped: [] };
2082
- }
2083
- const result = { applied: [], skipped: [] };
2084
- for (const file of files) {
2085
- if (applied.has(file)) {
2086
- result.skipped.push(file);
2087
- continue;
2088
- }
2089
- const sql = readFileSync3(join6(migrationsDir, file), "utf-8");
2090
- db.run(sql);
2091
- db.run("INSERT INTO _x_migrations (name) VALUES (?1)", [file]);
2092
- console.log(`[x] migration applied: ${file}`);
2093
- result.applied.push(file);
2094
- }
2095
- return result;
2096
- }
2097
- async function runPostgresMigrations(client, migrationsDir) {
2098
- await client.unsafe(`CREATE TABLE IF NOT EXISTS _x_migrations (
2099
- name TEXT PRIMARY KEY,
2100
- applied_at TIMESTAMP DEFAULT NOW()
2101
- )`);
2102
- const rows = await client.unsafe("SELECT name FROM _x_migrations");
2103
- const applied = new Set(rows.map((r) => r.name));
2104
- let files;
2105
- try {
2106
- files = readdirSync3(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
2107
- } catch {
2108
- return { applied: [], skipped: [] };
2109
- }
2110
- const result = { applied: [], skipped: [] };
2111
- for (const file of files) {
2112
- if (applied.has(file)) {
2113
- result.skipped.push(file);
2114
- continue;
2115
- }
2116
- const raw = readFileSync3(join6(migrationsDir, file), "utf-8");
2117
- await client.unsafe(raw);
2118
- await client.unsafe(`INSERT INTO _x_migrations (name) VALUES ('${file}')`);
2119
- console.log(`[x] migration applied: ${file}`);
2120
- result.applied.push(file);
2121
- }
2122
- return result;
2123
- }
2124
2427
  export {
2125
2428
  CLIENT_NAV_SCRIPT,
2126
2429
  DefaultNotFound,
@@ -2136,12 +2439,12 @@ export {
2136
2439
  checkCsrf,
2137
2440
  combineReporters,
2138
2441
  composeMiddleware,
2139
- connectPostgres,
2140
- connectSQLite,
2141
2442
  createApp,
2142
2443
  createHealthCheckHandler,
2444
+ createImageProxyHandler,
2143
2445
  createOtelReporter,
2144
2446
  createRateLimiter,
2447
+ createRedisRateLimitStore,
2145
2448
  createSentryReporter,
2146
2449
  defineConfig,
2147
2450
  escapeHtml2 as escapeHtml,
@@ -2164,8 +2467,6 @@ export {
2164
2467
  renderStreamingPage,
2165
2468
  reportException,
2166
2469
  resetServerFunctions,
2167
- runPostgresMigrations,
2168
- runSQLiteMigrations,
2169
2470
  scanApiDir,
2170
2471
  scanContent,
2171
2472
  scanLayouts,