@thexjs/core 1.8.4 → 1.9.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
@@ -39,7 +39,7 @@ import {
39
39
  verifyOrigin,
40
40
  withCsrfCookie,
41
41
  writeManifest
42
- } from "./chunk-VGTN4YI5.js";
42
+ } from "./chunk-ME4ES2PD.js";
43
43
  import {
44
44
  OTEL_ERROR_STATUS_CODE,
45
45
  REDACTED,
@@ -179,11 +179,49 @@ function withBackpressure(handler, options) {
179
179
  };
180
180
  }
181
181
 
182
- // src/build.ts
183
- import { cpSync, existsSync, mkdirSync, writeFileSync } from "fs";
184
- import { join as join2, relative as relative2 } from "path";
182
+ // src/createApp.ts
183
+ import { existsSync, watch } from "fs";
184
+ import { join as join2, resolve, sep as sep2 } from "path";
185
185
  import { createElement } from "react";
186
186
 
187
+ // src/bounded-cache.ts
188
+ var BoundedCache = class {
189
+ entries = /* @__PURE__ */ new Map();
190
+ maxEntries;
191
+ constructor(maxEntries = 500) {
192
+ this.maxEntries = maxEntries;
193
+ }
194
+ get(key) {
195
+ const value = this.entries.get(key);
196
+ if (value !== void 0) {
197
+ this.entries.delete(key);
198
+ this.entries.set(key, value);
199
+ }
200
+ return value;
201
+ }
202
+ set(key, value) {
203
+ this.entries.delete(key);
204
+ this.entries.set(key, value);
205
+ this.evict();
206
+ }
207
+ delete(key) {
208
+ this.entries.delete(key);
209
+ }
210
+ clear() {
211
+ this.entries.clear();
212
+ }
213
+ get size() {
214
+ return this.entries.size;
215
+ }
216
+ evict() {
217
+ while (this.entries.size > this.maxEntries) {
218
+ const oldestKey = this.entries.keys().next().value;
219
+ if (oldestKey === void 0) break;
220
+ this.entries.delete(oldestKey);
221
+ }
222
+ }
223
+ };
224
+
187
225
  // src/content.ts
188
226
  import { readdirSync, readFileSync, statSync } from "fs";
189
227
  import { join, relative, sep } from "path";
@@ -316,1396 +354,1081 @@ function renderMarkdown(md) {
316
354
  return html;
317
355
  }
318
356
 
319
- // src/island.tsx
320
- import { createContext, useContext } from "react";
321
- import { jsx } from "react/jsx-runtime";
322
- function createIslandRegistry() {
323
- return { entries: [], nextId: 0 };
357
+ // src/error-overlay.ts
358
+ function escapeHtml2(s) {
359
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
324
360
  }
325
- var IslandContext = createContext(null);
326
- function IslandProvider({
327
- registry,
328
- children
329
- }) {
330
- return /* @__PURE__ */ jsx(IslandContext.Provider, { value: registry, children });
361
+ function renderErrorOverlay(error) {
362
+ const message = error instanceof Error ? error.message : "Unknown error";
363
+ const stack = error instanceof Error ? error.stack ?? "" : "";
364
+ const frames = stack.split("\n").slice(1).map((line) => `<span class="frame">${escapeHtml2(line.trim())}</span>`).join("\n");
365
+ return `<!DOCTYPE html>
366
+ <html lang="en">
367
+ <head>
368
+ <meta charset="UTF-8" />
369
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
370
+ <title>Server Error</title>
371
+ <style>
372
+ * { margin: 0; padding: 0; box-sizing: border-box; }
373
+ body {
374
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
375
+ background: #1a1a2e;
376
+ color: #e0e0e0;
377
+ min-height: 100vh;
378
+ display: flex;
379
+ flex-direction: column;
380
+ }
381
+ .overlay {
382
+ flex: 1;
383
+ padding: 40px 24px;
384
+ max-width: 900px;
385
+ margin: 0 auto;
386
+ width: 100%;
387
+ }
388
+ .header { margin-bottom: 32px; }
389
+ .badge {
390
+ display: inline-block;
391
+ background: #e74c3c;
392
+ color: #fff;
393
+ font-size: 11px;
394
+ font-weight: 700;
395
+ letter-spacing: 0.05em;
396
+ text-transform: uppercase;
397
+ padding: 3px 10px;
398
+ border-radius: 4px;
399
+ margin-bottom: 12px;
400
+ }
401
+ h1 {
402
+ font-size: 22px;
403
+ font-weight: 600;
404
+ color: #f0f0f0;
405
+ line-height: 1.3;
406
+ }
407
+ .message-box {
408
+ background: #2a2a4a;
409
+ border: 1px solid #3a3a5a;
410
+ border-radius: 8px;
411
+ padding: 20px;
412
+ margin-bottom: 24px;
413
+ font-size: 15px;
414
+ word-break: break-word;
415
+ }
416
+ .message-box .label {
417
+ font-size: 11px;
418
+ font-weight: 600;
419
+ text-transform: uppercase;
420
+ letter-spacing: 0.05em;
421
+ color: #888;
422
+ margin-bottom: 8px;
423
+ }
424
+ .message-box .message {
425
+ color: #ff6b6b;
426
+ font-family: "SF Mono", "Fira Code", "Fira Mono", monospace;
427
+ font-size: 14px;
428
+ white-space: pre-wrap;
429
+ }
430
+ .stack-section { margin-bottom: 24px; }
431
+ .stack-section .label {
432
+ font-size: 11px;
433
+ font-weight: 600;
434
+ text-transform: uppercase;
435
+ letter-spacing: 0.05em;
436
+ color: #888;
437
+ margin-bottom: 12px;
438
+ }
439
+ .frame {
440
+ display: block;
441
+ padding: 6px 12px;
442
+ font-family: "SF Mono", "Fira Code", "Fira Mono", monospace;
443
+ font-size: 12px;
444
+ color: #b0b0d0;
445
+ line-height: 1.6;
446
+ border-left: 2px solid #3a3a5a;
447
+ margin-bottom: 2px;
448
+ }
449
+ .frame:first-child { border-left-color: #e74c3c; }
450
+ .hint {
451
+ font-size: 13px;
452
+ color: #888;
453
+ border-top: 1px solid #3a3a5a;
454
+ padding-top: 20px;
455
+ margin-top: 8px;
456
+ }
457
+ .hint a { color: #6ab0ff; }
458
+ </style>
459
+ </head>
460
+ <body>
461
+ <div class="overlay">
462
+ <div class="header">
463
+ <div class="badge">Server Error</div>
464
+ <h1>Unhandled Error During Render</h1>
465
+ </div>
466
+ <div class="message-box">
467
+ <div class="label">Error</div>
468
+ <div class="message">${escapeHtml2(message)}</div>
469
+ </div>
470
+ ${stack ? `<div class="stack-section"><div class="label">Stack Trace</div>${frames}</div>` : ""}
471
+ <div class="hint">
472
+ Fix the error and save the file. In development mode, the server will reload automatically.
473
+ </div>
474
+ </div>
475
+ </body>
476
+ </html>`;
331
477
  }
332
- function Island({
333
- name,
334
- client = "idle",
335
- children
336
- }) {
337
- const registry = useContext(IslandContext);
338
- if (registry) {
339
- const id = `x-island-${registry.nextId++}`;
340
- registry.entries.push({ name, id });
341
- return /* @__PURE__ */ jsx("div", { "data-island": name, "data-island-id": id, "data-island-client": client, children });
478
+
479
+ // src/images/proxy.ts
480
+ var DEFAULT_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
481
+ var ALLOWED_CONTENT_TYPES = /* @__PURE__ */ new Set([
482
+ "image/png",
483
+ "image/jpeg",
484
+ "image/gif",
485
+ "image/webp",
486
+ "image/avif",
487
+ "image/x-icon"
488
+ ]);
489
+ var RFC2606_RESERVED_TLD = /\.(example|test|invalid|localhost)$|^(localhost)$/;
490
+ var UpstreamImageTooLargeError = class extends Error {
491
+ maxBytes;
492
+ constructor(maxBytes) {
493
+ super(`Upstream image exceeds the ${maxBytes} byte limit`);
494
+ this.name = "UpstreamImageTooLargeError";
495
+ this.maxBytes = maxBytes;
342
496
  }
343
- return /* @__PURE__ */ jsx("div", { "data-island": name, "data-island-id": "x-island-0", "data-island-client": client, children });
497
+ };
498
+ function isIpLiteral(host) {
499
+ const stem = host.startsWith("[") ? host.slice(1, -1) : host;
500
+ return /^\d{1,3}(\.\d{1,3}){3}$/.test(stem) || stem.includes(":");
344
501
  }
345
-
346
- // src/render.ts
347
- import { renderToReadableStream, renderToStaticMarkup, renderToString } from "react-dom/server";
348
-
349
- // src/client-nav.ts
350
- var CLIENT_NAV_SCRIPT = `
351
- (function () {
352
- if (window.__xNav) return;
353
- window.__xNav = true;
354
-
355
- var cache = new Map();
356
-
357
- document.addEventListener("click", function (ev) {
358
- if (ev.defaultPrevented || ev.button !== 0) return;
359
- if (ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) return;
360
- var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
361
- if (!anchor) return;
362
- ev.preventDefault();
363
- if (anchor.href !== location.href) navigate(anchor, true);
364
- });
365
-
366
- document.addEventListener(
367
- "mouseover",
368
- function (ev) {
369
- var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
370
- if (!anchor || anchor.hasAttribute("data-no-prefetch")) return;
371
- prefetch(anchor);
372
- },
373
- { passive: true },
374
- );
375
-
376
- document.addEventListener(
377
- "focusin",
378
- function (ev) {
379
- var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
380
- if (!anchor || anchor.hasAttribute("data-no-prefetch")) return;
381
- prefetch(anchor);
382
- },
383
- { passive: true },
384
- );
385
-
386
- window.addEventListener("popstate", function () {
387
- navigate(new URL(location.href), false);
388
- });
389
-
390
- var style = document.createElement("style");
391
- style.textContent = [
392
- ".x-nav-loading{cursor:progress}",
393
- ".x-nav-loading::after{content:'';position:fixed;top:0;left:0;height:2px;width:100%;",
394
- "background:var(--x-accent,#6ab0ff);z-index:9999;animation:x-nav-progress .8s ease-in-out infinite}",
395
- "@keyframes x-nav-progress{0%{transform:translateX(-100%)}50%{transform:translateX(0)}100%{transform:translateX(100%)}}",
396
- ].join("");
397
- document.head.appendChild(style);
398
-
399
- function resolveLink(anchor) {
400
- if (!anchor) return null;
401
- if (anchor.hasAttribute("data-no-nav")) return null;
402
- if (anchor.target && anchor.target !== "_self") return null;
403
- if (anchor.hasAttribute("download")) return null;
404
- var href = anchor.getAttribute("href");
405
- if (!href) return null;
406
- if (/^(#|mailto:|tel:|javascript:)/i.test(href)) return null;
407
- var url;
408
- try {
409
- url = new URL(href, location.href);
410
- } catch (_) {
411
- return null;
412
- }
413
- if (url.origin !== location.origin) return null;
414
- var here = new URL(location.href);
415
- if (url.pathname === here.pathname && url.search === here.search && url.hash) return null;
416
- return anchor;
417
- }
418
-
419
- function setLoading(on) {
420
- document.documentElement.classList.toggle("x-nav-loading", on);
502
+ function isPrivateOrReservedAddress(host) {
503
+ const stem = host.startsWith("[") ? host.slice(1, -1) : host;
504
+ if (!stem.includes(":") && /^\d{1,3}(\.\d{1,3}){3}$/.test(stem)) {
505
+ const parts = stem.split(".").map((o) => Number(o));
506
+ if (parts.some((o) => !Number.isInteger(o) || o < 0 || o > 255)) return false;
507
+ return isPrivateOrReservedIPv4(parts);
421
508
  }
422
-
423
- function prefetch(url) {
424
- if (cache.has(url.href)) return cache.get(url.href);
425
- var promise = fetch(url.href, { headers: { "X-X-Nav": "1" } })
426
- .then(function (res) {
427
- return res.text().then(function (html) {
428
- var ct = res.headers.get("content-type") || "";
429
- return { html: html, ok: res.ok, finalUrl: res.url || url.href, isHtml: ct.indexOf("text/html") !== -1 };
430
- });
431
- })
432
- .catch(function (err) {
433
- cache.delete(url.href);
434
- throw err;
435
- });
436
- if (cache.size >= 30) {
437
- var first = cache.keys().next().value;
438
- if (first !== undefined) cache.delete(first);
509
+ if (stem.includes(":")) {
510
+ const v4Match = /(\d{1,3}(?:\.\d{1,3}){3})$/.exec(stem);
511
+ if (v4Match) {
512
+ const octets = (v4Match[1] ?? "").split(".").map((o) => Number(o));
513
+ return isPrivateOrReservedIPv4(octets);
439
514
  }
440
- cache.set(url.href, promise);
441
- return promise;
442
- }
443
-
444
- function navigate(url, push) {
445
- setLoading(true);
446
- prefetch(url)
447
- .then(function (payload) {
448
- if (!payload.isHtml) {
449
- location.href = url.href;
450
- return;
451
- }
452
- var doc = new DOMParser().parseFromString(payload.html, "text/html");
453
- var next = doc.getElementById("root");
454
- var root = document.getElementById("root");
455
- if (!next || !root) {
456
- location.href = url.href;
457
- return;
458
- }
459
- if (push) history.pushState({ xNav: true }, "", payload.finalUrl);
460
- if (doc.title) document.title = doc.title;
461
- if (window.__xIslandRoots) {
462
- // Must stay in sync with unmountIslandRoots() \u2014 same logic, different
463
- // execution context (this is an inline script, not a module import).
464
- for (var i = 0; i < window.__xIslandRoots.length; i++) {
465
- try { window.__xIslandRoots[i]?.unmount(); } catch (_) {}
466
- }
467
- window.__xIslandRoots.length = 0;
468
- }
469
- root.innerHTML = next.innerHTML;
470
- reexecuteScripts(root);
471
- if (url.hash) {
472
- var target = document.getElementById(url.hash.slice(1));
473
- if (target) {
474
- target.scrollIntoView();
475
- return;
476
- }
477
- }
478
- window.scrollTo(0, 0);
479
- })
480
- .catch(function () {
481
- location.href = url.href;
482
- })
483
- .finally(function () {
484
- setLoading(false);
485
- });
486
515
  }
487
-
488
- function reexecuteScripts(root) {
489
- var scripts = root.querySelectorAll("script");
490
- for (var i = 0; i < scripts.length; i++) {
491
- var old = scripts[i];
492
- var el = document.createElement("script");
493
- for (var j = 0; j < old.attributes.length; j++) {
494
- var attr = old.attributes[j];
495
- el.setAttribute(attr.name, attr.value);
516
+ const groups = ipv6Groups(stem);
517
+ if (groups) return isPrivateOrReservedIPv6(groups);
518
+ return false;
519
+ }
520
+ function isPrivateOrReservedIPv4(parts) {
521
+ const [a = 0, b = 0, c = 0] = parts;
522
+ return a === 0 || a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 127 || a === 169 && b === 254 || a === 100 && b >= 64 && b <= 127 || a === 192 && b === 0 && c === 0 || a === 192 && b === 0 && c === 2 || a === 198 && (b === 18 || b === 19) || a === 198 && b === 51 && c === 100 || a === 203 && b === 0 && c === 113 || a >= 224;
523
+ }
524
+ function ipv6Groups(ip) {
525
+ let head = ip;
526
+ let tailV4 = null;
527
+ const lastColon = ip.lastIndexOf(":");
528
+ if (lastColon !== -1) {
529
+ const tail = ip.slice(lastColon + 1);
530
+ if (tail.includes(".")) {
531
+ const [v0 = 0, v1 = 0, v2 = 0, v3 = 0] = tail.split(".").map((o) => Number(o));
532
+ if (v0 > 255 || v1 > 255 || v2 > 255 || v3 > 255) {
533
+ return null;
496
534
  }
497
- el.textContent = old.textContent;
498
- old.replaceWith(el);
535
+ tailV4 = [v0 * 256 + v1, v2 * 256 + v3];
536
+ head = ip.slice(0, lastColon);
499
537
  }
500
538
  }
501
-
502
- /** Soft reload current page without a full document reload (used by dev live-reload). */
503
- window.__xSoftReload = function () {
504
- navigate(new URL(location.href), false);
505
- };
506
- })();
507
- `.trim();
508
-
509
- // src/live-reload.ts
510
- var LIVE_RELOAD_SCRIPT = `
511
- (function () {
512
- var es = new EventSource("/__x/reload");
513
- es.addEventListener("reload", function () {
514
- es.close();
515
- if (typeof window.__xSoftReload === "function") {
516
- window.__xSoftReload();
517
- } else {
518
- window.location.reload();
539
+ const doubleColon = head.indexOf("::");
540
+ let left = "";
541
+ let right = "";
542
+ if (doubleColon !== -1) {
543
+ left = head.slice(0, doubleColon);
544
+ right = head.slice(doubleColon + 2);
545
+ } else {
546
+ left = head;
547
+ }
548
+ const parseGroups = (s, out) => {
549
+ if (s === "") return true;
550
+ for (const part of s.split(":")) {
551
+ if (!/^[0-9a-fA-F]{1,4}$/.test(part)) return false;
552
+ out.push(Number.parseInt(part, 16));
519
553
  }
520
- });
521
- es.addEventListener("hb", function () {});
522
- es.onerror = function () {
523
- es.close();
554
+ return true;
524
555
  };
525
- })();
526
- `.trim();
527
-
528
- // src/render.ts
529
- function escapeHtml2(s) {
530
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
556
+ const l = [];
557
+ const r = [];
558
+ if (!parseGroups(left, l) || !parseGroups(right, r)) return null;
559
+ if (doubleColon !== -1) {
560
+ const zeros = 8 - l.length - r.length - (tailV4?.length ?? 0);
561
+ if (zeros < 1) return null;
562
+ return [...l, ...new Array(zeros).fill(0), ...r, ...tailV4 ?? []];
563
+ }
564
+ const all = [...l, ...tailV4 ?? [], ...r];
565
+ return all.length === 8 ? all : null;
531
566
  }
532
- function escapeJsonForScript(s) {
533
- return s.replace(/<\//g, "<\\/");
567
+ function isPrivateOrReservedIPv6(groups) {
568
+ const [a = 0, b = 0, , , , , , last = 0] = groups;
569
+ return a === 0 && last === 1 || // loopback ::1
570
+ groups.every((g) => g === 0) || // unspecified ::
571
+ (a & 65024) === 64512 || // unique local fc00::/7
572
+ (a & 65472) === 65152 || // link-local fe80::/10
573
+ (a & 65280) === 65280 || // multicast ff00::/8
574
+ a === 8193 && b === 3512 || // documentation 2001:db8::/32
575
+ a === 100 && b === 65435 || // NAT64 64:ff9b::/96
576
+ a === 8193 && b === 16;
534
577
  }
535
- function buildHeadExtras(stylesheet) {
536
- return stylesheet ? `
537
- <link rel="stylesheet" href="${escapeHtml2(stylesheet)}" />` : "";
578
+ async function resolveHostDefault(hostname) {
579
+ if (RFC2606_RESERVED_TLD.test(hostname)) return [];
580
+ try {
581
+ const results = await Bun.dns.lookup(hostname);
582
+ return results.map((r) => r.address);
583
+ } catch {
584
+ return [];
585
+ }
538
586
  }
539
- function nonceAttr(nonce) {
540
- return nonce ? ` nonce="${nonce}"` : "";
587
+ function urlForIp(target, ip) {
588
+ const pinned = new URL(target.toString());
589
+ pinned.hostname = ip.includes(":") ? `[${ip}]` : ip;
590
+ return pinned;
541
591
  }
542
- function buildNavScriptTag(clientNav, nonce) {
543
- return clientNav === false ? "" : `
544
- <script${nonceAttr(nonce)}>${CLIENT_NAV_SCRIPT}</script>`;
592
+ function pinToVerifiedIp(target, verifiedIp) {
593
+ const init = { redirect: "manual", headers: { host: target.host } };
594
+ if (target.protocol === "https:") {
595
+ init.tls = { serverName: target.hostname };
596
+ }
597
+ return { url: urlForIp(target, verifiedIp), init };
545
598
  }
546
- function buildLiveReloadTag(liveReload, nonce) {
547
- return liveReload ? `
548
- <script${nonceAttr(nonce)}>${LIVE_RELOAD_SCRIPT}</script>` : "";
599
+ async function resolveProxyTarget(target, resolveHost) {
600
+ if (isIpLiteral(target.hostname)) {
601
+ if (isPrivateOrReservedAddress(target.hostname)) {
602
+ return { status: "reject-literal" };
603
+ }
604
+ return { status: "ok", url: target, init: { redirect: "manual" } };
605
+ }
606
+ let ips = [];
607
+ try {
608
+ ips = await resolveHost(target.hostname);
609
+ } catch {
610
+ ips = [];
611
+ }
612
+ if (ips.some((ip) => isPrivateOrReservedAddress(ip))) {
613
+ return { status: "reject-dns" };
614
+ }
615
+ const verifiedIp = ips[0];
616
+ if (verifiedIp !== void 0) {
617
+ const { url, init } = pinToVerifiedIp(target, verifiedIp);
618
+ return { status: "ok", url, init };
619
+ }
620
+ return { status: "ok", url: target, init: { redirect: "manual" } };
549
621
  }
550
- function htmlShell(title, headExtras, propsScript, scripts, bodySlot, navScriptTag, liveReloadTag) {
551
- const finalScripts = scripts ?? "";
552
- const inside = `${bodySlot}${propsScript ? `
553
- ${propsScript}` : ""}${finalScripts ? `
554
- ${finalScripts}` : ""}`;
555
- return `<!DOCTYPE html>
556
- <html lang="en">
557
- <head>
558
- <meta charset="UTF-8" />
559
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
560
- <title>${escapeHtml2(title)}</title>${headExtras}
561
- </head>
562
- <body>
563
- <div id="root">${inside}</div>
564
- ${navScriptTag ? ` ${navScriptTag}
565
- ` : ""}${liveReloadTag} </body>
566
- </html>`;
567
- }
568
- function renderPage(node, options = {}) {
569
- const body = renderToString(node);
570
- return buildShellHtml(body, options, options.islandScripts ?? []);
571
- }
572
- function renderStaticPage(node, options = {}) {
573
- const body = renderToStaticMarkup(node);
574
- return buildShellHtml(body, options, options.islandScripts ?? []);
575
- }
576
- async function renderPageOnce(node, options = {}) {
577
- const body = renderToString(node);
578
- const scripts = options.resolveIslandScripts ? await options.resolveIslandScripts() : options.islandScripts ?? [];
579
- return buildShellHtml(body, options, scripts);
580
- }
581
- function buildShellHtml(body, options, islandScripts) {
582
- const { islandProps } = options;
583
- const title = options.title ?? "x app";
584
- const nonce = options.cspNonce;
585
- const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
586
- const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json"${nonceAttr(nonce)}>${propsJson}</script>` : "";
587
- const islandScriptsHtml = islandScripts.map((src) => `<script data-island-script src="${escapeHtml2(src)}"></script>`).join("\n ");
588
- return htmlShell(
589
- title,
590
- buildHeadExtras(options.stylesheet),
591
- propsScript,
592
- islandScriptsHtml,
593
- body,
594
- buildNavScriptTag(options.clientNav, nonce),
595
- buildLiveReloadTag(options.liveReload, nonce)
596
- );
622
+ function enforceImageByteCount(body, maxBytes) {
623
+ if (body === null) return null;
624
+ const source = body;
625
+ const { readable, writable } = new TransformStream();
626
+ const writer = writable.getWriter();
627
+ let total = 0;
628
+ const pump = async () => {
629
+ const reader = source.getReader();
630
+ try {
631
+ while (true) {
632
+ const { done, value } = await reader.read();
633
+ if (done) break;
634
+ total += value.byteLength;
635
+ if (total > maxBytes) {
636
+ await reader.cancel().catch(() => {
637
+ });
638
+ await writer.abort(new UpstreamImageTooLargeError(maxBytes));
639
+ return;
640
+ }
641
+ await writer.write(value);
642
+ }
643
+ await writer.close();
644
+ } catch (err) {
645
+ await writer.abort(err);
646
+ }
647
+ };
648
+ void pump();
649
+ return readable;
597
650
  }
598
- function pumpStreamingResponse(source, options) {
599
- const { header, footer, onRenderError, onCancel } = options;
600
- const reader = source.getReader();
601
- let headerSent = false;
602
- let ended = false;
603
- async function readAhead(controller) {
604
- if (!headerSent) {
605
- headerSent = true;
606
- controller.enqueue(header);
651
+ function createImageProxyHandler(options = {}) {
652
+ const allowedHosts = new Set(options.remoteHosts ?? []);
653
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_IMAGE_BYTES;
654
+ const resolveHost = options.resolveHost ?? resolveHostDefault;
655
+ return async (req) => {
656
+ const reqUrl = new URL(req.url);
657
+ if (reqUrl.pathname !== "/_x/image") return null;
658
+ if (req.method !== "GET" && req.method !== "HEAD") return null;
659
+ const target = reqUrl.searchParams.get("url");
660
+ if (!target) return new Response("missing url param", { status: 400 });
661
+ let parsed;
662
+ try {
663
+ parsed = new URL(target);
664
+ } catch {
665
+ return new Response("invalid url param", { status: 400 });
607
666
  }
608
- while (true) {
609
- const { done, value } = await reader.read();
610
- if (done) {
611
- if (!ended) {
612
- const footerBytes = typeof footer === "function" ? await footer() : footer;
613
- ended = true;
614
- try {
615
- controller.enqueue(footerBytes);
616
- } catch {
617
- }
618
- controller.close();
619
- }
620
- return;
667
+ const allowedUrl = (u) => (u.protocol === "http:" || u.protocol === "https:") && allowedHosts.has(u.hostname);
668
+ if (!allowedUrl(parsed)) {
669
+ return new Response("host not allow-listed for image proxy", { status: 403 });
670
+ }
671
+ const rejectFor = (status, hop) => {
672
+ if (status === "reject-literal") {
673
+ return new Response(
674
+ hop ? "upstream redirected to a private or reserved address" : "target is a private or reserved address",
675
+ { status: 403 }
676
+ );
621
677
  }
622
- controller.enqueue(value);
623
- if (controller.desiredSize !== null && controller.desiredSize <= 0) return;
678
+ return new Response(
679
+ hop ? "upstream redirect resolves to a private or reserved address" : "target resolves to a private or reserved address",
680
+ { status: 403 }
681
+ );
682
+ };
683
+ const initial = await resolveProxyTarget(parsed, resolveHost);
684
+ if (initial.status !== "ok") {
685
+ return rejectFor(initial.status, false);
624
686
  }
625
- }
626
- return new ReadableStream({
627
- async pull(controller) {
628
- try {
629
- await readAhead(controller);
630
- } catch (err) {
631
- if (!ended) {
632
- ended = true;
633
- onRenderError?.(err);
634
- }
687
+ const wParam = reqUrl.searchParams.get("w");
688
+ const qParam = reqUrl.searchParams.get("q");
689
+ if (wParam !== null) {
690
+ const w = Number.parseInt(wParam, 10);
691
+ if (!Number.isFinite(w) || w < 1 || w > 8192) {
692
+ return new Response("invalid w param", { status: 400 });
693
+ }
694
+ }
695
+ if (qParam !== null) {
696
+ const q = Number.parseInt(qParam, 10);
697
+ if (!Number.isFinite(q) || q < 1 || q > 100) {
698
+ return new Response("invalid q param", { status: 400 });
699
+ }
700
+ }
701
+ const isRedirect = (status) => status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
702
+ let upstream;
703
+ try {
704
+ upstream = await fetch(initial.url, initial.init);
705
+ for (let hop = 0; hop < 5; hop++) {
706
+ if (!isRedirect(upstream.status)) break;
707
+ const location = upstream.headers.get("location");
708
+ let next;
635
709
  try {
636
- controller.error(err);
710
+ next = new URL(location ?? "", parsed);
637
711
  } catch {
712
+ return new Response("upstream redirect was not a valid URL", { status: 502 });
713
+ }
714
+ if (!allowedUrl(next)) {
715
+ return new Response("upstream redirected off the allow-list", { status: 403 });
716
+ }
717
+ const hopTarget = await resolveProxyTarget(next, resolveHost);
718
+ if (hopTarget.status !== "ok") {
719
+ return rejectFor(hopTarget.status, true);
638
720
  }
721
+ upstream = await fetch(hopTarget.url, hopTarget.init);
639
722
  }
640
- },
641
- cancel(reason) {
642
- reader.cancel(reason).catch(() => {
643
- });
644
- onCancel?.(reason);
723
+ } catch (err) {
724
+ return new Response(`upstream fetch failed: ${String(err)}`, { status: 502 });
645
725
  }
646
- });
647
- }
648
- async function renderStreamingPage(node, options = {}) {
649
- const { islandScripts, islandProps } = options;
650
- const title = escapeHtml2(options.title ?? "x app");
651
- const nonce = options.cspNonce;
652
- const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
653
- const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json"${nonceAttr(nonce)}>${propsJson}</script>` : "";
654
- const navScriptTag = buildNavScriptTag(options.clientNav, nonce);
655
- const liveReloadTag = buildLiveReloadTag(options.liveReload, nonce);
656
- const headExtras = buildHeadExtras(options.stylesheet);
657
- const footer = `</div>${navScriptTag}
658
- ${liveReloadTag} </body>
659
- </html>`;
660
- const reactStream = await renderToReadableStream(node, {
661
- onError(err) {
662
- console.error("[x] render error:", err);
726
+ if (isRedirect(upstream.status)) {
727
+ return new Response("too many upstream redirects", { status: 502 });
663
728
  }
664
- });
665
- const encoder = new TextEncoder();
666
- const header = `<!DOCTYPE html>
667
- <html lang="en">
668
- <head>
669
- <meta charset="UTF-8" />
670
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
671
- <title>${title}</title>${headExtras}
672
- </head>
673
- <body>
674
- <div id="root">`;
675
- return pumpStreamingResponse(reactStream, {
676
- header: encoder.encode(header),
677
- // Lazy footer: the island script list may only be knowable after the
678
- // render completed (single-render mode), so resolve it right before the
679
- // closing tags are emitted rather than up front.
680
- footer: async () => {
681
- const scripts = islandScripts ?? await options.resolveIslandScripts?.() ?? [];
682
- const islandScriptsHtml = scripts.map((src) => `<script data-island-script src="${escapeHtml2(src)}"></script>`).join("\n ");
683
- const rootFooter = `${propsScript ? ` ${propsScript}
684
- ` : ""}${islandScriptsHtml ? ` ${islandScriptsHtml}
685
- ` : ""}`;
686
- return encoder.encode(`${rootFooter}
687
- ${footer}`);
688
- },
689
- ...options.onRenderError ? { onRenderError: options.onRenderError } : {}
690
- });
729
+ if (!upstream.ok) {
730
+ return new Response("upstream error", { status: 502 });
731
+ }
732
+ const contentType = upstream.headers.get("content-type") ?? "";
733
+ const baseContentType = (contentType.split(";")[0] ?? "").trim();
734
+ if (!ALLOWED_CONTENT_TYPES.has(baseContentType)) {
735
+ return new Response("upstream did not return an image", { status: 502 });
736
+ }
737
+ const contentLength = upstream.headers.get("content-length");
738
+ if (contentLength !== null && Number(contentLength) > maxBytes) {
739
+ await upstream.body?.cancel().catch(() => {
740
+ });
741
+ return new Response("upstream image exceeds the size limit", { status: 502 });
742
+ }
743
+ return new Response(enforceImageByteCount(upstream.body, maxBytes), {
744
+ status: 200,
745
+ headers: {
746
+ "Content-Type": contentType,
747
+ // Cache aggressively client + edge side — the proxied URL is the
748
+ // cache key, and remote asset URLs like this one are typically
749
+ // content-hashed by the origin already.
750
+ "Cache-Control": "public, max-age=86400, immutable"
751
+ }
752
+ });
753
+ };
691
754
  }
692
755
 
693
- // src/build.ts
694
- async function build(options) {
695
- const outDir = options.outDir ?? join2(process.cwd(), ".x");
696
- const clientDir = join2(outDir, "client");
697
- const serverDir = join2(outDir, "server");
698
- const islandsDir = join2(clientDir, "_islands");
699
- mkdirSync(clientDir, { recursive: true });
700
- mkdirSync(serverDir, { recursive: true });
701
- mkdirSync(islandsDir, { recursive: true });
702
- const pagesDir = options.pagesDir ?? options.routesDir ?? "";
703
- const apiDir = options.apiDir;
704
- const actionsDir = options.actionsDir;
705
- const layoutsDir = options.layoutsDir ?? pagesDir;
706
- const projectRoot = pagesDir ? join2(pagesDir, "..", "..") : process.cwd();
707
- const publicDir = join2(projectRoot, "public");
708
- const hasPublicDir = existsSync(publicDir);
709
- const stylesheetHref = hasPublicDir && existsSync(join2(publicDir, "styles.css")) ? "/styles.css" : void 0;
710
- if (hasPublicDir) {
711
- cpSync(publicDir, clientDir, { recursive: true });
712
- console.log(`[x] build: copied public/ -> ${relative2(process.cwd(), clientDir)}`);
713
- }
714
- let routeEntries = [];
715
- if (pagesDir && existsSync(pagesDir)) {
716
- routeEntries = scanPages(pagesDir);
717
- }
718
- if (apiDir && existsSync(apiDir)) {
719
- routeEntries.push(...scanApiDir(apiDir));
720
- }
721
- const legacyApiDir = pagesDir ? join2(pagesDir, "api") : "";
722
- if (legacyApiDir && existsSync(legacyApiDir) && legacyApiDir !== apiDir) {
723
- routeEntries.push(...scanApiDir(legacyApiDir));
724
- }
725
- const actionModules = /* @__PURE__ */ new Map();
726
- if (actionsDir && existsSync(actionsDir)) {
727
- for (const actionFile of scanRoutes(actionsDir)) {
728
- const mod = await import(actionFile.filePath);
729
- const segments = actionFile.routePath.split("/").filter(Boolean);
730
- const parentPath = `/${segments.slice(0, -1).join("/")}`;
731
- const fnNames = [];
732
- const actions = mod.actions;
733
- if (actions) {
734
- registerServerFunctions(parentPath, actionFile.paramNames, actions);
735
- fnNames.push(...Object.keys(actions));
736
- }
737
- for (const [key, value] of Object.entries(mod)) {
738
- if (key === "default" || key === "actions" || typeof value !== "function") continue;
739
- registerServerFunctions(parentPath, actionFile.paramNames, {
740
- [key]: value
741
- });
742
- fnNames.push(key);
743
- }
744
- if (fnNames.length > 0) {
745
- actionModules.set(actionFile.filePath, { parentPath, fnNames });
746
- }
747
- }
756
+ // src/island.tsx
757
+ import { createContext, useContext } from "react";
758
+ import { jsx } from "react/jsx-runtime";
759
+ function createIslandRegistry() {
760
+ return { entries: [], nextId: 0 };
761
+ }
762
+ var IslandContext = createContext(null);
763
+ function IslandProvider({
764
+ registry,
765
+ children
766
+ }) {
767
+ return /* @__PURE__ */ jsx(IslandContext.Provider, { value: registry, children });
768
+ }
769
+ function Island({
770
+ name,
771
+ client = "idle",
772
+ children
773
+ }) {
774
+ const registry = useContext(IslandContext);
775
+ if (registry) {
776
+ const id = `x-island-${registry.nextId++}`;
777
+ registry.entries.push({ name, id });
778
+ return /* @__PURE__ */ jsx("div", { "data-island": name, "data-island-id": id, "data-island-client": client, children });
748
779
  }
749
- const dedicatedLayouts = layoutsDir && layoutsDir !== pagesDir && existsSync(layoutsDir) ? scanLayoutsDir(layoutsDir) : [];
750
- const nestedLayouts = pagesDir && existsSync(pagesDir) ? scanLayouts(pagesDir) : [];
751
- const layouts = [...dedicatedLayouts, ...nestedLayouts];
752
- const staticPages = [];
753
- const serverPages = [];
754
- const apiRoutes = [];
755
- for (const entry of routeEntries) {
756
- if (entry.isApi) {
757
- apiRoutes.push(entry);
758
- continue;
759
- }
760
- const mod = await import(entry.filePath);
761
- const Component = mod.default;
762
- if (!Component) {
763
- console.warn(`[x] ${entry.filePath} has no default export -- skipping`);
764
- continue;
765
- }
766
- const mode = mod.mode ?? "server";
767
- const layoutChain = findLayoutChain(entry.filePath, layouts, pagesDir);
768
- for (const rootLayout of dedicatedLayouts) {
769
- if (!layoutChain.some((l) => l.filePath === rootLayout.filePath)) {
770
- layoutChain.unshift(rootLayout);
780
+ return /* @__PURE__ */ jsx("div", { "data-island": name, "data-island-id": "x-island-0", "data-island-client": client, children });
781
+ }
782
+
783
+ // src/middleware.ts
784
+ function composeMiddleware(fns, handler) {
785
+ return async (ctx, _next) => {
786
+ let index = -1;
787
+ const dispatch = async (i) => {
788
+ if (i <= index) throw new Error("next() called multiple times");
789
+ index = i;
790
+ const fn = fns[i];
791
+ if (fn) {
792
+ return fn(ctx, () => dispatch(i + 1));
771
793
  }
772
- }
773
- const layoutModules = [];
774
- for (const l of layoutChain) {
775
- const layoutMod = await import(l.filePath);
776
- if (layoutMod.default) layoutModules.push(layoutMod.default);
777
- }
778
- const page = {
779
- entry,
780
- filePath: entry.filePath,
781
- mode,
782
- Component,
783
- layoutModules,
784
- layoutFilePaths: layoutChain.map((l) => l.filePath)
794
+ return handler(ctx);
785
795
  };
786
- if (mode === "static") {
787
- staticPages.push(page);
788
- } else {
789
- serverPages.push(page);
796
+ return tracePhase(
797
+ "x.middleware",
798
+ { route: new URL(ctx.request.url).pathname },
799
+ () => dispatch(0)
800
+ );
801
+ };
802
+ }
803
+
804
+ // src/not-found.tsx
805
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
806
+ function DefaultNotFound(_props) {
807
+ return /* @__PURE__ */ jsxs(
808
+ "main",
809
+ {
810
+ style: {
811
+ maxWidth: 640,
812
+ margin: "4rem auto",
813
+ padding: "0 1rem",
814
+ fontFamily: "system-ui, -apple-system, sans-serif",
815
+ textAlign: "center"
816
+ },
817
+ children: [
818
+ /* @__PURE__ */ jsx2("h1", { style: { fontSize: "4rem", fontWeight: 700, margin: "0 0 0.5rem", color: "#e74c3c" }, children: "404" }),
819
+ /* @__PURE__ */ jsx2("p", { style: { fontSize: "1.125rem", color: "#666", margin: "0 0 2rem" }, children: "This page could not be found." }),
820
+ /* @__PURE__ */ jsx2(
821
+ "a",
822
+ {
823
+ href: "/",
824
+ style: {
825
+ color: "#6ab0ff",
826
+ textDecoration: "underline",
827
+ fontSize: "0.875rem"
828
+ },
829
+ children: "Back to home"
830
+ }
831
+ )
832
+ ]
790
833
  }
791
- }
792
- let contentEntries = [];
793
- if (options.contentDir) {
794
- contentEntries = scanContent(options.contentDir);
795
- }
796
- console.log(
797
- `[x] build: ${staticPages.length} static, ${serverPages.length} server, ${contentEntries.length} content pages`
798
834
  );
799
- const writtenPaths = /* @__PURE__ */ new Set();
800
- for (const page of staticPages) {
801
- const params = {};
802
- const registry = createIslandRegistry();
803
- const pageContent = renderPageWithLayout(page.Component, params, page.layoutModules);
804
- const content = createElement(IslandProvider, { registry }, pageContent);
805
- const _html = renderStaticPage(content, { stylesheet: stylesheetHref });
806
- const outPath = page.entry.routePath === "/" ? "/index.html" : `${page.entry.routePath}/index.html`;
807
- const fullPath = join2(clientDir, outPath);
808
- mkdirSync(join2(fullPath, ".."), { recursive: true });
809
- if (writtenPaths.has(outPath)) {
810
- console.warn(` [warn] collision: ${page.entry.routePath} overwrites existing output`);
811
- }
812
- writtenPaths.add(outPath);
813
- let islandScripts = [];
814
- if (registry.entries.length > 0) {
815
- const uniqueNames = [...new Set(registry.entries.map((e) => e.name))];
816
- islandScripts = await bundleRouteIslandsToDisk(
817
- page.filePath,
818
- page.layoutFilePaths,
819
- uniqueNames,
820
- islandsDir,
821
- actionModules
822
- );
823
- console.log(
824
- ` [islands] ${uniqueNames.length} island(s) on ${page.entry.routePath} -> ${islandScripts.join(", ")}`
825
- );
835
+ }
836
+
837
+ // src/observability/health.ts
838
+ async function runChecks(checks) {
839
+ const results = {};
840
+ let allOk = true;
841
+ await Promise.all(
842
+ Object.entries(checks).map(async ([name, check]) => {
843
+ try {
844
+ const ok = await check();
845
+ results[name] = ok ? "ok" : "error";
846
+ if (!ok) allOk = false;
847
+ } catch {
848
+ results[name] = "error";
849
+ allOk = false;
850
+ }
851
+ })
852
+ );
853
+ return { status: allOk ? "ok" : "error", checks: results };
854
+ }
855
+ function createHealthCheckHandler(options = {}) {
856
+ const checks = options.checks ?? {};
857
+ return async (req) => {
858
+ const pathname = new URL(req.url).pathname;
859
+ if (pathname === "/healthz") {
860
+ return Response.json({ status: "ok" }, { status: 200 });
826
861
  }
827
- const finalHtml = renderStaticPage(content, { islandScripts, stylesheet: stylesheetHref });
828
- writeFileSync(fullPath, finalHtml, "utf-8");
829
- console.log(` [static] ${page.entry.routePath} -> ${outPath}`);
830
- }
831
- for (const content of contentEntries) {
832
- const registry = createIslandRegistry();
833
- const bodyHtml = renderMarkdown(content.body);
834
- const pageContent = createElement(StaticContentPage, {
835
- content,
836
- bodyHtml
837
- });
838
- const rendered = createElement(IslandProvider, { registry }, pageContent);
839
- const html = renderStaticPage(rendered, {
840
- title: content.frontmatter.title ?? content.slug,
841
- stylesheet: stylesheetHref
842
- });
843
- const outPath = content.routePath === "/" ? "/index.html" : `${content.routePath}/index.html`;
844
- const fullPath = join2(clientDir, outPath);
845
- mkdirSync(join2(fullPath, ".."), { recursive: true });
846
- if (writtenPaths.has(outPath)) {
847
- console.warn(` [warn] collision: content ${content.routePath} overwrites existing output`);
862
+ if (pathname === "/readyz") {
863
+ const result = await runChecks(checks);
864
+ return Response.json(result, { status: result.status === "ok" ? 200 : 503 });
848
865
  }
849
- writtenPaths.add(outPath);
850
- writeFileSync(fullPath, html, "utf-8");
851
- console.log(` [content] ${content.routePath} -> ${outPath}`);
852
- }
853
- if (pagesDir || options.routesDir || options.contentDir) {
854
- const srvOpts = {
855
- pagesDir: pagesDir || options.routesDir || ""
856
- };
857
- if (options.apiDir) srvOpts.apiDir = options.apiDir;
858
- if (options.layoutsDir) srvOpts.layoutsDir = options.layoutsDir;
859
- if (options.actionsDir) srvOpts.actionsDir = options.actionsDir;
860
- if (options.contentDir) srvOpts.contentDir = options.contentDir;
861
- const configImportPath = options.configPath ? relativeImportPath(serverDir, options.configPath) : void 0;
862
- const serverEntry = buildServerEntry(
863
- srvOpts,
864
- configImportPath,
865
- stylesheetHref
866
- );
867
- const serverEntryPath = join2(serverDir, "index.ts");
868
- writeFileSync(serverEntryPath, serverEntry, "utf-8");
869
- console.log(
870
- ` [server] ${serverPages.length} page routes, ${apiRoutes.length} api routes -> server/index.ts`
871
- );
872
- }
873
- console.log(`[x] build complete -> ${outDir}`);
866
+ return null;
867
+ };
874
868
  }
875
- function renderPageWithLayout(Component, params, layoutModules) {
876
- let content = createElement(Component, { params });
877
- for (const Layout of [...layoutModules].reverse()) {
878
- content = createElement(Layout, null, content);
869
+
870
+ // src/observability/logger.ts
871
+ function write(level, message, fields) {
872
+ const entry = {
873
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
874
+ level,
875
+ message: redactString(message),
876
+ ...redactValue(fields)
877
+ };
878
+ const line = JSON.stringify(entry);
879
+ if (level === "error") {
880
+ console.error(line);
881
+ } else if (level === "warn") {
882
+ console.warn(line);
883
+ } else {
884
+ console.log(line);
879
885
  }
880
- return content;
881
886
  }
882
- function StaticContentPage({ content, bodyHtml }) {
883
- return createElement(
884
- "article",
885
- null,
886
- content.frontmatter.title ? createElement("h1", null, content.frontmatter.title) : null,
887
- createElement("div", {
888
- // biome-ignore lint/security/noDangerouslySetInnerHtml: body is markdown rendered to HTML
889
- dangerouslySetInnerHTML: { __html: bodyHtml }
890
- })
891
- );
887
+ var logger = {
888
+ info: (message, fields) => write("info", message, fields),
889
+ warn: (message, fields) => write("warn", message, fields),
890
+ error: (message, fields) => write("error", message, fields)
891
+ };
892
+ function withRequestLogging(handler) {
893
+ return async (req, server) => {
894
+ const start = performance.now();
895
+ const requestId = traceRequestId(req);
896
+ const route = new URL(req.url).pathname;
897
+ try {
898
+ const res = await handler(req, server);
899
+ const isStream = res.headers.get("content-type")?.includes("text/event-stream");
900
+ console.log(
901
+ `[x][request] ${req.method} ${route} -> ${res.status}${isStream ? " (stream opened, not closed)" : ""}`
902
+ );
903
+ write("info", isStream ? "stream opened" : "request completed", {
904
+ requestId,
905
+ route,
906
+ method: req.method,
907
+ status: res.status,
908
+ durationMs: Math.round(performance.now() - start)
909
+ });
910
+ if (!res.headers.has("x-request-id")) {
911
+ res.headers.set("x-request-id", requestId);
912
+ }
913
+ return res;
914
+ } catch (err) {
915
+ write("error", "request failed", {
916
+ requestId,
917
+ route,
918
+ method: req.method,
919
+ status: 500,
920
+ durationMs: Math.round(performance.now() - start),
921
+ // Redacted before emission — a throwing driver or app error whose
922
+ // message embeds a secret must never leak it into the log sink.
923
+ error: redactString(err instanceof Error ? err.message : String(err))
924
+ });
925
+ throw err;
926
+ }
927
+ };
892
928
  }
893
- function buildServerEntry(opts, configImportPath, stylesheetHref) {
894
- const dirKeys = ["pagesDir", "apiDir", "layoutsDir", "actionsDir", "contentDir"];
895
- const lines = [
896
- "// Auto-generated by @thexjs/core build",
897
- 'import { createApp } from "@thexjs/core";'
898
- ];
899
- if (configImportPath) {
900
- lines.push("", "let userConfig = {};", "try {");
901
- lines.push(` const mod = await import(${JSON.stringify(configImportPath)});`);
902
- lines.push(" userConfig = mod.default ?? {};");
903
- lines.push("} catch (err) {");
904
- lines.push(
905
- ' console.warn("[x] failed to load x.config for security/observability options:", err);'
906
- );
907
- lines.push("}");
908
- }
909
- lines.push("", "const app = await createApp({");
910
- for (const key of dirKeys) {
911
- const val = opts[key];
912
- if (val) lines.push(` ${key}: ${JSON.stringify(val)},`);
913
- }
914
- if (stylesheetHref) lines.push(` stylesheetHref: ${JSON.stringify(stylesheetHref)},`);
915
- lines.push(' port: parseInt(process.env.PORT || "3000", 10),', " development: false,");
916
- if (configImportPath) {
917
- lines.push(" ...(userConfig.security ? { security: userConfig.security } : {}),");
918
- lines.push(
919
- " ...(userConfig.observability ? { observability: userConfig.observability } : {}),"
920
- );
921
- lines.push(" ...(userConfig.images ? { images: userConfig.images } : {}),");
929
+
930
+ // src/observability/metrics.ts
931
+ var noopMetrics = {
932
+ incr: () => {
933
+ },
934
+ observe: () => {
922
935
  }
923
- lines.push(
924
- "});",
925
- "",
926
- "const server = Bun.serve(app);",
927
- "",
928
- "console.log(`[x] production server running at ${server.url}`);",
929
- "",
930
- "// Graceful shutdown: stop accepting new connections, flush the error",
931
- "// reporter, then exit after in-flight requests have a moment to drain.",
932
- "let shuttingDown = false;",
933
- "async function shutdown(signal: string): Promise<void> {",
934
- " if (shuttingDown) return;",
935
- " shuttingDown = true;",
936
- " console.log(`[x] received ${signal} - shutting down`);",
937
- " try {",
938
- ' const { getErrorReporter } = await import("@thexjs/core");',
939
- " await getErrorReporter().flush?.();",
940
- " } catch {}",
941
- " server.stop(true);",
942
- " const exit = () => process.exit(0);",
943
- " const drainTimer = setTimeout(exit, 3000);",
944
- " drainTimer.unref?.();",
945
- "}",
946
- 'process.on("SIGTERM", () => shutdown("SIGTERM"));',
947
- 'process.on("SIGINT", () => shutdown("SIGINT"));',
948
- "",
949
- "// Request-level errors are caught inside createApp's fetch boundary;",
950
- "// anything that still escapes (a throw outside the request lifecycle,",
951
- "// a rejected promise from a background sweep) is reported through the",
952
- "// error reporter so the box reports instead of dying silently.",
953
- 'const { installProcessCrashHandlers } = await import("@thexjs/core");',
954
- // Fail fast on an uncaughtException: the singleton state may be corrupted,
955
- // so drain and let the orchestrator restart clean (see crash-handlers).
956
- "installProcessCrashHandlers({ exitOnCrash: true });"
957
- );
958
- return lines.join("\n");
959
- }
960
- function relativeImportPath(fromDir, toFile) {
961
- const rel = relative2(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
962
- return rel.startsWith(".") ? rel : `./${rel}`;
936
+ };
937
+ var DEFAULT_HISTOGRAM_BUCKETS_MS = [5, 10, 25, 50, 100, 250, 500, 1e3, 2500, 5e3, 1e4];
938
+ function seriesKey(name, labels) {
939
+ if (!labels) return name;
940
+ const sorted = Object.entries(labels).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${k}=${v}`);
941
+ return `${name}\0${sorted.join("\0")}`;
963
942
  }
964
-
965
- // src/createApp.ts
966
- import { existsSync as existsSync2, watch } from "fs";
967
- import { join as join3, resolve, sep as sep2 } from "path";
968
- import { createElement as createElement2 } from "react";
969
-
970
- // src/bounded-cache.ts
971
- var BoundedCache = class {
972
- entries = /* @__PURE__ */ new Map();
973
- maxEntries;
974
- constructor(maxEntries = 500) {
975
- this.maxEntries = maxEntries;
943
+ function createInMemoryMetrics(options = {}) {
944
+ const buckets = options.histogramBuckets ?? DEFAULT_HISTOGRAM_BUCKETS_MS;
945
+ const counters = /* @__PURE__ */ new Map();
946
+ const histograms = /* @__PURE__ */ new Map();
947
+ function incr(name, delta = 1, labels) {
948
+ const key = seriesKey(name, labels);
949
+ let series = counters.get(key);
950
+ if (!series) {
951
+ series = { name, labels: labels ?? {}, value: 0 };
952
+ counters.set(key, series);
953
+ }
954
+ series.value += delta;
976
955
  }
977
- get(key) {
978
- const value = this.entries.get(key);
979
- if (value !== void 0) {
980
- this.entries.delete(key);
981
- this.entries.set(key, value);
956
+ function observe(name, value, labels) {
957
+ const key = seriesKey(name, labels);
958
+ let acc = histograms.get(key);
959
+ if (!acc) {
960
+ acc = { bucketCounts: new Array(buckets.length).fill(0), sum: 0, count: 0 };
961
+ histograms.set(key, acc);
962
+ }
963
+ acc.sum += value;
964
+ acc.count += 1;
965
+ for (let i = 0; i < buckets.length; i += 1) {
966
+ const bound = buckets[i];
967
+ if (bound === void 0) break;
968
+ if (value <= bound) {
969
+ for (let j = i; j < buckets.length; j += 1) {
970
+ acc.bucketCounts[j] = (acc.bucketCounts[j] ?? 0) + 1;
971
+ }
972
+ break;
973
+ }
982
974
  }
983
- return value;
984
975
  }
985
- set(key, value) {
986
- this.entries.delete(key);
987
- this.entries.set(key, value);
988
- this.evict();
976
+ function labelsFromKey(key) {
977
+ const [name] = key.split("\0");
978
+ const labelPart = name !== void 0 ? key.slice(name.length + 1) : "";
979
+ const labels = {};
980
+ if (labelPart) {
981
+ for (const pair of labelPart.split("\0")) {
982
+ const eq = pair.indexOf("=");
983
+ if (eq > 0) labels[pair.slice(0, eq)] = pair.slice(eq + 1);
984
+ }
985
+ }
986
+ return { name: name ?? key, labels };
989
987
  }
990
- delete(key) {
991
- this.entries.delete(key);
988
+ function snapshot() {
989
+ const sortedCounters = [...counters.entries()].sort(([a], [b]) => a < b ? -1 : 1).map(([key, series]) => {
990
+ const { name, labels } = labelsFromKey(key);
991
+ return { name, labels, value: series.value };
992
+ });
993
+ const sortedHistograms = [...histograms.entries()].sort(([a], [b]) => a < b ? -1 : 1).map(([key, acc]) => {
994
+ const { name, labels } = labelsFromKey(key);
995
+ return { name, labels, bucketCounts: acc.bucketCounts, sum: acc.sum, count: acc.count };
996
+ });
997
+ return { counters: sortedCounters, histograms: sortedHistograms };
992
998
  }
993
- clear() {
994
- this.entries.clear();
999
+ function renderMetrics() {
1000
+ const snap = snapshot();
1001
+ const lines = [];
1002
+ for (const counter of snap.counters) {
1003
+ lines.push(`# TYPE ${counter.name} counter`);
1004
+ lines.push(`${counter.name}${formatLabels(counter.labels)} ${counter.value}`);
1005
+ }
1006
+ for (const h of snap.histograms) {
1007
+ const labelWithLe = (le) => {
1008
+ const labels = { ...h.labels, le };
1009
+ return formatLabels(labels);
1010
+ };
1011
+ lines.push(`# TYPE ${h.name} histogram`);
1012
+ for (let i = 0; i < buckets.length; i += 1) {
1013
+ lines.push(`${h.name}_bucket${labelWithLe(String(buckets[i]))} ${h.bucketCounts[i]}`);
1014
+ }
1015
+ lines.push(`${h.name}_bucket${labelWithLe("+Inf")} ${h.count}`);
1016
+ lines.push(`${h.name}_sum${formatLabels(h.labels)} ${h.sum}`);
1017
+ lines.push(`${h.name}_count${formatLabels(h.labels)} ${h.count}`);
1018
+ }
1019
+ return `${lines.join("\n")}
1020
+ `;
995
1021
  }
996
- get size() {
997
- return this.entries.size;
1022
+ function handleMetrics(req) {
1023
+ if (new URL(req.url).pathname !== "/metrics") return null;
1024
+ return new Response(renderMetrics(), {
1025
+ headers: { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" }
1026
+ });
998
1027
  }
999
- evict() {
1000
- while (this.entries.size > this.maxEntries) {
1001
- const oldestKey = this.entries.keys().next().value;
1002
- if (oldestKey === void 0) break;
1003
- this.entries.delete(oldestKey);
1028
+ return {
1029
+ incr,
1030
+ observe,
1031
+ snapshot,
1032
+ renderMetrics,
1033
+ handleMetrics,
1034
+ async flush() {
1004
1035
  }
1005
- }
1006
- };
1007
-
1008
- // src/error-overlay.ts
1009
- function escapeHtml3(s) {
1010
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1036
+ };
1011
1037
  }
1012
- function renderErrorOverlay(error) {
1013
- const message = error instanceof Error ? error.message : "Unknown error";
1014
- const stack = error instanceof Error ? error.stack ?? "" : "";
1015
- const frames = stack.split("\n").slice(1).map((line) => `<span class="frame">${escapeHtml3(line.trim())}</span>`).join("\n");
1016
- return `<!DOCTYPE html>
1017
- <html lang="en">
1018
- <head>
1019
- <meta charset="UTF-8" />
1020
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
1021
- <title>Server Error</title>
1022
- <style>
1023
- * { margin: 0; padding: 0; box-sizing: border-box; }
1024
- body {
1025
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
1026
- background: #1a1a2e;
1027
- color: #e0e0e0;
1028
- min-height: 100vh;
1029
- display: flex;
1030
- flex-direction: column;
1031
- }
1032
- .overlay {
1033
- flex: 1;
1034
- padding: 40px 24px;
1035
- max-width: 900px;
1036
- margin: 0 auto;
1037
- width: 100%;
1038
- }
1039
- .header { margin-bottom: 32px; }
1040
- .badge {
1041
- display: inline-block;
1042
- background: #e74c3c;
1043
- color: #fff;
1044
- font-size: 11px;
1045
- font-weight: 700;
1046
- letter-spacing: 0.05em;
1047
- text-transform: uppercase;
1048
- padding: 3px 10px;
1049
- border-radius: 4px;
1050
- margin-bottom: 12px;
1051
- }
1052
- h1 {
1053
- font-size: 22px;
1054
- font-weight: 600;
1055
- color: #f0f0f0;
1056
- line-height: 1.3;
1057
- }
1058
- .message-box {
1059
- background: #2a2a4a;
1060
- border: 1px solid #3a3a5a;
1061
- border-radius: 8px;
1062
- padding: 20px;
1063
- margin-bottom: 24px;
1064
- font-size: 15px;
1065
- word-break: break-word;
1066
- }
1067
- .message-box .label {
1068
- font-size: 11px;
1069
- font-weight: 600;
1070
- text-transform: uppercase;
1071
- letter-spacing: 0.05em;
1072
- color: #888;
1073
- margin-bottom: 8px;
1074
- }
1075
- .message-box .message {
1076
- color: #ff6b6b;
1077
- font-family: "SF Mono", "Fira Code", "Fira Mono", monospace;
1078
- font-size: 14px;
1079
- white-space: pre-wrap;
1080
- }
1081
- .stack-section { margin-bottom: 24px; }
1082
- .stack-section .label {
1083
- font-size: 11px;
1084
- font-weight: 600;
1085
- text-transform: uppercase;
1086
- letter-spacing: 0.05em;
1087
- color: #888;
1088
- margin-bottom: 12px;
1089
- }
1090
- .frame {
1091
- display: block;
1092
- padding: 6px 12px;
1093
- font-family: "SF Mono", "Fira Code", "Fira Mono", monospace;
1094
- font-size: 12px;
1095
- color: #b0b0d0;
1096
- line-height: 1.6;
1097
- border-left: 2px solid #3a3a5a;
1098
- margin-bottom: 2px;
1099
- }
1100
- .frame:first-child { border-left-color: #e74c3c; }
1101
- .hint {
1102
- font-size: 13px;
1103
- color: #888;
1104
- border-top: 1px solid #3a3a5a;
1105
- padding-top: 20px;
1106
- margin-top: 8px;
1107
- }
1108
- .hint a { color: #6ab0ff; }
1109
- </style>
1110
- </head>
1111
- <body>
1112
- <div class="overlay">
1113
- <div class="header">
1114
- <div class="badge">Server Error</div>
1115
- <h1>Unhandled Error During Render</h1>
1116
- </div>
1117
- <div class="message-box">
1118
- <div class="label">Error</div>
1119
- <div class="message">${escapeHtml3(message)}</div>
1120
- </div>
1121
- ${stack ? `<div class="stack-section"><div class="label">Stack Trace</div>${frames}</div>` : ""}
1122
- <div class="hint">
1123
- Fix the error and save the file. In development mode, the server will reload automatically.
1124
- </div>
1125
- </div>
1126
- </body>
1127
- </html>`;
1128
- }
1129
-
1130
- // src/images/proxy.ts
1131
- var DEFAULT_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
1132
- var ALLOWED_CONTENT_TYPES = /* @__PURE__ */ new Set([
1133
- "image/png",
1134
- "image/jpeg",
1135
- "image/gif",
1136
- "image/webp",
1137
- "image/avif",
1138
- "image/x-icon"
1139
- ]);
1140
- var RFC2606_RESERVED_TLD = /\.(example|test|invalid|localhost)$|^(localhost)$/;
1141
- var UpstreamImageTooLargeError = class extends Error {
1142
- maxBytes;
1143
- constructor(maxBytes) {
1144
- super(`Upstream image exceeds the ${maxBytes} byte limit`);
1145
- this.name = "UpstreamImageTooLargeError";
1146
- this.maxBytes = maxBytes;
1147
- }
1148
- };
1149
- function isIpLiteral(host) {
1150
- const stem = host.startsWith("[") ? host.slice(1, -1) : host;
1151
- return /^\d{1,3}(\.\d{1,3}){3}$/.test(stem) || stem.includes(":");
1152
- }
1153
- function isPrivateOrReservedAddress(host) {
1154
- const stem = host.startsWith("[") ? host.slice(1, -1) : host;
1155
- if (!stem.includes(":") && /^\d{1,3}(\.\d{1,3}){3}$/.test(stem)) {
1156
- const parts = stem.split(".").map((o) => Number(o));
1157
- if (parts.some((o) => !Number.isInteger(o) || o < 0 || o > 255)) return false;
1158
- return isPrivateOrReservedIPv4(parts);
1159
- }
1160
- if (stem.includes(":")) {
1161
- const v4Match = /(\d{1,3}(?:\.\d{1,3}){3})$/.exec(stem);
1162
- if (v4Match) {
1163
- const octets = (v4Match[1] ?? "").split(".").map((o) => Number(o));
1164
- return isPrivateOrReservedIPv4(octets);
1165
- }
1166
- }
1167
- const groups = ipv6Groups(stem);
1168
- if (groups) return isPrivateOrReservedIPv6(groups);
1169
- return false;
1170
- }
1171
- function isPrivateOrReservedIPv4(parts) {
1172
- const [a = 0, b = 0, c = 0] = parts;
1173
- return a === 0 || a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 127 || a === 169 && b === 254 || a === 100 && b >= 64 && b <= 127 || a === 192 && b === 0 && c === 0 || a === 192 && b === 0 && c === 2 || a === 198 && (b === 18 || b === 19) || a === 198 && b === 51 && c === 100 || a === 203 && b === 0 && c === 113 || a >= 224;
1174
- }
1175
- function ipv6Groups(ip) {
1176
- let head = ip;
1177
- let tailV4 = null;
1178
- const lastColon = ip.lastIndexOf(":");
1179
- if (lastColon !== -1) {
1180
- const tail = ip.slice(lastColon + 1);
1181
- if (tail.includes(".")) {
1182
- const [v0 = 0, v1 = 0, v2 = 0, v3 = 0] = tail.split(".").map((o) => Number(o));
1183
- if (v0 > 255 || v1 > 255 || v2 > 255 || v3 > 255) {
1184
- return null;
1185
- }
1186
- tailV4 = [v0 * 256 + v1, v2 * 256 + v3];
1187
- head = ip.slice(0, lastColon);
1188
- }
1189
- }
1190
- const doubleColon = head.indexOf("::");
1191
- let left = "";
1192
- let right = "";
1193
- if (doubleColon !== -1) {
1194
- left = head.slice(0, doubleColon);
1195
- right = head.slice(doubleColon + 2);
1196
- } else {
1197
- left = head;
1198
- }
1199
- const parseGroups = (s, out) => {
1200
- if (s === "") return true;
1201
- for (const part of s.split(":")) {
1202
- if (!/^[0-9a-fA-F]{1,4}$/.test(part)) return false;
1203
- out.push(Number.parseInt(part, 16));
1204
- }
1205
- return true;
1206
- };
1207
- const l = [];
1208
- const r = [];
1209
- if (!parseGroups(left, l) || !parseGroups(right, r)) return null;
1210
- if (doubleColon !== -1) {
1211
- const zeros = 8 - l.length - r.length - (tailV4?.length ?? 0);
1212
- if (zeros < 1) return null;
1213
- return [...l, ...new Array(zeros).fill(0), ...r, ...tailV4 ?? []];
1214
- }
1215
- const all = [...l, ...tailV4 ?? [], ...r];
1216
- return all.length === 8 ? all : null;
1217
- }
1218
- function isPrivateOrReservedIPv6(groups) {
1219
- const [a = 0, b = 0, , , , , , last = 0] = groups;
1220
- return a === 0 && last === 1 || // loopback ::1
1221
- groups.every((g) => g === 0) || // unspecified ::
1222
- (a & 65024) === 64512 || // unique local fc00::/7
1223
- (a & 65472) === 65152 || // link-local fe80::/10
1224
- (a & 65280) === 65280 || // multicast ff00::/8
1225
- a === 8193 && b === 3512 || // documentation 2001:db8::/32
1226
- a === 100 && b === 65435 || // NAT64 64:ff9b::/96
1227
- a === 8193 && b === 16;
1228
- }
1229
- async function resolveHostDefault(hostname) {
1230
- if (RFC2606_RESERVED_TLD.test(hostname)) return [];
1231
- try {
1232
- const results = await Bun.dns.lookup(hostname);
1233
- return results.map((r) => r.address);
1234
- } catch {
1235
- return [];
1236
- }
1237
- }
1238
- function urlForIp(target, ip) {
1239
- const pinned = new URL(target.toString());
1240
- pinned.hostname = ip.includes(":") ? `[${ip}]` : ip;
1241
- return pinned;
1242
- }
1243
- function pinToVerifiedIp(target, verifiedIp) {
1244
- const init = { redirect: "manual", headers: { host: target.host } };
1245
- if (target.protocol === "https:") {
1246
- init.tls = { serverName: target.hostname };
1247
- }
1248
- return { url: urlForIp(target, verifiedIp), init };
1249
- }
1250
- async function resolveProxyTarget(target, resolveHost) {
1251
- if (isIpLiteral(target.hostname)) {
1252
- if (isPrivateOrReservedAddress(target.hostname)) {
1253
- return { status: "reject-literal" };
1254
- }
1255
- return { status: "ok", url: target, init: { redirect: "manual" } };
1256
- }
1257
- let ips = [];
1258
- try {
1259
- ips = await resolveHost(target.hostname);
1260
- } catch {
1261
- ips = [];
1262
- }
1263
- if (ips.some((ip) => isPrivateOrReservedAddress(ip))) {
1264
- return { status: "reject-dns" };
1265
- }
1266
- const verifiedIp = ips[0];
1267
- if (verifiedIp !== void 0) {
1268
- const { url, init } = pinToVerifiedIp(target, verifiedIp);
1269
- return { status: "ok", url, init };
1270
- }
1271
- return { status: "ok", url: target, init: { redirect: "manual" } };
1272
- }
1273
- function enforceImageByteCount(body, maxBytes) {
1274
- if (body === null) return null;
1275
- const source = body;
1276
- const { readable, writable } = new TransformStream();
1277
- const writer = writable.getWriter();
1278
- let total = 0;
1279
- const pump = async () => {
1280
- const reader = source.getReader();
1281
- try {
1282
- while (true) {
1283
- const { done, value } = await reader.read();
1284
- if (done) break;
1285
- total += value.byteLength;
1286
- if (total > maxBytes) {
1287
- await reader.cancel().catch(() => {
1288
- });
1289
- await writer.abort(new UpstreamImageTooLargeError(maxBytes));
1290
- return;
1291
- }
1292
- await writer.write(value);
1293
- }
1294
- await writer.close();
1295
- } catch (err) {
1296
- await writer.abort(err);
1297
- }
1298
- };
1299
- void pump();
1300
- return readable;
1301
- }
1302
- function createImageProxyHandler(options = {}) {
1303
- const allowedHosts = new Set(options.remoteHosts ?? []);
1304
- const maxBytes = options.maxBytes ?? DEFAULT_MAX_IMAGE_BYTES;
1305
- const resolveHost = options.resolveHost ?? resolveHostDefault;
1306
- return async (req) => {
1307
- const reqUrl = new URL(req.url);
1308
- if (reqUrl.pathname !== "/_x/image") return null;
1309
- if (req.method !== "GET" && req.method !== "HEAD") return null;
1310
- const target = reqUrl.searchParams.get("url");
1311
- if (!target) return new Response("missing url param", { status: 400 });
1312
- let parsed;
1313
- try {
1314
- parsed = new URL(target);
1315
- } catch {
1316
- return new Response("invalid url param", { status: 400 });
1317
- }
1318
- const allowedUrl = (u) => (u.protocol === "http:" || u.protocol === "https:") && allowedHosts.has(u.hostname);
1319
- if (!allowedUrl(parsed)) {
1320
- return new Response("host not allow-listed for image proxy", { status: 403 });
1321
- }
1322
- const rejectFor = (status, hop) => {
1323
- if (status === "reject-literal") {
1324
- return new Response(
1325
- hop ? "upstream redirected to a private or reserved address" : "target is a private or reserved address",
1326
- { status: 403 }
1327
- );
1328
- }
1329
- return new Response(
1330
- hop ? "upstream redirect resolves to a private or reserved address" : "target resolves to a private or reserved address",
1331
- { status: 403 }
1332
- );
1333
- };
1334
- const initial = await resolveProxyTarget(parsed, resolveHost);
1335
- if (initial.status !== "ok") {
1336
- return rejectFor(initial.status, false);
1337
- }
1338
- const wParam = reqUrl.searchParams.get("w");
1339
- const qParam = reqUrl.searchParams.get("q");
1340
- if (wParam !== null) {
1341
- const w = Number.parseInt(wParam, 10);
1342
- if (!Number.isFinite(w) || w < 1 || w > 8192) {
1343
- return new Response("invalid w param", { status: 400 });
1344
- }
1345
- }
1346
- if (qParam !== null) {
1347
- const q = Number.parseInt(qParam, 10);
1348
- if (!Number.isFinite(q) || q < 1 || q > 100) {
1349
- return new Response("invalid q param", { status: 400 });
1350
- }
1351
- }
1352
- const isRedirect = (status) => status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
1353
- let upstream;
1354
- try {
1355
- upstream = await fetch(initial.url, initial.init);
1356
- for (let hop = 0; hop < 5; hop++) {
1357
- if (!isRedirect(upstream.status)) break;
1358
- const location = upstream.headers.get("location");
1359
- let next;
1360
- try {
1361
- next = new URL(location ?? "", parsed);
1362
- } catch {
1363
- return new Response("upstream redirect was not a valid URL", { status: 502 });
1364
- }
1365
- if (!allowedUrl(next)) {
1366
- return new Response("upstream redirected off the allow-list", { status: 403 });
1367
- }
1368
- const hopTarget = await resolveProxyTarget(next, resolveHost);
1369
- if (hopTarget.status !== "ok") {
1370
- return rejectFor(hopTarget.status, true);
1371
- }
1372
- upstream = await fetch(hopTarget.url, hopTarget.init);
1373
- }
1374
- } catch (err) {
1375
- return new Response(`upstream fetch failed: ${String(err)}`, { status: 502 });
1376
- }
1377
- if (isRedirect(upstream.status)) {
1378
- return new Response("too many upstream redirects", { status: 502 });
1379
- }
1380
- if (!upstream.ok) {
1381
- return new Response("upstream error", { status: 502 });
1382
- }
1383
- const contentType = upstream.headers.get("content-type") ?? "";
1384
- const baseContentType = (contentType.split(";")[0] ?? "").trim();
1385
- if (!ALLOWED_CONTENT_TYPES.has(baseContentType)) {
1386
- return new Response("upstream did not return an image", { status: 502 });
1387
- }
1388
- const contentLength = upstream.headers.get("content-length");
1389
- if (contentLength !== null && Number(contentLength) > maxBytes) {
1390
- await upstream.body?.cancel().catch(() => {
1391
- });
1392
- return new Response("upstream image exceeds the size limit", { status: 502 });
1393
- }
1394
- return new Response(enforceImageByteCount(upstream.body, maxBytes), {
1395
- status: 200,
1396
- headers: {
1397
- "Content-Type": contentType,
1398
- // Cache aggressively client + edge side — the proxied URL is the
1399
- // cache key, and remote asset URLs like this one are typically
1400
- // content-hashed by the origin already.
1401
- "Cache-Control": "public, max-age=86400, immutable"
1402
- }
1403
- });
1404
- };
1405
- }
1406
-
1407
- // src/middleware.ts
1408
- function composeMiddleware(fns, handler) {
1409
- return async (ctx, _next) => {
1410
- let index = -1;
1411
- const dispatch = async (i) => {
1412
- if (i <= index) throw new Error("next() called multiple times");
1413
- index = i;
1414
- const fn = fns[i];
1415
- if (fn) {
1416
- return fn(ctx, () => dispatch(i + 1));
1038
+ function createOtlpMetricsReporter(meter) {
1039
+ const counters = /* @__PURE__ */ new Map();
1040
+ const histograms = /* @__PURE__ */ new Map();
1041
+ return {
1042
+ incr(name, delta, labels) {
1043
+ let counter = counters.get(name);
1044
+ if (!counter) {
1045
+ counter = meter.createCounter(name, { description: `Counter ${name}` });
1046
+ counters.set(name, counter);
1417
1047
  }
1418
- return handler(ctx);
1419
- };
1420
- return tracePhase(
1421
- "x.middleware",
1422
- { route: new URL(ctx.request.url).pathname },
1423
- () => dispatch(0)
1424
- );
1425
- };
1426
- }
1427
-
1428
- // src/not-found.tsx
1429
- import { jsx as jsx2, jsxs } from "react/jsx-runtime";
1430
- function DefaultNotFound(_props) {
1431
- return /* @__PURE__ */ jsxs(
1432
- "main",
1433
- {
1434
- style: {
1435
- maxWidth: 640,
1436
- margin: "4rem auto",
1437
- padding: "0 1rem",
1438
- fontFamily: "system-ui, -apple-system, sans-serif",
1439
- textAlign: "center"
1440
- },
1441
- children: [
1442
- /* @__PURE__ */ jsx2("h1", { style: { fontSize: "4rem", fontWeight: 700, margin: "0 0 0.5rem", color: "#e74c3c" }, children: "404" }),
1443
- /* @__PURE__ */ jsx2("p", { style: { fontSize: "1.125rem", color: "#666", margin: "0 0 2rem" }, children: "This page could not be found." }),
1444
- /* @__PURE__ */ jsx2(
1445
- "a",
1446
- {
1447
- href: "/",
1448
- style: {
1449
- color: "#6ab0ff",
1450
- textDecoration: "underline",
1451
- fontSize: "0.875rem"
1452
- },
1453
- children: "Back to home"
1454
- }
1455
- )
1456
- ]
1457
- }
1458
- );
1459
- }
1460
-
1461
- // src/observability/health.ts
1462
- async function runChecks(checks) {
1463
- const results = {};
1464
- let allOk = true;
1465
- await Promise.all(
1466
- Object.entries(checks).map(async ([name, check]) => {
1467
- try {
1468
- const ok = await check();
1469
- results[name] = ok ? "ok" : "error";
1470
- if (!ok) allOk = false;
1471
- } catch {
1472
- results[name] = "error";
1473
- allOk = false;
1048
+ counter.add(delta ?? 1, labels);
1049
+ },
1050
+ observe(name, value, labels) {
1051
+ let histogram = histograms.get(name);
1052
+ if (!histogram) {
1053
+ histogram = meter.createHistogram(name, { description: `Histogram ${name}` });
1054
+ histograms.set(name, histogram);
1474
1055
  }
1475
- })
1476
- );
1477
- return { status: allOk ? "ok" : "error", checks: results };
1478
- }
1479
- function createHealthCheckHandler(options = {}) {
1480
- const checks = options.checks ?? {};
1481
- return async (req) => {
1482
- const pathname = new URL(req.url).pathname;
1483
- if (pathname === "/healthz") {
1484
- return Response.json({ status: "ok" }, { status: 200 });
1485
- }
1486
- if (pathname === "/readyz") {
1487
- const result = await runChecks(checks);
1488
- return Response.json(result, { status: result.status === "ok" ? 200 : 503 });
1056
+ histogram.record(value, labels);
1489
1057
  }
1490
- return null;
1491
1058
  };
1492
1059
  }
1493
-
1494
- // src/observability/logger.ts
1495
- function write(level, message, fields) {
1496
- const entry = {
1497
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1498
- level,
1499
- message: redactString(message),
1500
- ...redactValue(fields)
1501
- };
1502
- const line = JSON.stringify(entry);
1503
- if (level === "error") {
1504
- console.error(line);
1505
- } else if (level === "warn") {
1506
- console.warn(line);
1507
- } else {
1508
- console.log(line);
1509
- }
1060
+ function formatLabels(labels) {
1061
+ const entries = Object.entries(labels);
1062
+ if (entries.length === 0) return "";
1063
+ const escaped = entries.map(([k, v]) => `${k}="${escapeLabelValue(v)}"`).join(",");
1064
+ return `{${escaped}}`;
1510
1065
  }
1511
- var logger = {
1512
- info: (message, fields) => write("info", message, fields),
1513
- warn: (message, fields) => write("warn", message, fields),
1514
- error: (message, fields) => write("error", message, fields)
1515
- };
1516
- function withRequestLogging(handler) {
1066
+ function escapeLabelValue(value) {
1067
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
1068
+ }
1069
+ function withRequestMetrics(reporter, handler) {
1517
1070
  return async (req, server) => {
1518
1071
  const start = performance.now();
1519
- const requestId = traceRequestId(req);
1520
- const route = new URL(req.url).pathname;
1072
+ const method = req.method;
1521
1073
  try {
1522
1074
  const res = await handler(req, server);
1523
- const isStream = res.headers.get("content-type")?.includes("text/event-stream");
1524
- console.log(
1525
- `[x][request] ${req.method} ${route} -> ${res.status}${isStream ? " (stream opened, not closed)" : ""}`
1526
- );
1527
- write("info", isStream ? "stream opened" : "request completed", {
1528
- requestId,
1529
- route,
1530
- method: req.method,
1531
- status: res.status,
1532
- durationMs: Math.round(performance.now() - start)
1533
- });
1534
- if (!res.headers.has("x-request-id")) {
1535
- res.headers.set("x-request-id", requestId);
1536
- }
1075
+ reporter.incr("x_http_requests_total", 1, { method, status: String(res.status) });
1076
+ reporter.observe("x_http_request_duration_ms", performance.now() - start, { method });
1537
1077
  return res;
1538
1078
  } catch (err) {
1539
- write("error", "request failed", {
1540
- requestId,
1541
- route,
1542
- method: req.method,
1543
- status: 500,
1544
- durationMs: Math.round(performance.now() - start),
1545
- // Redacted before emission — a throwing driver or app error whose
1546
- // message embeds a secret must never leak it into the log sink.
1547
- error: redactString(err instanceof Error ? err.message : String(err))
1548
- });
1079
+ reporter.incr("x_http_requests_total", 1, { method, status: "500" });
1080
+ reporter.incr("x_http_errors_total", 1, { method });
1081
+ reporter.observe("x_http_request_duration_ms", performance.now() - start, { method });
1549
1082
  throw err;
1550
1083
  }
1551
1084
  };
1552
1085
  }
1553
1086
 
1554
- // src/observability/metrics.ts
1555
- var noopMetrics = {
1556
- incr: () => {
1557
- },
1558
- observe: () => {
1087
+ // src/render.ts
1088
+ import { renderToReadableStream, renderToStaticMarkup, renderToString } from "react-dom/server";
1089
+
1090
+ // src/client-nav.ts
1091
+ var CLIENT_NAV_SCRIPT = `
1092
+ (function () {
1093
+ if (window.__xNav) return;
1094
+ window.__xNav = true;
1095
+
1096
+ var cache = new Map();
1097
+
1098
+ document.addEventListener("click", function (ev) {
1099
+ if (ev.defaultPrevented || ev.button !== 0) return;
1100
+ if (ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) return;
1101
+ var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
1102
+ if (!anchor) return;
1103
+ ev.preventDefault();
1104
+ if (anchor.href !== location.href) navigate(anchor, true);
1105
+ });
1106
+
1107
+ document.addEventListener(
1108
+ "mouseover",
1109
+ function (ev) {
1110
+ var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
1111
+ if (!anchor || anchor.hasAttribute("data-no-prefetch")) return;
1112
+ prefetch(anchor);
1113
+ },
1114
+ { passive: true },
1115
+ );
1116
+
1117
+ document.addEventListener(
1118
+ "focusin",
1119
+ function (ev) {
1120
+ var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
1121
+ if (!anchor || anchor.hasAttribute("data-no-prefetch")) return;
1122
+ prefetch(anchor);
1123
+ },
1124
+ { passive: true },
1125
+ );
1126
+
1127
+ window.addEventListener("popstate", function () {
1128
+ navigate(new URL(location.href), false);
1129
+ });
1130
+
1131
+ var style = document.createElement("style");
1132
+ style.textContent = [
1133
+ ".x-nav-loading{cursor:progress}",
1134
+ ".x-nav-loading::after{content:'';position:fixed;top:0;left:0;height:2px;width:100%;",
1135
+ "background:var(--x-accent,#6ab0ff);z-index:9999;animation:x-nav-progress .8s ease-in-out infinite}",
1136
+ "@keyframes x-nav-progress{0%{transform:translateX(-100%)}50%{transform:translateX(0)}100%{transform:translateX(100%)}}",
1137
+ ].join("");
1138
+ document.head.appendChild(style);
1139
+
1140
+ function resolveLink(anchor) {
1141
+ if (!anchor) return null;
1142
+ if (anchor.hasAttribute("data-no-nav")) return null;
1143
+ if (anchor.target && anchor.target !== "_self") return null;
1144
+ if (anchor.hasAttribute("download")) return null;
1145
+ var href = anchor.getAttribute("href");
1146
+ if (!href) return null;
1147
+ if (/^(#|mailto:|tel:|javascript:)/i.test(href)) return null;
1148
+ var url;
1149
+ try {
1150
+ url = new URL(href, location.href);
1151
+ } catch (_) {
1152
+ return null;
1153
+ }
1154
+ if (url.origin !== location.origin) return null;
1155
+ var here = new URL(location.href);
1156
+ if (url.pathname === here.pathname && url.search === here.search && url.hash) return null;
1157
+ return anchor;
1158
+ }
1159
+
1160
+ function setLoading(on) {
1161
+ document.documentElement.classList.toggle("x-nav-loading", on);
1559
1162
  }
1560
- };
1561
- var DEFAULT_HISTOGRAM_BUCKETS_MS = [5, 10, 25, 50, 100, 250, 500, 1e3, 2500, 5e3, 1e4];
1562
- function seriesKey(name, labels) {
1563
- if (!labels) return name;
1564
- const sorted = Object.entries(labels).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${k}=${v}`);
1565
- return `${name}\0${sorted.join("\0")}`;
1566
- }
1567
- function createInMemoryMetrics(options = {}) {
1568
- const buckets = options.histogramBuckets ?? DEFAULT_HISTOGRAM_BUCKETS_MS;
1569
- const counters = /* @__PURE__ */ new Map();
1570
- const histograms = /* @__PURE__ */ new Map();
1571
- function incr(name, delta = 1, labels) {
1572
- const key = seriesKey(name, labels);
1573
- let series = counters.get(key);
1574
- if (!series) {
1575
- series = { name, labels: labels ?? {}, value: 0 };
1576
- counters.set(key, series);
1163
+
1164
+ function prefetch(url) {
1165
+ if (cache.has(url.href)) return cache.get(url.href);
1166
+ var promise = fetch(url.href, { headers: { "X-X-Nav": "1" } })
1167
+ .then(function (res) {
1168
+ return res.text().then(function (html) {
1169
+ var ct = res.headers.get("content-type") || "";
1170
+ return { html: html, ok: res.ok, finalUrl: res.url || url.href, isHtml: ct.indexOf("text/html") !== -1 };
1171
+ });
1172
+ })
1173
+ .catch(function (err) {
1174
+ cache.delete(url.href);
1175
+ throw err;
1176
+ });
1177
+ if (cache.size >= 30) {
1178
+ var first = cache.keys().next().value;
1179
+ if (first !== undefined) cache.delete(first);
1577
1180
  }
1578
- series.value += delta;
1181
+ cache.set(url.href, promise);
1182
+ return promise;
1579
1183
  }
1580
- function observe(name, value, labels) {
1581
- const key = seriesKey(name, labels);
1582
- let acc = histograms.get(key);
1583
- if (!acc) {
1584
- acc = { bucketCounts: new Array(buckets.length).fill(0), sum: 0, count: 0 };
1585
- histograms.set(key, acc);
1586
- }
1587
- acc.sum += value;
1588
- acc.count += 1;
1589
- for (let i = 0; i < buckets.length; i += 1) {
1590
- const bound = buckets[i];
1591
- if (bound === void 0) break;
1592
- if (value <= bound) {
1593
- for (let j = i; j < buckets.length; j += 1) {
1594
- acc.bucketCounts[j] = (acc.bucketCounts[j] ?? 0) + 1;
1184
+
1185
+ function navigate(url, push) {
1186
+ setLoading(true);
1187
+ prefetch(url)
1188
+ .then(function (payload) {
1189
+ if (!payload.isHtml) {
1190
+ location.href = url.href;
1191
+ return;
1595
1192
  }
1596
- break;
1597
- }
1598
- }
1193
+ var doc = new DOMParser().parseFromString(payload.html, "text/html");
1194
+ var next = doc.getElementById("root");
1195
+ var root = document.getElementById("root");
1196
+ if (!next || !root) {
1197
+ location.href = url.href;
1198
+ return;
1199
+ }
1200
+ if (push) history.pushState({ xNav: true }, "", payload.finalUrl);
1201
+ if (doc.title) document.title = doc.title;
1202
+ if (window.__xIslandRoots) {
1203
+ // Must stay in sync with unmountIslandRoots() \u2014 same logic, different
1204
+ // execution context (this is an inline script, not a module import).
1205
+ for (var i = 0; i < window.__xIslandRoots.length; i++) {
1206
+ try { window.__xIslandRoots[i]?.unmount(); } catch (_) {}
1207
+ }
1208
+ window.__xIslandRoots.length = 0;
1209
+ }
1210
+ root.innerHTML = next.innerHTML;
1211
+ reexecuteScripts(root);
1212
+ if (url.hash) {
1213
+ var target = document.getElementById(url.hash.slice(1));
1214
+ if (target) {
1215
+ target.scrollIntoView();
1216
+ return;
1217
+ }
1218
+ }
1219
+ window.scrollTo(0, 0);
1220
+ })
1221
+ .catch(function () {
1222
+ location.href = url.href;
1223
+ })
1224
+ .finally(function () {
1225
+ setLoading(false);
1226
+ });
1599
1227
  }
1600
- function labelsFromKey(key) {
1601
- const [name] = key.split("\0");
1602
- const labelPart = name !== void 0 ? key.slice(name.length + 1) : "";
1603
- const labels = {};
1604
- if (labelPart) {
1605
- for (const pair of labelPart.split("\0")) {
1606
- const eq = pair.indexOf("=");
1607
- if (eq > 0) labels[pair.slice(0, eq)] = pair.slice(eq + 1);
1228
+
1229
+ function reexecuteScripts(root) {
1230
+ var scripts = root.querySelectorAll("script");
1231
+ for (var i = 0; i < scripts.length; i++) {
1232
+ var old = scripts[i];
1233
+ var el = document.createElement("script");
1234
+ for (var j = 0; j < old.attributes.length; j++) {
1235
+ var attr = old.attributes[j];
1236
+ el.setAttribute(attr.name, attr.value);
1608
1237
  }
1238
+ el.textContent = old.textContent;
1239
+ old.replaceWith(el);
1609
1240
  }
1610
- return { name: name ?? key, labels };
1611
1241
  }
1612
- function snapshot() {
1613
- const sortedCounters = [...counters.entries()].sort(([a], [b]) => a < b ? -1 : 1).map(([key, series]) => {
1614
- const { name, labels } = labelsFromKey(key);
1615
- return { name, labels, value: series.value };
1616
- });
1617
- const sortedHistograms = [...histograms.entries()].sort(([a], [b]) => a < b ? -1 : 1).map(([key, acc]) => {
1618
- const { name, labels } = labelsFromKey(key);
1619
- return { name, labels, bucketCounts: acc.bucketCounts, sum: acc.sum, count: acc.count };
1620
- });
1621
- return { counters: sortedCounters, histograms: sortedHistograms };
1622
- }
1623
- function renderMetrics() {
1624
- const snap = snapshot();
1625
- const lines = [];
1626
- for (const counter of snap.counters) {
1627
- lines.push(`# TYPE ${counter.name} counter`);
1628
- lines.push(`${counter.name}${formatLabels(counter.labels)} ${counter.value}`);
1242
+
1243
+ /** Soft reload current page without a full document reload (used by dev live-reload). */
1244
+ window.__xSoftReload = function () {
1245
+ navigate(new URL(location.href), false);
1246
+ };
1247
+ })();
1248
+ `.trim();
1249
+
1250
+ // src/live-reload.ts
1251
+ var LIVE_RELOAD_SCRIPT = `
1252
+ (function () {
1253
+ var es = new EventSource("/__x/reload");
1254
+ es.addEventListener("reload", function () {
1255
+ es.close();
1256
+ if (typeof window.__xSoftReload === "function") {
1257
+ window.__xSoftReload();
1258
+ } else {
1259
+ window.location.reload();
1629
1260
  }
1630
- for (const h of snap.histograms) {
1631
- const labelWithLe = (le) => {
1632
- const labels = { ...h.labels, le };
1633
- return formatLabels(labels);
1634
- };
1635
- lines.push(`# TYPE ${h.name} histogram`);
1636
- for (let i = 0; i < buckets.length; i += 1) {
1637
- lines.push(`${h.name}_bucket${labelWithLe(String(buckets[i]))} ${h.bucketCounts[i]}`);
1261
+ });
1262
+ es.addEventListener("hb", function () {});
1263
+ es.onerror = function () {
1264
+ es.close();
1265
+ };
1266
+ })();
1267
+ `.trim();
1268
+
1269
+ // src/render.ts
1270
+ function escapeHtml3(s) {
1271
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1272
+ }
1273
+ function escapeJsonForScript(s) {
1274
+ return s.replace(/<\//g, "<\\/");
1275
+ }
1276
+ function buildHeadExtras(stylesheet) {
1277
+ return stylesheet ? `
1278
+ <link rel="stylesheet" href="${escapeHtml3(stylesheet)}" />` : "";
1279
+ }
1280
+ function nonceAttr(nonce) {
1281
+ return nonce ? ` nonce="${nonce}"` : "";
1282
+ }
1283
+ function buildNavScriptTag(clientNav, nonce) {
1284
+ return clientNav === false ? "" : `
1285
+ <script${nonceAttr(nonce)}>${CLIENT_NAV_SCRIPT}</script>`;
1286
+ }
1287
+ function buildLiveReloadTag(liveReload, nonce) {
1288
+ return liveReload ? `
1289
+ <script${nonceAttr(nonce)}>${LIVE_RELOAD_SCRIPT}</script>` : "";
1290
+ }
1291
+ function htmlShell(title, headExtras, propsScript, scripts, bodySlot, navScriptTag, liveReloadTag) {
1292
+ const finalScripts = scripts ?? "";
1293
+ const inside = `${bodySlot}${propsScript ? `
1294
+ ${propsScript}` : ""}${finalScripts ? `
1295
+ ${finalScripts}` : ""}`;
1296
+ return `<!DOCTYPE html>
1297
+ <html lang="en">
1298
+ <head>
1299
+ <meta charset="UTF-8" />
1300
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
1301
+ <title>${escapeHtml3(title)}</title>${headExtras}
1302
+ </head>
1303
+ <body>
1304
+ <div id="root">${inside}</div>
1305
+ ${navScriptTag ? ` ${navScriptTag}
1306
+ ` : ""}${liveReloadTag} </body>
1307
+ </html>`;
1308
+ }
1309
+ function renderPage(node, options = {}) {
1310
+ const body = renderToString(node);
1311
+ return buildShellHtml(body, options, options.islandScripts ?? []);
1312
+ }
1313
+ function renderStaticPage(node, options = {}) {
1314
+ const body = renderToStaticMarkup(node);
1315
+ return buildShellHtml(body, options, options.islandScripts ?? []);
1316
+ }
1317
+ async function renderPageOnce(node, options = {}) {
1318
+ const body = renderToString(node);
1319
+ const scripts = options.resolveIslandScripts ? await options.resolveIslandScripts() : options.islandScripts ?? [];
1320
+ return buildShellHtml(body, options, scripts);
1321
+ }
1322
+ function buildShellHtml(body, options, islandScripts) {
1323
+ const { islandProps } = options;
1324
+ const title = options.title ?? "x app";
1325
+ const nonce = options.cspNonce;
1326
+ const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
1327
+ const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json"${nonceAttr(nonce)}>${propsJson}</script>` : "";
1328
+ const islandScriptsHtml = islandScripts.map((src) => `<script data-island-script src="${escapeHtml3(src)}"></script>`).join("\n ");
1329
+ return htmlShell(
1330
+ title,
1331
+ buildHeadExtras(options.stylesheet),
1332
+ propsScript,
1333
+ islandScriptsHtml,
1334
+ body,
1335
+ buildNavScriptTag(options.clientNav, nonce),
1336
+ buildLiveReloadTag(options.liveReload, nonce)
1337
+ );
1338
+ }
1339
+ function pumpStreamingResponse(source, options) {
1340
+ const { header, footer, onRenderError, onCancel } = options;
1341
+ const reader = source.getReader();
1342
+ let headerSent = false;
1343
+ let ended = false;
1344
+ async function readAhead(controller) {
1345
+ if (!headerSent) {
1346
+ headerSent = true;
1347
+ controller.enqueue(header);
1348
+ }
1349
+ while (true) {
1350
+ const { done, value } = await reader.read();
1351
+ if (done) {
1352
+ if (!ended) {
1353
+ const footerBytes = typeof footer === "function" ? await footer() : footer;
1354
+ ended = true;
1355
+ try {
1356
+ controller.enqueue(footerBytes);
1357
+ } catch {
1358
+ }
1359
+ controller.close();
1360
+ }
1361
+ return;
1638
1362
  }
1639
- lines.push(`${h.name}_bucket${labelWithLe("+Inf")} ${h.count}`);
1640
- lines.push(`${h.name}_sum${formatLabels(h.labels)} ${h.sum}`);
1641
- lines.push(`${h.name}_count${formatLabels(h.labels)} ${h.count}`);
1363
+ controller.enqueue(value);
1364
+ if (controller.desiredSize !== null && controller.desiredSize <= 0) return;
1642
1365
  }
1643
- return `${lines.join("\n")}
1644
- `;
1645
- }
1646
- function handleMetrics(req) {
1647
- if (new URL(req.url).pathname !== "/metrics") return null;
1648
- return new Response(renderMetrics(), {
1649
- headers: { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" }
1650
- });
1651
1366
  }
1652
- return {
1653
- incr,
1654
- observe,
1655
- snapshot,
1656
- renderMetrics,
1657
- handleMetrics,
1658
- async flush() {
1659
- }
1660
- };
1661
- }
1662
- function createOtlpMetricsReporter(meter) {
1663
- const counters = /* @__PURE__ */ new Map();
1664
- const histograms = /* @__PURE__ */ new Map();
1665
- return {
1666
- incr(name, delta, labels) {
1667
- let counter = counters.get(name);
1668
- if (!counter) {
1669
- counter = meter.createCounter(name, { description: `Counter ${name}` });
1670
- counters.set(name, counter);
1367
+ return new ReadableStream({
1368
+ async pull(controller) {
1369
+ try {
1370
+ await readAhead(controller);
1371
+ } catch (err) {
1372
+ if (!ended) {
1373
+ ended = true;
1374
+ onRenderError?.(err);
1375
+ }
1376
+ try {
1377
+ controller.error(err);
1378
+ } catch {
1379
+ }
1671
1380
  }
1672
- counter.add(delta ?? 1, labels);
1673
1381
  },
1674
- observe(name, value, labels) {
1675
- let histogram = histograms.get(name);
1676
- if (!histogram) {
1677
- histogram = meter.createHistogram(name, { description: `Histogram ${name}` });
1678
- histograms.set(name, histogram);
1679
- }
1680
- histogram.record(value, labels);
1382
+ cancel(reason) {
1383
+ reader.cancel(reason).catch(() => {
1384
+ });
1385
+ onCancel?.(reason);
1681
1386
  }
1682
- };
1683
- }
1684
- function formatLabels(labels) {
1685
- const entries = Object.entries(labels);
1686
- if (entries.length === 0) return "";
1687
- const escaped = entries.map(([k, v]) => `${k}="${escapeLabelValue(v)}"`).join(",");
1688
- return `{${escaped}}`;
1689
- }
1690
- function escapeLabelValue(value) {
1691
- return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
1387
+ });
1692
1388
  }
1693
- function withRequestMetrics(reporter, handler) {
1694
- return async (req, server) => {
1695
- const start = performance.now();
1696
- const method = req.method;
1697
- try {
1698
- const res = await handler(req, server);
1699
- reporter.incr("x_http_requests_total", 1, { method, status: String(res.status) });
1700
- reporter.observe("x_http_request_duration_ms", performance.now() - start, { method });
1701
- return res;
1702
- } catch (err) {
1703
- reporter.incr("x_http_requests_total", 1, { method, status: "500" });
1704
- reporter.incr("x_http_errors_total", 1, { method });
1705
- reporter.observe("x_http_request_duration_ms", performance.now() - start, { method });
1706
- throw err;
1389
+ async function renderStreamingPage(node, options = {}) {
1390
+ const { islandScripts, islandProps } = options;
1391
+ const title = escapeHtml3(options.title ?? "x app");
1392
+ const nonce = options.cspNonce;
1393
+ const propsJson = islandProps ? escapeJsonForScript(JSON.stringify(islandProps)) : "";
1394
+ const propsScript = islandProps ? `<script id="__X_ISLAND_PROPS" type="application/json"${nonceAttr(nonce)}>${propsJson}</script>` : "";
1395
+ const navScriptTag = buildNavScriptTag(options.clientNav, nonce);
1396
+ const liveReloadTag = buildLiveReloadTag(options.liveReload, nonce);
1397
+ const headExtras = buildHeadExtras(options.stylesheet);
1398
+ const footer = `</div>${navScriptTag}
1399
+ ${liveReloadTag} </body>
1400
+ </html>`;
1401
+ const reactStream = await renderToReadableStream(node, {
1402
+ onError(err) {
1403
+ console.error("[x] render error:", err);
1707
1404
  }
1708
- };
1405
+ });
1406
+ const encoder = new TextEncoder();
1407
+ const header = `<!DOCTYPE html>
1408
+ <html lang="en">
1409
+ <head>
1410
+ <meta charset="UTF-8" />
1411
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
1412
+ <title>${title}</title>${headExtras}
1413
+ </head>
1414
+ <body>
1415
+ <div id="root">`;
1416
+ return pumpStreamingResponse(reactStream, {
1417
+ header: encoder.encode(header),
1418
+ // Lazy footer: the island script list may only be knowable after the
1419
+ // render completed (single-render mode), so resolve it right before the
1420
+ // closing tags are emitted rather than up front.
1421
+ footer: async () => {
1422
+ const scripts = islandScripts ?? await options.resolveIslandScripts?.() ?? [];
1423
+ const islandScriptsHtml = scripts.map((src) => `<script data-island-script src="${escapeHtml3(src)}"></script>`).join("\n ");
1424
+ const rootFooter = `${propsScript ? ` ${propsScript}
1425
+ ` : ""}${islandScriptsHtml ? ` ${islandScriptsHtml}
1426
+ ` : ""}`;
1427
+ return encoder.encode(`${rootFooter}
1428
+ ${footer}`);
1429
+ },
1430
+ ...options.onRenderError ? { onRenderError: options.onRenderError } : {}
1431
+ });
1709
1432
  }
1710
1433
 
1711
1434
  // src/security/headers.ts
@@ -1964,7 +1687,7 @@ function zip(as, bs) {
1964
1687
  return out;
1965
1688
  }
1966
1689
  function projectRootFromRoutesDir(routesDir) {
1967
- return join3(routesDir, "..", "..");
1690
+ return join2(routesDir, "..", "..");
1968
1691
  }
1969
1692
  function resolvePublicAsset(publicDir, pathname) {
1970
1693
  let decoded;
@@ -1973,7 +1696,7 @@ function resolvePublicAsset(publicDir, pathname) {
1973
1696
  } catch {
1974
1697
  return null;
1975
1698
  }
1976
- const target = resolve(join3(publicDir, decoded));
1699
+ const target = resolve(join2(publicDir, decoded));
1977
1700
  const root = resolve(publicDir);
1978
1701
  if (target !== root && !target.startsWith(root + sep2)) return null;
1979
1702
  return target;
@@ -1992,9 +1715,9 @@ async function serveStaticAsset(publicDir, req) {
1992
1715
  return new Response(file);
1993
1716
  }
1994
1717
  function wrapWithLayouts(Component, params, loaderData, layoutModules) {
1995
- let content = createElement2(Component, { params, loaderData });
1718
+ let content = createElement(Component, { params, loaderData });
1996
1719
  for (const Layout of [...layoutModules].reverse()) {
1997
- content = createElement2(Layout, null, content);
1720
+ content = createElement(Layout, null, content);
1998
1721
  }
1999
1722
  return content;
2000
1723
  }
@@ -2002,11 +1725,11 @@ function renderContentPage(content, stylesheet, dev = false, nonce) {
2002
1725
  const title = content.frontmatter.title ?? content.slug;
2003
1726
  const bodyHtml = renderMarkdown(content.body);
2004
1727
  const body = renderPage(
2005
- createElement2(
1728
+ createElement(
2006
1729
  "article",
2007
1730
  null,
2008
- content.frontmatter.title ? createElement2("h1", null, content.frontmatter.title) : null,
2009
- createElement2("div", {
1731
+ content.frontmatter.title ? createElement("h1", null, content.frontmatter.title) : null,
1732
+ createElement("div", {
2010
1733
  // biome-ignore lint/security/noDangerouslySetInnerHtml: body is markdown rendered to HTML
2011
1734
  dangerouslySetInnerHTML: { __html: bodyHtml }
2012
1735
  })
@@ -2020,9 +1743,6 @@ function renderContentPage(content, stylesheet, dev = false, nonce) {
2020
1743
  );
2021
1744
  return body;
2022
1745
  }
2023
- function defineConfig(config) {
2024
- return config;
2025
- }
2026
1746
  function importDev(path, dev) {
2027
1747
  return dev ? import(`${path}?t=${Date.now()}`) : import(path);
2028
1748
  }
@@ -2030,7 +1750,7 @@ async function createApp(options) {
2030
1750
  const dev = options.development ?? false;
2031
1751
  const primaryDir = options.pagesDir || options.routesDir || "src/pages";
2032
1752
  const projectRoot = projectRootFromRoutesDir(primaryDir);
2033
- const resolvedActionsDir = options.actionsDir ?? (existsSync2(join3(projectRoot, "src", "actions")) ? join3(projectRoot, "src", "actions") : void 0);
1753
+ const resolvedActionsDir = options.actionsDir ?? (existsSync(join2(projectRoot, "src", "actions")) ? join2(projectRoot, "src", "actions") : void 0);
2034
1754
  let handlers = [];
2035
1755
  let contentHandlers = [];
2036
1756
  let publicDir = null;
@@ -2102,7 +1822,7 @@ async function createApp(options) {
2102
1822
  });
2103
1823
  }
2104
1824
  async function renderNotFound(_req) {
2105
- const content = notFoundLayout ? createElement2(notFoundLayout, null, createElement2(notFoundComponent, { params: {} })) : createElement2(notFoundComponent, { params: {} });
1825
+ const content = notFoundLayout ? createElement(notFoundLayout, null, createElement(notFoundComponent, { params: {} })) : createElement(notFoundComponent, { params: {} });
2106
1826
  const cspNonce = generateCspNonce();
2107
1827
  const html = renderPage(content, {
2108
1828
  title: "404 \u2014 Not Found",
@@ -2179,7 +1899,7 @@ async function createApp(options) {
2179
1899
  loaderData = result2;
2180
1900
  }
2181
1901
  const registry = createIslandRegistry();
2182
- const content = createElement2(
1902
+ const content = createElement(
2183
1903
  IslandProvider,
2184
1904
  { registry },
2185
1905
  wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
@@ -2239,7 +1959,7 @@ async function createApp(options) {
2239
1959
  loaderData = result2;
2240
1960
  }
2241
1961
  const registry = createIslandRegistry();
2242
- const content = createElement2(
1962
+ const content = createElement(
2243
1963
  IslandProvider,
2244
1964
  { registry },
2245
1965
  wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
@@ -2310,9 +2030,9 @@ async function createApp(options) {
2310
2030
  async function buildHandlers() {
2311
2031
  if (options.preloaded) {
2312
2032
  const preloaded = options.preloaded;
2313
- const candidatePublicDir2 = join3(projectRoot, "public");
2314
- publicDir = existsSync2(candidatePublicDir2) ? candidatePublicDir2 : null;
2315
- stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync2(join3(publicDir, "styles.css")) ? "/styles.css" : void 0);
2033
+ const candidatePublicDir2 = join2(projectRoot, "public");
2034
+ publicDir = existsSync(candidatePublicDir2) ? candidatePublicDir2 : null;
2035
+ stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync(join2(publicDir, "styles.css")) ? "/styles.css" : void 0);
2316
2036
  if (preloaded.notFoundComponent) notFoundComponent = preloaded.notFoundComponent;
2317
2037
  if (preloaded.notFoundLayout) notFoundLayout = preloaded.notFoundLayout;
2318
2038
  const loaded2 = [];
@@ -2362,11 +2082,11 @@ async function createApp(options) {
2362
2082
  const apiDir = options.apiDir;
2363
2083
  let found = scanPages(pagesDir);
2364
2084
  const apiFound = [];
2365
- if (apiDir && existsSync2(apiDir)) {
2085
+ if (apiDir && existsSync(apiDir)) {
2366
2086
  apiFound.push(...scanApiDir(apiDir));
2367
2087
  }
2368
- const legacyApiDir = join3(pagesDir, "api");
2369
- if (existsSync2(legacyApiDir) && legacyApiDir !== apiDir) {
2088
+ const legacyApiDir = join2(pagesDir, "api");
2089
+ if (existsSync(legacyApiDir) && legacyApiDir !== apiDir) {
2370
2090
  apiFound.push(...scanApiDir(legacyApiDir));
2371
2091
  }
2372
2092
  found = found.filter((r) => !r.isApi);
@@ -2400,9 +2120,9 @@ async function createApp(options) {
2400
2120
  }
2401
2121
  }
2402
2122
  }
2403
- const candidatePublicDir = join3(projectRoot, "public");
2404
- publicDir = existsSync2(candidatePublicDir) ? candidatePublicDir : null;
2405
- stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync2(join3(publicDir, "styles.css")) ? "/styles.css" : void 0);
2123
+ const candidatePublicDir = join2(projectRoot, "public");
2124
+ publicDir = existsSync(candidatePublicDir) ? candidatePublicDir : null;
2125
+ stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync(join2(publicDir, "styles.css")) ? "/styles.css" : void 0);
2406
2126
  const notFoundEntry = scanNotFound(pagesDir);
2407
2127
  if (notFoundEntry) {
2408
2128
  const mod = await importDev(notFoundEntry.filePath, dev);
@@ -2630,7 +2350,7 @@ async function createApp(options) {
2630
2350
  let rebuildTimeout = null;
2631
2351
  const sseClients = /* @__PURE__ */ new Set();
2632
2352
  try {
2633
- const srcDir = join3(primaryDir, "..", "..", "src");
2353
+ const srcDir = join2(primaryDir, "..", "..", "src");
2634
2354
  const watchDirs = [
2635
2355
  ...new Set(
2636
2356
  [primaryDir, options.apiDir, options.layoutsDir, resolvedActionsDir, srcDir].filter(
@@ -2743,62 +2463,398 @@ data: ${data}
2743
2463
  reportException(error, { phase: "api" });
2744
2464
  return new Response("Internal Server Error", { status: 500 });
2745
2465
  }
2746
- };
2466
+ };
2467
+ }
2468
+ const prodFetchInner = async (req, server) => {
2469
+ const url = new URL(req.url).pathname;
2470
+ const healthResult = await healthHandler(req);
2471
+ if (healthResult !== null) return healthResult;
2472
+ if (metricsReporter?.handleMetrics) {
2473
+ const metricsResult = await metricsReporter.handleMetrics(req);
2474
+ if (metricsResult !== null) return metricsResult;
2475
+ }
2476
+ if (rateLimiter) {
2477
+ const limited = await rateLimitMiddleware(rateLimiter, req, server);
2478
+ if (limited !== null) {
2479
+ metricsReporter?.incr("x_rate_limit_rejections_total", 1, { method: req.method });
2480
+ return limited;
2481
+ }
2482
+ }
2483
+ const revalidationResult = await handleRevalidation(req);
2484
+ if (revalidationResult !== null) return revalidationResult;
2485
+ const mismatchResult = await handleHydrationMismatch(req);
2486
+ if (mismatchResult !== null) return mismatchResult;
2487
+ const serverFnResult = await serverFnHandler(req);
2488
+ if (serverFnResult !== null) return serverFnResult;
2489
+ const staticAsset = await serveStaticAsset(publicDir, req);
2490
+ if (staticAsset !== null) return staticAsset;
2491
+ const islandBundle = serveIslandBundle(req);
2492
+ if (islandBundle !== null) return islandBundle;
2493
+ const proxiedImage = await imageProxyHandler(req);
2494
+ if (proxiedImage !== null) return proxiedImage;
2495
+ for (const h of handlers) {
2496
+ const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
2497
+ if (params !== null) {
2498
+ return h.handler(req);
2499
+ }
2500
+ }
2501
+ for (const h of contentHandlers) {
2502
+ if (h.entry.routePath === url) {
2503
+ return h.handler(req);
2504
+ }
2505
+ }
2506
+ return renderNotFound(req);
2507
+ };
2508
+ const prodFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(withBodySizeLimit(prodFetchInner), req, server));
2509
+ const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
2510
+ const prodFetchTraced = withRequestTracing(prodFetchBase);
2511
+ const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchTraced) : prodFetchTraced;
2512
+ return {
2513
+ routes: {},
2514
+ development: false,
2515
+ port: options.port ?? 3e3,
2516
+ fetch: prodFetch,
2517
+ error: (error) => {
2518
+ reportException(error, { phase: "api" });
2519
+ return new Response("Internal Server Error", { status: 500 });
2520
+ }
2521
+ };
2522
+ }
2523
+
2524
+ // src/application.ts
2525
+ function bypassBackpressure(req, development, hasMetricsEndpoint) {
2526
+ const pathname = new URL(req.url).pathname;
2527
+ return pathname === "/healthz" || pathname === "/readyz" || hasMetricsEndpoint && pathname === "/metrics" || pathname.startsWith("/_islands/") || development && pathname === "/__x/reload";
2528
+ }
2529
+ function saturatedResponse(error) {
2530
+ return new Response("Service Unavailable", {
2531
+ status: 503,
2532
+ headers: {
2533
+ "Content-Type": "text/plain; charset=utf-8",
2534
+ "Retry-After": String(error.retryAfterSeconds)
2535
+ }
2536
+ });
2537
+ }
2538
+ function defineConfig(config) {
2539
+ return config;
2540
+ }
2541
+ async function createApp2(options) {
2542
+ const { backpressure, ...baseOptions } = options;
2543
+ const app = await createApp(baseOptions);
2544
+ if (backpressure === void 0 || backpressure === false) return app;
2545
+ const controller = createBackpressureController(backpressure);
2546
+ const baseFetch = app.fetch;
2547
+ const metrics = options.observability?.metrics;
2548
+ const hasMetricsEndpoint = metrics?.handleMetrics !== void 0;
2549
+ const fetch2 = async (req, server) => {
2550
+ if (bypassBackpressure(req, app.development, hasMetricsEndpoint)) {
2551
+ return baseFetch(req, server);
2552
+ }
2553
+ const startedAt = performance.now();
2554
+ let lease;
2555
+ try {
2556
+ lease = await controller.acquire(req.signal);
2557
+ } catch (error) {
2558
+ if (error instanceof BackpressureSaturatedError) {
2559
+ metrics?.incr("x_backpressure_rejections_total", 1, { method: req.method });
2560
+ metrics?.incr("x_http_requests_total", 1, { method: req.method, status: "503" });
2561
+ metrics?.observe("x_http_request_duration_ms", performance.now() - startedAt, {
2562
+ method: req.method
2563
+ });
2564
+ return saturatedResponse(error);
2565
+ }
2566
+ if (req.signal.aborted) {
2567
+ metrics?.incr("x_http_requests_total", 1, { method: req.method, status: "499" });
2568
+ metrics?.observe("x_http_request_duration_ms", performance.now() - startedAt, {
2569
+ method: req.method
2570
+ });
2571
+ return new Response(null, { status: 499 });
2572
+ }
2573
+ throw error;
2574
+ }
2575
+ try {
2576
+ return await baseFetch(req, server);
2577
+ } finally {
2578
+ lease.release();
2579
+ }
2580
+ };
2581
+ return { ...app, fetch: fetch2 };
2582
+ }
2583
+
2584
+ // src/build.ts
2585
+ import { cpSync, existsSync as existsSync2, mkdirSync, writeFileSync } from "fs";
2586
+ import { join as join3, relative as relative2 } from "path";
2587
+ import { createElement as createElement2 } from "react";
2588
+ async function build(options) {
2589
+ const outDir = options.outDir ?? join3(process.cwd(), ".x");
2590
+ const clientDir = join3(outDir, "client");
2591
+ const serverDir = join3(outDir, "server");
2592
+ const islandsDir = join3(clientDir, "_islands");
2593
+ mkdirSync(clientDir, { recursive: true });
2594
+ mkdirSync(serverDir, { recursive: true });
2595
+ mkdirSync(islandsDir, { recursive: true });
2596
+ const pagesDir = options.pagesDir ?? options.routesDir ?? "";
2597
+ const apiDir = options.apiDir;
2598
+ const actionsDir = options.actionsDir;
2599
+ const layoutsDir = options.layoutsDir ?? pagesDir;
2600
+ const projectRoot = pagesDir ? join3(pagesDir, "..", "..") : process.cwd();
2601
+ const publicDir = join3(projectRoot, "public");
2602
+ const hasPublicDir = existsSync2(publicDir);
2603
+ const stylesheetHref = hasPublicDir && existsSync2(join3(publicDir, "styles.css")) ? "/styles.css" : void 0;
2604
+ if (hasPublicDir) {
2605
+ cpSync(publicDir, clientDir, { recursive: true });
2606
+ console.log(`[x] build: copied public/ -> ${relative2(process.cwd(), clientDir)}`);
2607
+ }
2608
+ let routeEntries = [];
2609
+ if (pagesDir && existsSync2(pagesDir)) {
2610
+ routeEntries = scanPages(pagesDir);
2611
+ }
2612
+ if (apiDir && existsSync2(apiDir)) {
2613
+ routeEntries.push(...scanApiDir(apiDir));
2614
+ }
2615
+ const legacyApiDir = pagesDir ? join3(pagesDir, "api") : "";
2616
+ if (legacyApiDir && existsSync2(legacyApiDir) && legacyApiDir !== apiDir) {
2617
+ routeEntries.push(...scanApiDir(legacyApiDir));
2618
+ }
2619
+ const actionModules = /* @__PURE__ */ new Map();
2620
+ if (actionsDir && existsSync2(actionsDir)) {
2621
+ for (const actionFile of scanRoutes(actionsDir)) {
2622
+ const mod = await import(actionFile.filePath);
2623
+ const segments = actionFile.routePath.split("/").filter(Boolean);
2624
+ const parentPath = `/${segments.slice(0, -1).join("/")}`;
2625
+ const fnNames = [];
2626
+ const actions = mod.actions;
2627
+ if (actions) {
2628
+ registerServerFunctions(parentPath, actionFile.paramNames, actions);
2629
+ fnNames.push(...Object.keys(actions));
2630
+ }
2631
+ for (const [key, value] of Object.entries(mod)) {
2632
+ if (key === "default" || key === "actions" || typeof value !== "function") continue;
2633
+ registerServerFunctions(parentPath, actionFile.paramNames, {
2634
+ [key]: value
2635
+ });
2636
+ fnNames.push(key);
2637
+ }
2638
+ if (fnNames.length > 0) {
2639
+ actionModules.set(actionFile.filePath, { parentPath, fnNames });
2640
+ }
2641
+ }
2747
2642
  }
2748
- const prodFetchInner = async (req, server) => {
2749
- const url = new URL(req.url).pathname;
2750
- const healthResult = await healthHandler(req);
2751
- if (healthResult !== null) return healthResult;
2752
- if (metricsReporter?.handleMetrics) {
2753
- const metricsResult = await metricsReporter.handleMetrics(req);
2754
- if (metricsResult !== null) return metricsResult;
2643
+ const dedicatedLayouts = layoutsDir && layoutsDir !== pagesDir && existsSync2(layoutsDir) ? scanLayoutsDir(layoutsDir) : [];
2644
+ const nestedLayouts = pagesDir && existsSync2(pagesDir) ? scanLayouts(pagesDir) : [];
2645
+ const layouts = [...dedicatedLayouts, ...nestedLayouts];
2646
+ const staticPages = [];
2647
+ const serverPages = [];
2648
+ const apiRoutes = [];
2649
+ for (const entry of routeEntries) {
2650
+ if (entry.isApi) {
2651
+ apiRoutes.push(entry);
2652
+ continue;
2755
2653
  }
2756
- if (rateLimiter) {
2757
- const limited = await rateLimitMiddleware(rateLimiter, req, server);
2758
- if (limited !== null) {
2759
- metricsReporter?.incr("x_rate_limit_rejections_total", 1, { method: req.method });
2760
- return limited;
2761
- }
2654
+ const mod = await import(entry.filePath);
2655
+ const Component = mod.default;
2656
+ if (!Component) {
2657
+ console.warn(`[x] ${entry.filePath} has no default export -- skipping`);
2658
+ continue;
2762
2659
  }
2763
- const revalidationResult = await handleRevalidation(req);
2764
- if (revalidationResult !== null) return revalidationResult;
2765
- const mismatchResult = await handleHydrationMismatch(req);
2766
- if (mismatchResult !== null) return mismatchResult;
2767
- const serverFnResult = await serverFnHandler(req);
2768
- if (serverFnResult !== null) return serverFnResult;
2769
- const staticAsset = await serveStaticAsset(publicDir, req);
2770
- if (staticAsset !== null) return staticAsset;
2771
- const islandBundle = serveIslandBundle(req);
2772
- if (islandBundle !== null) return islandBundle;
2773
- const proxiedImage = await imageProxyHandler(req);
2774
- if (proxiedImage !== null) return proxiedImage;
2775
- for (const h of handlers) {
2776
- const params = extractParams(h.entry.routePath, h.entry.paramNames, url);
2777
- if (params !== null) {
2778
- return h.handler(req);
2660
+ const mode = mod.mode ?? "server";
2661
+ const layoutChain = findLayoutChain(entry.filePath, layouts, pagesDir);
2662
+ for (const rootLayout of dedicatedLayouts) {
2663
+ if (!layoutChain.some((l) => l.filePath === rootLayout.filePath)) {
2664
+ layoutChain.unshift(rootLayout);
2779
2665
  }
2780
2666
  }
2781
- for (const h of contentHandlers) {
2782
- if (h.entry.routePath === url) {
2783
- return h.handler(req);
2784
- }
2667
+ const layoutModules = [];
2668
+ for (const l of layoutChain) {
2669
+ const layoutMod = await import(l.filePath);
2670
+ if (layoutMod.default) layoutModules.push(layoutMod.default);
2785
2671
  }
2786
- return renderNotFound(req);
2787
- };
2788
- const prodFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(withBodySizeLimit(prodFetchInner), req, server));
2789
- const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
2790
- const prodFetchTraced = withRequestTracing(prodFetchBase);
2791
- const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchTraced) : prodFetchTraced;
2792
- return {
2793
- routes: {},
2794
- development: false,
2795
- port: options.port ?? 3e3,
2796
- fetch: prodFetch,
2797
- error: (error) => {
2798
- reportException(error, { phase: "api" });
2799
- return new Response("Internal Server Error", { status: 500 });
2672
+ const page = {
2673
+ entry,
2674
+ filePath: entry.filePath,
2675
+ mode,
2676
+ Component,
2677
+ layoutModules,
2678
+ layoutFilePaths: layoutChain.map((l) => l.filePath)
2679
+ };
2680
+ if (mode === "static") {
2681
+ staticPages.push(page);
2682
+ } else {
2683
+ serverPages.push(page);
2800
2684
  }
2801
- };
2685
+ }
2686
+ let contentEntries = [];
2687
+ if (options.contentDir) {
2688
+ contentEntries = scanContent(options.contentDir);
2689
+ }
2690
+ console.log(
2691
+ `[x] build: ${staticPages.length} static, ${serverPages.length} server, ${contentEntries.length} content pages`
2692
+ );
2693
+ const writtenPaths = /* @__PURE__ */ new Set();
2694
+ for (const page of staticPages) {
2695
+ const params = {};
2696
+ const registry = createIslandRegistry();
2697
+ const pageContent = renderPageWithLayout(page.Component, params, page.layoutModules);
2698
+ const content = createElement2(IslandProvider, { registry }, pageContent);
2699
+ const _html = renderStaticPage(content, { stylesheet: stylesheetHref });
2700
+ const outPath = page.entry.routePath === "/" ? "/index.html" : `${page.entry.routePath}/index.html`;
2701
+ const fullPath = join3(clientDir, outPath);
2702
+ mkdirSync(join3(fullPath, ".."), { recursive: true });
2703
+ if (writtenPaths.has(outPath)) {
2704
+ console.warn(` [warn] collision: ${page.entry.routePath} overwrites existing output`);
2705
+ }
2706
+ writtenPaths.add(outPath);
2707
+ let islandScripts = [];
2708
+ if (registry.entries.length > 0) {
2709
+ const uniqueNames = [...new Set(registry.entries.map((e) => e.name))];
2710
+ islandScripts = await bundleRouteIslandsToDisk(
2711
+ page.filePath,
2712
+ page.layoutFilePaths,
2713
+ uniqueNames,
2714
+ islandsDir,
2715
+ actionModules
2716
+ );
2717
+ console.log(
2718
+ ` [islands] ${uniqueNames.length} island(s) on ${page.entry.routePath} -> ${islandScripts.join(", ")}`
2719
+ );
2720
+ }
2721
+ const finalHtml = renderStaticPage(content, { islandScripts, stylesheet: stylesheetHref });
2722
+ writeFileSync(fullPath, finalHtml, "utf-8");
2723
+ console.log(` [static] ${page.entry.routePath} -> ${outPath}`);
2724
+ }
2725
+ for (const content of contentEntries) {
2726
+ const registry = createIslandRegistry();
2727
+ const bodyHtml = renderMarkdown(content.body);
2728
+ const pageContent = createElement2(StaticContentPage, {
2729
+ content,
2730
+ bodyHtml
2731
+ });
2732
+ const rendered = createElement2(IslandProvider, { registry }, pageContent);
2733
+ const html = renderStaticPage(rendered, {
2734
+ title: content.frontmatter.title ?? content.slug,
2735
+ stylesheet: stylesheetHref
2736
+ });
2737
+ const outPath = content.routePath === "/" ? "/index.html" : `${content.routePath}/index.html`;
2738
+ const fullPath = join3(clientDir, outPath);
2739
+ mkdirSync(join3(fullPath, ".."), { recursive: true });
2740
+ if (writtenPaths.has(outPath)) {
2741
+ console.warn(` [warn] collision: content ${content.routePath} overwrites existing output`);
2742
+ }
2743
+ writtenPaths.add(outPath);
2744
+ writeFileSync(fullPath, html, "utf-8");
2745
+ console.log(` [content] ${content.routePath} -> ${outPath}`);
2746
+ }
2747
+ if (pagesDir || options.routesDir || options.contentDir) {
2748
+ const srvOpts = {
2749
+ pagesDir: pagesDir || options.routesDir || ""
2750
+ };
2751
+ if (options.apiDir) srvOpts.apiDir = options.apiDir;
2752
+ if (options.layoutsDir) srvOpts.layoutsDir = options.layoutsDir;
2753
+ if (options.actionsDir) srvOpts.actionsDir = options.actionsDir;
2754
+ if (options.contentDir) srvOpts.contentDir = options.contentDir;
2755
+ const configImportPath = options.configPath ? relativeImportPath(serverDir, options.configPath) : void 0;
2756
+ const serverEntry = buildServerEntry(
2757
+ srvOpts,
2758
+ configImportPath,
2759
+ stylesheetHref
2760
+ );
2761
+ const serverEntryPath = join3(serverDir, "index.ts");
2762
+ writeFileSync(serverEntryPath, serverEntry, "utf-8");
2763
+ console.log(
2764
+ ` [server] ${serverPages.length} page routes, ${apiRoutes.length} api routes -> server/index.ts`
2765
+ );
2766
+ }
2767
+ console.log(`[x] build complete -> ${outDir}`);
2768
+ }
2769
+ function renderPageWithLayout(Component, params, layoutModules) {
2770
+ let content = createElement2(Component, { params });
2771
+ for (const Layout of [...layoutModules].reverse()) {
2772
+ content = createElement2(Layout, null, content);
2773
+ }
2774
+ return content;
2775
+ }
2776
+ function StaticContentPage({ content, bodyHtml }) {
2777
+ return createElement2(
2778
+ "article",
2779
+ null,
2780
+ content.frontmatter.title ? createElement2("h1", null, content.frontmatter.title) : null,
2781
+ createElement2("div", {
2782
+ // biome-ignore lint/security/noDangerouslySetInnerHtml: body is markdown rendered to HTML
2783
+ dangerouslySetInnerHTML: { __html: bodyHtml }
2784
+ })
2785
+ );
2786
+ }
2787
+ function buildServerEntry(opts, configImportPath, stylesheetHref) {
2788
+ const dirKeys = ["pagesDir", "apiDir", "layoutsDir", "actionsDir", "contentDir"];
2789
+ const lines = [
2790
+ "// Auto-generated by @thexjs/core build",
2791
+ 'import { createApp } from "@thexjs/core";'
2792
+ ];
2793
+ if (configImportPath) {
2794
+ lines.push("", "let userConfig = {};", "try {");
2795
+ lines.push(` const mod = await import(${JSON.stringify(configImportPath)});`);
2796
+ lines.push(" userConfig = mod.default ?? {};");
2797
+ lines.push("} catch (err) {");
2798
+ lines.push(' console.warn("[x] failed to load x.config runtime options:", err);');
2799
+ lines.push("}");
2800
+ }
2801
+ lines.push("", "const app = await createApp({");
2802
+ for (const key of dirKeys) {
2803
+ const val = opts[key];
2804
+ if (val) lines.push(` ${key}: ${JSON.stringify(val)},`);
2805
+ }
2806
+ if (stylesheetHref) lines.push(` stylesheetHref: ${JSON.stringify(stylesheetHref)},`);
2807
+ lines.push(' port: parseInt(process.env.PORT || "3000", 10),', " development: false,");
2808
+ if (configImportPath) {
2809
+ lines.push(" ...(userConfig.security ? { security: userConfig.security } : {}),");
2810
+ lines.push(
2811
+ " ...(userConfig.observability ? { observability: userConfig.observability } : {}),"
2812
+ );
2813
+ lines.push(" ...(userConfig.images ? { images: userConfig.images } : {}),");
2814
+ lines.push(
2815
+ " ...(userConfig.backpressure !== undefined ? { backpressure: userConfig.backpressure } : {}),"
2816
+ );
2817
+ }
2818
+ lines.push(
2819
+ "});",
2820
+ "",
2821
+ "const server = Bun.serve(app);",
2822
+ "",
2823
+ "console.log(`[x] production server running at ${server.url}`);",
2824
+ "",
2825
+ "// Graceful shutdown: stop accepting new connections, flush the error",
2826
+ "// reporter, then exit after in-flight requests have a moment to drain.",
2827
+ "let shuttingDown = false;",
2828
+ "async function shutdown(signal: string): Promise<void> {",
2829
+ " if (shuttingDown) return;",
2830
+ " shuttingDown = true;",
2831
+ " console.log(`[x] received ${signal} - shutting down`);",
2832
+ " try {",
2833
+ ' const { getErrorReporter } = await import("@thexjs/core");',
2834
+ " await getErrorReporter().flush?.();",
2835
+ " } catch {}",
2836
+ " server.stop(true);",
2837
+ " const exit = () => process.exit(0);",
2838
+ " const drainTimer = setTimeout(exit, 3000);",
2839
+ " drainTimer.unref?.();",
2840
+ "}",
2841
+ 'process.on("SIGTERM", () => shutdown("SIGTERM"));',
2842
+ 'process.on("SIGINT", () => shutdown("SIGINT"));',
2843
+ "",
2844
+ "// Request-level errors are caught inside createApp's fetch boundary;",
2845
+ "// anything that still escapes (a throw outside the request lifecycle,",
2846
+ "// a rejected promise from a background sweep) is reported through the",
2847
+ "// error reporter so the box reports instead of dying silently.",
2848
+ 'const { installProcessCrashHandlers } = await import("@thexjs/core");',
2849
+ // Fail fast on an uncaughtException: the singleton state may be corrupted,
2850
+ // so drain and let the orchestrator restart clean (see crash-handlers).
2851
+ "installProcessCrashHandlers({ exitOnCrash: true });"
2852
+ );
2853
+ return lines.join("\n");
2854
+ }
2855
+ function relativeImportPath(fromDir, toFile) {
2856
+ const rel = relative2(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
2857
+ return rel.startsWith(".") ? rel : `./${rel}`;
2802
2858
  }
2803
2859
 
2804
2860
  // src/image.tsx
@@ -3079,7 +3135,7 @@ export {
3079
3135
  combineReporters,
3080
3136
  composeMiddleware,
3081
3137
  configureTrustedProxy,
3082
- createApp,
3138
+ createApp2 as createApp,
3083
3139
  createBackpressureController,
3084
3140
  createConsoleAuditSink,
3085
3141
  createHealthCheckHandler,