@thexjs/core 1.3.0 → 1.3.1

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.
@@ -0,0 +1,683 @@
1
+ // src/security/env-isolation.ts
2
+ var PUBLIC_ENV_PREFIX = "THEXJS_PUBLIC_";
3
+ var ENV_ACCESS_PATTERNS = [
4
+ /\bprocess\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
5
+ /\bprocess\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g,
6
+ /\bBun\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
7
+ /\bBun\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g,
8
+ /\bimport\.meta\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
9
+ /\bimport\.meta\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g
10
+ ];
11
+ var SUSPICIOUS_ENV_PATTERNS = [
12
+ {
13
+ re: /\b(?:process|Bun|import\.meta)\.env\s*\[[^"'`]/g,
14
+ label: "dynamic env key access"
15
+ },
16
+ {
17
+ re: /\b(?:process|Bun|import\.meta)\.env\[["'][^"']*["']\s*\+/g,
18
+ label: "concatenated env key access"
19
+ },
20
+ {
21
+ re: /\b(?:process|Bun)\.env\b(?!\s*(?:\.|\[))/g,
22
+ label: "bare process.env access (aliasing/mutation)"
23
+ }
24
+ ];
25
+ function findLeakedEnvKeys(code) {
26
+ const found = /* @__PURE__ */ new Set();
27
+ for (const pattern of ENV_ACCESS_PATTERNS) {
28
+ for (const match of code.matchAll(pattern)) {
29
+ const key = match[1];
30
+ if (key && !key.startsWith(PUBLIC_ENV_PREFIX)) {
31
+ found.add(key);
32
+ }
33
+ }
34
+ }
35
+ for (const { re, label } of SUSPICIOUS_ENV_PATTERNS) {
36
+ re.lastIndex = 0;
37
+ if (re.test(code)) found.add(`process.env (${label})`);
38
+ }
39
+ return [...found];
40
+ }
41
+ var EnvLeakageError = class extends Error {
42
+ constructor(file, keys) {
43
+ super(
44
+ `[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.`
45
+ );
46
+ this.file = file;
47
+ this.keys = keys;
48
+ this.name = "EnvLeakageError";
49
+ }
50
+ file;
51
+ keys;
52
+ };
53
+ function assertNoEnvLeakage(code, file) {
54
+ const leaked = findLeakedEnvKeys(code);
55
+ if (leaked.length > 0) {
56
+ throw new EnvLeakageError(file, leaked);
57
+ }
58
+ }
59
+
60
+ // src/observability/monitoring.ts
61
+ var noopReporter = {
62
+ captureException: () => {
63
+ }
64
+ };
65
+ var activeReporter = noopReporter;
66
+ function setErrorReporter(reporter) {
67
+ activeReporter = reporter;
68
+ }
69
+ function getErrorReporter() {
70
+ return activeReporter;
71
+ }
72
+ function reportException(error, context) {
73
+ try {
74
+ activeReporter.captureException(error, context);
75
+ } catch (reportingError) {
76
+ console.error("[x] error reporter threw while handling an exception:", reportingError);
77
+ }
78
+ }
79
+ function createSentryReporter(sentry) {
80
+ return {
81
+ captureException(error, context) {
82
+ sentry.captureException(error, { extra: { ...context } });
83
+ },
84
+ async flush() {
85
+ await sentry.flush?.(2e3);
86
+ }
87
+ };
88
+ }
89
+ var OTEL_ERROR_STATUS_CODE = 2;
90
+ function createOtelReporter(tracer) {
91
+ return {
92
+ captureException(error, context) {
93
+ const span = tracer.startSpan(`x.${context.phase}.error`);
94
+ span.recordException(error);
95
+ span.setStatus({
96
+ code: OTEL_ERROR_STATUS_CODE,
97
+ message: error instanceof Error ? error.message : String(error)
98
+ });
99
+ span.end();
100
+ }
101
+ };
102
+ }
103
+ function combineReporters(...reporters) {
104
+ return {
105
+ captureException(error, context) {
106
+ for (const reporter of reporters) {
107
+ try {
108
+ reporter.captureException(error, context);
109
+ } catch (err) {
110
+ console.error("[x] error reporter threw while handling an exception:", err);
111
+ }
112
+ }
113
+ },
114
+ async flush() {
115
+ await Promise.all(reporters.map((r) => r.flush?.()));
116
+ }
117
+ };
118
+ }
119
+
120
+ // src/router.ts
121
+ import { readdirSync, statSync, writeFileSync } from "fs";
122
+ import { join, relative, sep } from "path";
123
+ var ROUTE_FILE = /\.(tsx|ts)$/;
124
+ function scanPages(rootDir) {
125
+ return scanRoutes(rootDir).map((r) => ({ ...r, isApi: false }));
126
+ }
127
+ function scanApiDir(rootDir) {
128
+ return scanRoutes(rootDir).map((r) => ({
129
+ ...r,
130
+ routePath: r.routePath === "/" ? "/api" : `/api${r.routePath}`,
131
+ isApi: true
132
+ }));
133
+ }
134
+ function scanRoutes(rootDir) {
135
+ try {
136
+ statSync(rootDir);
137
+ } catch {
138
+ return [];
139
+ }
140
+ const entries = [];
141
+ function walk(dir) {
142
+ for (const name of readdirSync(dir)) {
143
+ if (name.startsWith("_") || name.startsWith(".")) continue;
144
+ const full = join(dir, name);
145
+ const stat = statSync(full);
146
+ if (stat.isDirectory()) {
147
+ walk(full);
148
+ continue;
149
+ }
150
+ if (!ROUTE_FILE.test(name)) continue;
151
+ const rel = relative(rootDir, full).replace(ROUTE_FILE, "");
152
+ entries.push(toRouteEntry(rel, full));
153
+ }
154
+ }
155
+ walk(rootDir);
156
+ return entries;
157
+ }
158
+ function toRouteEntry(relPath, filePath) {
159
+ const segments = relPath.split(sep);
160
+ const paramNames = [];
161
+ const isApi = segments[0] === "api";
162
+ const routeSegments = segments.map((segment) => {
163
+ if (segment === "index") return "";
164
+ if (segment.startsWith("[...") && segment.endsWith("]")) {
165
+ const name = segment.slice(4, -1);
166
+ paramNames.push(name);
167
+ return "*";
168
+ }
169
+ if (segment.startsWith("[") && segment.endsWith("]")) {
170
+ const name = segment.slice(1, -1);
171
+ paramNames.push(name);
172
+ return `:${name}`;
173
+ }
174
+ return segment;
175
+ });
176
+ const joined = routeSegments.filter((s) => s.length > 0).join("/");
177
+ const routePath = joined.length === 0 ? "/" : `/${joined}`;
178
+ return { filePath, routePath, paramNames, isApi };
179
+ }
180
+ function scanLayouts(rootDir) {
181
+ const entries = [];
182
+ function walk(dir) {
183
+ for (const name of readdirSync(dir)) {
184
+ if (name.startsWith(".")) continue;
185
+ const full = join(dir, name);
186
+ const stat = statSync(full);
187
+ if (stat.isDirectory()) {
188
+ walk(full);
189
+ } else if (name === "_layout.tsx" || name === "_layout.ts") {
190
+ entries.push({ filePath: full, dirPath: dir });
191
+ }
192
+ }
193
+ }
194
+ walk(rootDir);
195
+ return entries;
196
+ }
197
+ function scanLayoutsDir(layoutsDir) {
198
+ const entries = [];
199
+ try {
200
+ if (!statSync(layoutsDir).isDirectory()) return entries;
201
+ } catch {
202
+ return entries;
203
+ }
204
+ for (const name of readdirSync(layoutsDir)) {
205
+ if (name.startsWith(".")) continue;
206
+ const full = join(layoutsDir, name);
207
+ const stat = statSync(full);
208
+ if (stat.isFile() && (name.endsWith(".tsx") || name.endsWith(".ts"))) {
209
+ entries.push({ filePath: full, dirPath: layoutsDir });
210
+ }
211
+ }
212
+ return entries;
213
+ }
214
+ function findLayoutChain(routeFilePath, layouts, routesDir) {
215
+ const routeDir = join(routeFilePath, "..");
216
+ const chain = [];
217
+ let current = routeDir;
218
+ while (current.startsWith(routesDir)) {
219
+ const layout = layouts.find((l) => l.dirPath === current);
220
+ if (layout) chain.unshift(layout);
221
+ const parent = join(current, "..");
222
+ if (parent === current) break;
223
+ current = parent;
224
+ }
225
+ return chain;
226
+ }
227
+ var NOT_FOUND_CANDIDATES = ["_404.tsx", "_404.ts"];
228
+ function scanNotFound(rootDir) {
229
+ for (const name of NOT_FOUND_CANDIDATES) {
230
+ const full = join(rootDir, name);
231
+ try {
232
+ statSync(full);
233
+ return { filePath: full };
234
+ } catch {
235
+ }
236
+ }
237
+ return null;
238
+ }
239
+ function scanMiddleware(rootDir) {
240
+ const entries = [];
241
+ function walk(dir) {
242
+ for (const name of readdirSync(dir)) {
243
+ if (name.startsWith(".")) continue;
244
+ const full = join(dir, name);
245
+ const stat = statSync(full);
246
+ if (stat.isDirectory()) {
247
+ walk(full);
248
+ } else if (name === "_middleware.ts" || name === "_middleware.tsx") {
249
+ entries.push({ filePath: full, dirPath: dir });
250
+ }
251
+ }
252
+ }
253
+ walk(rootDir);
254
+ return entries;
255
+ }
256
+ function findMiddlewareChain(routeFilePath, middleware, routesDir) {
257
+ const routeDir = join(routeFilePath, "..");
258
+ const chain = [];
259
+ let current = routeDir;
260
+ while (current.startsWith(routesDir)) {
261
+ const mw = middleware.find((m) => m.dirPath === current);
262
+ if (mw) chain.unshift(mw);
263
+ const parent = join(current, "..");
264
+ if (parent === current) break;
265
+ current = parent;
266
+ }
267
+ return chain;
268
+ }
269
+ function routePatternToRegex(routePath) {
270
+ const regexStr = routePath.replace(/\//g, "\\/").replace(/:(\w+)/g, "([^/]+)").replace(/\*/g, "(.+)");
271
+ return new RegExp(`^${regexStr}$`);
272
+ }
273
+ function extractParams(routePath, paramNames, url) {
274
+ const regex = routePatternToRegex(routePath);
275
+ const match = url.match(regex);
276
+ if (!match) return null;
277
+ const params = {};
278
+ let idx = 1;
279
+ for (const name of paramNames) {
280
+ const value = match[idx];
281
+ if (value !== void 0) {
282
+ params[name] = safeDecodeURIComponent(value);
283
+ }
284
+ idx++;
285
+ }
286
+ return params;
287
+ }
288
+ function safeDecodeURIComponent(value) {
289
+ try {
290
+ return decodeURIComponent(value);
291
+ } catch {
292
+ return value;
293
+ }
294
+ }
295
+ function generateManifestSource(routes) {
296
+ const routeEntries = routes.map((r) => {
297
+ const paramsType = r.paramNames.length === 0 ? "Record<string, never>" : `{ ${r.paramNames.map((n) => `${n}: string`).join("; ")} }`;
298
+ return ` "${r.routePath}": ${paramsType};`;
299
+ });
300
+ return `// Auto-generated by @thexjs/core -- do not edit
301
+ export type RouteMap = {
302
+ ${routeEntries.join("\n")}
303
+ };
304
+
305
+ export function href<T extends keyof RouteMap & string>(
306
+ path: T,
307
+ ...[params]: RouteMap[T] extends Record<string, never> ? [] : [RouteMap[T]]
308
+ ): string {
309
+ if (!params) return path;
310
+ let result: string = path;
311
+ for (const [key, value] of Object.entries(params)) {
312
+ result = result.replace(new RegExp(\`:\${key}(?=/|$)\`), encodeURIComponent(String(value)));
313
+ }
314
+ result = result.replace(/\\*+$/, "");
315
+ return result;
316
+ }
317
+ `;
318
+ }
319
+ function writeManifest(routes, routesDir) {
320
+ const source = generateManifestSource(routes);
321
+ const manifestPath = join(routesDir, "..", "x-routes.ts");
322
+ writeFileSync(manifestPath, source, "utf-8");
323
+ return manifestPath;
324
+ }
325
+
326
+ // src/security/csrf.ts
327
+ var CSRF_COOKIE_NAME = "x_csrf_token";
328
+ var CSRF_HEADER_NAME = "x-csrf-token";
329
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
330
+ var SECURE_COOKIE_FLAG = process.env.NODE_ENV === "production" ? "; Secure" : "";
331
+ function originFromHeader(value) {
332
+ if (!value) return null;
333
+ try {
334
+ return new URL(value).origin;
335
+ } catch {
336
+ return null;
337
+ }
338
+ }
339
+ function requestOrigin(req) {
340
+ const url = new URL(req.url);
341
+ return `${url.protocol}//${url.host}`;
342
+ }
343
+ function verifyOrigin(req, allowedOrigins = []) {
344
+ if (SAFE_METHODS.has(req.method)) return { ok: true };
345
+ const selfOrigin = requestOrigin(req);
346
+ const allowed = new Set([selfOrigin, ...allowedOrigins].filter(Boolean));
347
+ const origin = originFromHeader(req.headers.get("origin"));
348
+ if (origin) {
349
+ return allowed.has(origin) ? { ok: true } : { ok: false, reason: `origin "${origin}" is not an allowed origin` };
350
+ }
351
+ const referer = originFromHeader(req.headers.get("referer"));
352
+ if (referer) {
353
+ return allowed.has(referer) ? { ok: true } : { ok: false, reason: `referer origin "${referer}" is not an allowed origin` };
354
+ }
355
+ return { ok: false, reason: "missing Origin and Referer headers on a mutating request" };
356
+ }
357
+ function generateCsrfToken() {
358
+ return crypto.randomUUID().replace(/-/g, "") + crypto.randomUUID().replace(/-/g, "");
359
+ }
360
+ function readCookie(req, name) {
361
+ const header = req.headers.get("cookie");
362
+ if (!header) return null;
363
+ for (const part of header.split(";")) {
364
+ const [key, ...rest] = part.trim().split("=");
365
+ if (key === name) return rest.join("=");
366
+ }
367
+ return null;
368
+ }
369
+ function verifyCsrfToken(req) {
370
+ if (SAFE_METHODS.has(req.method)) return { ok: true };
371
+ const cookieToken = readCookie(req, CSRF_COOKIE_NAME);
372
+ const headerToken = req.headers.get(CSRF_HEADER_NAME);
373
+ if (!cookieToken || !headerToken) {
374
+ return { ok: false, reason: `missing CSRF cookie or "${CSRF_HEADER_NAME}" header` };
375
+ }
376
+ if (cookieToken !== headerToken) {
377
+ return { ok: false, reason: "CSRF token mismatch" };
378
+ }
379
+ return { ok: true };
380
+ }
381
+ function withCsrfCookie(req, res) {
382
+ if (readCookie(req, CSRF_COOKIE_NAME)) return res;
383
+ const token = generateCsrfToken();
384
+ const headers = new Headers(res.headers);
385
+ headers.append(
386
+ "Set-Cookie",
387
+ `${CSRF_COOKIE_NAME}=${token}; Path=/; SameSite=Lax${SECURE_COOKIE_FLAG}`
388
+ );
389
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
390
+ }
391
+ function checkCsrf(req, options = {}) {
392
+ if (options.disabled) return { ok: true };
393
+ const originResult = verifyOrigin(req, options.allowedOrigins ?? []);
394
+ if (!originResult.ok) return originResult;
395
+ if (options.requireToken) {
396
+ const tokenResult = verifyCsrfToken(req);
397
+ if (!tokenResult.ok) return tokenResult;
398
+ }
399
+ return { ok: true };
400
+ }
401
+
402
+ // src/server-functions.ts
403
+ import { writeFileSync as writeFileSync2 } from "fs";
404
+ import { join as join2 } from "path";
405
+ function generateServerFunctionClient(routeFilePath, fnNames, endpointBase) {
406
+ const fnCalls = fnNames.map(
407
+ (name) => `
408
+ export async function ${name}(...args: unknown[]): Promise<unknown> {
409
+ const res = await fetch("${endpointBase}/${name}", {
410
+ method: "POST",
411
+ headers: { "Content-Type": "application/json" },
412
+ body: JSON.stringify(args),
413
+ });
414
+ if (!res.ok) throw new Error(await res.text());
415
+ return res.json();
416
+ }`
417
+ ).join("\n");
418
+ return `// Auto-generated client for server functions in ${routeFilePath}
419
+ // Do not edit.
420
+
421
+ ${fnCalls}
422
+ `;
423
+ }
424
+ var ACTION_ROUTES = [];
425
+ function resetServerFunctions() {
426
+ ACTION_ROUTES.length = 0;
427
+ }
428
+ function registerServerFunctions(routePath, paramNames, fns) {
429
+ const fnMap = new Map(Object.entries(fns));
430
+ const existing = ACTION_ROUTES.find((e) => e.routePath === routePath);
431
+ if (existing) {
432
+ for (const [name, fn] of fnMap) {
433
+ existing.fns.set(name, fn);
434
+ }
435
+ } else {
436
+ ACTION_ROUTES.push({ routePath, paramNames, fns: fnMap });
437
+ }
438
+ }
439
+ function getServerFunctionHandler(csrfOptions) {
440
+ return async (req) => {
441
+ if (req.method !== "POST") return null;
442
+ const url = new URL(req.url);
443
+ if (!url.pathname.startsWith("/__x/actions/")) return null;
444
+ const csrfResult = checkCsrf(req, csrfOptions);
445
+ if (!csrfResult.ok) {
446
+ return new Response(`Forbidden: ${csrfResult.reason}`, { status: 403 });
447
+ }
448
+ const parts = url.pathname.replace("/__x/actions/", "").split("/");
449
+ if (parts.length < 1) return null;
450
+ const actionName = parts.pop();
451
+ if (!actionName) return null;
452
+ const concretePath = `/${parts.join("/")}`;
453
+ for (const entry of ACTION_ROUTES) {
454
+ const params = extractActionParams(entry.routePath, entry.paramNames, concretePath);
455
+ if (params === null) continue;
456
+ const fn = entry.fns.get(actionName);
457
+ if (!fn) return new Response("Function not found", { status: 404 });
458
+ let args = [];
459
+ try {
460
+ const body = await req.json();
461
+ args = Array.isArray(body) ? body : [body];
462
+ } catch {
463
+ return new Response("Invalid request body", { status: 400 });
464
+ }
465
+ try {
466
+ const result = await fn(...args);
467
+ return Response.json(result);
468
+ } catch (err) {
469
+ reportException(err, { route: concretePath, phase: "action" });
470
+ const message = err instanceof Error ? err.message : "Internal error";
471
+ return new Response(message, { status: 500 });
472
+ }
473
+ }
474
+ return new Response("Not found", { status: 404 });
475
+ };
476
+ }
477
+ function extractActionParams(routePath, paramNames, url) {
478
+ const regex = routePatternToRegex(routePath);
479
+ const match = url.match(regex);
480
+ if (!match) return null;
481
+ const params = {};
482
+ let idx = 1;
483
+ for (const name of paramNames) {
484
+ const value = match[idx];
485
+ if (value !== void 0) {
486
+ params[name] = safeDecodeURIComponent2(value);
487
+ }
488
+ idx++;
489
+ }
490
+ return params;
491
+ }
492
+ function safeDecodeURIComponent2(value) {
493
+ try {
494
+ return decodeURIComponent(value);
495
+ } catch {
496
+ return value;
497
+ }
498
+ }
499
+
500
+ // src/island-bundle.ts
501
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync as writeFileSync3 } from "fs";
502
+ import { basename, join as join3 } from "path";
503
+ function actionsRewritePlugin(actionModules) {
504
+ return {
505
+ name: "x-actions-rewrite",
506
+ setup(build) {
507
+ if (actionModules.size === 0) return;
508
+ build.onLoad({ filter: /\.(ts|tsx)$/ }, (args) => {
509
+ const info = actionModules.get(args.path);
510
+ if (!info) return void 0;
511
+ const endpointBase = info.parentPath === "/" ? "/__x/actions" : `/__x/actions${info.parentPath}`;
512
+ const contents = generateServerFunctionClient(args.path, info.fnNames, endpointBase);
513
+ return { contents, loader: "ts" };
514
+ });
515
+ }
516
+ };
517
+ }
518
+ function generateHydrateEntry(routeAbsPath, layoutAbsPaths = []) {
519
+ const layoutImports = layoutAbsPaths.map((p, i) => `import * as Layout${i} from "${p}";`).join("\n");
520
+ const lookupParts = ["Route.islands?.[name]"];
521
+ for (let i = 0; i < layoutAbsPaths.length; i++) {
522
+ lookupParts.push(`Layout${i}.islands?.[name]`);
523
+ }
524
+ const lookup = lookupParts.join(" ?? ");
525
+ return `import React from "react";
526
+ import { hydrateRoot } from "react-dom/client";
527
+ import * as Route from "${routeAbsPath}";
528
+ ${layoutImports}
529
+
530
+ function resolveIsland(name: string) {
531
+ return ${lookup};
532
+ }
533
+
534
+ // Islands whose render is non-deterministic (e.g. \`useState(() => ...)\` with
535
+ // Math.random) can't be hydrated against their SSR output. React recovers by
536
+ // re-rendering client-side, so the island is still fully interactive -- the
537
+ // mismatch is benign, so swallow the recovery so it doesn't spam the console
538
+ // or cascade into React's event system.
539
+ function onRecoverableError() {}
540
+
541
+ document.querySelectorAll("[data-island]").forEach((el) => {
542
+ const name = el.getAttribute("data-island");
543
+ if (!name) return;
544
+ const Component = resolveIsland(name);
545
+ if (!Component) return;
546
+ hydrateRoot(el, React.createElement(Component), { onRecoverableError });
547
+ });
548
+ `;
549
+ }
550
+ function generateFallbackHydration(islandNames) {
551
+ return `// x island hydration fallback \u2014 ${islandNames.join(", ")}
552
+ document.querySelectorAll("[data-island]").forEach(function(el) {
553
+ el.setAttribute("data-island-hydrated", "false");
554
+ });
555
+ `;
556
+ }
557
+ function hashId(str) {
558
+ let h = 0;
559
+ for (let i = 0; i < str.length; i++) {
560
+ h = Math.imul(31, h) + str.charCodeAt(i) | 0;
561
+ }
562
+ return Math.abs(h).toString(36);
563
+ }
564
+ function islandEntryId(routeFilePath) {
565
+ return `${basename(routeFilePath).replace(/\.(tsx|ts)$/, "")}-${hashId(routeFilePath)}`;
566
+ }
567
+ function wrapIslandBundle(code) {
568
+ return `;(function () {
569
+ ${code}
570
+ })();
571
+ `;
572
+ }
573
+ async function buildIslandBundleInMemory(routeFilePath, layoutFilePaths, islandNames, actionModules, projectRoot) {
574
+ const entryId = islandEntryId(routeFilePath);
575
+ const scratchRoot = join3(projectRoot, ".x", "islands-tmp");
576
+ mkdirSync(scratchRoot, { recursive: true });
577
+ const scratchDir = mkdtempSync(join3(scratchRoot, "x-islands-"));
578
+ try {
579
+ const entryPath = join3(scratchDir, `${entryId}.tsx`);
580
+ writeFileSync3(entryPath, generateHydrateEntry(routeFilePath, layoutFilePaths), "utf-8");
581
+ const result = await Bun.build({
582
+ entrypoints: [entryPath],
583
+ target: "browser",
584
+ plugins: [actionsRewritePlugin(actionModules)]
585
+ });
586
+ if (!result.success) {
587
+ for (const log of result.logs) {
588
+ console.warn(` [islands] build error: ${log.message}`);
589
+ }
590
+ return wrapIslandBundle(generateFallbackHydration(islandNames));
591
+ }
592
+ const outputs = result.outputs.filter((o) => o.kind === "entry-point");
593
+ const built = outputs[0] ?? result.outputs[0];
594
+ if (!built) return wrapIslandBundle(generateFallbackHydration(islandNames));
595
+ const code = await built.text();
596
+ assertNoEnvLeakage(code, entryPath);
597
+ return wrapIslandBundle(code);
598
+ } catch (err) {
599
+ if (err instanceof EnvLeakageError) {
600
+ console.error(
601
+ `\x1B[1;31m\u{1F512} SECURITY: [islands] ${err.message}\x1B[0m
602
+ Falling back to a non-interactive hydration stub \u2014 fix the env isolation (prefix with THEXJS_PUBLIC_ or move the access server-side) before relying on this page's client behavior.`
603
+ );
604
+ return wrapIslandBundle(generateFallbackHydration(islandNames));
605
+ }
606
+ console.warn(` [islands] build failed for ${routeFilePath}:`, err);
607
+ return wrapIslandBundle(generateFallbackHydration(islandNames));
608
+ } finally {
609
+ rmSync(scratchDir, { recursive: true, force: true });
610
+ }
611
+ }
612
+ async function bundleRouteIslandsToDisk(routeFilePath, layoutFilePaths, islandNames, islandsDir, actionModules) {
613
+ const entryId = islandEntryId(routeFilePath);
614
+ const outdir = join3(islandsDir, entryId);
615
+ mkdirSync(outdir, { recursive: true });
616
+ const bundlePath = join3(outdir, `${entryId}.js`);
617
+ const hydrateEntry = generateHydrateEntry(routeFilePath, layoutFilePaths);
618
+ const entryPath = join3(outdir, `${entryId}.tsx`);
619
+ writeFileSync3(entryPath, hydrateEntry, "utf-8");
620
+ try {
621
+ const result = await Bun.build({
622
+ entrypoints: [entryPath],
623
+ target: "browser",
624
+ plugins: [actionsRewritePlugin(actionModules)]
625
+ });
626
+ if (result.success) {
627
+ const outputs = result.outputs.filter((o) => o.kind === "entry-point");
628
+ const built = outputs[0] ?? result.outputs[0];
629
+ if (built) {
630
+ const code = await built.text();
631
+ assertNoEnvLeakage(code, bundlePath);
632
+ writeFileSync3(bundlePath, wrapIslandBundle(code), "utf-8");
633
+ return [`/_islands/${entryId}/${entryId}.js`];
634
+ }
635
+ }
636
+ for (const log of result.logs) {
637
+ console.warn(` [islands] build error: ${log.message}`);
638
+ }
639
+ } catch (err) {
640
+ if (err instanceof EnvLeakageError) throw err;
641
+ console.warn(` [islands] build failed for ${routeFilePath}:`, err);
642
+ }
643
+ writeFileSync3(bundlePath, wrapIslandBundle(generateFallbackHydration(islandNames)), "utf-8");
644
+ return [`/_islands/${entryId}/${entryId}.js`];
645
+ }
646
+
647
+ export {
648
+ PUBLIC_ENV_PREFIX,
649
+ findLeakedEnvKeys,
650
+ EnvLeakageError,
651
+ assertNoEnvLeakage,
652
+ noopReporter,
653
+ setErrorReporter,
654
+ getErrorReporter,
655
+ reportException,
656
+ createSentryReporter,
657
+ createOtelReporter,
658
+ combineReporters,
659
+ scanPages,
660
+ scanApiDir,
661
+ scanRoutes,
662
+ scanLayouts,
663
+ scanLayoutsDir,
664
+ findLayoutChain,
665
+ scanNotFound,
666
+ scanMiddleware,
667
+ findMiddlewareChain,
668
+ extractParams,
669
+ generateManifestSource,
670
+ writeManifest,
671
+ verifyOrigin,
672
+ generateCsrfToken,
673
+ verifyCsrfToken,
674
+ withCsrfCookie,
675
+ checkCsrf,
676
+ generateServerFunctionClient,
677
+ resetServerFunctions,
678
+ registerServerFunctions,
679
+ getServerFunctionHandler,
680
+ islandEntryId,
681
+ buildIslandBundleInMemory,
682
+ bundleRouteIslandsToDisk
683
+ };