@bractjs/bractjs 0.1.26 → 0.1.28
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/README.md +283 -58
- package/bin/cli.ts +18 -1
- package/package.json +1 -1
- package/src/__tests__/build-path.test.ts +29 -0
- package/src/__tests__/codegen-write.test.ts +67 -0
- package/src/__tests__/codegen.test.ts +64 -1
- package/src/__tests__/compile-safety.test.ts +4 -0
- package/src/__tests__/csp.test.ts +10 -0
- package/src/__tests__/define-actions.test.ts +69 -0
- package/src/__tests__/env.test.ts +18 -0
- package/src/__tests__/fetcher-store.test.ts +67 -0
- package/src/__tests__/fixtures/app/root.tsx +7 -2
- package/src/__tests__/fixtures/app/routes/boom.tsx +9 -0
- package/src/__tests__/fixtures/app/routes/client-only.tsx +16 -0
- package/src/__tests__/fixtures/app/routes/counter.tsx +16 -0
- package/src/__tests__/fixtures/app/routes/data-only.tsx +16 -0
- package/src/__tests__/fixtures/app/routes/intent-demo.tsx +46 -0
- package/src/__tests__/fixtures/app/routes/protected-client-only.tsx +15 -0
- package/src/__tests__/fixtures/app/routes/search-demo.tsx +39 -0
- package/src/__tests__/form-data-helpers.test.ts +43 -0
- package/src/__tests__/integration.test.ts +56 -0
- package/src/__tests__/loader.test.ts +32 -1
- package/src/__tests__/nav-utils.test.ts +46 -0
- package/src/__tests__/prerender.test.ts +102 -0
- package/src/__tests__/programmatic-api.test.ts +20 -1
- package/src/__tests__/revalidation.test.ts +65 -0
- package/src/__tests__/route-lint.test.ts +74 -0
- package/src/__tests__/route-table.test.ts +33 -0
- package/src/__tests__/safe-validate.test.ts +96 -0
- package/src/__tests__/scroll-restoration.test.ts +66 -0
- package/src/__tests__/search-serializer.test.ts +42 -0
- package/src/__tests__/search-validation.test.ts +125 -0
- package/src/__tests__/security.test.ts +110 -1
- package/src/__tests__/selective-ssr.test.ts +85 -0
- package/src/__tests__/spa-mode.test.ts +77 -0
- package/src/__tests__/typed-routing.test.ts +239 -0
- package/src/build/bundler.ts +33 -0
- package/src/build/prerender.ts +88 -0
- package/src/build/route-lint.ts +49 -0
- package/src/client/ClientRouter.tsx +239 -47
- package/src/client/build-path.ts +24 -0
- package/src/client/cache.ts +8 -0
- package/src/client/components/Await.tsx +9 -2
- package/src/client/components/Form.tsx +23 -34
- package/src/client/components/Link.tsx +105 -11
- package/src/client/components/Outlet.tsx +8 -2
- package/src/client/components/ScrollRestoration.tsx +125 -0
- package/src/client/entry.tsx +39 -2
- package/src/client/fetcher-store.ts +61 -0
- package/src/client/form-utils.ts +3 -0
- package/src/client/hooks/useActionData.ts +7 -3
- package/src/client/hooks/useFetcher.ts +116 -33
- package/src/client/hooks/useFetchers.ts +23 -0
- package/src/client/hooks/useLoaderData.ts +8 -4
- package/src/client/hooks/useLocation.ts +27 -0
- package/src/client/hooks/useNavigate.ts +51 -0
- package/src/client/hooks/useParams.ts +15 -4
- package/src/client/hooks/useRevalidator.ts +26 -0
- package/src/client/hooks/useSearch.ts +73 -0
- package/src/client/hooks/useSearchParams.ts +21 -6
- package/src/client/nav-utils.ts +26 -0
- package/src/client/prefetch.ts +110 -15
- package/src/client/registry.ts +131 -0
- package/src/client/revalidation.ts +25 -0
- package/src/client/router.tsx +28 -1
- package/src/client/scroll-restoration.ts +48 -0
- package/src/client/search-serializer.ts +40 -0
- package/src/client/types.ts +6 -0
- package/src/codegen/route-codegen.ts +201 -29
- package/src/config/load.ts +21 -0
- package/src/dev/hmr-client.ts +3 -1
- package/src/dev/route-table.ts +27 -0
- package/src/dev/server.ts +106 -8
- package/src/dev/watcher.ts +25 -3
- package/src/index.ts +44 -3
- package/src/server/action-handler.ts +12 -3
- package/src/server/action-registry.ts +35 -0
- package/src/server/csp.ts +10 -1
- package/src/server/csrf.ts +26 -0
- package/src/server/env.ts +26 -5
- package/src/server/layout.ts +31 -1
- package/src/server/loader.ts +14 -8
- package/src/server/render.ts +18 -3
- package/src/server/request-handler.ts +50 -8
- package/src/server/search.ts +43 -0
- package/src/server/serve.ts +88 -1
- package/src/server/spa.ts +62 -0
- package/src/server/stream-handler.ts +10 -1
- package/src/server/validate.ts +85 -13
- package/src/shared/context.ts +5 -0
- package/src/shared/define-actions.ts +39 -0
- package/src/shared/form-data.ts +34 -0
- package/src/shared/route-types.ts +83 -2
- package/templates/new-app/app/root.tsx +2 -1
- package/templates/new-app/bractjs.config.ts +7 -12
- package/types/config.d.ts +21 -0
- package/types/index.d.ts +210 -10
- package/types/route.d.ts +62 -2
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
2
|
import { scanRoutes } from "../server/scanner.ts";
|
|
3
3
|
import type { Segment } from "../server/scanner.ts";
|
|
4
|
+
import { hashString } from "../build/hash.ts";
|
|
4
5
|
|
|
5
6
|
// Convert [param] / [...catchAll] notation to :param colon-style for URLs.
|
|
6
7
|
function patternToColon(urlPattern: string): string {
|
|
@@ -34,6 +35,8 @@ function substituteParams(pattern: string, params: string[]): string {
|
|
|
34
35
|
// backtick, ${ }, or quote into the generated TS source.
|
|
35
36
|
const SAFE_PATTERN_RE = /^\/(?:[A-Za-z0-9_\-]+|:[A-Za-z_][A-Za-z0-9_]*)(?:\/(?:[A-Za-z0-9_\-]+|:[A-Za-z_][A-Za-z0-9_]*))*$|^\/$/;
|
|
36
37
|
const SAFE_IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
38
|
+
// Same guard the module-registry codegen applies before emitting import paths.
|
|
39
|
+
const SAFE_FILEPATH_RE = /^[A-Za-z0-9._\/\-\[\]]+$/;
|
|
37
40
|
|
|
38
41
|
function assertSafePattern(pattern: string): void {
|
|
39
42
|
if (!SAFE_PATTERN_RE.test(pattern)) {
|
|
@@ -45,6 +48,11 @@ function assertSafeParam(name: string): void {
|
|
|
45
48
|
throw new Error(`[bractjs] codegen: refusing to emit unsafe param name: ${JSON.stringify(name)}`);
|
|
46
49
|
}
|
|
47
50
|
}
|
|
51
|
+
function assertSafeFilePath(filePath: string): void {
|
|
52
|
+
if (!SAFE_FILEPATH_RE.test(filePath) || filePath.split("/").includes("..")) {
|
|
53
|
+
throw new Error(`[bractjs] codegen: refusing to emit unsafe file path: ${JSON.stringify(filePath)}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
48
56
|
|
|
49
57
|
function builderEntry(pattern: string, params: string[]): string {
|
|
50
58
|
assertSafePattern(pattern);
|
|
@@ -78,35 +86,70 @@ const HEADER =
|
|
|
78
86
|
"\n" +
|
|
79
87
|
"/* eslint-disable */\n";
|
|
80
88
|
|
|
89
|
+
// `RouteSearchParamsMap` / `RouteContextMap` are owned by the package
|
|
90
|
+
// (`@bractjs/bractjs`) so users have a single stable module to augment. We do
|
|
91
|
+
// NOT seed per-route keys here: seeding `"/posts": Record<string,string>` would
|
|
92
|
+
// conflict with a user augmentation declaring `"/posts": { page: string }`
|
|
93
|
+
// (duplicate-property error). Instead `SearchParams<T>` / `Context<T>` fall back
|
|
94
|
+
// to the permissive default for any route the user hasn't augmented.
|
|
81
95
|
function searchParamsTypeLines(routes: Array<{ pattern: string }>): string {
|
|
82
|
-
// Route files may declare `export type SearchParams = { page: string }`.
|
|
83
|
-
// We emit a mapped type that falls back to Record<string,string> per route.
|
|
84
|
-
// Users augment via module augmentation or via their route file's export.
|
|
85
96
|
if (routes.length === 0) {
|
|
86
97
|
return "export type SearchParams<_T extends AppRoutes> = Record<string, string>;";
|
|
87
98
|
}
|
|
88
99
|
const branches = routes
|
|
89
100
|
.map((r) => {
|
|
90
101
|
assertSafePattern(r.pattern);
|
|
91
|
-
|
|
102
|
+
const key = JSON.stringify(r.pattern);
|
|
103
|
+
// Use `extends Record<K, infer V>` rather than `keyof` + index access:
|
|
104
|
+
// RouteSearchParamsMap may be `{}` (no user augmentation), and indexing an
|
|
105
|
+
// empty interface — even inside a `K extends keyof M` guard — trips
|
|
106
|
+
// TS2538 "cannot be used as an index type". The Record-infer form resolves
|
|
107
|
+
// V only when the route is augmented, and falls back otherwise.
|
|
108
|
+
return " T extends " + key +
|
|
109
|
+
" ? (RouteSearchParamsMap extends Record<" + key + ", infer V> ? V : Record<string, string>) :";
|
|
92
110
|
})
|
|
93
111
|
.join("\n");
|
|
94
|
-
const mapEntries = routes
|
|
95
|
-
.map((r) => " " + JSON.stringify(r.pattern) + ": Record<string, string>;")
|
|
96
|
-
.join("\n");
|
|
97
112
|
return [
|
|
98
|
-
"// Augment RouteSearchParamsMap to type search params
|
|
99
|
-
"//
|
|
100
|
-
"export interface RouteSearchParamsMap {",
|
|
101
|
-
mapEntries,
|
|
102
|
-
"}",
|
|
103
|
-
"",
|
|
113
|
+
"// Augment RouteSearchParamsMap (on the package) to type a route's search params:",
|
|
114
|
+
"// declare module \"@bractjs/bractjs\" { interface RouteSearchParamsMap { \"/blog\": { page: string } } }",
|
|
104
115
|
"export type SearchParams<T extends AppRoutes> =",
|
|
105
116
|
branches,
|
|
106
117
|
" Record<string, string>;",
|
|
107
118
|
].join("\n");
|
|
108
119
|
}
|
|
109
120
|
|
|
121
|
+
// Per-route VALIDATED search shapes, inferred from each route's `searchSchema`
|
|
122
|
+
// export via type-only `typeof import(...)`. Routes without a schema fall back
|
|
123
|
+
// to the user's RouteSearchParamsMap augmentation, then a permissive record.
|
|
124
|
+
// This map feeds `Register.routes.searchOutput` → `useSearch`/`useSetSearch`/
|
|
125
|
+
// `<Link search>`; the legacy string-valued `search` member is untouched.
|
|
126
|
+
function searchOutputTypeLines(routes: Array<{ pattern: string; filePath: string }>): string {
|
|
127
|
+
if (routes.length === 0) {
|
|
128
|
+
return "export type GeneratedSearchOutput = Record<never, never>;";
|
|
129
|
+
}
|
|
130
|
+
const entries = routes
|
|
131
|
+
.map((r) => {
|
|
132
|
+
assertSafePattern(r.pattern);
|
|
133
|
+
assertSafeFilePath(r.filePath);
|
|
134
|
+
const key = JSON.stringify(r.pattern);
|
|
135
|
+
const spec = JSON.stringify("./" + r.filePath.split("\\").join("/"));
|
|
136
|
+
return " " + key + ": typeof import(" + spec + ") extends { searchSchema: infer S }\n" +
|
|
137
|
+
" ? InferSchemaOutput<S>\n" +
|
|
138
|
+
" : (RouteSearchParamsMap extends Record<" + key + ", infer V> ? V : Record<string, unknown>);";
|
|
139
|
+
})
|
|
140
|
+
.join("\n");
|
|
141
|
+
return [
|
|
142
|
+
"// Validated search shape per route, inferred from `searchSchema` exports.",
|
|
143
|
+
"export type GeneratedSearchOutput = {",
|
|
144
|
+
entries,
|
|
145
|
+
"};",
|
|
146
|
+
"",
|
|
147
|
+
"/** Validated search object for a route — what `useSearch<T>()` returns. */",
|
|
148
|
+
"export type SearchOutput<T extends AppRoutes> =",
|
|
149
|
+
" T extends keyof GeneratedSearchOutput ? GeneratedSearchOutput[T] : Record<string, unknown>;",
|
|
150
|
+
].join("\n");
|
|
151
|
+
}
|
|
152
|
+
|
|
110
153
|
function contextTypeLines(routes: Array<{ pattern: string }>): string {
|
|
111
154
|
if (routes.length === 0) {
|
|
112
155
|
return "export type Context<_T extends AppRoutes> = Record<string, unknown>;";
|
|
@@ -114,31 +157,126 @@ function contextTypeLines(routes: Array<{ pattern: string }>): string {
|
|
|
114
157
|
const branches = routes
|
|
115
158
|
.map((r) => {
|
|
116
159
|
assertSafePattern(r.pattern);
|
|
117
|
-
|
|
160
|
+
const key = JSON.stringify(r.pattern);
|
|
161
|
+
// See SearchParams above for why this uses `extends Record<K, infer V>`.
|
|
162
|
+
return " T extends " + key +
|
|
163
|
+
" ? (RouteContextMap extends Record<" + key + ", infer V> ? V : Record<string, unknown>) :";
|
|
118
164
|
})
|
|
119
165
|
.join("\n");
|
|
120
|
-
const mapEntries = routes
|
|
121
|
-
.map((r) => " " + JSON.stringify(r.pattern) + ": Record<string, unknown>;")
|
|
122
|
-
.join("\n");
|
|
123
166
|
return [
|
|
124
|
-
"// Augment RouteContextMap to type
|
|
125
|
-
"//
|
|
126
|
-
"export interface RouteContextMap {",
|
|
127
|
-
mapEntries,
|
|
128
|
-
"}",
|
|
129
|
-
"",
|
|
167
|
+
"// Augment RouteContextMap (on the package) to type a route's context:",
|
|
168
|
+
"// declare module \"@bractjs/bractjs\" { interface RouteContextMap { \"/blog\": { user: User } } }",
|
|
130
169
|
"export type Context<T extends AppRoutes> =",
|
|
131
170
|
branches,
|
|
132
171
|
" Record<string, unknown>;",
|
|
133
172
|
].join("\n");
|
|
134
173
|
}
|
|
135
174
|
|
|
175
|
+
// The `Register` augmentation: this is what wires the app's routes into the
|
|
176
|
+
// package's runtime helpers (<Link>, useNavigate, useParams, useSearchParams).
|
|
177
|
+
function registerAugmentationLines(routes: Array<{ pattern: string; params: string[] }>): string {
|
|
178
|
+
const paramEntries = routes
|
|
179
|
+
.map((r) => {
|
|
180
|
+
assertSafePattern(r.pattern);
|
|
181
|
+
r.params.forEach(assertSafeParam);
|
|
182
|
+
const shape = r.params.length === 0
|
|
183
|
+
? "{}"
|
|
184
|
+
: "{ " + r.params.map((p) => p + ": string").join("; ") + " }";
|
|
185
|
+
return " " + JSON.stringify(r.pattern) + ": " + shape + ";";
|
|
186
|
+
})
|
|
187
|
+
.join("\n");
|
|
188
|
+
return [
|
|
189
|
+
"// Registers this app's routes with BractJS. After this augmentation, <Link>,",
|
|
190
|
+
"// useNavigate, useParams, and useSearchParams are type-safe against AppRoutes.",
|
|
191
|
+
"declare module \"@bractjs/bractjs\" {",
|
|
192
|
+
" interface Register {",
|
|
193
|
+
" routes: {",
|
|
194
|
+
" routes: AppRoutes;",
|
|
195
|
+
" params: {",
|
|
196
|
+
paramEntries,
|
|
197
|
+
" };",
|
|
198
|
+
" search: RouteSearchParamsMap;",
|
|
199
|
+
" searchOutput: GeneratedSearchOutput;",
|
|
200
|
+
" };",
|
|
201
|
+
" }",
|
|
202
|
+
"}",
|
|
203
|
+
].join("\n");
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// ── Freshness fingerprint ────────────────────────────────────────────────
|
|
207
|
+
// The generated file embeds a hash of its route patterns so the dev server can
|
|
208
|
+
// detect drift precisely (and skip rewrites when nothing changed, which would
|
|
209
|
+
// otherwise trigger an editor reload loop). Patterns are sorted everywhere so
|
|
210
|
+
// the output is identical across machines regardless of filesystem scan order.
|
|
211
|
+
|
|
212
|
+
const FINGERPRINT_RE = /^\/\/ bractjs:routes ([0-9a-f]+) \((\d+) routes?\)$/m;
|
|
213
|
+
|
|
214
|
+
/** Stable 8-hex fingerprint of a route-pattern set (order-independent). */
|
|
215
|
+
export function routesFingerprint(patterns: string[]): Promise<string> {
|
|
216
|
+
return hashString([...patterns].sort().join("\n"));
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Extract the fingerprint hash previously written into a generated file, or null. */
|
|
220
|
+
export function readFingerprint(src: string | null): string | null {
|
|
221
|
+
if (!src) return null;
|
|
222
|
+
const m = src.match(FINGERPRINT_RE);
|
|
223
|
+
return m ? m[1] : null;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* A precise human-readable reason the generated types are stale, or null when
|
|
228
|
+
* fresh. `patterns` must be colon-style (the form the generated file embeds);
|
|
229
|
+
* prefer {@link explainStalenessForApp} which derives them for you.
|
|
230
|
+
*/
|
|
231
|
+
export async function explainStaleness(
|
|
232
|
+
oldSrc: string | null,
|
|
233
|
+
patterns: string[],
|
|
234
|
+
): Promise<string | null> {
|
|
235
|
+
if (!oldSrc) return "route-types.gen.ts is missing — generating it";
|
|
236
|
+
const current = await routesFingerprint(patterns);
|
|
237
|
+
if (readFingerprint(oldSrc) === current) return null;
|
|
238
|
+
// Recover the old pattern set from the union members to report add/remove
|
|
239
|
+
// counts. The last member ends with `;`, so allow an optional trailing `;`.
|
|
240
|
+
const old = new Set(
|
|
241
|
+
[...oldSrc.matchAll(/^ {2}\| "([^"]+)";?$/gm)].map((m) => m[1]),
|
|
242
|
+
);
|
|
243
|
+
const now = new Set(patterns);
|
|
244
|
+
const added = patterns.filter((p) => !old.has(p)).length;
|
|
245
|
+
const removed = [...old].filter((p) => !now.has(p)).length;
|
|
246
|
+
const parts: string[] = [];
|
|
247
|
+
if (added) parts.push(`+${added} added`);
|
|
248
|
+
if (removed) parts.push(`-${removed} removed`);
|
|
249
|
+
const detail = parts.length ? ` (${parts.join(", ")})` : "";
|
|
250
|
+
return `routes changed since last codegen${detail} — regenerating`;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Colon-style route patterns for an app dir (the form the generated file uses). */
|
|
254
|
+
export async function routePatternsForApp(appDir: string): Promise<string[]> {
|
|
255
|
+
const routeFiles = await scanRoutes(appDir);
|
|
256
|
+
return routeFiles.map((r) => patternToColon(r.urlPattern));
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** {@link explainStaleness} against the current generated file + route set on disk. */
|
|
260
|
+
export async function explainStalenessForApp(
|
|
261
|
+
appDir: string,
|
|
262
|
+
outPath?: string,
|
|
263
|
+
): Promise<string | null> {
|
|
264
|
+
const dest = outPath ?? join(appDir, "route-types.gen.ts");
|
|
265
|
+
const existing = await Bun.file(dest).text().catch(() => null);
|
|
266
|
+
return explainStaleness(existing, await routePatternsForApp(appDir));
|
|
267
|
+
}
|
|
268
|
+
|
|
136
269
|
export async function generateRouteTypes(appDir: string): Promise<string> {
|
|
137
270
|
const routeFiles = await scanRoutes(appDir);
|
|
138
|
-
const routes = routeFiles
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
271
|
+
const routes = routeFiles
|
|
272
|
+
.map((r) => ({
|
|
273
|
+
pattern: patternToColon(r.urlPattern),
|
|
274
|
+
params: paramsFromSegments(r.segments),
|
|
275
|
+
filePath: r.filePath,
|
|
276
|
+
}))
|
|
277
|
+
// Deterministic order independent of filesystem scan order, so the output
|
|
278
|
+
// is byte-identical across machines (and the idempotent write works).
|
|
279
|
+
.sort((a, b) => a.pattern.localeCompare(b.pattern));
|
|
142
280
|
|
|
143
281
|
const union = routes.length > 0
|
|
144
282
|
? routes.map((r) => {
|
|
@@ -149,8 +287,22 @@ export async function generateRouteTypes(appDir: string): Promise<string> {
|
|
|
149
287
|
|
|
150
288
|
const builderEntries = routes.map((r) => builderEntry(r.pattern, r.params)).join("\n");
|
|
151
289
|
|
|
290
|
+
// `RouteSearchParamsMap` / `RouteContextMap` are imported from the package so
|
|
291
|
+
// the local `SearchParams<T>` / `Context<T>` reference the same interfaces the
|
|
292
|
+
// user augments via `declare module "@bractjs/bractjs"`. `InferSchemaOutput`
|
|
293
|
+
// derives each route's validated search shape from its `searchSchema` export.
|
|
294
|
+
const IMPORTS = 'import type { RouteSearchParamsMap, RouteContextMap, InferSchemaOutput } from "@bractjs/bractjs";';
|
|
295
|
+
|
|
296
|
+
// Freshness breadcrumb: lets the dev server detect drift without re-deriving
|
|
297
|
+
// the whole file, and lets writeRouteTypes skip identical writes.
|
|
298
|
+
const fingerprint = await routesFingerprint(routes.map((r) => r.pattern));
|
|
299
|
+
const FINGERPRINT = `// bractjs:routes ${fingerprint} (${routes.length} route${routes.length === 1 ? "" : "s"})`;
|
|
300
|
+
|
|
152
301
|
return [
|
|
153
302
|
HEADER,
|
|
303
|
+
FINGERPRINT,
|
|
304
|
+
IMPORTS,
|
|
305
|
+
"",
|
|
154
306
|
"export type AppRoutes =",
|
|
155
307
|
union + ";",
|
|
156
308
|
"",
|
|
@@ -158,16 +310,24 @@ export async function generateRouteTypes(appDir: string): Promise<string> {
|
|
|
158
310
|
"",
|
|
159
311
|
searchParamsTypeLines(routes),
|
|
160
312
|
"",
|
|
313
|
+
searchOutputTypeLines(routes),
|
|
314
|
+
"",
|
|
161
315
|
contextTypeLines(routes),
|
|
162
316
|
"",
|
|
163
317
|
"export type TypedLoaderArgs<T extends AppRoutes> = {",
|
|
164
318
|
" request: Request;",
|
|
165
319
|
" params: RouteParams<T>;",
|
|
166
320
|
" context: Context<T>;",
|
|
321
|
+
" search: T extends keyof GeneratedSearchOutput ? GeneratedSearchOutput[T] : Record<string, unknown>;",
|
|
167
322
|
"};",
|
|
168
323
|
"export type TypedActionArgs<T extends AppRoutes> =",
|
|
169
324
|
" TypedLoaderArgs<T> & { formData: FormData };",
|
|
170
325
|
"",
|
|
326
|
+
"/** Loader args fully typed for a route literal: `loader(args: LoaderArgsFor<\"/posts\">)`. */",
|
|
327
|
+
"export type LoaderArgsFor<T extends AppRoutes> = TypedLoaderArgs<T>;",
|
|
328
|
+
"/** Action args fully typed for a route literal: `action(args: ActionArgsFor<\"/posts\">)`. */",
|
|
329
|
+
"export type ActionArgsFor<T extends AppRoutes> = TypedActionArgs<T>;",
|
|
330
|
+
"",
|
|
171
331
|
"/** A locale-prefixed variant of a route (E2 i18n routing). */",
|
|
172
332
|
"export type LocalizedRoute<T extends AppRoutes> = `/${string}${T}`;",
|
|
173
333
|
"",
|
|
@@ -175,11 +335,23 @@ export async function generateRouteTypes(appDir: string): Promise<string> {
|
|
|
175
335
|
builderEntries,
|
|
176
336
|
"} as const;",
|
|
177
337
|
"",
|
|
338
|
+
// No routes → AppRoutes is `never`; nothing to register.
|
|
339
|
+
routes.length > 0 ? registerAugmentationLines(routes) : "",
|
|
340
|
+
"",
|
|
178
341
|
].join("\n");
|
|
179
342
|
}
|
|
180
343
|
|
|
181
|
-
export async function writeRouteTypes(
|
|
344
|
+
export async function writeRouteTypes(
|
|
345
|
+
appDir: string,
|
|
346
|
+
outPath?: string,
|
|
347
|
+
): Promise<{ dest: string; written: boolean }> {
|
|
182
348
|
const dest = outPath ?? join(appDir, "route-types.gen.ts");
|
|
183
|
-
|
|
349
|
+
const next = await generateRouteTypes(appDir);
|
|
350
|
+
// Skip the write (and the log, and the resulting file-watcher event) when the
|
|
351
|
+
// content is unchanged — otherwise auto-codegen in dev would loop the editor.
|
|
352
|
+
const existing = await Bun.file(dest).text().catch(() => null);
|
|
353
|
+
if (existing === next) return { dest, written: false };
|
|
354
|
+
await Bun.write(dest, next);
|
|
184
355
|
console.log("[bract] codegen →", dest);
|
|
356
|
+
return { dest, written: true };
|
|
185
357
|
}
|
package/src/config/load.ts
CHANGED
|
@@ -25,6 +25,7 @@ export function validateUserConfig(cfg: unknown): Partial<BractJSConfig> {
|
|
|
25
25
|
};
|
|
26
26
|
|
|
27
27
|
check("port", typeof c.port === "number" && Number.isFinite(c.port), "a finite number");
|
|
28
|
+
check("hmrPort", typeof c.hmrPort === "number" && Number.isFinite(c.hmrPort), "a finite number");
|
|
28
29
|
check("appDir", typeof c.appDir === "string", "a string");
|
|
29
30
|
check("publicDir", typeof c.publicDir === "string", "a string");
|
|
30
31
|
check("buildDir", typeof c.buildDir === "string", "a string");
|
|
@@ -45,10 +46,30 @@ export function validateUserConfig(cfg: unknown): Partial<BractJSConfig> {
|
|
|
45
46
|
check("onStart", typeof c.onStart === "function", "a function");
|
|
46
47
|
check("onShutdown", typeof c.onShutdown === "function", "a function");
|
|
47
48
|
check("onError", typeof c.onError === "function", "a function");
|
|
49
|
+
check("ssr", typeof c.ssr === "boolean", "a boolean");
|
|
50
|
+
check(
|
|
51
|
+
"prerender",
|
|
52
|
+
typeof c.prerender === "function" ||
|
|
53
|
+
(Array.isArray(c.prerender) && c.prerender.every((p) => typeof p === "string")),
|
|
54
|
+
"an array of paths or a function returning one",
|
|
55
|
+
);
|
|
48
56
|
|
|
49
57
|
return c as Partial<BractJSConfig>;
|
|
50
58
|
}
|
|
51
59
|
|
|
60
|
+
/**
|
|
61
|
+
* Identity helper for `bractjs.config.ts` — wrap your default export to get
|
|
62
|
+
* autocomplete and type-checking on the config fields (no runtime effect):
|
|
63
|
+
*
|
|
64
|
+
* ```ts
|
|
65
|
+
* import { defineConfig } from "@bractjs/bractjs";
|
|
66
|
+
* export default defineConfig({ port: 3000, clientEnv: ["PUBLIC_API_URL"] });
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
export function defineConfig(config: Partial<BractJSConfig>): Partial<BractJSConfig> {
|
|
70
|
+
return config;
|
|
71
|
+
}
|
|
72
|
+
|
|
52
73
|
/**
|
|
53
74
|
* Load `bractjs.config.ts` (or `.js`) from the user's cwd if present.
|
|
54
75
|
* Returns an empty object when no file exists — callers fall back to defaults.
|
package/src/dev/hmr-client.ts
CHANGED
|
@@ -23,7 +23,9 @@ export const hmrClientScript: string = `
|
|
|
23
23
|
}
|
|
24
24
|
|
|
25
25
|
function connect() {
|
|
26
|
-
|
|
26
|
+
// Port published by the server's dev bootstrap (config hmrPort), else 3001.
|
|
27
|
+
var port = window.__BRACTJS_HMR_PORT__ || 3001;
|
|
28
|
+
var ws = new WebSocket("ws://localhost:" + port);
|
|
27
29
|
ws.onmessage = function (event) {
|
|
28
30
|
try {
|
|
29
31
|
var msg = JSON.parse(event.data);
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export interface RouteTableRow {
|
|
2
|
+
pattern: string;
|
|
3
|
+
file: string;
|
|
4
|
+
hasLoader: boolean;
|
|
5
|
+
hasAction: boolean;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Render a compact route inventory for the dev server boot log, so a developer
|
|
10
|
+
* can see at a glance what routes the app matched (and which have data/mutation
|
|
11
|
+
* handlers). Pure string formatting — no I/O.
|
|
12
|
+
*/
|
|
13
|
+
export function formatRouteTable(rows: RouteTableRow[]): string {
|
|
14
|
+
if (rows.length === 0) return "[bractjs] no routes found under routes/";
|
|
15
|
+
const sorted = [...rows].sort((a, b) => a.pattern.localeCompare(b.pattern));
|
|
16
|
+
const patternWidth = Math.max(7, ...sorted.map((r) => r.pattern.length));
|
|
17
|
+
const lines = sorted.map((r) => {
|
|
18
|
+
const markers = [r.hasLoader ? "loader" : "", r.hasAction ? "action" : ""]
|
|
19
|
+
.filter(Boolean)
|
|
20
|
+
.join(" ");
|
|
21
|
+
return ` ${r.pattern.padEnd(patternWidth)} ${markers.padEnd(13)} ${r.file}`;
|
|
22
|
+
});
|
|
23
|
+
return [
|
|
24
|
+
`[bractjs] ${rows.length} route${rows.length === 1 ? "" : "s"}:`,
|
|
25
|
+
...lines,
|
|
26
|
+
].join("\n");
|
|
27
|
+
}
|
package/src/dev/server.ts
CHANGED
|
@@ -1,13 +1,66 @@
|
|
|
1
1
|
import { createServer } from "../server/serve.ts";
|
|
2
|
-
import { setRuntimeMode } from "../server/env.ts";
|
|
2
|
+
import { setRuntimeMode, setDevHmrPort } from "../server/env.ts";
|
|
3
3
|
import { createHmrServer } from "./hmr-server.ts";
|
|
4
4
|
import { watchApp } from "./watcher.ts";
|
|
5
5
|
import { rebuildClient } from "./rebuilder.ts";
|
|
6
|
-
import { filePathToPattern } from "../server/scanner.ts";
|
|
7
|
-
import { basename, extname } from "node:path";
|
|
6
|
+
import { filePathToPattern, scanRoutes } from "../server/scanner.ts";
|
|
7
|
+
import { basename, extname, join, resolve } from "node:path";
|
|
8
8
|
import type { LifecycleHooks } from "../server/lifecycle.ts";
|
|
9
9
|
import { loadUserConfig } from "../config/load.ts";
|
|
10
10
|
import type { BractJSConfig } from "../server/serve.ts";
|
|
11
|
+
import { writeRouteTypes, explainStalenessForApp } from "../codegen/route-codegen.ts";
|
|
12
|
+
import { lintRouteModuleSource } from "../build/route-lint.ts";
|
|
13
|
+
import { formatRouteTable, type RouteTableRow } from "./route-table.ts";
|
|
14
|
+
|
|
15
|
+
// Warn-once across HMR rebuilds so the same lint message doesn't spam the log.
|
|
16
|
+
const warnedRouteIssues = new Set<string>();
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Statically lint route modules and print the route table. Reads each route
|
|
20
|
+
* file's source once (no module execution, no per-request cost). Returns the
|
|
21
|
+
* table rows so the boot path can print them alongside the HMR port.
|
|
22
|
+
*/
|
|
23
|
+
async function inspectRoutes(appDir: string): Promise<RouteTableRow[]> {
|
|
24
|
+
const routes = await scanRoutes(appDir);
|
|
25
|
+
const rows: RouteTableRow[] = [];
|
|
26
|
+
for (const r of routes) {
|
|
27
|
+
let src = "";
|
|
28
|
+
try {
|
|
29
|
+
src = await Bun.file(resolve(process.cwd(), appDir, r.filePath)).text();
|
|
30
|
+
} catch {
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
for (const warning of lintRouteModuleSource(src, r.filePath)) {
|
|
34
|
+
const key = r.filePath + "\0" + warning;
|
|
35
|
+
if (warnedRouteIssues.has(key)) continue;
|
|
36
|
+
warnedRouteIssues.add(key);
|
|
37
|
+
console.warn(`[bractjs] ${warning}`);
|
|
38
|
+
}
|
|
39
|
+
rows.push({
|
|
40
|
+
pattern: r.urlPattern === "" ? "/" : "/" + r.urlPattern,
|
|
41
|
+
file: r.filePath,
|
|
42
|
+
hasLoader: /^export\s+(?:async\s+)?function\s+loader\b|^export\s+const\s+loader\b/m.test(src),
|
|
43
|
+
hasAction: /^export\s+(?:async\s+)?function\s+action\b|^export\s+const\s+action\b/m.test(src),
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
return rows;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Regenerate typed routes if the route set drifted from the last codegen.
|
|
51
|
+
* Idempotent: writeRouteTypes skips the write when content is unchanged, so it
|
|
52
|
+
* never triggers an editor reload loop. Runs at boot and on add/remove/rename.
|
|
53
|
+
*/
|
|
54
|
+
async function syncRouteTypes(appDir: string): Promise<void> {
|
|
55
|
+
try {
|
|
56
|
+
const reason = await explainStalenessForApp(appDir);
|
|
57
|
+
if (reason) console.log(`[bractjs] ${reason}`);
|
|
58
|
+
await writeRouteTypes(appDir);
|
|
59
|
+
} catch (err) {
|
|
60
|
+
// Codegen is a DX aid, never fatal to the dev loop.
|
|
61
|
+
console.warn("[bractjs] route codegen skipped:", err instanceof Error ? err.message : err);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
11
64
|
|
|
12
65
|
export interface DevServerOptions {
|
|
13
66
|
/** HTTP port for the app server. Default: config.port ?? 3000. */
|
|
@@ -38,15 +91,42 @@ export async function createDevServer(options?: DevServerOptions): Promise<DevSe
|
|
|
38
91
|
// for any source-import path, dev or `bractjs start`), so no separate dev hook
|
|
39
92
|
// is needed here.
|
|
40
93
|
|
|
41
|
-
const hmrPort = options?.hmrPort ?? 3001;
|
|
94
|
+
const hmrPort = options?.hmrPort ?? merged.hmrPort ?? 3001;
|
|
42
95
|
const appPort = options?.port ?? merged.port ?? 3000;
|
|
96
|
+
// Publish the port so the SSR dev bootstrap tells the HMR client where to connect.
|
|
97
|
+
setDevHmrPort(hmrPort);
|
|
98
|
+
|
|
99
|
+
const appDir = merged.appDir ?? "./app";
|
|
43
100
|
|
|
44
|
-
|
|
101
|
+
// Keep typed routes fresh on boot (covers "added a route while the server was
|
|
102
|
+
// down"). Idempotent — no-op write when nothing changed.
|
|
103
|
+
await syncRouteTypes(appDir);
|
|
104
|
+
|
|
105
|
+
// Friendly port-conflict message instead of a raw Bun EADDRINUSE stack.
|
|
106
|
+
const onPortInUse = (which: "app server" | "HMR socket", port: number): never => {
|
|
107
|
+
console.error(
|
|
108
|
+
`[bractjs] Port ${port} is already in use (${which}). ` +
|
|
109
|
+
`Set \`port\` (and \`hmrPort\` for the HMR socket) in bractjs.config.ts, ` +
|
|
110
|
+
`or stop the process using it.`,
|
|
111
|
+
);
|
|
112
|
+
return process.exit(1);
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
let hmr: ReturnType<typeof createHmrServer>;
|
|
116
|
+
try {
|
|
117
|
+
hmr = createHmrServer(hmrPort);
|
|
118
|
+
} catch (err) {
|
|
119
|
+
if ((err as { code?: string }).code === "EADDRINUSE") onPortInUse("HMR socket", hmrPort);
|
|
120
|
+
throw err;
|
|
121
|
+
}
|
|
45
122
|
|
|
46
123
|
// Build client bundle before the HTTP server starts accepting requests
|
|
47
124
|
const { duration: initialMs } = await rebuildClient(merged);
|
|
48
125
|
console.log(`[bractjs] initial client build in ${initialMs}ms`);
|
|
49
126
|
|
|
127
|
+
// Lint route modules + collect the route table (read sources once, no exec).
|
|
128
|
+
const routeRows = await inspectRoutes(appDir);
|
|
129
|
+
|
|
50
130
|
// Load user lifecycle hooks if defined (e.g. app/lifecycle.ts)
|
|
51
131
|
let lifecycle: LifecycleHooks = {};
|
|
52
132
|
try {
|
|
@@ -57,9 +137,26 @@ export async function createDevServer(options?: DevServerOptions): Promise<DevSe
|
|
|
57
137
|
// No lifecycle file — that's fine
|
|
58
138
|
}
|
|
59
139
|
|
|
60
|
-
|
|
140
|
+
let srv: ReturnType<typeof createServer>;
|
|
141
|
+
try {
|
|
142
|
+
srv = createServer({ port: appPort, ...merged, ...lifecycle });
|
|
143
|
+
} catch (err) {
|
|
144
|
+
hmr.stop();
|
|
145
|
+
if ((err as { code?: string }).code === "EADDRINUSE") onPortInUse("app server", appPort);
|
|
146
|
+
throw err;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
watchApp(appDir, async (file, info) => {
|
|
150
|
+
// Add/remove/rename of a route file changes the route set → regenerate
|
|
151
|
+
// typed routes. Saves (content changes) never alter the generated output
|
|
152
|
+
// (it uses type-only `typeof import(...)`), so skip codegen on those.
|
|
153
|
+
if (info.renameSeen && file.startsWith("routes/")) {
|
|
154
|
+
await syncRouteTypes(appDir);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Re-lint changed route modules (warn-once dedupes repeats).
|
|
158
|
+
if (file.startsWith("routes/")) await inspectRoutes(appDir);
|
|
61
159
|
|
|
62
|
-
watchApp(merged.appDir ?? "./app", async (file) => {
|
|
63
160
|
const { duration } = await rebuildClient(merged);
|
|
64
161
|
|
|
65
162
|
// Route files (not layout): do a fine-grained module swap without full reload.
|
|
@@ -81,7 +178,8 @@ export async function createDevServer(options?: DevServerOptions): Promise<DevSe
|
|
|
81
178
|
}
|
|
82
179
|
});
|
|
83
180
|
|
|
84
|
-
console.log(
|
|
181
|
+
console.log(formatRouteTable(routeRows));
|
|
182
|
+
console.log(`BractJS dev server on http://localhost:${appPort} (HMR ws://localhost:${hmrPort})`);
|
|
85
183
|
|
|
86
184
|
return {
|
|
87
185
|
stop() {
|
package/src/dev/watcher.ts
CHANGED
|
@@ -3,21 +3,42 @@ import { watch } from "node:fs";
|
|
|
3
3
|
|
|
4
4
|
const WATCHED_EXTENSIONS = new Set([".tsx", ".ts", ".css"]);
|
|
5
5
|
|
|
6
|
+
/** Extra info about a debounced change burst. */
|
|
7
|
+
export interface WatchChangeInfo {
|
|
8
|
+
/** The last file event type seen in the burst. */
|
|
9
|
+
event: "rename" | "change";
|
|
10
|
+
/**
|
|
11
|
+
* True when ANY event in the burst was a "rename" (add/remove/rename) — not
|
|
12
|
+
* just the last one. `fs.watch` collapses bursts, so this is OR-accumulated
|
|
13
|
+
* across the debounce window; the codegen trigger keys on it.
|
|
14
|
+
*/
|
|
15
|
+
renameSeen: boolean;
|
|
16
|
+
}
|
|
17
|
+
|
|
6
18
|
/**
|
|
7
19
|
* Watches appDir for file changes and calls onChange with the changed file path.
|
|
8
20
|
* Debounces rapid changes within 50ms to avoid duplicate rebuilds.
|
|
9
21
|
*/
|
|
10
|
-
export function watchApp(
|
|
22
|
+
export function watchApp(
|
|
23
|
+
appDir: string,
|
|
24
|
+
onChange: (file: string, info: WatchChangeInfo) => void,
|
|
25
|
+
): void {
|
|
11
26
|
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
|
|
12
27
|
let pendingFile = "";
|
|
28
|
+
let lastEvent: "rename" | "change" = "change";
|
|
29
|
+
let renameSeen = false;
|
|
13
30
|
|
|
14
|
-
watch(appDir, { recursive: true }, (
|
|
31
|
+
watch(appDir, { recursive: true }, (eventType, filename) => {
|
|
15
32
|
if (!filename) return;
|
|
16
33
|
|
|
17
34
|
const ext = path.extname(filename);
|
|
18
35
|
if (!WATCHED_EXTENSIONS.has(ext)) return;
|
|
19
36
|
|
|
20
37
|
pendingFile = filename;
|
|
38
|
+
lastEvent = eventType === "rename" ? "rename" : "change";
|
|
39
|
+
// OR-accumulate across the debounce window: a save (change) immediately
|
|
40
|
+
// followed by a create (rename) must not lose the rename signal.
|
|
41
|
+
if (lastEvent === "rename") renameSeen = true;
|
|
21
42
|
|
|
22
43
|
if (debounceTimer !== null) {
|
|
23
44
|
clearTimeout(debounceTimer);
|
|
@@ -26,7 +47,8 @@ export function watchApp(appDir: string, onChange: (file: string) => void): void
|
|
|
26
47
|
debounceTimer = setTimeout(() => {
|
|
27
48
|
debounceTimer = null;
|
|
28
49
|
console.log(`✓ ${path.basename(pendingFile)} changed`);
|
|
29
|
-
onChange(pendingFile);
|
|
50
|
+
onChange(pendingFile, { event: lastEvent, renameSeen });
|
|
51
|
+
renameSeen = false;
|
|
30
52
|
}, 50);
|
|
31
53
|
});
|
|
32
54
|
}
|