@thexjs/core 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,201 +1,18 @@
1
- // src/router.ts
2
- import { readdirSync, statSync, writeFileSync } from "fs";
3
- import { join, relative, sep } from "path";
4
- var ROUTE_FILE = /\.(tsx|ts)$/;
5
- function scanPages(rootDir) {
6
- return scanRoutes(rootDir).map((r) => ({ ...r, isApi: false }));
7
- }
8
- function scanApiDir(rootDir) {
9
- return scanRoutes(rootDir).map((r) => ({
10
- ...r,
11
- routePath: r.routePath === "/" ? "/api" : `/api${r.routePath}`,
12
- isApi: true
13
- }));
14
- }
15
- function scanRoutes(rootDir) {
16
- try {
17
- statSync(rootDir);
18
- } catch {
19
- return [];
20
- }
21
- const entries = [];
22
- function walk(dir) {
23
- for (const name of readdirSync(dir)) {
24
- if (name.startsWith("_") || name.startsWith(".")) continue;
25
- const full = join(dir, name);
26
- const stat = statSync(full);
27
- if (stat.isDirectory()) {
28
- walk(full);
29
- continue;
30
- }
31
- if (!ROUTE_FILE.test(name)) continue;
32
- const rel = relative(rootDir, full).replace(ROUTE_FILE, "");
33
- entries.push(toRouteEntry(rel, full));
34
- }
35
- }
36
- walk(rootDir);
37
- return entries;
38
- }
39
- function toRouteEntry(relPath, filePath) {
40
- const segments = relPath.split(sep);
41
- const paramNames = [];
42
- const isApi = segments[0] === "api";
43
- const routeSegments = segments.map((segment) => {
44
- if (segment === "index") return "";
45
- if (segment.startsWith("[...") && segment.endsWith("]")) {
46
- const name = segment.slice(4, -1);
47
- paramNames.push(name);
48
- return "*";
49
- }
50
- if (segment.startsWith("[") && segment.endsWith("]")) {
51
- const name = segment.slice(1, -1);
52
- paramNames.push(name);
53
- return `:${name}`;
54
- }
55
- return segment;
56
- });
57
- const joined = routeSegments.filter((s) => s.length > 0).join("/");
58
- const routePath = joined.length === 0 ? "/" : `/${joined}`;
59
- return { filePath, routePath, paramNames, isApi };
60
- }
61
- function scanLayouts(rootDir) {
62
- const entries = [];
63
- function walk(dir) {
64
- for (const name of readdirSync(dir)) {
65
- if (name.startsWith(".")) continue;
66
- const full = join(dir, name);
67
- const stat = statSync(full);
68
- if (stat.isDirectory()) {
69
- walk(full);
70
- } else if (name === "_layout.tsx" || name === "_layout.ts") {
71
- entries.push({ filePath: full, dirPath: dir });
72
- }
73
- }
74
- }
75
- walk(rootDir);
76
- return entries;
77
- }
78
- function scanLayoutsDir(layoutsDir) {
79
- const entries = [];
80
- try {
81
- if (!statSync(layoutsDir).isDirectory()) return entries;
82
- } catch {
83
- return entries;
84
- }
85
- for (const name of readdirSync(layoutsDir)) {
86
- if (name.startsWith(".")) continue;
87
- const full = join(layoutsDir, name);
88
- const stat = statSync(full);
89
- if (stat.isFile() && (name.endsWith(".tsx") || name.endsWith(".ts"))) {
90
- entries.push({ filePath: full, dirPath: layoutsDir });
91
- }
92
- }
93
- return entries;
94
- }
95
- function findLayoutChain(routeFilePath, layouts, routesDir) {
96
- const routeDir = join(routeFilePath, "..");
97
- const chain = [];
98
- let current = routeDir;
99
- while (current.startsWith(routesDir)) {
100
- const layout = layouts.find((l) => l.dirPath === current);
101
- if (layout) chain.unshift(layout);
102
- const parent = join(current, "..");
103
- if (parent === current) break;
104
- current = parent;
105
- }
106
- return chain;
107
- }
108
- var NOT_FOUND_CANDIDATES = ["_404.tsx", "_404.ts"];
109
- function scanNotFound(rootDir) {
110
- for (const name of NOT_FOUND_CANDIDATES) {
111
- const full = join(rootDir, name);
112
- try {
113
- statSync(full);
114
- return { filePath: full };
115
- } catch {
116
- }
117
- }
118
- return null;
119
- }
120
- function scanMiddleware(rootDir) {
121
- const entries = [];
122
- function walk(dir) {
123
- for (const name of readdirSync(dir)) {
124
- if (name.startsWith(".")) continue;
125
- const full = join(dir, name);
126
- const stat = statSync(full);
127
- if (stat.isDirectory()) {
128
- walk(full);
129
- } else if (name === "_middleware.ts" || name === "_middleware.tsx") {
130
- entries.push({ filePath: full, dirPath: dir });
131
- }
132
- }
133
- }
134
- walk(rootDir);
135
- return entries;
136
- }
137
- function findMiddlewareChain(routeFilePath, middleware, routesDir) {
138
- const routeDir = join(routeFilePath, "..");
139
- const chain = [];
140
- let current = routeDir;
141
- while (current.startsWith(routesDir)) {
142
- const mw = middleware.find((m) => m.dirPath === current);
143
- if (mw) chain.unshift(mw);
144
- const parent = join(current, "..");
145
- if (parent === current) break;
146
- current = parent;
147
- }
148
- return chain;
149
- }
150
- function routePatternToRegex(routePath) {
151
- const regexStr = routePath.replace(/\//g, "\\/").replace(/:(\w+)/g, "([^/]+)").replace(/\*/g, "(.+)");
152
- return new RegExp(`^${regexStr}$`);
153
- }
154
- function extractParams(routePath, paramNames, url) {
155
- const regex = routePatternToRegex(routePath);
156
- const match = url.match(regex);
157
- if (!match) return null;
158
- const params = {};
159
- let idx = 1;
160
- for (const name of paramNames) {
161
- const value = match[idx];
162
- if (value !== void 0) {
163
- params[name] = value;
164
- }
165
- idx++;
166
- }
167
- return params;
168
- }
169
- function generateManifestSource(routes) {
170
- const routeEntries = routes.map((r) => {
171
- const paramsType = r.paramNames.length === 0 ? "Record<string, never>" : `{ ${r.paramNames.map((n) => `${n}: string`).join("; ")} }`;
172
- return ` "${r.routePath}": ${paramsType};`;
173
- });
174
- return `// Auto-generated by @thexjs/core -- do not edit
175
- export type RouteMap = {
176
- ${routeEntries.join("\n")}
177
- };
178
-
179
- export function href<T extends keyof RouteMap & string>(
180
- path: T,
181
- ...[params]: RouteMap[T] extends Record<string, never> ? [] : [RouteMap[T]]
182
- ): string {
183
- if (!params) return path;
184
- let result: string = path;
185
- for (const [key, value] of Object.entries(params)) {
186
- result = result.replace(new RegExp(\`:\${key}(?=/|$)\`), encodeURIComponent(String(value)));
187
- }
188
- result = result.replace(/\\*+$/, "");
189
- return result;
190
- }
191
- `;
192
- }
193
- function writeManifest(routes, routesDir) {
194
- const source = generateManifestSource(routes);
195
- const manifestPath = join(routesDir, "..", "x-routes.ts");
196
- writeFileSync(manifestPath, source, "utf-8");
197
- return manifestPath;
198
- }
1
+ import {
2
+ extractParams,
3
+ findLayoutChain,
4
+ findMiddlewareChain,
5
+ generateManifestSource,
6
+ routePatternToRegex,
7
+ scanApiDir,
8
+ scanLayouts,
9
+ scanLayoutsDir,
10
+ scanMiddleware,
11
+ scanNotFound,
12
+ scanPages,
13
+ scanRoutes,
14
+ writeManifest
15
+ } from "./chunk-Y3MLOFAG.js";
199
16
 
200
17
  // src/not-found.tsx
201
18
  import { jsx, jsxs } from "react/jsx-runtime";
@@ -538,20 +355,20 @@ ${liveReloadTag} </body>
538
355
 
539
356
  // src/createApp.ts
540
357
  import { existsSync, watch } from "fs";
541
- import { join as join5, resolve, sep as sep3 } from "path";
358
+ import { join as join4, resolve, sep as sep2 } from "path";
542
359
  import { createElement } from "react";
543
360
 
544
361
  // src/content.ts
545
- import { readFileSync, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
546
- import { join as join2, relative as relative2, sep as sep2 } from "path";
362
+ import { readFileSync, readdirSync, statSync } from "fs";
363
+ import { join, relative, sep } from "path";
547
364
  var CONTENT_FILE = /\.(md|mdx)$/;
548
365
  function scanContent(rootDir) {
549
366
  const entries = [];
550
367
  function walk(dir) {
551
- for (const name of readdirSync2(dir)) {
368
+ for (const name of readdirSync(dir)) {
552
369
  if (name.startsWith(".")) continue;
553
- const full = join2(dir, name);
554
- const stat = statSync2(full);
370
+ const full = join(dir, name);
371
+ const stat = statSync(full);
555
372
  if (stat.isDirectory()) {
556
373
  walk(full);
557
374
  continue;
@@ -559,7 +376,7 @@ function scanContent(rootDir) {
559
376
  if (!CONTENT_FILE.test(name)) continue;
560
377
  const raw = readFileSync(full, "utf-8");
561
378
  const { frontmatter, body } = parseFrontmatter(raw);
562
- const rel = relative2(rootDir, full).replace(CONTENT_FILE, "");
379
+ const rel = relative(rootDir, full).replace(CONTENT_FILE, "");
563
380
  const slug = name.replace(CONTENT_FILE, "");
564
381
  const routePath = toContentRoutePath(rel);
565
382
  entries.push({ filePath: full, routePath, slug, frontmatter, body });
@@ -569,7 +386,7 @@ function scanContent(rootDir) {
569
386
  return entries;
570
387
  }
571
388
  function toContentRoutePath(relPath) {
572
- const segments = relPath.split(sep2).filter((s) => s !== "index");
389
+ const segments = relPath.split(sep).filter((s) => s !== "index");
573
390
  const joined = segments.join("/");
574
391
  return joined.length === 0 ? "/" : `/${joined}`;
575
392
  }
@@ -629,8 +446,12 @@ function decodeLinkUrl(url) {
629
446
  return url;
630
447
  }
631
448
  }
449
+ function stripUrlControlChars(url) {
450
+ return url.replace(/[\t\n\r]/g, "");
451
+ }
632
452
  function isSafeLinkUrl(url) {
633
- const scheme = LINK_SCHEME_RE.exec(decodeLinkUrl(url.trim()))?.[1]?.toLowerCase();
453
+ const clean = stripUrlControlChars(url);
454
+ const scheme = LINK_SCHEME_RE.exec(decodeLinkUrl(clean.trim()))?.[1]?.toLowerCase();
634
455
  return scheme === void 0 || ALLOWED_LINK_SCHEMES.has(scheme);
635
456
  }
636
457
  function renderMarkdown(md) {
@@ -643,10 +464,10 @@ function renderMarkdown(md) {
643
464
  html = html.replace(/^### (.+)$/gm, "<h3>$1</h3>").replace(/^## (.+)$/gm, "<h2>$1</h2>").replace(/^# (.+)$/gm, "<h1>$1</h1>").replace(/`([^`]+)`/g, (_m, code) => {
644
465
  inlineCodes.push(code);
645
466
  return `__X_CODE_${inlineCodes.length - 1}__`;
646
- }).replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>").replace(
647
- /\[([^\]]+)\]\(([^)]+)\)/g,
648
- (_m, text, href) => isSafeLinkUrl(href) ? `<a href="${href}">${text}</a>` : text
649
- ).replace(/__X_CODE_(\d+)__/g, (_m, i) => `<code>${inlineCodes[Number.parseInt(i)]}</code>`);
467
+ }).replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>").replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, text, href) => {
468
+ const clean = stripUrlControlChars(href);
469
+ return isSafeLinkUrl(clean) ? `<a href="${clean}">${text}</a>` : text;
470
+ }).replace(/__X_CODE_(\d+)__/g, (_m, i) => `<code>${inlineCodes[Number.parseInt(i)]}</code>`);
650
471
  html = html.replace(/__X_FENCE_(\d+)__/g, (_m, i) => fences[Number.parseInt(i)] ?? "");
651
472
  const blocks = html.split(/\n\n+/);
652
473
  html = blocks.map((b) => {
@@ -865,8 +686,8 @@ function Island({
865
686
  }
866
687
 
867
688
  // src/island-bundle.ts
868
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync as writeFileSync3 } from "fs";
869
- import { basename, join as join4 } from "path";
689
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
690
+ import { basename, join as join3 } from "path";
870
691
 
871
692
  // src/security/env-isolation.ts
872
693
  var PUBLIC_ENV_PREFIX = "THEXJS_PUBLIC_";
@@ -928,8 +749,8 @@ function assertNoEnvLeakage(code, file) {
928
749
  }
929
750
 
930
751
  // src/server-functions.ts
931
- import { writeFileSync as writeFileSync2 } from "fs";
932
- import { join as join3 } from "path";
752
+ import { writeFileSync } from "fs";
753
+ import { join as join2 } from "path";
933
754
 
934
755
  // src/observability/monitoring.ts
935
756
  var noopReporter = {
@@ -1229,12 +1050,12 @@ ${code}
1229
1050
  }
1230
1051
  async function buildIslandBundleInMemory(routeFilePath, layoutFilePaths, islandNames, actionModules, projectRoot) {
1231
1052
  const entryId = islandEntryId(routeFilePath);
1232
- const scratchRoot = join4(projectRoot, ".x", "islands-tmp");
1053
+ const scratchRoot = join3(projectRoot, ".x", "islands-tmp");
1233
1054
  mkdirSync(scratchRoot, { recursive: true });
1234
- const scratchDir = mkdtempSync(join4(scratchRoot, "x-islands-"));
1055
+ const scratchDir = mkdtempSync(join3(scratchRoot, "x-islands-"));
1235
1056
  try {
1236
- const entryPath = join4(scratchDir, `${entryId}.tsx`);
1237
- writeFileSync3(entryPath, generateHydrateEntry(routeFilePath, layoutFilePaths), "utf-8");
1057
+ const entryPath = join3(scratchDir, `${entryId}.tsx`);
1058
+ writeFileSync2(entryPath, generateHydrateEntry(routeFilePath, layoutFilePaths), "utf-8");
1238
1059
  const result = await Bun.build({
1239
1060
  entrypoints: [entryPath],
1240
1061
  target: "browser",
@@ -1368,6 +1189,163 @@ function withRequestLogging(handler) {
1368
1189
  };
1369
1190
  }
1370
1191
 
1192
+ // src/observability/metrics.ts
1193
+ var noopMetrics = {
1194
+ incr: () => {
1195
+ },
1196
+ observe: () => {
1197
+ }
1198
+ };
1199
+ var DEFAULT_HISTOGRAM_BUCKETS_MS = [5, 10, 25, 50, 100, 250, 500, 1e3, 2500, 5e3, 1e4];
1200
+ function seriesKey(name, labels) {
1201
+ if (!labels) return name;
1202
+ const sorted = Object.entries(labels).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${k}=${v}`);
1203
+ return `${name}\0${sorted.join("\0")}`;
1204
+ }
1205
+ function createInMemoryMetrics(options = {}) {
1206
+ const buckets = options.histogramBuckets ?? DEFAULT_HISTOGRAM_BUCKETS_MS;
1207
+ const counters = /* @__PURE__ */ new Map();
1208
+ const histograms = /* @__PURE__ */ new Map();
1209
+ function incr(name, delta = 1, labels) {
1210
+ const key = seriesKey(name, labels);
1211
+ let series = counters.get(key);
1212
+ if (!series) {
1213
+ series = { name, labels: labels ?? {}, value: 0 };
1214
+ counters.set(key, series);
1215
+ }
1216
+ series.value += delta;
1217
+ }
1218
+ function observe(name, value, labels) {
1219
+ const key = seriesKey(name, labels);
1220
+ let acc = histograms.get(key);
1221
+ if (!acc) {
1222
+ acc = { bucketCounts: new Array(buckets.length).fill(0), sum: 0, count: 0 };
1223
+ histograms.set(key, acc);
1224
+ }
1225
+ acc.sum += value;
1226
+ acc.count += 1;
1227
+ for (let i = 0; i < buckets.length; i += 1) {
1228
+ const bound = buckets[i];
1229
+ if (bound === void 0) break;
1230
+ if (value <= bound) {
1231
+ for (let j = i; j < buckets.length; j += 1) {
1232
+ acc.bucketCounts[j] = (acc.bucketCounts[j] ?? 0) + 1;
1233
+ }
1234
+ break;
1235
+ }
1236
+ }
1237
+ }
1238
+ function labelsFromKey(key) {
1239
+ const [name] = key.split("\0");
1240
+ const labelPart = name !== void 0 ? key.slice(name.length + 1) : "";
1241
+ const labels = {};
1242
+ if (labelPart) {
1243
+ for (const pair of labelPart.split("\0")) {
1244
+ const eq = pair.indexOf("=");
1245
+ if (eq > 0) labels[pair.slice(0, eq)] = pair.slice(eq + 1);
1246
+ }
1247
+ }
1248
+ return { name: name ?? key, labels };
1249
+ }
1250
+ function snapshot() {
1251
+ const sortedCounters = [...counters.entries()].sort(([a], [b]) => a < b ? -1 : 1).map(([key, series]) => {
1252
+ const { name, labels } = labelsFromKey(key);
1253
+ return { name, labels, value: series.value };
1254
+ });
1255
+ const sortedHistograms = [...histograms.entries()].sort(([a], [b]) => a < b ? -1 : 1).map(([key, acc]) => {
1256
+ const { name, labels } = labelsFromKey(key);
1257
+ return { name, labels, bucketCounts: acc.bucketCounts, sum: acc.sum, count: acc.count };
1258
+ });
1259
+ return { counters: sortedCounters, histograms: sortedHistograms };
1260
+ }
1261
+ function renderMetrics() {
1262
+ const snap = snapshot();
1263
+ const lines = [];
1264
+ for (const counter of snap.counters) {
1265
+ lines.push(`# TYPE ${counter.name} counter`);
1266
+ lines.push(`${counter.name}${formatLabels(counter.labels)} ${counter.value}`);
1267
+ }
1268
+ for (const h of snap.histograms) {
1269
+ const labelWithLe = (le) => {
1270
+ const labels = { ...h.labels, le };
1271
+ return formatLabels(labels);
1272
+ };
1273
+ lines.push(`# TYPE ${h.name} histogram`);
1274
+ for (let i = 0; i < buckets.length; i += 1) {
1275
+ lines.push(`${h.name}_bucket${labelWithLe(String(buckets[i]))} ${h.bucketCounts[i]}`);
1276
+ }
1277
+ lines.push(`${h.name}_bucket${labelWithLe("+Inf")} ${h.count}`);
1278
+ lines.push(`${h.name}_sum${formatLabels(h.labels)} ${h.sum}`);
1279
+ lines.push(`${h.name}_count${formatLabels(h.labels)} ${h.count}`);
1280
+ }
1281
+ return `${lines.join("\n")}
1282
+ `;
1283
+ }
1284
+ function handleMetrics(req) {
1285
+ if (new URL(req.url).pathname !== "/metrics") return null;
1286
+ return new Response(renderMetrics(), {
1287
+ headers: { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" }
1288
+ });
1289
+ }
1290
+ return {
1291
+ incr,
1292
+ observe,
1293
+ snapshot,
1294
+ renderMetrics,
1295
+ handleMetrics,
1296
+ async flush() {
1297
+ }
1298
+ };
1299
+ }
1300
+ function createOtlpMetricsReporter(meter) {
1301
+ const counters = /* @__PURE__ */ new Map();
1302
+ const histograms = /* @__PURE__ */ new Map();
1303
+ return {
1304
+ incr(name, delta, labels) {
1305
+ let counter = counters.get(name);
1306
+ if (!counter) {
1307
+ counter = meter.createCounter(name, { description: `Counter ${name}` });
1308
+ counters.set(name, counter);
1309
+ }
1310
+ counter.add(delta ?? 1, labels);
1311
+ },
1312
+ observe(name, value, labels) {
1313
+ let histogram = histograms.get(name);
1314
+ if (!histogram) {
1315
+ histogram = meter.createHistogram(name, { description: `Histogram ${name}` });
1316
+ histograms.set(name, histogram);
1317
+ }
1318
+ histogram.record(value, labels);
1319
+ }
1320
+ };
1321
+ }
1322
+ function formatLabels(labels) {
1323
+ const entries = Object.entries(labels);
1324
+ if (entries.length === 0) return "";
1325
+ const escaped = entries.map(([k, v]) => `${k}="${escapeLabelValue(v)}"`).join(",");
1326
+ return `{${escaped}}`;
1327
+ }
1328
+ function escapeLabelValue(value) {
1329
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
1330
+ }
1331
+ function withRequestMetrics(reporter, handler) {
1332
+ return async (req, server) => {
1333
+ const start = performance.now();
1334
+ const method = req.method;
1335
+ try {
1336
+ const res = await handler(req, server);
1337
+ reporter.incr("x_http_requests_total", 1, { method, status: String(res.status) });
1338
+ reporter.observe("x_http_request_duration_ms", performance.now() - start, { method });
1339
+ return res;
1340
+ } catch (err) {
1341
+ reporter.incr("x_http_requests_total", 1, { method, status: "500" });
1342
+ reporter.incr("x_http_errors_total", 1, { method });
1343
+ reporter.observe("x_http_request_duration_ms", performance.now() - start, { method });
1344
+ throw err;
1345
+ }
1346
+ };
1347
+ }
1348
+
1371
1349
  // src/security/headers.ts
1372
1350
  var DEFAULT_CSP = "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'";
1373
1351
  function buildSecurityHeaders(options = {}) {
@@ -1503,7 +1481,7 @@ function createRedisRateLimitStoreFromClient(clientFactory) {
1503
1481
 
1504
1482
  // src/createApp.ts
1505
1483
  function projectRootFromRoutesDir(routesDir) {
1506
- return join5(routesDir, "..", "..");
1484
+ return join4(routesDir, "..", "..");
1507
1485
  }
1508
1486
  function resolvePublicAsset(publicDir, pathname) {
1509
1487
  let decoded;
@@ -1512,9 +1490,9 @@ function resolvePublicAsset(publicDir, pathname) {
1512
1490
  } catch {
1513
1491
  return null;
1514
1492
  }
1515
- const target = resolve(join5(publicDir, decoded));
1493
+ const target = resolve(join4(publicDir, decoded));
1516
1494
  const root = resolve(publicDir);
1517
- if (target !== root && !target.startsWith(root + sep3)) return null;
1495
+ if (target !== root && !target.startsWith(root + sep2)) return null;
1518
1496
  return target;
1519
1497
  }
1520
1498
  async function serveStaticAsset(publicDir, req) {
@@ -1564,7 +1542,7 @@ async function createApp(options) {
1564
1542
  const dev = options.development ?? false;
1565
1543
  const primaryDir = options.pagesDir || options.routesDir || "src/pages";
1566
1544
  const projectRoot = projectRootFromRoutesDir(primaryDir);
1567
- const resolvedActionsDir = options.actionsDir ?? (existsSync(join5(projectRoot, "src", "actions")) ? join5(projectRoot, "src", "actions") : void 0);
1545
+ const resolvedActionsDir = options.actionsDir ?? (existsSync(join4(projectRoot, "src", "actions")) ? join4(projectRoot, "src", "actions") : void 0);
1568
1546
  let handlers = [];
1569
1547
  let contentHandlers = [];
1570
1548
  let publicDir = null;
@@ -1610,6 +1588,7 @@ async function createApp(options) {
1610
1588
  setErrorReporter(options.observability.errorReporter);
1611
1589
  }
1612
1590
  const healthHandler = createHealthCheckHandler(options.observability?.health ?? {});
1591
+ const metricsReporter = options.observability?.metrics;
1613
1592
  const rateLimiter = options.security?.rateLimit === false ? null : createRateLimiter(options.security?.rateLimit ?? {});
1614
1593
  const securityHeadersOptions = options.security?.headers;
1615
1594
  const loggingEnabled = options.observability?.logging ?? true;
@@ -1644,6 +1623,7 @@ async function createApp(options) {
1644
1623
  return new Response(`Method ${method} not allowed`, { status: 405 });
1645
1624
  } catch (err) {
1646
1625
  reportException(err, { route: route.routePath, phase: "api" });
1626
+ metricsReporter?.incr("x_http_errors_total", 1, { phase: "api" });
1647
1627
  console.error("[x] API handler error:", err);
1648
1628
  if (dev) {
1649
1629
  return new Response(renderErrorOverlay(err), {
@@ -1744,6 +1724,7 @@ async function createApp(options) {
1744
1724
  return baseHandler({ params, request: req });
1745
1725
  } catch (err) {
1746
1726
  reportException(err, { route: route.routePath, phase: "ssr" });
1727
+ metricsReporter?.incr("x_http_errors_total", 1, { phase: "ssr" });
1747
1728
  console.error("[x] route handler error:", err);
1748
1729
  if (dev) {
1749
1730
  return new Response(renderErrorOverlay(err), {
@@ -1758,9 +1739,9 @@ async function createApp(options) {
1758
1739
  async function buildHandlers() {
1759
1740
  if (options.preloaded) {
1760
1741
  const preloaded = options.preloaded;
1761
- const candidatePublicDir2 = join5(projectRoot, "public");
1742
+ const candidatePublicDir2 = join4(projectRoot, "public");
1762
1743
  publicDir = existsSync(candidatePublicDir2) ? candidatePublicDir2 : null;
1763
- stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync(join5(publicDir, "styles.css")) ? "/styles.css" : void 0);
1744
+ stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync(join4(publicDir, "styles.css")) ? "/styles.css" : void 0);
1764
1745
  if (preloaded.notFoundComponent) notFoundComponent = preloaded.notFoundComponent;
1765
1746
  if (preloaded.notFoundLayout) notFoundLayout = preloaded.notFoundLayout;
1766
1747
  const loaded2 = [];
@@ -1814,7 +1795,7 @@ async function createApp(options) {
1814
1795
  if (apiDir && existsSync(apiDir)) {
1815
1796
  apiFound.push(...scanApiDir(apiDir));
1816
1797
  }
1817
- const legacyApiDir = join5(pagesDir, "api");
1798
+ const legacyApiDir = join4(pagesDir, "api");
1818
1799
  if (existsSync(legacyApiDir) && legacyApiDir !== apiDir) {
1819
1800
  apiFound.push(...scanApiDir(legacyApiDir));
1820
1801
  }
@@ -1849,9 +1830,9 @@ async function createApp(options) {
1849
1830
  }
1850
1831
  }
1851
1832
  }
1852
- const candidatePublicDir = join5(projectRoot, "public");
1833
+ const candidatePublicDir = join4(projectRoot, "public");
1853
1834
  publicDir = existsSync(candidatePublicDir) ? candidatePublicDir : null;
1854
- stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync(join5(publicDir, "styles.css")) ? "/styles.css" : void 0);
1835
+ stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync(join4(publicDir, "styles.css")) ? "/styles.css" : void 0);
1855
1836
  const notFoundEntry = scanNotFound(pagesDir);
1856
1837
  if (notFoundEntry) {
1857
1838
  const mod = await importDev(notFoundEntry.filePath, dev);
@@ -2007,7 +1988,7 @@ async function createApp(options) {
2007
1988
  let rebuildTimeout = null;
2008
1989
  const sseClients = /* @__PURE__ */ new Set();
2009
1990
  try {
2010
- const srcDir = join5(primaryDir, "..", "..", "src");
1991
+ const srcDir = join4(primaryDir, "..", "..", "src");
2011
1992
  const watchDirs = [
2012
1993
  ...new Set(
2013
1994
  [primaryDir, options.apiDir, options.layoutsDir, resolvedActionsDir, srcDir].filter(
@@ -2032,9 +2013,16 @@ async function createApp(options) {
2032
2013
  const url = new URL(req.url).pathname;
2033
2014
  const healthResult = await healthHandler(req);
2034
2015
  if (healthResult !== null) return healthResult;
2016
+ if (metricsReporter?.handleMetrics) {
2017
+ const metricsResult = await metricsReporter.handleMetrics(req);
2018
+ if (metricsResult !== null) return metricsResult;
2019
+ }
2035
2020
  if (rateLimiter) {
2036
2021
  const limited = await rateLimitMiddleware(rateLimiter, req, server);
2037
- if (limited !== null) return limited;
2022
+ if (limited !== null) {
2023
+ metricsReporter?.incr("x_rate_limit_rejections_total", 1, { method: req.method });
2024
+ return limited;
2025
+ }
2038
2026
  }
2039
2027
  if (url === "/__x/reload") {
2040
2028
  const body = new ReadableStream({
@@ -2095,7 +2083,8 @@ data: ${data}
2095
2083
  return renderNotFound(req);
2096
2084
  };
2097
2085
  const devFetchHardened = async (req, server) => withResponseHardening(await devFetchInner(req, server));
2098
- const devFetch = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
2086
+ const devFetchBase = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
2087
+ const devFetch = metricsReporter ? withRequestMetrics(metricsReporter, devFetchBase) : devFetchBase;
2099
2088
  return {
2100
2089
  routes: {},
2101
2090
  development: true,
@@ -2107,9 +2096,16 @@ data: ${data}
2107
2096
  const url = new URL(req.url).pathname;
2108
2097
  const healthResult = await healthHandler(req);
2109
2098
  if (healthResult !== null) return healthResult;
2099
+ if (metricsReporter?.handleMetrics) {
2100
+ const metricsResult = await metricsReporter.handleMetrics(req);
2101
+ if (metricsResult !== null) return metricsResult;
2102
+ }
2110
2103
  if (rateLimiter) {
2111
2104
  const limited = await rateLimitMiddleware(rateLimiter, req, server);
2112
- if (limited !== null) return limited;
2105
+ if (limited !== null) {
2106
+ metricsReporter?.incr("x_rate_limit_rejections_total", 1, { method: req.method });
2107
+ return limited;
2108
+ }
2113
2109
  }
2114
2110
  const revalidationResult = await handleRevalidation(req);
2115
2111
  if (revalidationResult !== null) return revalidationResult;
@@ -2135,7 +2131,8 @@ data: ${data}
2135
2131
  return renderNotFound(req);
2136
2132
  };
2137
2133
  const prodFetchHardened = async (req, server) => withResponseHardening(await prodFetchInner(req, server));
2138
- const prodFetch = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
2134
+ const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
2135
+ const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchBase) : prodFetchBase;
2139
2136
  return {
2140
2137
  routes: {},
2141
2138
  development: false,
@@ -2145,14 +2142,14 @@ data: ${data}
2145
2142
  }
2146
2143
 
2147
2144
  // src/build.ts
2148
- import { cpSync, existsSync as existsSync2, mkdirSync as mkdirSync2, writeFileSync as writeFileSync4 } from "fs";
2149
- import { join as join6, relative as relative3 } from "path";
2145
+ import { cpSync, existsSync as existsSync2, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
2146
+ import { join as join5, relative as relative2 } from "path";
2150
2147
  import { createElement as createElement2 } from "react";
2151
2148
  async function build(options) {
2152
- const outDir = options.outDir ?? join6(process.cwd(), ".x");
2153
- const clientDir = join6(outDir, "client");
2154
- const serverDir = join6(outDir, "server");
2155
- const islandsDir = join6(clientDir, "_islands");
2149
+ const outDir = options.outDir ?? join5(process.cwd(), ".x");
2150
+ const clientDir = join5(outDir, "client");
2151
+ const serverDir = join5(outDir, "server");
2152
+ const islandsDir = join5(clientDir, "_islands");
2156
2153
  mkdirSync2(clientDir, { recursive: true });
2157
2154
  mkdirSync2(serverDir, { recursive: true });
2158
2155
  mkdirSync2(islandsDir, { recursive: true });
@@ -2160,13 +2157,13 @@ async function build(options) {
2160
2157
  const apiDir = options.apiDir;
2161
2158
  const actionsDir = options.actionsDir;
2162
2159
  const layoutsDir = options.layoutsDir ?? pagesDir;
2163
- const projectRoot = pagesDir ? join6(pagesDir, "..", "..") : process.cwd();
2164
- const publicDir = join6(projectRoot, "public");
2160
+ const projectRoot = pagesDir ? join5(pagesDir, "..", "..") : process.cwd();
2161
+ const publicDir = join5(projectRoot, "public");
2165
2162
  const hasPublicDir = existsSync2(publicDir);
2166
- const stylesheetHref = hasPublicDir && existsSync2(join6(publicDir, "styles.css")) ? "/styles.css" : void 0;
2163
+ const stylesheetHref = hasPublicDir && existsSync2(join5(publicDir, "styles.css")) ? "/styles.css" : void 0;
2167
2164
  if (hasPublicDir) {
2168
2165
  cpSync(publicDir, clientDir, { recursive: true });
2169
- console.log(`[x] build: copied public/ -> ${relative3(process.cwd(), clientDir)}`);
2166
+ console.log(`[x] build: copied public/ -> ${relative2(process.cwd(), clientDir)}`);
2170
2167
  }
2171
2168
  let routeEntries = [];
2172
2169
  if (pagesDir && existsSync2(pagesDir)) {
@@ -2175,7 +2172,7 @@ async function build(options) {
2175
2172
  if (apiDir && existsSync2(apiDir)) {
2176
2173
  routeEntries.push(...scanApiDir(apiDir));
2177
2174
  }
2178
- const legacyApiDir = pagesDir ? join6(pagesDir, "api") : "";
2175
+ const legacyApiDir = pagesDir ? join5(pagesDir, "api") : "";
2179
2176
  if (legacyApiDir && existsSync2(legacyApiDir) && legacyApiDir !== apiDir) {
2180
2177
  routeEntries.push(...scanApiDir(legacyApiDir));
2181
2178
  }
@@ -2261,8 +2258,8 @@ async function build(options) {
2261
2258
  const content = createElement2(IslandProvider, { registry }, pageContent);
2262
2259
  const html = renderStaticPage(content, { stylesheet: stylesheetHref });
2263
2260
  const outPath = page.entry.routePath === "/" ? "/index.html" : `${page.entry.routePath}/index.html`;
2264
- const fullPath = join6(clientDir, outPath);
2265
- mkdirSync2(join6(fullPath, ".."), { recursive: true });
2261
+ const fullPath = join5(clientDir, outPath);
2262
+ mkdirSync2(join5(fullPath, ".."), { recursive: true });
2266
2263
  if (writtenPaths.has(outPath)) {
2267
2264
  console.warn(` [warn] collision: ${page.entry.routePath} overwrites existing output`);
2268
2265
  }
@@ -2282,7 +2279,7 @@ async function build(options) {
2282
2279
  );
2283
2280
  }
2284
2281
  const finalHtml = renderStaticPage(content, { islandScripts, stylesheet: stylesheetHref });
2285
- writeFileSync4(fullPath, finalHtml, "utf-8");
2282
+ writeFileSync3(fullPath, finalHtml, "utf-8");
2286
2283
  console.log(` [static] ${page.entry.routePath} -> ${outPath}`);
2287
2284
  }
2288
2285
  for (const content of contentEntries) {
@@ -2298,13 +2295,13 @@ async function build(options) {
2298
2295
  stylesheet: stylesheetHref
2299
2296
  });
2300
2297
  const outPath = content.routePath === "/" ? "/index.html" : `${content.routePath}/index.html`;
2301
- const fullPath = join6(clientDir, outPath);
2302
- mkdirSync2(join6(fullPath, ".."), { recursive: true });
2298
+ const fullPath = join5(clientDir, outPath);
2299
+ mkdirSync2(join5(fullPath, ".."), { recursive: true });
2303
2300
  if (writtenPaths.has(outPath)) {
2304
2301
  console.warn(` [warn] collision: content ${content.routePath} overwrites existing output`);
2305
2302
  }
2306
2303
  writtenPaths.add(outPath);
2307
- writeFileSync4(fullPath, html, "utf-8");
2304
+ writeFileSync3(fullPath, html, "utf-8");
2308
2305
  console.log(` [content] ${content.routePath} -> ${outPath}`);
2309
2306
  }
2310
2307
  if (pagesDir || options.routesDir || options.contentDir) {
@@ -2321,8 +2318,8 @@ async function build(options) {
2321
2318
  configImportPath,
2322
2319
  stylesheetHref
2323
2320
  );
2324
- const serverEntryPath = join6(serverDir, "index.ts");
2325
- writeFileSync4(serverEntryPath, serverEntry, "utf-8");
2321
+ const serverEntryPath = join5(serverDir, "index.ts");
2322
+ writeFileSync3(serverEntryPath, serverEntry, "utf-8");
2326
2323
  console.log(
2327
2324
  ` [server] ${serverPages.length} page routes, ${apiRoutes.length} api routes -> server/index.ts`
2328
2325
  );
@@ -2331,12 +2328,12 @@ async function build(options) {
2331
2328
  }
2332
2329
  async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, islandsDir, actionModules) {
2333
2330
  const entryId = islandEntryId(routeFilePath);
2334
- const outdir = join6(islandsDir, entryId);
2331
+ const outdir = join5(islandsDir, entryId);
2335
2332
  mkdirSync2(outdir, { recursive: true });
2336
- const bundlePath = join6(outdir, `${entryId}.js`);
2333
+ const bundlePath = join5(outdir, `${entryId}.js`);
2337
2334
  const hydrateEntry = generateHydrateEntry(routeFilePath, layoutFilePaths);
2338
- const entryPath = join6(outdir, `${entryId}.tsx`);
2339
- writeFileSync4(entryPath, hydrateEntry, "utf-8");
2335
+ const entryPath = join5(outdir, `${entryId}.tsx`);
2336
+ writeFileSync3(entryPath, hydrateEntry, "utf-8");
2340
2337
  try {
2341
2338
  const result = await Bun.build({
2342
2339
  entrypoints: [entryPath],
@@ -2349,7 +2346,7 @@ async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, i
2349
2346
  if (!built) throw new Error("bun build produced no output");
2350
2347
  const code = await built.text();
2351
2348
  assertNoEnvLeakage(code, bundlePath);
2352
- writeFileSync4(bundlePath, wrapIslandBundle(code), "utf-8");
2349
+ writeFileSync3(bundlePath, wrapIslandBundle(code), "utf-8");
2353
2350
  return [`/_islands/${entryId}/${entryId}.js`];
2354
2351
  }
2355
2352
  for (const log of result.logs) {
@@ -2358,7 +2355,7 @@ async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, i
2358
2355
  } catch (err) {
2359
2356
  console.warn(` [islands] build failed for ${routeFilePath}:`, err);
2360
2357
  }
2361
- writeFileSync4(bundlePath, wrapIslandBundle(generateFallbackHydration(islandNames)), "utf-8");
2358
+ writeFileSync3(bundlePath, wrapIslandBundle(generateFallbackHydration(islandNames)), "utf-8");
2362
2359
  return [`/_islands/${entryId}/${entryId}.js`];
2363
2360
  }
2364
2361
  function renderPageWithLayout(Component, params, layoutModules) {
@@ -2441,7 +2438,7 @@ function buildServerEntry(opts, configImportPath, stylesheetHref) {
2441
2438
  return lines.join("\n");
2442
2439
  }
2443
2440
  function relativeImportPath(fromDir, toFile) {
2444
- const rel = relative3(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
2441
+ const rel = relative2(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
2445
2442
  return rel.startsWith(".") ? rel : `./${rel}`;
2446
2443
  }
2447
2444
 
@@ -2461,6 +2458,7 @@ function Link({ href, children, clientNav = true, prefetch = true, ...rest }) {
2461
2458
  }
2462
2459
  export {
2463
2460
  CLIENT_NAV_SCRIPT,
2461
+ DEFAULT_HISTOGRAM_BUCKETS_MS,
2464
2462
  DefaultNotFound,
2465
2463
  EnvLeakageError,
2466
2464
  Island,
@@ -2477,7 +2475,9 @@ export {
2477
2475
  createApp,
2478
2476
  createHealthCheckHandler,
2479
2477
  createImageProxyHandler,
2478
+ createInMemoryMetrics,
2480
2479
  createOtelReporter,
2480
+ createOtlpMetricsReporter,
2481
2481
  createRateLimiter,
2482
2482
  createRedisRateLimitStore,
2483
2483
  createSentryReporter,
@@ -2492,6 +2492,7 @@ export {
2492
2492
  getErrorReporter,
2493
2493
  getServerFunctionHandler,
2494
2494
  logger,
2495
+ noopMetrics,
2495
2496
  noopReporter,
2496
2497
  rateLimitMiddleware,
2497
2498
  registerServerFunctions,
@@ -2515,5 +2516,6 @@ export {
2515
2516
  verifyOrigin,
2516
2517
  withCsrfCookie,
2517
2518
  withRequestLogging,
2519
+ withRequestMetrics,
2518
2520
  writeManifest
2519
2521
  };