@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.
- package/dist/adapter.d.ts +8 -0
- package/dist/adapter.js +44 -16
- package/dist/chunk-MYYP67KQ.js +683 -0
- package/dist/index.js +56 -477
- package/package.json +1 -1
- package/dist/chunk-O6SIM7EF.js +0 -221
package/dist/index.js
CHANGED
|
@@ -1,9 +1,27 @@
|
|
|
1
1
|
import {
|
|
2
|
+
EnvLeakageError,
|
|
3
|
+
PUBLIC_ENV_PREFIX,
|
|
4
|
+
assertNoEnvLeakage,
|
|
5
|
+
buildIslandBundleInMemory,
|
|
6
|
+
bundleRouteIslandsToDisk,
|
|
7
|
+
checkCsrf,
|
|
8
|
+
combineReporters,
|
|
9
|
+
createOtelReporter,
|
|
10
|
+
createSentryReporter,
|
|
2
11
|
extractParams,
|
|
3
12
|
findLayoutChain,
|
|
13
|
+
findLeakedEnvKeys,
|
|
4
14
|
findMiddlewareChain,
|
|
15
|
+
generateCsrfToken,
|
|
5
16
|
generateManifestSource,
|
|
6
|
-
|
|
17
|
+
generateServerFunctionClient,
|
|
18
|
+
getErrorReporter,
|
|
19
|
+
getServerFunctionHandler,
|
|
20
|
+
islandEntryId,
|
|
21
|
+
noopReporter,
|
|
22
|
+
registerServerFunctions,
|
|
23
|
+
reportException,
|
|
24
|
+
resetServerFunctions,
|
|
7
25
|
scanApiDir,
|
|
8
26
|
scanLayouts,
|
|
9
27
|
scanLayoutsDir,
|
|
@@ -11,12 +29,16 @@ import {
|
|
|
11
29
|
scanNotFound,
|
|
12
30
|
scanPages,
|
|
13
31
|
scanRoutes,
|
|
32
|
+
setErrorReporter,
|
|
33
|
+
verifyCsrfToken,
|
|
34
|
+
verifyOrigin,
|
|
35
|
+
withCsrfCookie,
|
|
14
36
|
writeManifest
|
|
15
|
-
} from "./chunk-
|
|
37
|
+
} from "./chunk-MYYP67KQ.js";
|
|
16
38
|
|
|
17
39
|
// src/build.ts
|
|
18
|
-
import { cpSync, existsSync, mkdirSync
|
|
19
|
-
import { join as
|
|
40
|
+
import { cpSync, existsSync, mkdirSync, writeFileSync } from "fs";
|
|
41
|
+
import { join as join2, relative as relative2 } from "path";
|
|
20
42
|
import { createElement } from "react";
|
|
21
43
|
|
|
22
44
|
// src/content.ts
|
|
@@ -170,416 +192,6 @@ function Island({
|
|
|
170
192
|
return /* @__PURE__ */ jsx("div", { "data-island": name, "data-island-id": id, "data-island-client": client, children });
|
|
171
193
|
}
|
|
172
194
|
|
|
173
|
-
// src/island-bundle.ts
|
|
174
|
-
import { mkdirSync, mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
|
|
175
|
-
import { basename, join as join3 } from "path";
|
|
176
|
-
|
|
177
|
-
// src/security/env-isolation.ts
|
|
178
|
-
var PUBLIC_ENV_PREFIX = "THEXJS_PUBLIC_";
|
|
179
|
-
var ENV_ACCESS_PATTERNS = [
|
|
180
|
-
/\bprocess\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
|
|
181
|
-
/\bprocess\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g,
|
|
182
|
-
/\bBun\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
|
|
183
|
-
/\bBun\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g,
|
|
184
|
-
/\bimport\.meta\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
|
|
185
|
-
/\bimport\.meta\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g
|
|
186
|
-
];
|
|
187
|
-
var SUSPICIOUS_ENV_PATTERNS = [
|
|
188
|
-
{
|
|
189
|
-
re: /\b(?:process|Bun|import\.meta)\.env\s*\[[^"'`]/g,
|
|
190
|
-
label: "dynamic env key access"
|
|
191
|
-
},
|
|
192
|
-
{
|
|
193
|
-
re: /\b(?:process|Bun|import\.meta)\.env\[["'][^"']*["']\s*\+/g,
|
|
194
|
-
label: "concatenated env key access"
|
|
195
|
-
},
|
|
196
|
-
{
|
|
197
|
-
re: /\b(?:process|Bun)\.env\b(?!\s*(?:\.|\[))/g,
|
|
198
|
-
label: "bare process.env access (aliasing/mutation)"
|
|
199
|
-
}
|
|
200
|
-
];
|
|
201
|
-
function findLeakedEnvKeys(code) {
|
|
202
|
-
const found = /* @__PURE__ */ new Set();
|
|
203
|
-
for (const pattern of ENV_ACCESS_PATTERNS) {
|
|
204
|
-
for (const match of code.matchAll(pattern)) {
|
|
205
|
-
const key = match[1];
|
|
206
|
-
if (key && !key.startsWith(PUBLIC_ENV_PREFIX)) {
|
|
207
|
-
found.add(key);
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
for (const { re, label } of SUSPICIOUS_ENV_PATTERNS) {
|
|
212
|
-
re.lastIndex = 0;
|
|
213
|
-
if (re.test(code)) found.add(`process.env (${label})`);
|
|
214
|
-
}
|
|
215
|
-
return [...found];
|
|
216
|
-
}
|
|
217
|
-
var EnvLeakageError = class extends Error {
|
|
218
|
-
constructor(file, keys) {
|
|
219
|
-
super(
|
|
220
|
-
`[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.`
|
|
221
|
-
);
|
|
222
|
-
this.file = file;
|
|
223
|
-
this.keys = keys;
|
|
224
|
-
this.name = "EnvLeakageError";
|
|
225
|
-
}
|
|
226
|
-
file;
|
|
227
|
-
keys;
|
|
228
|
-
};
|
|
229
|
-
function assertNoEnvLeakage(code, file) {
|
|
230
|
-
const leaked = findLeakedEnvKeys(code);
|
|
231
|
-
if (leaked.length > 0) {
|
|
232
|
-
throw new EnvLeakageError(file, leaked);
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
// src/server-functions.ts
|
|
237
|
-
import { writeFileSync } from "fs";
|
|
238
|
-
import { join as join2 } from "path";
|
|
239
|
-
|
|
240
|
-
// src/observability/monitoring.ts
|
|
241
|
-
var noopReporter = {
|
|
242
|
-
captureException: () => {
|
|
243
|
-
}
|
|
244
|
-
};
|
|
245
|
-
var activeReporter = noopReporter;
|
|
246
|
-
function setErrorReporter(reporter) {
|
|
247
|
-
activeReporter = reporter;
|
|
248
|
-
}
|
|
249
|
-
function getErrorReporter() {
|
|
250
|
-
return activeReporter;
|
|
251
|
-
}
|
|
252
|
-
function reportException(error, context) {
|
|
253
|
-
try {
|
|
254
|
-
activeReporter.captureException(error, context);
|
|
255
|
-
} catch (reportingError) {
|
|
256
|
-
console.error("[x] error reporter threw while handling an exception:", reportingError);
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
function createSentryReporter(sentry) {
|
|
260
|
-
return {
|
|
261
|
-
captureException(error, context) {
|
|
262
|
-
sentry.captureException(error, { extra: { ...context } });
|
|
263
|
-
},
|
|
264
|
-
async flush() {
|
|
265
|
-
await sentry.flush?.(2e3);
|
|
266
|
-
}
|
|
267
|
-
};
|
|
268
|
-
}
|
|
269
|
-
var OTEL_ERROR_STATUS_CODE = 2;
|
|
270
|
-
function createOtelReporter(tracer) {
|
|
271
|
-
return {
|
|
272
|
-
captureException(error, context) {
|
|
273
|
-
const span = tracer.startSpan(`x.${context.phase}.error`);
|
|
274
|
-
span.recordException(error);
|
|
275
|
-
span.setStatus({
|
|
276
|
-
code: OTEL_ERROR_STATUS_CODE,
|
|
277
|
-
message: error instanceof Error ? error.message : String(error)
|
|
278
|
-
});
|
|
279
|
-
span.end();
|
|
280
|
-
}
|
|
281
|
-
};
|
|
282
|
-
}
|
|
283
|
-
function combineReporters(...reporters) {
|
|
284
|
-
return {
|
|
285
|
-
captureException(error, context) {
|
|
286
|
-
for (const reporter of reporters) {
|
|
287
|
-
try {
|
|
288
|
-
reporter.captureException(error, context);
|
|
289
|
-
} catch (err) {
|
|
290
|
-
console.error("[x] error reporter threw while handling an exception:", err);
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
},
|
|
294
|
-
async flush() {
|
|
295
|
-
await Promise.all(reporters.map((r) => r.flush?.()));
|
|
296
|
-
}
|
|
297
|
-
};
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
// src/security/csrf.ts
|
|
301
|
-
var CSRF_COOKIE_NAME = "x_csrf_token";
|
|
302
|
-
var CSRF_HEADER_NAME = "x-csrf-token";
|
|
303
|
-
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
|
|
304
|
-
var SECURE_COOKIE_FLAG = process.env.NODE_ENV === "production" ? "; Secure" : "";
|
|
305
|
-
function originFromHeader(value) {
|
|
306
|
-
if (!value) return null;
|
|
307
|
-
try {
|
|
308
|
-
return new URL(value).origin;
|
|
309
|
-
} catch {
|
|
310
|
-
return null;
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
function requestOrigin(req) {
|
|
314
|
-
const url = new URL(req.url);
|
|
315
|
-
return `${url.protocol}//${url.host}`;
|
|
316
|
-
}
|
|
317
|
-
function verifyOrigin(req, allowedOrigins = []) {
|
|
318
|
-
if (SAFE_METHODS.has(req.method)) return { ok: true };
|
|
319
|
-
const selfOrigin = requestOrigin(req);
|
|
320
|
-
const allowed = new Set([selfOrigin, ...allowedOrigins].filter(Boolean));
|
|
321
|
-
const origin = originFromHeader(req.headers.get("origin"));
|
|
322
|
-
if (origin) {
|
|
323
|
-
return allowed.has(origin) ? { ok: true } : { ok: false, reason: `origin "${origin}" is not an allowed origin` };
|
|
324
|
-
}
|
|
325
|
-
const referer = originFromHeader(req.headers.get("referer"));
|
|
326
|
-
if (referer) {
|
|
327
|
-
return allowed.has(referer) ? { ok: true } : { ok: false, reason: `referer origin "${referer}" is not an allowed origin` };
|
|
328
|
-
}
|
|
329
|
-
return { ok: false, reason: "missing Origin and Referer headers on a mutating request" };
|
|
330
|
-
}
|
|
331
|
-
function generateCsrfToken() {
|
|
332
|
-
return crypto.randomUUID().replace(/-/g, "") + crypto.randomUUID().replace(/-/g, "");
|
|
333
|
-
}
|
|
334
|
-
function readCookie(req, name) {
|
|
335
|
-
const header = req.headers.get("cookie");
|
|
336
|
-
if (!header) return null;
|
|
337
|
-
for (const part of header.split(";")) {
|
|
338
|
-
const [key, ...rest] = part.trim().split("=");
|
|
339
|
-
if (key === name) return rest.join("=");
|
|
340
|
-
}
|
|
341
|
-
return null;
|
|
342
|
-
}
|
|
343
|
-
function verifyCsrfToken(req) {
|
|
344
|
-
if (SAFE_METHODS.has(req.method)) return { ok: true };
|
|
345
|
-
const cookieToken = readCookie(req, CSRF_COOKIE_NAME);
|
|
346
|
-
const headerToken = req.headers.get(CSRF_HEADER_NAME);
|
|
347
|
-
if (!cookieToken || !headerToken) {
|
|
348
|
-
return { ok: false, reason: `missing CSRF cookie or "${CSRF_HEADER_NAME}" header` };
|
|
349
|
-
}
|
|
350
|
-
if (cookieToken !== headerToken) {
|
|
351
|
-
return { ok: false, reason: "CSRF token mismatch" };
|
|
352
|
-
}
|
|
353
|
-
return { ok: true };
|
|
354
|
-
}
|
|
355
|
-
function withCsrfCookie(req, res) {
|
|
356
|
-
if (readCookie(req, CSRF_COOKIE_NAME)) return res;
|
|
357
|
-
const token = generateCsrfToken();
|
|
358
|
-
const headers = new Headers(res.headers);
|
|
359
|
-
headers.append(
|
|
360
|
-
"Set-Cookie",
|
|
361
|
-
`${CSRF_COOKIE_NAME}=${token}; Path=/; SameSite=Lax${SECURE_COOKIE_FLAG}`
|
|
362
|
-
);
|
|
363
|
-
return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
|
|
364
|
-
}
|
|
365
|
-
function checkCsrf(req, options = {}) {
|
|
366
|
-
if (options.disabled) return { ok: true };
|
|
367
|
-
const originResult = verifyOrigin(req, options.allowedOrigins ?? []);
|
|
368
|
-
if (!originResult.ok) return originResult;
|
|
369
|
-
if (options.requireToken) {
|
|
370
|
-
const tokenResult = verifyCsrfToken(req);
|
|
371
|
-
if (!tokenResult.ok) return tokenResult;
|
|
372
|
-
}
|
|
373
|
-
return { ok: true };
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
// src/server-functions.ts
|
|
377
|
-
function generateServerFunctionClient(routeFilePath, fnNames, endpointBase) {
|
|
378
|
-
const fnCalls = fnNames.map(
|
|
379
|
-
(name) => `
|
|
380
|
-
export async function ${name}(...args: unknown[]): Promise<unknown> {
|
|
381
|
-
const res = await fetch("${endpointBase}/${name}", {
|
|
382
|
-
method: "POST",
|
|
383
|
-
headers: { "Content-Type": "application/json" },
|
|
384
|
-
body: JSON.stringify(args),
|
|
385
|
-
});
|
|
386
|
-
if (!res.ok) throw new Error(await res.text());
|
|
387
|
-
return res.json();
|
|
388
|
-
}`
|
|
389
|
-
).join("\n");
|
|
390
|
-
return `// Auto-generated client for server functions in ${routeFilePath}
|
|
391
|
-
// Do not edit.
|
|
392
|
-
|
|
393
|
-
${fnCalls}
|
|
394
|
-
`;
|
|
395
|
-
}
|
|
396
|
-
var ACTION_ROUTES = [];
|
|
397
|
-
function resetServerFunctions() {
|
|
398
|
-
ACTION_ROUTES.length = 0;
|
|
399
|
-
}
|
|
400
|
-
function registerServerFunctions(routePath, paramNames, fns) {
|
|
401
|
-
const fnMap = new Map(Object.entries(fns));
|
|
402
|
-
const existing = ACTION_ROUTES.find((e) => e.routePath === routePath);
|
|
403
|
-
if (existing) {
|
|
404
|
-
for (const [name, fn] of fnMap) {
|
|
405
|
-
existing.fns.set(name, fn);
|
|
406
|
-
}
|
|
407
|
-
} else {
|
|
408
|
-
ACTION_ROUTES.push({ routePath, paramNames, fns: fnMap });
|
|
409
|
-
}
|
|
410
|
-
}
|
|
411
|
-
function getServerFunctionHandler(csrfOptions) {
|
|
412
|
-
return async (req) => {
|
|
413
|
-
if (req.method !== "POST") return null;
|
|
414
|
-
const url = new URL(req.url);
|
|
415
|
-
if (!url.pathname.startsWith("/__x/actions/")) return null;
|
|
416
|
-
const csrfResult = checkCsrf(req, csrfOptions);
|
|
417
|
-
if (!csrfResult.ok) {
|
|
418
|
-
return new Response(`Forbidden: ${csrfResult.reason}`, { status: 403 });
|
|
419
|
-
}
|
|
420
|
-
const parts = url.pathname.replace("/__x/actions/", "").split("/");
|
|
421
|
-
if (parts.length < 1) return null;
|
|
422
|
-
const actionName = parts.pop();
|
|
423
|
-
if (!actionName) return null;
|
|
424
|
-
const concretePath = `/${parts.join("/")}`;
|
|
425
|
-
for (const entry of ACTION_ROUTES) {
|
|
426
|
-
const params = extractActionParams(entry.routePath, entry.paramNames, concretePath);
|
|
427
|
-
if (params === null) continue;
|
|
428
|
-
const fn = entry.fns.get(actionName);
|
|
429
|
-
if (!fn) return new Response("Function not found", { status: 404 });
|
|
430
|
-
let args = [];
|
|
431
|
-
try {
|
|
432
|
-
const body = await req.json();
|
|
433
|
-
args = Array.isArray(body) ? body : [body];
|
|
434
|
-
} catch {
|
|
435
|
-
return new Response("Invalid request body", { status: 400 });
|
|
436
|
-
}
|
|
437
|
-
try {
|
|
438
|
-
const result = await fn(...args);
|
|
439
|
-
return Response.json(result);
|
|
440
|
-
} catch (err) {
|
|
441
|
-
reportException(err, { route: concretePath, phase: "action" });
|
|
442
|
-
const message = err instanceof Error ? err.message : "Internal error";
|
|
443
|
-
return new Response(message, { status: 500 });
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
return new Response("Not found", { status: 404 });
|
|
447
|
-
};
|
|
448
|
-
}
|
|
449
|
-
function extractActionParams(routePath, paramNames, url) {
|
|
450
|
-
const regex = routePatternToRegex(routePath);
|
|
451
|
-
const match = url.match(regex);
|
|
452
|
-
if (!match) return null;
|
|
453
|
-
const params = {};
|
|
454
|
-
let idx = 1;
|
|
455
|
-
for (const name of paramNames) {
|
|
456
|
-
const value = match[idx];
|
|
457
|
-
if (value !== void 0) {
|
|
458
|
-
params[name] = safeDecodeURIComponent(value);
|
|
459
|
-
}
|
|
460
|
-
idx++;
|
|
461
|
-
}
|
|
462
|
-
return params;
|
|
463
|
-
}
|
|
464
|
-
function safeDecodeURIComponent(value) {
|
|
465
|
-
try {
|
|
466
|
-
return decodeURIComponent(value);
|
|
467
|
-
} catch {
|
|
468
|
-
return value;
|
|
469
|
-
}
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
// src/island-bundle.ts
|
|
473
|
-
function actionsRewritePlugin(actionModules) {
|
|
474
|
-
return {
|
|
475
|
-
name: "x-actions-rewrite",
|
|
476
|
-
setup(build2) {
|
|
477
|
-
if (actionModules.size === 0) return;
|
|
478
|
-
build2.onLoad({ filter: /\.(ts|tsx)$/ }, (args) => {
|
|
479
|
-
const info = actionModules.get(args.path);
|
|
480
|
-
if (!info) return void 0;
|
|
481
|
-
const endpointBase = info.parentPath === "/" ? "/__x/actions" : `/__x/actions${info.parentPath}`;
|
|
482
|
-
const contents = generateServerFunctionClient(args.path, info.fnNames, endpointBase);
|
|
483
|
-
return { contents, loader: "ts" };
|
|
484
|
-
});
|
|
485
|
-
}
|
|
486
|
-
};
|
|
487
|
-
}
|
|
488
|
-
function generateHydrateEntry(routeAbsPath, layoutAbsPaths = []) {
|
|
489
|
-
const layoutImports = layoutAbsPaths.map((p, i) => `import * as Layout${i} from "${p}";`).join("\n");
|
|
490
|
-
const lookupParts = ["Route.islands?.[name]"];
|
|
491
|
-
for (let i = 0; i < layoutAbsPaths.length; i++) {
|
|
492
|
-
lookupParts.push(`Layout${i}.islands?.[name]`);
|
|
493
|
-
}
|
|
494
|
-
const lookup = lookupParts.join(" ?? ");
|
|
495
|
-
return `import React from "react";
|
|
496
|
-
import { hydrateRoot } from "react-dom/client";
|
|
497
|
-
import * as Route from "${routeAbsPath}";
|
|
498
|
-
${layoutImports}
|
|
499
|
-
|
|
500
|
-
function resolveIsland(name: string) {
|
|
501
|
-
return ${lookup};
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
// Islands whose render is non-deterministic (e.g. \`useState(() => ...)\` with
|
|
505
|
-
// Math.random) can't be hydrated against their SSR output. React recovers by
|
|
506
|
-
// re-rendering client-side, so the island is still fully interactive -- the
|
|
507
|
-
// mismatch is benign, so swallow the recovery so it doesn't spam the console
|
|
508
|
-
// or cascade into React's event system.
|
|
509
|
-
function onRecoverableError() {}
|
|
510
|
-
|
|
511
|
-
document.querySelectorAll("[data-island]").forEach((el) => {
|
|
512
|
-
const name = el.getAttribute("data-island");
|
|
513
|
-
if (!name) return;
|
|
514
|
-
const Component = resolveIsland(name);
|
|
515
|
-
if (!Component) return;
|
|
516
|
-
hydrateRoot(el, React.createElement(Component), { onRecoverableError });
|
|
517
|
-
});
|
|
518
|
-
`;
|
|
519
|
-
}
|
|
520
|
-
function generateFallbackHydration(islandNames) {
|
|
521
|
-
return `// x island hydration fallback \u2014 ${islandNames.join(", ")}
|
|
522
|
-
document.querySelectorAll("[data-island]").forEach(function(el) {
|
|
523
|
-
el.setAttribute("data-island-hydrated", "false");
|
|
524
|
-
});
|
|
525
|
-
`;
|
|
526
|
-
}
|
|
527
|
-
function hashId(str) {
|
|
528
|
-
let h = 0;
|
|
529
|
-
for (let i = 0; i < str.length; i++) {
|
|
530
|
-
h = Math.imul(31, h) + str.charCodeAt(i) | 0;
|
|
531
|
-
}
|
|
532
|
-
return Math.abs(h).toString(36);
|
|
533
|
-
}
|
|
534
|
-
function islandEntryId(routeFilePath) {
|
|
535
|
-
return `${basename(routeFilePath).replace(/\.(tsx|ts)$/, "")}-${hashId(routeFilePath)}`;
|
|
536
|
-
}
|
|
537
|
-
function wrapIslandBundle(code) {
|
|
538
|
-
return `;(function () {
|
|
539
|
-
${code}
|
|
540
|
-
})();
|
|
541
|
-
`;
|
|
542
|
-
}
|
|
543
|
-
async function buildIslandBundleInMemory(routeFilePath, layoutFilePaths, islandNames, actionModules, projectRoot) {
|
|
544
|
-
const entryId = islandEntryId(routeFilePath);
|
|
545
|
-
const scratchRoot = join3(projectRoot, ".x", "islands-tmp");
|
|
546
|
-
mkdirSync(scratchRoot, { recursive: true });
|
|
547
|
-
const scratchDir = mkdtempSync(join3(scratchRoot, "x-islands-"));
|
|
548
|
-
try {
|
|
549
|
-
const entryPath = join3(scratchDir, `${entryId}.tsx`);
|
|
550
|
-
writeFileSync2(entryPath, generateHydrateEntry(routeFilePath, layoutFilePaths), "utf-8");
|
|
551
|
-
const result = await Bun.build({
|
|
552
|
-
entrypoints: [entryPath],
|
|
553
|
-
target: "browser",
|
|
554
|
-
plugins: [actionsRewritePlugin(actionModules)]
|
|
555
|
-
});
|
|
556
|
-
if (!result.success) {
|
|
557
|
-
for (const log of result.logs) {
|
|
558
|
-
console.warn(` [islands] build error: ${log.message}`);
|
|
559
|
-
}
|
|
560
|
-
return wrapIslandBundle(generateFallbackHydration(islandNames));
|
|
561
|
-
}
|
|
562
|
-
const outputs = result.outputs.filter((o) => o.kind === "entry-point");
|
|
563
|
-
const built = outputs[0] ?? result.outputs[0];
|
|
564
|
-
if (!built) return wrapIslandBundle(generateFallbackHydration(islandNames));
|
|
565
|
-
const code = await built.text();
|
|
566
|
-
assertNoEnvLeakage(code, entryPath);
|
|
567
|
-
return wrapIslandBundle(code);
|
|
568
|
-
} catch (err) {
|
|
569
|
-
if (err instanceof EnvLeakageError) {
|
|
570
|
-
console.error(
|
|
571
|
-
`\x1B[1;31m\u{1F512} SECURITY: [islands] ${err.message}\x1B[0m
|
|
572
|
-
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.`
|
|
573
|
-
);
|
|
574
|
-
return wrapIslandBundle(generateFallbackHydration(islandNames));
|
|
575
|
-
}
|
|
576
|
-
console.warn(` [islands] build failed for ${routeFilePath}:`, err);
|
|
577
|
-
return wrapIslandBundle(generateFallbackHydration(islandNames));
|
|
578
|
-
} finally {
|
|
579
|
-
rmSync(scratchDir, { recursive: true, force: true });
|
|
580
|
-
}
|
|
581
|
-
}
|
|
582
|
-
|
|
583
195
|
// src/render.ts
|
|
584
196
|
import { renderToReadableStream, renderToStaticMarkup, renderToString } from "react-dom/server";
|
|
585
197
|
|
|
@@ -888,21 +500,21 @@ ${liveReloadTag} </body>
|
|
|
888
500
|
|
|
889
501
|
// src/build.ts
|
|
890
502
|
async function build(options) {
|
|
891
|
-
const outDir = options.outDir ??
|
|
892
|
-
const clientDir =
|
|
893
|
-
const serverDir =
|
|
894
|
-
const islandsDir =
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
503
|
+
const outDir = options.outDir ?? join2(process.cwd(), ".x");
|
|
504
|
+
const clientDir = join2(outDir, "client");
|
|
505
|
+
const serverDir = join2(outDir, "server");
|
|
506
|
+
const islandsDir = join2(clientDir, "_islands");
|
|
507
|
+
mkdirSync(clientDir, { recursive: true });
|
|
508
|
+
mkdirSync(serverDir, { recursive: true });
|
|
509
|
+
mkdirSync(islandsDir, { recursive: true });
|
|
898
510
|
const pagesDir = options.pagesDir ?? options.routesDir ?? "";
|
|
899
511
|
const apiDir = options.apiDir;
|
|
900
512
|
const actionsDir = options.actionsDir;
|
|
901
513
|
const layoutsDir = options.layoutsDir ?? pagesDir;
|
|
902
|
-
const projectRoot = pagesDir ?
|
|
903
|
-
const publicDir =
|
|
514
|
+
const projectRoot = pagesDir ? join2(pagesDir, "..", "..") : process.cwd();
|
|
515
|
+
const publicDir = join2(projectRoot, "public");
|
|
904
516
|
const hasPublicDir = existsSync(publicDir);
|
|
905
|
-
const stylesheetHref = hasPublicDir && existsSync(
|
|
517
|
+
const stylesheetHref = hasPublicDir && existsSync(join2(publicDir, "styles.css")) ? "/styles.css" : void 0;
|
|
906
518
|
if (hasPublicDir) {
|
|
907
519
|
cpSync(publicDir, clientDir, { recursive: true });
|
|
908
520
|
console.log(`[x] build: copied public/ -> ${relative2(process.cwd(), clientDir)}`);
|
|
@@ -914,7 +526,7 @@ async function build(options) {
|
|
|
914
526
|
if (apiDir && existsSync(apiDir)) {
|
|
915
527
|
routeEntries.push(...scanApiDir(apiDir));
|
|
916
528
|
}
|
|
917
|
-
const legacyApiDir = pagesDir ?
|
|
529
|
+
const legacyApiDir = pagesDir ? join2(pagesDir, "api") : "";
|
|
918
530
|
if (legacyApiDir && existsSync(legacyApiDir) && legacyApiDir !== apiDir) {
|
|
919
531
|
routeEntries.push(...scanApiDir(legacyApiDir));
|
|
920
532
|
}
|
|
@@ -1000,8 +612,8 @@ async function build(options) {
|
|
|
1000
612
|
const content = createElement(IslandProvider, { registry }, pageContent);
|
|
1001
613
|
const _html = renderStaticPage(content, { stylesheet: stylesheetHref });
|
|
1002
614
|
const outPath = page.entry.routePath === "/" ? "/index.html" : `${page.entry.routePath}/index.html`;
|
|
1003
|
-
const fullPath =
|
|
1004
|
-
|
|
615
|
+
const fullPath = join2(clientDir, outPath);
|
|
616
|
+
mkdirSync(join2(fullPath, ".."), { recursive: true });
|
|
1005
617
|
if (writtenPaths.has(outPath)) {
|
|
1006
618
|
console.warn(` [warn] collision: ${page.entry.routePath} overwrites existing output`);
|
|
1007
619
|
}
|
|
@@ -1009,7 +621,7 @@ async function build(options) {
|
|
|
1009
621
|
let islandScripts = [];
|
|
1010
622
|
if (registry.entries.length > 0) {
|
|
1011
623
|
const uniqueNames = [...new Set(registry.entries.map((e) => e.name))];
|
|
1012
|
-
islandScripts = await
|
|
624
|
+
islandScripts = await bundleRouteIslandsToDisk(
|
|
1013
625
|
page.filePath,
|
|
1014
626
|
page.layoutFilePaths,
|
|
1015
627
|
uniqueNames,
|
|
@@ -1021,7 +633,7 @@ async function build(options) {
|
|
|
1021
633
|
);
|
|
1022
634
|
}
|
|
1023
635
|
const finalHtml = renderStaticPage(content, { islandScripts, stylesheet: stylesheetHref });
|
|
1024
|
-
|
|
636
|
+
writeFileSync(fullPath, finalHtml, "utf-8");
|
|
1025
637
|
console.log(` [static] ${page.entry.routePath} -> ${outPath}`);
|
|
1026
638
|
}
|
|
1027
639
|
for (const content of contentEntries) {
|
|
@@ -1037,13 +649,13 @@ async function build(options) {
|
|
|
1037
649
|
stylesheet: stylesheetHref
|
|
1038
650
|
});
|
|
1039
651
|
const outPath = content.routePath === "/" ? "/index.html" : `${content.routePath}/index.html`;
|
|
1040
|
-
const fullPath =
|
|
1041
|
-
|
|
652
|
+
const fullPath = join2(clientDir, outPath);
|
|
653
|
+
mkdirSync(join2(fullPath, ".."), { recursive: true });
|
|
1042
654
|
if (writtenPaths.has(outPath)) {
|
|
1043
655
|
console.warn(` [warn] collision: content ${content.routePath} overwrites existing output`);
|
|
1044
656
|
}
|
|
1045
657
|
writtenPaths.add(outPath);
|
|
1046
|
-
|
|
658
|
+
writeFileSync(fullPath, html, "utf-8");
|
|
1047
659
|
console.log(` [content] ${content.routePath} -> ${outPath}`);
|
|
1048
660
|
}
|
|
1049
661
|
if (pagesDir || options.routesDir || options.contentDir) {
|
|
@@ -1060,47 +672,14 @@ async function build(options) {
|
|
|
1060
672
|
configImportPath,
|
|
1061
673
|
stylesheetHref
|
|
1062
674
|
);
|
|
1063
|
-
const serverEntryPath =
|
|
1064
|
-
|
|
675
|
+
const serverEntryPath = join2(serverDir, "index.ts");
|
|
676
|
+
writeFileSync(serverEntryPath, serverEntry, "utf-8");
|
|
1065
677
|
console.log(
|
|
1066
678
|
` [server] ${serverPages.length} page routes, ${apiRoutes.length} api routes -> server/index.ts`
|
|
1067
679
|
);
|
|
1068
680
|
}
|
|
1069
681
|
console.log(`[x] build complete -> ${outDir}`);
|
|
1070
682
|
}
|
|
1071
|
-
async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, islandsDir, actionModules) {
|
|
1072
|
-
const entryId = islandEntryId(routeFilePath);
|
|
1073
|
-
const outdir = join4(islandsDir, entryId);
|
|
1074
|
-
mkdirSync2(outdir, { recursive: true });
|
|
1075
|
-
const bundlePath = join4(outdir, `${entryId}.js`);
|
|
1076
|
-
const hydrateEntry = generateHydrateEntry(routeFilePath, layoutFilePaths);
|
|
1077
|
-
const entryPath = join4(outdir, `${entryId}.tsx`);
|
|
1078
|
-
writeFileSync3(entryPath, hydrateEntry, "utf-8");
|
|
1079
|
-
try {
|
|
1080
|
-
const result = await Bun.build({
|
|
1081
|
-
entrypoints: [entryPath],
|
|
1082
|
-
target: "browser",
|
|
1083
|
-
plugins: [actionsRewritePlugin(actionModules)]
|
|
1084
|
-
});
|
|
1085
|
-
if (result.success) {
|
|
1086
|
-
const outputs = result.outputs.filter((o) => o.kind === "entry-point");
|
|
1087
|
-
const built = outputs[0] ?? result.outputs[0];
|
|
1088
|
-
if (!built) throw new Error("bun build produced no output");
|
|
1089
|
-
const code = await built.text();
|
|
1090
|
-
assertNoEnvLeakage(code, bundlePath);
|
|
1091
|
-
writeFileSync3(bundlePath, wrapIslandBundle(code), "utf-8");
|
|
1092
|
-
return [`/_islands/${entryId}/${entryId}.js`];
|
|
1093
|
-
}
|
|
1094
|
-
for (const log of result.logs) {
|
|
1095
|
-
console.warn(` [islands] build error: ${log.message}`);
|
|
1096
|
-
}
|
|
1097
|
-
} catch (err) {
|
|
1098
|
-
if (err instanceof EnvLeakageError) throw err;
|
|
1099
|
-
console.warn(` [islands] build failed for ${routeFilePath}:`, err);
|
|
1100
|
-
}
|
|
1101
|
-
writeFileSync3(bundlePath, wrapIslandBundle(generateFallbackHydration(islandNames)), "utf-8");
|
|
1102
|
-
return [`/_islands/${entryId}/${entryId}.js`];
|
|
1103
|
-
}
|
|
1104
683
|
function renderPageWithLayout(Component, params, layoutModules) {
|
|
1105
684
|
let content = createElement(Component, { params });
|
|
1106
685
|
for (const Layout of [...layoutModules].reverse()) {
|
|
@@ -1184,7 +763,7 @@ function relativeImportPath(fromDir, toFile) {
|
|
|
1184
763
|
|
|
1185
764
|
// src/createApp.ts
|
|
1186
765
|
import { existsSync as existsSync2, watch } from "fs";
|
|
1187
|
-
import { join as
|
|
766
|
+
import { join as join3, resolve, sep as sep2 } from "path";
|
|
1188
767
|
import { createElement as createElement2 } from "react";
|
|
1189
768
|
|
|
1190
769
|
// src/error-overlay.ts
|
|
@@ -1840,7 +1419,7 @@ function routeMatchesForSort(entry) {
|
|
|
1840
1419
|
return isStatic ? 0 : isCatchAll ? 2 : 1;
|
|
1841
1420
|
}
|
|
1842
1421
|
function projectRootFromRoutesDir(routesDir) {
|
|
1843
|
-
return
|
|
1422
|
+
return join3(routesDir, "..", "..");
|
|
1844
1423
|
}
|
|
1845
1424
|
function resolvePublicAsset(publicDir, pathname) {
|
|
1846
1425
|
let decoded;
|
|
@@ -1849,7 +1428,7 @@ function resolvePublicAsset(publicDir, pathname) {
|
|
|
1849
1428
|
} catch {
|
|
1850
1429
|
return null;
|
|
1851
1430
|
}
|
|
1852
|
-
const target = resolve(
|
|
1431
|
+
const target = resolve(join3(publicDir, decoded));
|
|
1853
1432
|
const root = resolve(publicDir);
|
|
1854
1433
|
if (target !== root && !target.startsWith(root + sep2)) return null;
|
|
1855
1434
|
return target;
|
|
@@ -1901,7 +1480,7 @@ async function createApp(options) {
|
|
|
1901
1480
|
const dev = options.development ?? false;
|
|
1902
1481
|
const primaryDir = options.pagesDir || options.routesDir || "src/pages";
|
|
1903
1482
|
const projectRoot = projectRootFromRoutesDir(primaryDir);
|
|
1904
|
-
const resolvedActionsDir = options.actionsDir ?? (existsSync2(
|
|
1483
|
+
const resolvedActionsDir = options.actionsDir ?? (existsSync2(join3(projectRoot, "src", "actions")) ? join3(projectRoot, "src", "actions") : void 0);
|
|
1905
1484
|
let handlers = [];
|
|
1906
1485
|
let contentHandlers = [];
|
|
1907
1486
|
let publicDir = null;
|
|
@@ -2110,9 +1689,9 @@ async function createApp(options) {
|
|
|
2110
1689
|
async function buildHandlers() {
|
|
2111
1690
|
if (options.preloaded) {
|
|
2112
1691
|
const preloaded = options.preloaded;
|
|
2113
|
-
const candidatePublicDir2 =
|
|
1692
|
+
const candidatePublicDir2 = join3(projectRoot, "public");
|
|
2114
1693
|
publicDir = existsSync2(candidatePublicDir2) ? candidatePublicDir2 : null;
|
|
2115
|
-
stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync2(
|
|
1694
|
+
stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync2(join3(publicDir, "styles.css")) ? "/styles.css" : void 0);
|
|
2116
1695
|
if (preloaded.notFoundComponent) notFoundComponent = preloaded.notFoundComponent;
|
|
2117
1696
|
if (preloaded.notFoundLayout) notFoundLayout = preloaded.notFoundLayout;
|
|
2118
1697
|
const loaded2 = [];
|
|
@@ -2165,7 +1744,7 @@ async function createApp(options) {
|
|
|
2165
1744
|
if (apiDir && existsSync2(apiDir)) {
|
|
2166
1745
|
apiFound.push(...scanApiDir(apiDir));
|
|
2167
1746
|
}
|
|
2168
|
-
const legacyApiDir =
|
|
1747
|
+
const legacyApiDir = join3(pagesDir, "api");
|
|
2169
1748
|
if (existsSync2(legacyApiDir) && legacyApiDir !== apiDir) {
|
|
2170
1749
|
apiFound.push(...scanApiDir(legacyApiDir));
|
|
2171
1750
|
}
|
|
@@ -2200,9 +1779,9 @@ async function createApp(options) {
|
|
|
2200
1779
|
}
|
|
2201
1780
|
}
|
|
2202
1781
|
}
|
|
2203
|
-
const candidatePublicDir =
|
|
1782
|
+
const candidatePublicDir = join3(projectRoot, "public");
|
|
2204
1783
|
publicDir = existsSync2(candidatePublicDir) ? candidatePublicDir : null;
|
|
2205
|
-
stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync2(
|
|
1784
|
+
stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync2(join3(publicDir, "styles.css")) ? "/styles.css" : void 0);
|
|
2206
1785
|
const notFoundEntry = scanNotFound(pagesDir);
|
|
2207
1786
|
if (notFoundEntry) {
|
|
2208
1787
|
const mod = await importDev(notFoundEntry.filePath, dev);
|
|
@@ -2362,7 +1941,7 @@ async function createApp(options) {
|
|
|
2362
1941
|
let rebuildTimeout = null;
|
|
2363
1942
|
const sseClients = /* @__PURE__ */ new Set();
|
|
2364
1943
|
try {
|
|
2365
|
-
const srcDir =
|
|
1944
|
+
const srcDir = join3(primaryDir, "..", "..", "src");
|
|
2366
1945
|
const watchDirs = [
|
|
2367
1946
|
...new Set(
|
|
2368
1947
|
[primaryDir, options.apiDir, options.layoutsDir, resolvedActionsDir, srcDir].filter(
|
package/package.json
CHANGED