@thexjs/core 1.1.0 → 1.2.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.
@@ -0,0 +1,153 @@
1
+ interface AdapterOptions {
2
+ /** Project root (defaults to process.cwd()). */
3
+ projectRoot?: string;
4
+ /** Matches CreateAppOptions -- same directories used by the dev/build pipeline. */
5
+ pagesDir?: string;
6
+ routesDir?: string;
7
+ apiDir?: string;
8
+ layoutsDir?: string;
9
+ actionsDir?: string;
10
+ contentDir?: string;
11
+ /** Security options (CSRF, headers, rate limiting). */
12
+ security?: Record<string, unknown>;
13
+ /** Observability options (logging, health checks, error reporting). */
14
+ observability?: Record<string, unknown>;
15
+ /** Remote image proxy options for /_x/image. */
16
+ images?: {
17
+ remoteHosts?: string[];
18
+ };
19
+ }
20
+ /** A single file that needs to be transpiled from .ts/.tsx source into a
21
+ * Node-runnable .mjs module and given a stable import identifier so the
22
+ * generated entrypoint can `import * as X from "..."` it statically. */
23
+ interface CompiledModuleRef {
24
+ /** Absolute path to the original .ts/.tsx source file. */
25
+ sourcePath: string;
26
+ /** Absolute path to the transpiled .mjs file (inside the build scratch dir). */
27
+ compiledPath: string;
28
+ /** Stable JS identifier used for the static import in the generated entry file. */
29
+ identifier: string;
30
+ }
31
+ interface ResolvedRoute {
32
+ routePath: string;
33
+ paramNames: string[];
34
+ isApi: boolean;
35
+ mode: "static" | "server";
36
+ revalidate?: number;
37
+ route: CompiledModuleRef;
38
+ layoutChain: CompiledModuleRef[];
39
+ middlewareChain: CompiledModuleRef[];
40
+ }
41
+ interface ResolvedAction {
42
+ parentPath: string;
43
+ paramNames: string[];
44
+ module: CompiledModuleRef;
45
+ }
46
+ interface BuildManifest {
47
+ /** The project root the build ran from (used to relativize emitted paths). */
48
+ projectRoot: string;
49
+ pagesDirLabel: string;
50
+ routes: ResolvedRoute[];
51
+ actions: ResolvedAction[];
52
+ notFound?: CompiledModuleRef;
53
+ rootLayout?: CompiledModuleRef;
54
+ hasServerSurface: boolean;
55
+ /** Resolved stylesheet <link> href for server-rendered pages (baked at build time). */
56
+ stylesheetHref?: string;
57
+ /** Security options serialized for the generated entry. */
58
+ security?: AdapterOptions["security"];
59
+ /** Observability options serialized for the generated entry. */
60
+ observability?: AdapterOptions["observability"];
61
+ /** Remote image proxy options serialized for the generated entry. */
62
+ images?: AdapterOptions["images"];
63
+ }
64
+
65
+ /** Registry of every unique source file that needs transpiling, keyed by absolute path. */
66
+ declare class ModuleRegistry {
67
+ private scratchDir;
68
+ private byPath;
69
+ constructor(scratchDir: string);
70
+ ref(sourcePath: string, prefix: string): CompiledModuleRef;
71
+ all(): CompiledModuleRef[];
72
+ }
73
+ /**
74
+ * Resolve the full set of server-mode routes, API routes, layout chains,
75
+ * middleware chains and standalone server-action files -- entirely at build
76
+ * time, using the same scanners `createApp`/`build` use internally. Nothing
77
+ * here touches the filesystem at request time, which is what makes the
78
+ * output safe to run on any Node.js runtime (no dynamic fs scanning,
79
+ * no dynamic `import(path)` of a `.tsx` file).
80
+ */
81
+ declare function resolveBuildManifest(options: AdapterOptions, scratchDir: string): Promise<BuildManifest>;
82
+ declare function allModuleRefs(manifest: BuildManifest): CompiledModuleRef[];
83
+
84
+ /**
85
+ * Transpiles each referenced route/layout/middleware/action source file
86
+ * (TSX/TS, authored for Bun) into a standalone Node-runnable ESM module.
87
+ *
88
+ * We deliberately transpile file-by-file (rather than letting the final
89
+ * bundle step follow dynamic `import()` calls) because `@thexjs/core`'s own
90
+ * scanners find these files by walking the filesystem at *runtime* -- that
91
+ * strategy only works on Bun, which understands `.tsx`/`.ts` natively.
92
+ * A deployed Node.js runtime does not, so every route file that will run
93
+ * inside the render function has to already be plain JS before it gets
94
+ * there. `react`/`react-dom`/`@thexjs/core` stay external here; they get
95
+ * inlined once, together, in the final bundle step so we don't duplicate
96
+ * framework code per-route.
97
+ */
98
+ declare function transpileModules(refs: CompiledModuleRef[]): Promise<void>;
99
+
100
+ /**
101
+ * Serializes runtime config (security / observability / images) into the
102
+ * generated entry. Only JSON-serializable values can cross the build
103
+ * boundary -- a `security.errorReporter` or `observability.logger` callback
104
+ * in `x.config.ts` must not silently vanish, or the deployed function would
105
+ * drift from `x start`. Fail the build loudly with the offending keys.
106
+ */
107
+ declare function serializeRuntimeOptions(label: string, options: Record<string, unknown> | undefined): string;
108
+ /**
109
+ * Emits the source for the adapter render-function entry module.
110
+ *
111
+ * Every route/layout/middleware/action module is imported *statically* (no
112
+ * `import(pathVariable)` anywhere) so the bundler can trace and inline the
113
+ * whole dependency graph -- including `@thexjs/core`, `react-dom/server`,
114
+ * etc -- into one standalone file.
115
+ *
116
+ * The request pipeline is not reimplemented here: the entry builds a real
117
+ * `createApp()` from `@thexjs/core` (with a pre-resolved route manifest so
118
+ * no filesystem scanning or dynamic `.tsx` import happens at request time)
119
+ * and delegates every request to `app.fetch()`. That means the deployed
120
+ * function behaves exactly like the `x start` production server -- health
121
+ * checks, rate limiting, revalidation, server actions, SSR with
122
+ * loaders/layouts/middleware, API routes, security headers, the 404 page,
123
+ * request logging -- all of it, with no drift between the two.
124
+ *
125
+ * The returned module exports a `handler` function; the platform adapter
126
+ * decides its signature (e.g. a Node `(req, res)` bridge for Vercel).
127
+ */
128
+ declare function generateAdapterEntry(manifest: BuildManifest, entryDir: string): string;
129
+
130
+ /**
131
+ * The scratch directory that holds the transient (transpiled module / entry
132
+ * source) files the bundler reads before inlining everything into
133
+ * `index.mjs`. Part of the adapter SDK contract: the entry generator computes
134
+ * relative `import` paths off the directory the adapter creates via this
135
+ * helper, so both sides must agree on the same location.
136
+ */
137
+ declare function adapterScratchDir(functionDir: string): string;
138
+ /**
139
+ * Bundles the pure `index.mjs` render function that inlines the whole
140
+ * SSR/API dependency graph (`@thexjs/core`, `react`, `react-dom`, every
141
+ * route/layout/middleware/action module) so it runs on a platform's Node
142
+ * runtime with zero `node_modules` and zero dynamic filesystem access at
143
+ * request time.
144
+ *
145
+ * `entrySource` (as produced by `generateAdapterEntry`, plus whatever
146
+ * platform bridge the adapter appended) should reference the transpiled
147
+ * module refs by compiled path. The scratch dir lives *inside* `functionDir`
148
+ * (inside the project tree) so Bun's bare-import resolution walks up to the
149
+ * project's real `node_modules`.
150
+ */
151
+ declare function bundleRenderFunction(functionDir: string, entrySource: string): Promise<void>;
152
+
153
+ export { type AdapterOptions, type BuildManifest, type CompiledModuleRef, ModuleRegistry, type ResolvedAction, type ResolvedRoute, adapterScratchDir, allModuleRefs, bundleRenderFunction, generateAdapterEntry, resolveBuildManifest, serializeRuntimeOptions, transpileModules };
@@ -0,0 +1,320 @@
1
+ import {
2
+ findLayoutChain,
3
+ findMiddlewareChain,
4
+ scanApiDir,
5
+ scanLayouts,
6
+ scanLayoutsDir,
7
+ scanMiddleware,
8
+ scanNotFound,
9
+ scanPages,
10
+ scanRoutes
11
+ } from "./chunk-Y3MLOFAG.js";
12
+
13
+ // src/adapter/scan.ts
14
+ import { existsSync } from "fs";
15
+ import { join } from "path";
16
+ var idCounter = 0;
17
+ function nextIdentifier(prefix) {
18
+ idCounter += 1;
19
+ return `__x_${prefix}_${idCounter}`;
20
+ }
21
+ var ModuleRegistry = class {
22
+ constructor(scratchDir) {
23
+ this.scratchDir = scratchDir;
24
+ }
25
+ scratchDir;
26
+ byPath = /* @__PURE__ */ new Map();
27
+ ref(sourcePath, prefix) {
28
+ const existing = this.byPath.get(sourcePath);
29
+ if (existing) return existing;
30
+ const identifier = nextIdentifier(prefix);
31
+ const compiledPath = join(this.scratchDir, `${identifier}.mjs`);
32
+ const entry = { sourcePath, compiledPath, identifier };
33
+ this.byPath.set(sourcePath, entry);
34
+ return entry;
35
+ }
36
+ all() {
37
+ return [...this.byPath.values()];
38
+ }
39
+ };
40
+ async function resolveBuildManifest(options, scratchDir) {
41
+ const projectRoot = options.projectRoot ?? process.cwd();
42
+ const pagesDir = options.pagesDir || options.routesDir || join(projectRoot, "src", "pages");
43
+ const apiDir = options.apiDir;
44
+ const layoutsDir = options.layoutsDir || pagesDir;
45
+ const actionsDir = options.actionsDir ?? (existsSync(join(projectRoot, "src", "actions")) ? join(projectRoot, "src", "actions") : void 0);
46
+ const registry = new ModuleRegistry(scratchDir);
47
+ let found = existsSync(pagesDir) ? scanPages(pagesDir) : [];
48
+ const apiFound = [];
49
+ if (apiDir && existsSync(apiDir)) apiFound.push(...scanApiDir(apiDir));
50
+ const legacyApiDir = join(pagesDir, "api");
51
+ if (existsSync(legacyApiDir) && legacyApiDir !== apiDir) {
52
+ apiFound.push(...scanApiDir(legacyApiDir));
53
+ }
54
+ found = found.filter((r) => !r.isApi);
55
+ found.push(...apiFound);
56
+ const dedicatedLayouts = options.layoutsDir && existsSync(options.layoutsDir) ? scanLayoutsDir(options.layoutsDir) : [];
57
+ const nestedLayouts = existsSync(pagesDir) ? scanLayouts(pagesDir) : [];
58
+ const layouts = [...dedicatedLayouts, ...nestedLayouts];
59
+ const middlewareEntries = existsSync(pagesDir) ? scanMiddleware(pagesDir) : [];
60
+ const routes = [];
61
+ for (const entry of found) {
62
+ if (entry.isApi) {
63
+ routes.push({
64
+ routePath: entry.routePath,
65
+ paramNames: entry.paramNames,
66
+ isApi: true,
67
+ mode: "server",
68
+ route: registry.ref(entry.filePath, "api"),
69
+ layoutChain: [],
70
+ middlewareChain: []
71
+ });
72
+ continue;
73
+ }
74
+ const mod = await import(entry.filePath);
75
+ if (!mod.default && !mod.actions) continue;
76
+ if ((mod.mode ?? "server") === "static") continue;
77
+ const layoutChain = findLayoutChain(entry.filePath, layouts, pagesDir);
78
+ const missingDedicated = dedicatedLayouts.filter(
79
+ (rootLayout2) => !layoutChain.some((l) => l.filePath === rootLayout2.filePath)
80
+ );
81
+ if (missingDedicated.length > 0) layoutChain.unshift(...missingDedicated);
82
+ const mwChain = findMiddlewareChain(entry.filePath, middlewareEntries, pagesDir);
83
+ routes.push({
84
+ routePath: entry.routePath,
85
+ paramNames: entry.paramNames,
86
+ isApi: false,
87
+ mode: mod.mode ?? "server",
88
+ ...mod.revalidate !== void 0 ? { revalidate: mod.revalidate } : {},
89
+ route: registry.ref(entry.filePath, "page"),
90
+ layoutChain: layoutChain.map((l) => registry.ref(l.filePath, "layout")),
91
+ middlewareChain: mwChain.map((m) => registry.ref(m.filePath, "mw"))
92
+ });
93
+ }
94
+ const actions = [];
95
+ if (actionsDir && existsSync(actionsDir)) {
96
+ for (const actionFile of scanRoutes(actionsDir)) {
97
+ const segments = actionFile.routePath.split("/").filter(Boolean);
98
+ const fileName = segments[segments.length - 1] ?? "";
99
+ const parentPath = fileName === "index" || !fileName ? actionFile.routePath : `/${segments.slice(0, -1).join("/")}`;
100
+ actions.push({
101
+ parentPath,
102
+ paramNames: actionFile.paramNames,
103
+ module: registry.ref(actionFile.filePath, "action")
104
+ });
105
+ }
106
+ }
107
+ const notFoundEntry = existsSync(pagesDir) ? scanNotFound(pagesDir) : null;
108
+ const notFound = notFoundEntry ? registry.ref(notFoundEntry.filePath, "notfound") : void 0;
109
+ const rootLayoutEntry = dedicatedLayouts[0] ?? layouts.find((l) => l.dirPath === pagesDir);
110
+ const rootLayout = rootLayoutEntry ? registry.ref(rootLayoutEntry.filePath, "rootlayout") : void 0;
111
+ return {
112
+ projectRoot,
113
+ pagesDirLabel: pagesDir,
114
+ routes,
115
+ actions,
116
+ ...notFound ? { notFound } : {},
117
+ ...rootLayout ? { rootLayout } : {},
118
+ hasServerSurface: routes.length > 0 || actions.length > 0,
119
+ ...existsSync(join(projectRoot, "public", "styles.css")) ? { stylesheetHref: "/styles.css" } : {},
120
+ security: options.security,
121
+ observability: options.observability,
122
+ images: options.images
123
+ };
124
+ }
125
+ function allModuleRefs(manifest) {
126
+ const map = /* @__PURE__ */ new Map();
127
+ const add = (ref) => map.set(ref.sourcePath, ref);
128
+ for (const r of manifest.routes) {
129
+ add(r.route);
130
+ for (const l of r.layoutChain) add(l);
131
+ for (const m of r.middlewareChain) add(m);
132
+ }
133
+ for (const a of manifest.actions) add(a.module);
134
+ if (manifest.notFound) add(manifest.notFound);
135
+ if (manifest.rootLayout) add(manifest.rootLayout);
136
+ return [...map.values()];
137
+ }
138
+
139
+ // src/adapter/transpile.ts
140
+ import { mkdirSync } from "fs";
141
+ import { dirname } from "path";
142
+ async function transpileModules(refs) {
143
+ for (const ref of refs) {
144
+ const result = await Bun.build({
145
+ entrypoints: [ref.sourcePath],
146
+ target: "node",
147
+ format: "esm",
148
+ splitting: false,
149
+ external: ["react", "react/*", "react-dom", "react-dom/*", "@thexjs/core", "@thexjs/core/*"]
150
+ });
151
+ if (!result.success || result.outputs.length === 0) {
152
+ const messages = result.logs.map((l) => l.message).join("\n");
153
+ throw new Error(`[@thexjs/core] failed to transpile ${ref.sourcePath}:
154
+ ${messages}`);
155
+ }
156
+ const [output] = result.outputs;
157
+ mkdirSync(dirname(ref.compiledPath), { recursive: true });
158
+ await Bun.write(ref.compiledPath, await output.arrayBuffer());
159
+ }
160
+ }
161
+
162
+ // src/adapter/generate-entry.ts
163
+ import { relative } from "path";
164
+ function importPath(from, ref) {
165
+ let rel = relative(from, ref.compiledPath).replaceAll("\\", "/");
166
+ if (!rel.startsWith(".")) rel = `./${rel}`;
167
+ return rel;
168
+ }
169
+ function serializeRuntimeOptions(label, options) {
170
+ if (options === void 0) return "{}";
171
+ const offenders = [];
172
+ JSON.stringify(options, (key, value) => {
173
+ if (typeof value === "function" || typeof value === "symbol") offenders.push(`${label}.${key}`);
174
+ return value;
175
+ });
176
+ if (offenders.length > 0) {
177
+ throw new Error(
178
+ `[@thexjs/core] cannot serialize ${offenders.join(", ")} into the adapter entry \u2014 only JSON-serializable values (no functions/symbols) can be forwarded to a serverless runtime. Move the callable into a server file or configure it directly on the platform.`
179
+ );
180
+ }
181
+ return JSON.stringify(options) ?? "{}";
182
+ }
183
+ function generateAdapterEntry(manifest, entryDir) {
184
+ const lines = [];
185
+ lines.push(
186
+ "// Auto-generated by @thexjs/core adapter SDK -- do not edit.",
187
+ 'import { createApp, registerServerFunctions } from "@thexjs/core";',
188
+ ""
189
+ );
190
+ const securityOpts = serializeRuntimeOptions("security", manifest.security);
191
+ const observabilityOpts = serializeRuntimeOptions("observability", manifest.observability);
192
+ const imagesOpts = serializeRuntimeOptions("images", manifest.images);
193
+ lines.push(
194
+ `const __x_security = ${securityOpts};`,
195
+ `const __x_observability = ${observabilityOpts};`,
196
+ `const __x_images = ${imagesOpts};`,
197
+ ""
198
+ );
199
+ const refs = /* @__PURE__ */ new Map();
200
+ const collect = (ref) => refs.set(ref.identifier, ref);
201
+ for (const r of manifest.routes) {
202
+ collect(r.route);
203
+ for (const l of r.layoutChain) collect(l);
204
+ for (const m of r.middlewareChain) collect(m);
205
+ }
206
+ for (const a of manifest.actions) collect(a.module);
207
+ if (manifest.notFound) collect(manifest.notFound);
208
+ if (manifest.rootLayout) collect(manifest.rootLayout);
209
+ for (const ref of refs.values()) {
210
+ lines.push(`import * as ${ref.identifier} from "${importPath(entryDir, ref)}";`);
211
+ }
212
+ lines.push("");
213
+ for (const a of manifest.actions) {
214
+ lines.push(
215
+ "{",
216
+ ` const mod = ${a.module.identifier};`,
217
+ ` const parentPath = ${JSON.stringify(a.parentPath)};`,
218
+ ` const paramNames = ${JSON.stringify(a.paramNames)};`,
219
+ " if (mod.actions) registerServerFunctions(parentPath, paramNames, mod.actions);",
220
+ " for (const [key, value] of Object.entries(mod)) {",
221
+ ` if (key === "default" || key === "actions" || typeof value !== "function") continue;`,
222
+ " registerServerFunctions(parentPath, paramNames, { [key]: value });",
223
+ " }",
224
+ "}"
225
+ );
226
+ }
227
+ lines.push("");
228
+ const rel = (abs) => {
229
+ const r = relative(manifest.projectRoot, abs).replaceAll("\\", "/");
230
+ return r.startsWith(".") ? r : `./${r}`;
231
+ };
232
+ lines.push("const __x_preloadedRoutes = [");
233
+ for (const r of manifest.routes) {
234
+ const entryObj = {
235
+ routePath: r.routePath,
236
+ paramNames: r.paramNames,
237
+ isApi: r.isApi,
238
+ filePath: rel(r.route.sourcePath)
239
+ };
240
+ const layoutMods = r.layoutChain.map((l) => `${l.identifier}.default`).join(", ");
241
+ const mwMods = r.middlewareChain.map((m) => `${m.identifier}.middleware`).join(", ");
242
+ lines.push(
243
+ " {",
244
+ ` entry: ${JSON.stringify(entryObj)},`,
245
+ ` mode: ${JSON.stringify(r.mode)},`,
246
+ ...r.revalidate !== void 0 ? [` revalidate: ${r.revalidate},`] : [],
247
+ ` module: ${r.route.identifier},`,
248
+ ` layoutModules: [${layoutMods}].filter(Boolean),`,
249
+ ` middlewareModules: [${mwMods}].filter(Boolean),`,
250
+ " islandScripts: [],",
251
+ " },"
252
+ );
253
+ }
254
+ lines.push("];");
255
+ lines.push("");
256
+ lines.push(
257
+ "const __x_app = await createApp({",
258
+ ` pagesDir: ${JSON.stringify(rel(manifest.pagesDirLabel))},`,
259
+ " development: false,",
260
+ " port: parseInt(process.env.PORT || '3000', 10),",
261
+ ...manifest.stylesheetHref ? [` stylesheetHref: ${JSON.stringify(manifest.stylesheetHref)},`] : [],
262
+ " ...(Object.keys(__x_security).length > 0 ? { security: __x_security } : {}),",
263
+ " ...(Object.keys(__x_observability).length > 0 ? { observability: __x_observability } : {}),",
264
+ " ...(Object.keys(__x_images).length > 0 ? { images: __x_images } : {}),",
265
+ " preloaded: {",
266
+ " routes: __x_preloadedRoutes,",
267
+ ...manifest.notFound ? [` notFoundComponent: ${manifest.notFound.identifier}.default ?? undefined,`] : [],
268
+ ...manifest.rootLayout ? [` notFoundLayout: ${manifest.rootLayout.identifier}.default ?? undefined,`] : [],
269
+ " },",
270
+ "});",
271
+ ""
272
+ );
273
+ lines.push("");
274
+ lines.push("export { __x_app };");
275
+ lines.push("");
276
+ return lines.join("\n");
277
+ }
278
+
279
+ // src/adapter/bundle.ts
280
+ import { mkdirSync as mkdirSync2, rmSync, writeFileSync } from "fs";
281
+ import { join as join2 } from "path";
282
+ function adapterScratchDir(functionDir) {
283
+ return join2(functionDir, ".scratch");
284
+ }
285
+ async function bundleRenderFunction(functionDir, entrySource) {
286
+ mkdirSync2(functionDir, { recursive: true });
287
+ const scratchDir = adapterScratchDir(functionDir);
288
+ mkdirSync2(scratchDir, { recursive: true });
289
+ try {
290
+ const entryPath = join2(scratchDir, "entry.mjs");
291
+ writeFileSync(entryPath, entrySource, "utf-8");
292
+ const result = await Bun.build({
293
+ entrypoints: [entryPath],
294
+ target: "node",
295
+ format: "esm",
296
+ splitting: false,
297
+ minify: false
298
+ });
299
+ if (!result.success || result.outputs.length === 0) {
300
+ const messages = result.logs.map((l) => l.message).join("\n");
301
+ throw new Error(`[@thexjs/core] failed to bundle render function:
302
+ ${messages}`);
303
+ }
304
+ const [output] = result.outputs;
305
+ const code = await output.text();
306
+ writeFileSync(join2(functionDir, "index.mjs"), code, "utf-8");
307
+ } finally {
308
+ rmSync(scratchDir, { recursive: true, force: true });
309
+ }
310
+ }
311
+ export {
312
+ ModuleRegistry,
313
+ adapterScratchDir,
314
+ allModuleRefs,
315
+ bundleRenderFunction,
316
+ generateAdapterEntry,
317
+ resolveBuildManifest,
318
+ serializeRuntimeOptions,
319
+ transpileModules
320
+ };
@@ -0,0 +1,214 @@
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
+ }
199
+
200
+ export {
201
+ scanPages,
202
+ scanApiDir,
203
+ scanRoutes,
204
+ scanLayouts,
205
+ scanLayoutsDir,
206
+ findLayoutChain,
207
+ scanNotFound,
208
+ scanMiddleware,
209
+ findMiddlewareChain,
210
+ routePatternToRegex,
211
+ extractParams,
212
+ generateManifestSource,
213
+ writeManifest
214
+ };