@sigil-dev/grimoire 0.9.3 → 0.9.4

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.
@@ -8,7 +8,11 @@ export interface MatchedRoute {
8
8
  pageServer?: RouteFile;
9
9
  }
10
10
 
11
- export function matchRoute(tree: RouteTree, url: URL): MatchedRoute | null {
11
+ export function matchRoute(
12
+ tree: RouteTree,
13
+ url: URL,
14
+ matchers?: Record<string, (value: string) => boolean>,
15
+ ): MatchedRoute | null {
12
16
  const pathname = url.pathname;
13
17
 
14
18
  // check server routes first
@@ -29,6 +33,16 @@ export function matchRoute(tree: RouteTree, url: URL): MatchedRoute | null {
29
33
  const params = matchPattern(route.path, pathname);
30
34
  if (params === null) continue;
31
35
 
36
+ // [param=matcher] validation — a false matcher rejects the route
37
+ let matched = true;
38
+ for (const [param, name] of Object.entries(route.paramMatchers ?? {})) {
39
+ const fn = matchers?.[name];
40
+ if (!fn || !fn(params[param] ?? "")) {
41
+ matched = false;
42
+ break;
43
+ }
44
+ }
45
+ if (!matched) continue;
32
46
  // find applicable layouts by matching route pattern prefix, not URL pathname.
33
47
  // pathname.startsWith(l.path) would fail for parameterized layouts like /w/:workspace.
34
48
  const layoutMatches = (l: RouteFile) =>
@@ -81,29 +95,41 @@ function matchPattern(
81
95
  const pathParts = pathname.split("/").filter(Boolean);
82
96
 
83
97
  const params: Record<string, string> = {};
84
- let pi = 0;
85
- let pj = 0;
86
- while (pi < patternParts.length) {
98
+
99
+ // Depth-first walk over (patternIndex, pathIndex). Optional segments try
100
+ // consuming one path segment first, then zero — so /[[lang]]/about matches
101
+ // both /en/about and /about.
102
+ function walk(pi: number, pj: number): boolean {
103
+ if (pi === patternParts.length) return pj === pathParts.length;
87
104
  const patternPart = patternParts[pi]!;
88
105
 
89
106
  if (patternPart.startsWith("*")) {
90
- // Rest param — captures zero or more remaining path segments joined by "/".
107
+ // Rest param — captures zero or more remaining segments joined by "/".
91
108
  // Rest must be the last segment in the pattern.
92
109
  params[patternPart.slice(1)] = pathParts.slice(pj).join("/");
93
- return params;
110
+ return true;
94
111
  }
95
112
 
96
- if (pj >= pathParts.length) return null;
97
- const pathPart = pathParts[pj]!;
113
+ const optional = /^:(.+)\?$/.exec(patternPart);
114
+ if (optional) {
115
+ const name = optional[1]!;
116
+ if (pj < pathParts.length) {
117
+ params[name] = pathParts[pj]!;
118
+ if (walk(pi + 1, pj + 1)) return true;
119
+ delete params[name];
120
+ }
121
+ return walk(pi + 1, pj);
122
+ }
123
+
124
+ if (pj >= pathParts.length) return false;
98
125
 
99
126
  if (patternPart.startsWith(":")) {
100
- params[patternPart.slice(1)] = pathPart;
101
- } else if (patternPart !== pathPart) {
102
- return null;
127
+ params[patternPart.slice(1)] = pathParts[pj]!;
128
+ return walk(pi + 1, pj + 1);
103
129
  }
104
- pi++;
105
- pj++;
130
+ if (patternPart !== pathParts[pj]) return false;
131
+ return walk(pi + 1, pj + 1);
106
132
  }
107
- if (pj < pathParts.length) return null;
108
- return params;
133
+
134
+ return walk(0, 0) ? params : null;
109
135
  }
@@ -1,3 +1,4 @@
1
+ import { existsSync } from "node:fs";
1
2
  import { basename, join, relative } from "node:path";
2
3
 
3
4
  export interface RouteFile {
@@ -13,7 +14,16 @@ export interface RouteFile {
13
14
  | "error"
14
15
  | "simple";
15
16
  paramNames: string[]; // ["slug"] in /blog/:slug
17
+ optionalParamNames: string[]; // ["lang"] in /[[lang]]
16
18
  restParamNames: string[]; // ["rest"] in /blog/*rest
19
+ /** param name → matcher name; ["id"] → "int" for /post/[id=int] */
20
+ paramMatchers: Record<string, string>;
21
+ }
22
+
23
+ /** A src/params/<name>.ts module exporting match(value: string): boolean. */
24
+ export interface ParamMatcherFile {
25
+ name: string;
26
+ filePath: string;
17
27
  }
18
28
 
19
29
  export interface RouteTree {
@@ -21,12 +31,19 @@ export interface RouteTree {
21
31
  layouts: RouteFile[]; // layout + layout.server
22
32
  servers: RouteFile[]; // +server.ts API routes
23
33
  errors: RouteFile[]; // +error.tsx
34
+ paramMatcherFiles: ParamMatcherFile[]; // from src/params/*.ts
24
35
  }
25
36
 
26
37
  export function filePathToRoutePath(
27
38
  filePath: string,
28
39
  routesDir: string,
29
- ): { pattern: string; params: string[]; restParams: string[] } {
40
+ ): {
41
+ pattern: string;
42
+ params: string[];
43
+ optionalParams: string[];
44
+ restParams: string[];
45
+ paramMatchers: Record<string, string>;
46
+ } {
30
47
  const rel = relative(routesDir, filePath)
31
48
  .replace(/\\/g, "/")
32
49
  .replace(/\.(tsx?|jsx?)$/, "")
@@ -34,11 +51,24 @@ export function filePathToRoutePath(
34
51
  .replace(/\/+/g, "/"); // collapse double slashes
35
52
 
36
53
  const params: string[] = [];
54
+ const optionalParams: string[] = [];
37
55
  const restParams: string[] = [];
56
+ const paramMatchers: Record<string, string> = {};
38
57
  const pattern =
39
58
  rel
40
59
  .replace(/\/?(\+\w+(\.\w+)?|index)$/, "") // index/+page → directory
41
- .replace(/\[(\.\.\.)?([^\]]+)\]/g, (_, dots, name) => {
60
+ // [[param]] → :param? (must run before [param] — [[x]] contains [x])
61
+ .replace(/\[\[([^\]]+)\]\]/g, (_, name: string) => {
62
+ optionalParams.push(name);
63
+ return `:${name}?`;
64
+ })
65
+ // [param=matcher] → :param with a validation matcher (before [param])
66
+ .replace(/\[([^\]=]+)=([^\]=]+)\]/g, (_, name: string, matcher: string) => {
67
+ params.push(name);
68
+ paramMatchers[name] = matcher;
69
+ return `:${name}`;
70
+ })
71
+ .replace(/\[(\.\.\.)?([^\]]+)\]/g, (_, dots: string, name: string) => {
42
72
  // [...rest] → *rest (captures zero or more remaining path segments)
43
73
  if (dots) {
44
74
  restParams.push(name);
@@ -51,7 +81,7 @@ export function filePathToRoutePath(
51
81
  .replace(/^\/?/, "/") || // ensure leading slash
52
82
  "/";
53
83
 
54
- return { pattern, params, restParams };
84
+ return { pattern, params, optionalParams, restParams, paramMatchers };
55
85
  }
56
86
 
57
87
  export async function scanRoutes(
@@ -64,13 +94,24 @@ export async function scanRoutes(
64
94
  const servers: RouteFile[] = [];
65
95
  const errors: RouteFile[] = [];
66
96
 
97
+ // convention: src/params/<name>.ts sits beside src/routes
98
+ const paramsDir = join(routesDir, "..", "params");
99
+ const paramMatcherFiles: ParamMatcherFile[] = [];
100
+ if (existsSync(paramsDir)) {
101
+ const paramGlob = new Bun.Glob("*.{ts,js}");
102
+ for await (const file of paramGlob.scan(paramsDir)) {
103
+ paramMatcherFiles.push({
104
+ name: basename(file).replace(/\.(ts|js)$/, ""),
105
+ filePath: join(paramsDir, file),
106
+ });
107
+ }
108
+ }
109
+
67
110
  for await (const file of glob.scan(routesDir)) {
68
111
  const filePath = join(routesDir, file);
69
112
  const name = basename(file).replace(/\.(tsx?|jsx?)$/, "");
70
- const { pattern, params, restParams } = filePathToRoutePath(
71
- filePath,
72
- routesDir,
73
- );
113
+ const { pattern, params, optionalParams, restParams, paramMatchers } =
114
+ filePathToRoutePath(filePath, routesDir);
74
115
 
75
116
  let type: RouteFile["type"];
76
117
  if (name === "+page") type = "page";
@@ -89,7 +130,9 @@ export async function scanRoutes(
89
130
  clientPath, // add this
90
131
  type,
91
132
  paramNames: params,
133
+ optionalParamNames: optionalParams,
92
134
  restParamNames: restParams,
135
+ paramMatchers,
93
136
  };
94
137
 
95
138
  if (type === "simple" || type === "page" || type === "pageServer")
@@ -99,9 +142,12 @@ export async function scanRoutes(
99
142
  if (type === "error") errors.push(routeFile);
100
143
  }
101
144
 
102
- // sort so static routes match before dynamic ones, rest params last
145
+ // sort so static routes match before dynamic ones; optional params sort
146
+ // between static and required; rest params last
103
147
  const scoreRoute = (r: RouteFile) =>
104
- r.paramNames.length + r.restParamNames.length * 1000;
148
+ r.paramNames.length * 2 +
149
+ r.optionalParamNames.length +
150
+ r.restParamNames.length * 1000;
105
151
  routes.sort((a, b) => scoreRoute(a) - scoreRoute(b));
106
152
  servers.sort((a, b) => scoreRoute(a) - scoreRoute(b));
107
153
 
@@ -124,7 +170,7 @@ export async function scanRoutes(
124
170
  assertNoDuplicatePaths(servers, "API route");
125
171
  assertNoDuplicatePaths(errors, "error page");
126
172
 
127
- return { routes, layouts, servers, errors };
173
+ return { routes, layouts, servers, errors, paramMatcherFiles };
128
174
  }
129
175
 
130
176
  function assertNoDuplicatePaths(files: RouteFile[], label: string): void {
@@ -65,8 +65,14 @@ export async function rebuildForChange(
65
65
  transformRoutes(allClientRoutes, compiledDir, "dom", plugins),
66
66
  ]);
67
67
  await Promise.all([
68
- Bun.write(hydrateManifest, generateManifest(allClientRoutes, allHFiles)),
69
- Bun.write(domManifest, generateManifest(allClientRoutes, allDFiles)),
68
+ Bun.write(
69
+ hydrateManifest,
70
+ generateManifest(allClientRoutes, allHFiles, tree.paramMatcherFiles),
71
+ ),
72
+ Bun.write(
73
+ domManifest,
74
+ generateManifest(allClientRoutes, allDFiles, tree.paramMatcherFiles),
75
+ ),
70
76
  ]);
71
77
  }
72
78
 
@@ -156,8 +162,14 @@ export async function buildProject(
156
162
  const hydrateManifest = join(process.cwd(), ".grimoire/_routes.hydrate.js");
157
163
  const domManifest = join(process.cwd(), ".grimoire/_routes.dom.js");
158
164
  await Promise.all([
159
- Bun.write(hydrateManifest, generateManifest(clientRoutes, hydrateFiles)),
160
- Bun.write(domManifest, generateManifest(clientRoutes, domFiles)),
165
+ Bun.write(
166
+ hydrateManifest,
167
+ generateManifest(clientRoutes, hydrateFiles, tree.paramMatcherFiles),
168
+ ),
169
+ Bun.write(
170
+ domManifest,
171
+ generateManifest(clientRoutes, domFiles, tree.paramMatcherFiles),
172
+ ),
161
173
  ]);
162
174
 
163
175
  const resolvedAlias = makeAliases(config);
@@ -150,6 +150,19 @@ export async function createServer(config: GrimoireConfig = {}) {
150
150
  const loader = dev
151
151
  ? makeDevLoader(graph, process.cwd())
152
152
  : (p: string) => import(p);
153
+
154
+ // [param=matcher] validation — load src/params/*.ts once at startup
155
+ const paramMatcherFns: Record<string, (value: string) => boolean> = {};
156
+ for (const pm of tree.paramMatcherFiles ?? []) {
157
+ try {
158
+ const mod = await loader(pm.filePath);
159
+ if (typeof mod.match === "function") {
160
+ paramMatcherFns[pm.name] = mod.match;
161
+ }
162
+ } catch (e) {
163
+ logger.warn(`failed to load param matcher "${pm.name}":`, e);
164
+ }
165
+ }
153
166
  // Load hooks.server.ts
154
167
  const {
155
168
  handle: hooksHandle,
@@ -364,8 +377,7 @@ export async function createServer(config: GrimoireConfig = {}) {
364
377
  };
365
378
  const resolve: ResolveFunction = async (evt) => {
366
379
  // matching happens here — after handle() has run
367
- const matched = matchRoute(tree, evt.url);
368
-
380
+ const matched = matchRoute(tree, evt.url, paramMatcherFns);
369
381
  if (!matched) {
370
382
  const error = findClosestError(tree.errors, evt.url.pathname);
371
383
  if (error) {
@@ -435,6 +447,17 @@ export async function createServer(config: GrimoireConfig = {}) {
435
447
  ) {
436
448
  const mod = await loader(matched.pageServer.filePath);
437
449
 
450
+ // named actions: ?/create dispatches export `create`
451
+ const actionName = [...evt.url.searchParams.keys()]
452
+ .find((k) => k.startsWith("/"))
453
+ ?.slice(1);
454
+ const handler = actionName
455
+ ? mod[actionName]
456
+ : mod[evt.request.method];
457
+ if (actionName && !handler) {
458
+ return new Response("Not Found", { status: 404 });
459
+ }
460
+
438
461
  if (
439
462
  mod.csrf !== false &&
440
463
  evt.request.method !== "GET" &&
@@ -450,8 +473,6 @@ export async function createServer(config: GrimoireConfig = {}) {
450
473
  return new Response("Forbidden", { status: 403 });
451
474
  }
452
475
  }
453
-
454
- const handler = mod[evt.request.method];
455
476
  if (handler) {
456
477
  let result: any;
457
478
  try {
@@ -461,6 +482,7 @@ export async function createServer(config: GrimoireConfig = {}) {
461
482
  url: evt.url,
462
483
  locals: evt.locals,
463
484
  fetch: patchedFetch,
485
+ cookies,
464
486
  });
465
487
  } catch (e) {
466
488
  if (isRedirectResult(e)) {
@@ -512,7 +534,7 @@ export async function createServer(config: GrimoireConfig = {}) {
512
534
  headers: { Location: redirectTo },
513
535
  });
514
536
  }
515
- if (evt.request.method !== "GET") {
537
+ if (!actionName && evt.request.method !== "GET") {
516
538
  return new Response("Method Not Allowed", { status: 405 });
517
539
  }
518
540
  }
@@ -12,6 +12,7 @@ export interface TypegenConfig {
12
12
  export interface RouteGroup {
13
13
  dir: string;
14
14
  paramNames: string[];
15
+ optionalParamNames: string[];
15
16
  restParamNames: string[];
16
17
  page?: RouteFile;
17
18
  pageServer?: RouteFile;
@@ -50,6 +51,7 @@ export function groupByDirectory(tree: RouteTree): Map<string, RouteGroup> {
50
51
  groups.set(dir, {
51
52
  dir,
52
53
  paramNames: file.paramNames,
54
+ optionalParamNames: file.optionalParamNames,
53
55
  restParamNames: file.restParamNames,
54
56
  });
55
57
  }
@@ -57,6 +59,9 @@ export function groupByDirectory(tree: RouteTree): Map<string, RouteGroup> {
57
59
  if (file.paramNames.length > g.paramNames.length) {
58
60
  g.paramNames = file.paramNames;
59
61
  }
62
+ if (file.optionalParamNames.length > g.optionalParamNames.length) {
63
+ g.optionalParamNames = file.optionalParamNames;
64
+ }
60
65
  if (file.restParamNames.length > g.restParamNames.length) {
61
66
  g.restParamNames = file.restParamNames;
62
67
  }
@@ -93,12 +98,16 @@ export function toImportPath(from: string, to: string): string {
93
98
 
94
99
  export function buildParams(
95
100
  paramNames: string[],
101
+ optionalParamNames: string[] = [],
96
102
  restParamNames: string[] = [],
97
103
  ): string {
98
- const all = [...paramNames, ...restParamNames];
104
+ const all = [
105
+ ...paramNames.map((p) => ` ${p}: string;`),
106
+ ...optionalParamNames.map((p) => ` ${p}: string | undefined;`),
107
+ ...restParamNames.map((p) => ` ${p}: string;`),
108
+ ];
99
109
  if (all.length === 0) return "{}";
100
- const props = all.map((p) => ` ${p}: string;`).join("\n");
101
- return `{\n${props}\n}`;
110
+ return `{\n${all.join("\n")}\n}`;
102
111
  }
103
112
 
104
113
  function generateTypesForGroup(group: RouteGroup, outFileDir: string): string {
@@ -107,7 +116,11 @@ function generateTypesForGroup(group: RouteGroup, outFileDir: string): string {
107
116
  "",
108
117
  ];
109
118
 
110
- const paramsType = buildParams(group.paramNames, group.restParamNames);
119
+ const paramsType = buildParams(
120
+ group.paramNames,
121
+ group.optionalParamNames,
122
+ group.restParamNames,
123
+ );
111
124
 
112
125
  // --- Params ---
113
126
  lines.push(`export type Params = ${paramsType};`, "");
@@ -136,11 +149,25 @@ function generateTypesForGroup(group: RouteGroup, outFileDir: string): string {
136
149
  ` request: Request;`,
137
150
  ` url: URL;`,
138
151
  ` locals: App.Locals;`,
152
+ ` parent: () => Promise<Record<string, unknown>>;`,
139
153
  `}) => Record<string, unknown> | Promise<Record<string, unknown>>;`,
140
154
  "",
141
155
  );
142
156
  // Actions — all exports except load and default
143
157
  lines.push(
158
+ `type ActionCookies = {`,
159
+ ` get(name: string): string | undefined;`,
160
+ ` set(name: string, value: string, options?: {`,
161
+ ` path?: string;`,
162
+ ` domain?: string;`,
163
+ ` maxAge?: number;`,
164
+ ` expires?: Date;`,
165
+ ` httpOnly?: boolean;`,
166
+ ` secure?: boolean;`,
167
+ ` sameSite?: "strict" | "lax" | "none";`,
168
+ ` }): void;`,
169
+ ` delete(name: string): void;`,
170
+ `};`,
144
171
  `type _ActionKeys = Exclude<keyof _PS, "load" | "default">;`,
145
172
  `export type Actions = {`,
146
173
  ` [K in _ActionKeys]: (ctx: {`,
@@ -148,6 +175,7 @@ function generateTypesForGroup(group: RouteGroup, outFileDir: string): string {
148
175
  ` request: Request;`,
149
176
  ` url: URL;`,
150
177
  ` locals: App.Locals;`,
178
+ ` cookies: ActionCookies;`,
151
179
  ` }) => unknown | Promise<unknown>;`,
152
180
  `};`,
153
181
  "",
@@ -183,6 +211,7 @@ function generateTypesForGroup(group: RouteGroup, outFileDir: string): string {
183
211
  ` request: Request;`,
184
212
  ` url: URL;`,
185
213
  ` locals: App.Locals;`,
214
+ ` parent: () => Promise<Record<string, unknown>>;`,
186
215
  `}) => Record<string, unknown> | Promise<Record<string, unknown>>;`,
187
216
  "",
188
217
  );
@@ -259,6 +288,8 @@ function generateAmbient(): string {
259
288
  " request: Request;",
260
289
  " url: URL;",
261
290
  " locals: App.Locals;",
291
+ " fetch: typeof fetch;",
292
+ " parent: () => Promise<Record<string, unknown>>;",
262
293
  "}) => Record<string, unknown> | Promise<Record<string, unknown>>;",
263
294
  "",
264
295
  "type LayoutServerLoad<",
@@ -268,6 +299,8 @@ function generateAmbient(): string {
268
299
  " request: Request;",
269
300
  " url: URL;",
270
301
  " locals: App.Locals;",
302
+ " fetch: typeof fetch;",
303
+ " parent: () => Promise<Record<string, unknown>>;",
271
304
  "}) => Record<string, unknown> | Promise<Record<string, unknown>>;",
272
305
  "",
273
306
  "type RequestHandler<",
package/src/types.ts CHANGED
@@ -37,6 +37,8 @@ export interface LoadContext {
37
37
  url: URL;
38
38
  locals: Record<string, unknown>; // set by plugins/hooks
39
39
  fetch: typeof globalThis.fetch; // ← add
40
+ /** Data returned by parent layouts' loads, merged outermost-first. */
41
+ parent: () => Promise<Record<string, unknown>>;
40
42
  }
41
43
 
42
44
  export interface TypedLoadContext<
@@ -47,6 +49,8 @@ export interface TypedLoadContext<
47
49
  url: URL;
48
50
  locals: App.Locals;
49
51
  fetch: typeof fetch;
52
+ /** Data returned by parent layouts' loads, merged outermost-first. */
53
+ parent: () => Promise<Record<string, unknown>>;
50
54
  }
51
55
 
52
56
  export interface RenderContext {