@emeryld/rrroutes-contract 2.1.7 → 2.1.9

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.
@@ -1,16 +1,63 @@
1
1
  import { z } from 'zod';
2
- import { AnyLeaf, Append, Leaf, Merge, MergeArray, MethodCfg, NodeCfg, Prettify } from './routesV3.core';
2
+ import { AnyLeaf, Append, HttpMethod, Leaf, Merge, MergeArray, MethodCfg, NodeCfg, Prettify } from './routesV3.core';
3
+ declare const paginationField: z.ZodDefault<z.ZodOptional<z.ZodObject<{
4
+ cursor: z.ZodOptional<z.ZodString>;
5
+ limit: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
6
+ }, z.core.$strip>>>;
7
+ type PaginationField = typeof paginationField;
3
8
  type ZodTypeAny = z.ZodTypeAny;
4
9
  type ParamZod<Name extends string, S extends ZodTypeAny> = z.ZodObject<{
5
10
  [K in Name]: S;
6
11
  }>;
7
- /**
8
- * Runtime helper that mirrors the typed merge used by the builder.
9
- * @param a Previously merged params schema inherited from parent segments.
10
- * @param b Newly introduced params schema.
11
- * @returns Intersection of schemas when both exist, otherwise whichever is defined.
12
- */
13
- declare function mergeSchemas<A extends ZodTypeAny | undefined, B extends ZodTypeAny | undefined>(a: A, b: B): A extends ZodTypeAny ? (B extends ZodTypeAny ? ReturnType<typeof z.intersection<A, B>> : A) : B;
12
+ type ZodArrayAny = z.ZodArray<ZodTypeAny>;
13
+ type AnyZodObject = z.ZodObject<any>;
14
+ type MergedParamsResult<PS, Name extends string, P extends ZodTypeAny> = PS extends ZodTypeAny ? z.ZodIntersection<PS, ParamZod<Name, P>> : ParamZod<Name, P>;
15
+ declare const defaultFeedOutputSchema: z.ZodObject<{
16
+ items: z.ZodArray<z.ZodUnknown>;
17
+ nextCursor: z.ZodOptional<z.ZodString>;
18
+ }, z.core.$strip>;
19
+ type FeedOutputSchema<C extends MethodCfg> = C['outputSchema'] extends ZodArrayAny ? z.ZodObject<{
20
+ items: C['outputSchema'];
21
+ nextCursor: z.ZodOptional<z.ZodString>;
22
+ }> : C['outputSchema'] extends ZodTypeAny ? z.ZodObject<{
23
+ items: z.ZodArray<C['outputSchema']>;
24
+ nextCursor: z.ZodOptional<z.ZodString>;
25
+ }> : typeof defaultFeedOutputSchema;
26
+ type BaseMethodCfg<C extends MethodCfg> = Merge<Omit<MethodCfg, 'querySchema' | 'outputSchema' | 'feed'>, Omit<C, 'querySchema' | 'outputSchema' | 'feed'>>;
27
+ type FeedField<C extends MethodCfg> = C['feed'] extends true ? {
28
+ feed: true;
29
+ } : {
30
+ feed?: boolean;
31
+ };
32
+ type AddPaginationToQuery<Q extends AnyZodObject | undefined> = Q extends z.ZodObject<infer Shape> ? z.ZodObject<Shape & {
33
+ pagination: PaginationField;
34
+ }> : z.ZodObject<{
35
+ pagination: PaginationField;
36
+ }>;
37
+ type FeedQueryField<C extends MethodCfg> = {
38
+ querySchema: AddPaginationToQuery<C['querySchema'] extends AnyZodObject ? C['querySchema'] : undefined>;
39
+ };
40
+ type NonFeedQueryField<C extends MethodCfg> = C['querySchema'] extends ZodTypeAny ? {
41
+ querySchema: C['querySchema'];
42
+ } : {
43
+ querySchema?: undefined;
44
+ };
45
+ type FeedOutputField<C extends MethodCfg> = {
46
+ outputSchema: FeedOutputSchema<C>;
47
+ };
48
+ type NonFeedOutputField<C extends MethodCfg> = C['outputSchema'] extends ZodTypeAny ? {
49
+ outputSchema: C['outputSchema'];
50
+ } : {
51
+ outputSchema?: undefined;
52
+ };
53
+ type ParamsField<C extends MethodCfg, PS> = C['paramsSchema'] extends ZodTypeAny ? {
54
+ paramsSchema: C['paramsSchema'];
55
+ } : {
56
+ paramsSchema: PS;
57
+ };
58
+ type EffectiveFeedFields<C extends MethodCfg, PS> = C['feed'] extends true ? FeedField<C> & FeedQueryField<C> & FeedOutputField<C> & ParamsField<C, PS> : FeedField<C> & NonFeedQueryField<C> & NonFeedOutputField<C> & ParamsField<C, PS>;
59
+ type EffectiveCfg<C extends MethodCfg, PS> = Prettify<Merge<MethodCfg, BaseMethodCfg<C> & EffectiveFeedFields<C, PS>>>;
60
+ type BuiltLeaf<M extends HttpMethod, Base extends string, I extends NodeCfg, C extends MethodCfg, PS> = Leaf<M, Base, Merge<I, EffectiveCfg<C, PS>>>;
14
61
  /** Builder surface used by `resource(...)` to accumulate leaves. */
15
62
  export interface Branch<Base extends string, Acc extends readonly AnyLeaf[], I extends NodeCfg, PS extends ZodTypeAny | undefined> {
16
63
  /**
@@ -29,7 +76,7 @@ export interface Branch<Base extends string, Acc extends readonly AnyLeaf[], I e
29
76
  * @param paramsSchema Zod schema for the parameter value.
30
77
  * @param builder Callback that produces leaves beneath the parameterized segment.
31
78
  */
32
- routeParameter<Name extends string, P extends ZodTypeAny, R extends readonly AnyLeaf[]>(name: Name, paramsSchema: P, builder: (r: Branch<`${Base}/:${Name}`, readonly [], I, ReturnType<typeof mergeSchemas<PS, ParamZod<Name, P>>>>) => R): Branch<Base, MergeArray<Acc, R>, I, ReturnType<typeof mergeSchemas<PS, ParamZod<Name, P>>>>;
79
+ routeParameter<Name extends string, P extends ZodTypeAny, R extends readonly AnyLeaf[]>(name: Name, paramsSchema: P, builder: (r: Branch<`${Base}/:${Name}`, readonly [], I, MergedParamsResult<PS, Name, P>>) => R): Branch<Base, MergeArray<Acc, R>, I, MergedParamsResult<PS, Name, P>>;
33
80
  /**
34
81
  * Merge additional node configuration that subsequent leaves will inherit.
35
82
  * @param cfg Partial node configuration.
@@ -39,37 +86,35 @@ export interface Branch<Base extends string, Acc extends readonly AnyLeaf[], I e
39
86
  * Register a GET leaf at the current path.
40
87
  * @param cfg Method configuration (schemas, flags, descriptions, etc).
41
88
  */
42
- get<C extends Omit<MethodCfg, 'paramsSchema'>>(cfg: C): Branch<Base, Append<Acc, Prettify<Leaf<'get', Base, Merge<Merge<I, C>, {
43
- paramsSchema: PS;
44
- }>>>>, I, PS>;
89
+ get<C extends MethodCfg>(cfg: C): Branch<Base, Append<Acc, Prettify<BuiltLeaf<'get', Base, I, C, PS>>>, I, PS>;
45
90
  /**
46
91
  * Register a POST leaf at the current path.
47
92
  * @param cfg Method configuration (schemas, flags, descriptions, etc).
48
93
  */
49
- post<C extends Omit<MethodCfg, 'paramsSchema'>>(cfg: C): Branch<Base, Append<Acc, Leaf<'post', Base, Merge<Merge<I, C>, {
50
- paramsSchema: PS;
51
- }>>>, I, PS>;
94
+ post<C extends Omit<MethodCfg, 'feed'>>(cfg: C): Branch<Base, Append<Acc, Prettify<BuiltLeaf<'post', Base, I, Merge<C, {
95
+ feed: false;
96
+ }>, PS>>>, I, PS>;
52
97
  /**
53
98
  * Register a PUT leaf at the current path.
54
99
  * @param cfg Method configuration (schemas, flags, descriptions, etc).
55
100
  */
56
- put<C extends Omit<MethodCfg, 'paramsSchema'>>(cfg: C): Branch<Base, Append<Acc, Leaf<'put', Base, Merge<Merge<I, C>, {
57
- paramsSchema: PS;
58
- }>>>, I, PS>;
101
+ put<C extends Omit<MethodCfg, 'feed'>>(cfg: C): Branch<Base, Append<Acc, Prettify<BuiltLeaf<'put', Base, I, Merge<C, {
102
+ feed: false;
103
+ }>, PS>>>, I, PS>;
59
104
  /**
60
105
  * Register a PATCH leaf at the current path.
61
106
  * @param cfg Method configuration (schemas, flags, descriptions, etc).
62
107
  */
63
- patch<C extends Omit<MethodCfg, 'paramsSchema'>>(cfg: C): Branch<Base, Append<Acc, Leaf<'patch', Base, Merge<Merge<I, C>, {
64
- paramsSchema: PS;
65
- }>>>, I, PS>;
108
+ patch<C extends Omit<MethodCfg, 'feed'>>(cfg: C): Branch<Base, Append<Acc, Prettify<BuiltLeaf<'patch', Base, I, Merge<C, {
109
+ feed: false;
110
+ }>, PS>>>, I, PS>;
66
111
  /**
67
112
  * Register a DELETE leaf at the current path.
68
113
  * @param cfg Method configuration (schemas, flags, descriptions, etc).
69
114
  */
70
- delete<C extends Omit<MethodCfg, 'paramsSchema'>>(cfg: C): Branch<Base, Append<Acc, Leaf<'delete', Base, Merge<Merge<I, C>, {
71
- paramsSchema: PS;
72
- }>>>, I, PS>;
115
+ delete<C extends Omit<MethodCfg, 'feed'>>(cfg: C): Branch<Base, Append<Acc, Prettify<BuiltLeaf<'delete', Base, I, Merge<C, {
116
+ feed: false;
117
+ }>, PS>>>, I, PS>;
73
118
  /**
74
119
  * Finish the branch and return the collected leaves.
75
120
  * @returns Readonly tuple of accumulated leaves.
@@ -6,6 +6,17 @@ export declare const CrudDefaultPagination: z.ZodObject<{
6
6
  limit: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
7
7
  cursor: z.ZodOptional<z.ZodString>;
8
8
  }, z.core.$strip>;
9
+ declare const CrudPaginationField: z.ZodDefault<z.ZodOptional<z.ZodObject<{
10
+ limit: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
11
+ cursor: z.ZodOptional<z.ZodString>;
12
+ }, z.core.$strip>>>;
13
+ type CrudPaginationField = typeof CrudPaginationField;
14
+ type AnyCrudZodObject = z.ZodObject<any>;
15
+ type AddCrudPagination<Q extends AnyCrudZodObject | undefined> = Q extends z.ZodObject<infer Shape> ? z.ZodObject<Shape & {
16
+ pagination: CrudPaginationField;
17
+ }> : z.ZodObject<{
18
+ pagination: CrudPaginationField;
19
+ }>;
9
20
  /**
10
21
  * Merge two Zod schemas at runtime; matches the typing pattern used in builder.
11
22
  * @param a Existing params schema inherited from parent branches.
@@ -103,7 +114,7 @@ type CrudLeavesTuple<Base extends string, I extends NodeCfg, PS extends ZodType
103
114
  ...(Flag<C['enable'] extends CrudEnable ? C['enable']['list'] : undefined, true> extends true ? [
104
115
  Leaf<'get', `${Base}/${Name}`, WithParams<Omit<I, never> & {
105
116
  feed: true;
106
- querySchema: C['list'] extends CrudListCfg ? C['list']['querySchema'] : typeof CrudDefaultPagination;
117
+ querySchema: C['list'] extends CrudListCfg ? AddCrudPagination<C['list']['querySchema'] extends AnyCrudZodObject ? C['list']['querySchema'] : undefined> : AddCrudPagination<undefined>;
107
118
  outputSchema: C['list'] extends CrudListCfg ? C['list']['outputSchema'] extends ZodType ? C['list']['outputSchema'] : z.ZodObject<{
108
119
  items: z.ZodArray<C['itemOutputSchema']>;
109
120
  nextCursor: z.ZodOptional<z.ZodString>;
@@ -0,0 +1,2 @@
1
+ import { AnyLeaf } from "../core/routesV3.core";
2
+ export declare function renderLeafDocsMarkdown(leaves: AnyLeaf[]): string;
package/dist/index.cjs CHANGED
@@ -27,6 +27,7 @@ __export(index_exports, {
27
27
  finalize: () => finalize,
28
28
  mergeArrays: () => mergeArrays,
29
29
  mergeSchemas: () => mergeSchemas2,
30
+ renderLeafDocsMarkdown: () => renderLeafDocsMarkdown,
30
31
  resource: () => resource,
31
32
  resourceWithCrud: () => resourceWithCrud,
32
33
  withCrud: () => withCrud
@@ -35,6 +36,51 @@ module.exports = __toCommonJS(index_exports);
35
36
 
36
37
  // src/core/routesV3.builder.ts
37
38
  var import_zod = require("zod");
39
+ var defaultFeedQuerySchema = import_zod.z.object({
40
+ cursor: import_zod.z.string().optional(),
41
+ limit: import_zod.z.coerce.number().min(1).max(100).default(20)
42
+ });
43
+ var paginationField = defaultFeedQuerySchema.optional().default(defaultFeedQuerySchema.parse({}));
44
+ var defaultFeedOutputSchema = import_zod.z.object({
45
+ items: import_zod.z.array(import_zod.z.unknown()),
46
+ nextCursor: import_zod.z.string().optional()
47
+ });
48
+ function augmentFeedQuerySchema(schema) {
49
+ if (schema && !(schema instanceof import_zod.z.ZodObject)) {
50
+ console.warn("Feed queries must be a ZodObject; default pagination applied.");
51
+ return import_zod.z.object({
52
+ pagination: paginationField
53
+ });
54
+ }
55
+ const base = schema ?? import_zod.z.object({});
56
+ return base.extend({
57
+ pagination: paginationField
58
+ });
59
+ }
60
+ function augmentFeedOutputSchema(schema) {
61
+ if (!schema) return defaultFeedOutputSchema;
62
+ if (schema instanceof import_zod.z.ZodArray) {
63
+ return import_zod.z.object({
64
+ items: schema,
65
+ nextCursor: import_zod.z.string().optional()
66
+ });
67
+ }
68
+ if (schema instanceof import_zod.z.ZodObject) {
69
+ const shape = schema.shape ? schema.shape : schema._def?.shape?.();
70
+ const hasItems = Boolean(shape?.items);
71
+ if (hasItems) {
72
+ return schema.extend({ nextCursor: import_zod.z.string().optional() });
73
+ }
74
+ return import_zod.z.object({
75
+ items: import_zod.z.array(schema),
76
+ nextCursor: import_zod.z.string().optional()
77
+ });
78
+ }
79
+ return import_zod.z.object({
80
+ items: import_zod.z.array(schema),
81
+ nextCursor: import_zod.z.string().optional()
82
+ });
83
+ }
38
84
  function mergeSchemas(a, b) {
39
85
  if (a && b) return import_zod.z.intersection(a, b);
40
86
  return a ?? b;
@@ -49,7 +95,20 @@ function resource(base, inherited) {
49
95
  let currentParamsSchema = mergedParamsSchema;
50
96
  function add(method, cfg) {
51
97
  const effectiveParamsSchema = cfg.paramsSchema ?? currentParamsSchema;
52
- const fullCfg = effectiveParamsSchema ? { ...inheritedCfg, ...cfg, paramsSchema: effectiveParamsSchema } : { ...inheritedCfg, ...cfg };
98
+ const effectiveQuerySchema = cfg.feed === true ? augmentFeedQuerySchema(cfg.querySchema) : cfg.querySchema;
99
+ const effectiveOutputSchema = cfg.feed === true ? augmentFeedOutputSchema(cfg.outputSchema) : cfg.outputSchema;
100
+ const fullCfg = effectiveParamsSchema ? {
101
+ ...inheritedCfg,
102
+ ...cfg,
103
+ paramsSchema: effectiveParamsSchema,
104
+ ...effectiveQuerySchema ? { querySchema: effectiveQuerySchema } : {},
105
+ ...effectiveOutputSchema ? { outputSchema: effectiveOutputSchema } : {}
106
+ } : {
107
+ ...inheritedCfg,
108
+ ...cfg,
109
+ ...effectiveQuerySchema ? { querySchema: effectiveQuerySchema } : {},
110
+ ...effectiveOutputSchema ? { outputSchema: effectiveOutputSchema } : {}
111
+ };
53
112
  const leaf = {
54
113
  method,
55
114
  path: currentBase,
@@ -86,7 +145,7 @@ function resource(base, inherited) {
86
145
  routeParameter(name, paramsSchema, builder) {
87
146
  const childBase = `${currentBase}/:${name}`;
88
147
  const paramObj = import_zod.z.object({ [name]: paramsSchema });
89
- const childParams = mergeSchemas(currentParamsSchema, paramObj);
148
+ const childParams = currentParamsSchema ? mergeSchemas(currentParamsSchema, paramObj) : paramObj;
90
149
  const child = makeBranch(childBase, inheritedCfg, childParams);
91
150
  const leaves = builder(child);
92
151
  for (const l of leaves) stack.push(l);
@@ -162,6 +221,7 @@ var CrudDefaultPagination = import_zod2.z.object({
162
221
  limit: import_zod2.z.coerce.number().min(1).max(100).default(20),
163
222
  cursor: import_zod2.z.string().optional()
164
223
  });
224
+ var CrudPaginationField = CrudDefaultPagination.optional().default(CrudDefaultPagination.parse({}));
165
225
  function mergeSchemas2(a, b) {
166
226
  if (a && b) return import_zod2.z.intersection(a, b);
167
227
  return a ?? b;
@@ -238,6 +298,93 @@ function resourceWithCrud(base, inherited) {
238
298
  function defineSocketEvents(config, events) {
239
299
  return { config, events };
240
300
  }
301
+
302
+ // src/docs/docs.ts
303
+ var import_zod3 = require("zod");
304
+ function summarizeSchema(schema) {
305
+ if (!schema) return void 0;
306
+ if (schema instanceof import_zod3.ZodObject) {
307
+ const shape = schema.shape;
308
+ return {
309
+ type: "object",
310
+ fields: Object.fromEntries(
311
+ Object.entries(shape).map(([key, value]) => {
312
+ const def2 = value._def;
313
+ return [
314
+ key,
315
+ {
316
+ typeName: def2?.typeName,
317
+ description: def2?.description
318
+ }
319
+ ];
320
+ })
321
+ )
322
+ };
323
+ }
324
+ if (schema instanceof import_zod3.ZodArray) {
325
+ return {
326
+ type: "array",
327
+ // @ts-ignore
328
+ element: summarizeSchema(schema.unwrap())
329
+ };
330
+ }
331
+ const def = schema._def;
332
+ return { typeName: def?.typeName ?? "unknown" };
333
+ }
334
+ function leavesToDocs(leaves) {
335
+ return leaves.map((leaf) => {
336
+ const { method, path, cfg } = leaf;
337
+ return {
338
+ method,
339
+ path,
340
+ description: cfg.description,
341
+ feed: cfg.feed,
342
+ body: summarizeSchema(cfg.bodySchema),
343
+ query: summarizeSchema(cfg.querySchema),
344
+ params: summarizeSchema(cfg.paramsSchema),
345
+ output: summarizeSchema(cfg.outputSchema),
346
+ files: cfg.bodyFiles
347
+ };
348
+ });
349
+ }
350
+ function renderLeafDocsMarkdown(leaves) {
351
+ const docs = leavesToDocs(leaves);
352
+ docs.sort((a, b) => {
353
+ const p = a.path.localeCompare(b.path);
354
+ return p !== 0 ? p : a.method.localeCompare(b.method);
355
+ });
356
+ return docs.map((d) => {
357
+ const lines = [];
358
+ lines.push(`### \`${d.method.toUpperCase()} ${d.path}\``);
359
+ if (d.description) {
360
+ lines.push("", d.description);
361
+ }
362
+ if (d.feed) {
363
+ lines.push("", "_Feed endpoint_");
364
+ }
365
+ function pushJson(title, value) {
366
+ if (!value) return;
367
+ lines.push(
368
+ "",
369
+ `**${title}**`,
370
+ "```json",
371
+ JSON.stringify(value, null, 2),
372
+ "```"
373
+ );
374
+ }
375
+ pushJson("Query", d.query);
376
+ pushJson("Params", d.params);
377
+ pushJson("Body", d.body);
378
+ pushJson("Output", d.output);
379
+ if (d.files && d.files.length > 0) {
380
+ lines.push("", "**Multipart files**");
381
+ d.files.forEach((f) => {
382
+ lines.push(`- \`${f.name}\` (maxCount: ${f.maxCount})`);
383
+ });
384
+ }
385
+ return lines.join("\n");
386
+ }).join("\n\n");
387
+ }
241
388
  // Annotate the CommonJS export names for ESM import in node:
242
389
  0 && (module.exports = {
243
390
  CrudDefaultPagination,
@@ -247,6 +394,7 @@ function defineSocketEvents(config, events) {
247
394
  finalize,
248
395
  mergeArrays,
249
396
  mergeSchemas,
397
+ renderLeafDocsMarkdown,
250
398
  resource,
251
399
  resourceWithCrud,
252
400
  withCrud
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/core/routesV3.builder.ts","../src/core/routesV3.core.ts","../src/core/routesV3.finalize.ts","../src/crud/routesV3.crud.ts","../src/sockets/socket.index.ts"],"sourcesContent":["export * from './core/routesV3.builder';\nexport * from './core/routesV3.core';\nexport * from './core/routesV3.finalize';\nexport * from './crud/routesV3.crud';\nexport * from './sockets/socket.index';","import { z } from 'zod';\nimport {\n AnyLeaf,\n Append,\n HttpMethod,\n Leaf,\n Merge,\n MergeArray,\n MethodCfg,\n NodeCfg,\n Prettify,\n} from './routesV3.core';\n\ntype ZodTypeAny = z.ZodTypeAny;\ntype ParamZod<Name extends string, S extends ZodTypeAny> = z.ZodObject<{ [K in Name]: S }>;\n\n/**\n * Runtime helper that mirrors the typed merge used by the builder.\n * @param a Previously merged params schema inherited from parent segments.\n * @param b Newly introduced params schema.\n * @returns Intersection of schemas when both exist, otherwise whichever is defined.\n */\nfunction mergeSchemas<A extends ZodTypeAny | undefined, B extends ZodTypeAny | undefined>(\n a: A,\n b: B,\n): A extends ZodTypeAny ? (B extends ZodTypeAny ? ReturnType<typeof z.intersection<A, B>> : A) : B {\n if (a && b) return z.intersection(a as any, b as any) as any;\n return (a ?? b) as any;\n}\n\n/** Builder surface used by `resource(...)` to accumulate leaves. */\nexport interface Branch<\n Base extends string,\n Acc extends readonly AnyLeaf[],\n I extends NodeCfg,\n PS extends ZodTypeAny | undefined,\n> {\n // --- structure ---\n /**\n * Enter or define a static child segment.\n * Optionally accepts extra config and/or a builder to populate nested routes.\n * @param name Child segment literal (no leading slash).\n * @param cfg Optional node configuration to merge for descendants.\n * @param builder Callback to produce leaves for the child branch.\n */\n sub<Name extends string, J extends NodeCfg>(\n name: Name,\n cfg?: J,\n ): Branch<`${Base}/${Name}`, Acc, Merge<I, NonNullable<J>>, PS>;\n\n sub<Name extends string, J extends NodeCfg | undefined, R extends readonly AnyLeaf[]>(\n name: Name,\n cfg: J,\n builder: (r: Branch<`${Base}/${Name}`, readonly [], Merge<I, NonNullable<J>>, PS>) => R,\n ): Branch<Base, Append<Acc, R[number]>, Merge<I, NonNullable<J>>, PS>;\n\n sub<Name extends string, R extends readonly AnyLeaf[]>(\n name: Name,\n builder: (r: Branch<`${Base}/${Name}`, readonly [], I, PS>) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, PS>;\n\n // --- parameterized segment (single signature) ---\n /**\n * Introduce a `:param` segment and merge its schema into downstream leaves.\n * @param name Parameter key (without leading colon).\n * @param paramsSchema Zod schema for the parameter value.\n * @param builder Callback that produces leaves beneath the parameterized segment.\n */\n routeParameter<Name extends string, P extends ZodTypeAny, R extends readonly AnyLeaf[]>(\n name: Name,\n paramsSchema: P,\n builder: (\n r: Branch<\n `${Base}/:${Name}`,\n readonly [],\n I,\n ReturnType<typeof mergeSchemas<PS, ParamZod<Name, P>>>\n >,\n ) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, ReturnType<typeof mergeSchemas<PS, ParamZod<Name, P>>>>;\n\n // --- flags inheritance ---\n /**\n * Merge additional node configuration that subsequent leaves will inherit.\n * @param cfg Partial node configuration.\n */\n with<J extends NodeCfg>(cfg: J): Branch<Base, Acc, Merge<I, J>, PS>;\n\n // --- methods (return Branch to keep chaining) ---\n /**\n * Register a GET leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n get<C extends Omit<MethodCfg, 'paramsSchema'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<Acc, Prettify<Leaf<'get', Base, Merge<Merge<I, C>, { paramsSchema: PS }>>>>,\n I,\n PS\n >;\n\n /**\n * Register a POST leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n post<C extends Omit<MethodCfg, 'paramsSchema'>>(\n cfg: C,\n ): Branch<Base, Append<Acc, Leaf<'post', Base, Merge<Merge<I, C>, { paramsSchema: PS }>>>, I, PS>;\n\n /**\n * Register a PUT leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n put<C extends Omit<MethodCfg, 'paramsSchema'>>(\n cfg: C,\n ): Branch<Base, Append<Acc, Leaf<'put', Base, Merge<Merge<I, C>, { paramsSchema: PS }>>>, I, PS>;\n\n /**\n * Register a PATCH leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n patch<C extends Omit<MethodCfg, 'paramsSchema'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<Acc, Leaf<'patch', Base, Merge<Merge<I, C>, { paramsSchema: PS }>>>,\n I,\n PS\n >;\n\n /**\n * Register a DELETE leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n delete<C extends Omit<MethodCfg, 'paramsSchema'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<Acc, Leaf<'delete', Base, Merge<Merge<I, C>, { paramsSchema: PS }>>>,\n I,\n PS\n >;\n\n // --- finalize this subtree ---\n /**\n * Finish the branch and return the collected leaves.\n * @returns Readonly tuple of accumulated leaves.\n */\n done(): Readonly<Acc>;\n}\n\n/**\n * Start building a resource at the given base path.\n * @param base Root path for the resource (e.g. `/v1`).\n * @param inherited Optional node configuration applied to all descendants.\n * @returns Root `Branch` instance used to compose the route tree.\n */\nexport function resource<Base extends string, I extends NodeCfg = {}>(\n base: Base,\n inherited?: I,\n): Branch<Base, readonly [], I, undefined> {\n const rootBase = base;\n const rootInherited: NodeCfg = { ...(inherited as NodeCfg) };\n\n function makeBranch<Base2 extends string, I2 extends NodeCfg, PS2 extends ZodTypeAny | undefined>(\n base2: Base2,\n inherited2: I2,\n mergedParamsSchema?: PS2,\n ) {\n const stack: AnyLeaf[] = [];\n let currentBase: string = base2;\n let inheritedCfg: NodeCfg = { ...(inherited2 as NodeCfg) };\n let currentParamsSchema: PS2 = mergedParamsSchema as PS2;\n\n function add<M extends HttpMethod, C extends MethodCfg>(method: M, cfg: C) {\n // If the method didn’t provide a paramsSchema, inject the active merged one.\n const effectiveParamsSchema = (cfg.paramsSchema ?? currentParamsSchema) as PS2 | undefined;\n const fullCfg = (\n effectiveParamsSchema\n ? { ...inheritedCfg, ...cfg, paramsSchema: effectiveParamsSchema }\n : { ...inheritedCfg, ...cfg }\n ) as Merge<I2, C>;\n\n const leaf = {\n method,\n path: currentBase as Base2,\n cfg: fullCfg,\n } as const;\n\n stack.push(leaf as unknown as AnyLeaf);\n\n // Return same runtime obj, but with Acc including this new leaf\n return api as unknown as Branch<Base2, Append<readonly [], typeof leaf>, I2, PS2>;\n }\n\n const api: any = {\n // compose a plain subpath (optional cfg) with optional builder\n sub<Name extends string, J extends NodeCfg | undefined = undefined>(\n name: Name,\n cfgOrBuilder?: J | ((r: any) => readonly AnyLeaf[]),\n maybeBuilder?: (r: any) => readonly AnyLeaf[],\n ) {\n let cfg: NodeCfg | undefined;\n let builder: ((r: any) => readonly AnyLeaf[]) | undefined;\n\n if (typeof cfgOrBuilder === 'function') {\n builder = cfgOrBuilder as any;\n } else {\n cfg = cfgOrBuilder as NodeCfg | undefined;\n builder = maybeBuilder;\n }\n\n const childBase = `${currentBase}/${name}` as const;\n const childInherited = { ...inheritedCfg, ...(cfg ?? {}) } as Merge<I2, NonNullable<J>>;\n\n if (builder) {\n // params schema PS2 flows through unchanged on plain sub\n const child = makeBranch(childBase, childInherited, currentParamsSchema);\n const leaves = builder(child) as readonly AnyLeaf[];\n for (const l of leaves) stack.push(l);\n return api as Branch<\n Base2,\n Append<readonly [], (typeof leaves)[number]>,\n typeof childInherited,\n PS2\n >;\n } else {\n currentBase = childBase;\n inheritedCfg = childInherited;\n return api as Branch<`${Base2}/${Name}`, readonly [], typeof childInherited, PS2>;\n }\n },\n\n // the single param function: name + schema + builder\n routeParameter<Name extends string, P extends ZodTypeAny, R extends readonly AnyLeaf[]>(\n name: Name,\n paramsSchema: P,\n builder: (\n r: Branch<\n `${Base2}/:${Name}`,\n readonly [],\n I2,\n ReturnType<typeof mergeSchemas<PS2, ParamZod<Name, P>>>\n >,\n ) => R,\n ) {\n const childBase = `${currentBase}/:${name}` as const;\n // Wrap the value schema under the param name before merging with inherited params schema\n const paramObj: ParamZod<Name, P> = z.object({ [name]: paramsSchema } as Record<Name, P>);\n const childParams = mergeSchemas<PS2, ParamZod<Name, P>>(currentParamsSchema, paramObj);\n const child = makeBranch(childBase, inheritedCfg as I2, childParams);\n const leaves = builder(child) as readonly AnyLeaf[];\n for (const l of leaves) stack.push(l);\n return api as Branch<\n Base2,\n Append<readonly [], (typeof leaves)[number]>,\n I2,\n ReturnType<typeof mergeSchemas<PS2, ParamZod<Name, P>>>\n >;\n },\n\n with<J extends NodeCfg>(cfg: J) {\n inheritedCfg = { ...inheritedCfg, ...cfg };\n return api as Branch<Base2, readonly [], Merge<I2, J>, PS2>;\n },\n\n // methods (inject current params schema if missing)\n get<C extends MethodCfg>(cfg: C) {\n return add('get', cfg);\n },\n post<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('post', { ...cfg, feed: false });\n },\n put<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('put', { ...cfg, feed: false });\n },\n patch<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('patch', { ...cfg, feed: false });\n },\n delete<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('delete', { ...cfg, feed: false });\n },\n\n done() {\n return stack;\n },\n };\n\n return api as Branch<Base2, readonly [], I2, PS2>;\n }\n\n // Root branch starts with no params schema (PS = undefined)\n return makeBranch(rootBase, rootInherited, undefined);\n}\n\n/**\n * Merge two readonly tuples (preserves literal tuple information).\n * @param arr1 First tuple.\n * @param arr2 Second tuple.\n * @returns New tuple containing values from both inputs.\n */\nexport const mergeArrays = <T extends readonly any[], S extends readonly any[]>(\n arr1: T,\n arr2: S,\n) => {\n return [...arr1, ...arr2] as [...T, ...S];\n};\n","import { z, ZodTypeAny } from 'zod';\n\n/** Supported HTTP verbs for the routes DSL. */\nexport type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\n/** Declarative description of a multipart upload field. */\nexport type FileField = {\n /** Form field name used for uploads. */\n name: string;\n /** Maximum number of files accepted for this field. */\n maxCount: number;\n};\n\n/** Configuration that applies to an entire branch of the route tree. */\nexport type NodeCfg = {\n /** @deprecated. Does nothing. */\n authenticated?: boolean;\n};\n\n/** Per-method configuration merged with inherited node config. */\nexport type MethodCfg = {\n /** Zod schema describing the request body. */\n bodySchema?: ZodTypeAny;\n /** Zod schema describing the query string. */\n querySchema?: ZodTypeAny;\n /** Zod schema describing path params (overrides inferred params). */\n paramsSchema?: ZodTypeAny;\n /** Zod schema describing the response payload. */\n outputSchema?: ZodTypeAny;\n /** Multipart upload definitions for the route. */\n bodyFiles?: FileField[];\n /** Marks the route as an infinite feed (enables cursor helpers). */\n feed?: boolean;\n /** Optional human-readable description for docs/debugging. */\n description?: string;\n};\n\n/** Immutable representation of a single HTTP route in the tree. */\nexport type Leaf<M extends HttpMethod, P extends string, C extends MethodCfg> = {\n /** Lowercase HTTP method (get/post/...). */\n readonly method: M;\n /** Concrete path for the route (e.g. `/v1/users/:userId`). */\n readonly path: P;\n /** Readonly snapshot of route configuration. */\n readonly cfg: Readonly<C>;\n};\n\n/** Convenience union covering all generated leaves. */\nexport type AnyLeaf = Leaf<HttpMethod, string, MethodCfg>;\n\n/** Merge two object types while keeping nice IntelliSense output. */\nexport type Merge<A, B> = Prettify<Omit<A, keyof B> & B>;\n\n/** Append a new element to a readonly tuple type. */\nexport type Append<T extends readonly unknown[], X> = [...T, X];\n\n/** Concatenate two readonly tuple types. */\nexport type MergeArray<A extends readonly unknown[], B extends readonly unknown[]> = [\n ...A,\n ...B,\n];\n\n// helpers (optional)\ntype SegmentParams<S extends string> = S extends `:${infer P}` ? P : never;\ntype Split<S extends string> = S extends ''\n ? []\n : S extends `${infer A}/${infer B}`\n ? [A, ...Split<B>]\n : [S];\ntype ExtractParamNames<Path extends string> = SegmentParams<Split<Path>[number]>;\n\n/** Derive a params object type from a literal route string. */\nexport type ExtractParamsFromPath<Path extends string> =\n ExtractParamNames<Path> extends never ? never : Record<ExtractParamNames<Path>, string | number>;\n\n/**\n * Interpolate `:params` in a path using the given values.\n * @param path Literal route string containing `:param` segments.\n * @param params Object of parameter values to interpolate.\n * @returns Path string with parameters substituted.\n */\nexport function compilePath<Path extends string>(path: Path, params: ExtractParamsFromPath<Path>) {\n if (!params) return path;\n return path.replace(/:([A-Za-z0-9_]+)/g, (_, k) => {\n const v = (params as any)[k];\n if (v === undefined || v === null) throw new Error(`Missing param :${k}`);\n return String(v);\n });\n}\n\n/**\n * Build a deterministic cache key for the given leaf.\n * The key matches the shape consumed by React Query helpers.\n * @param args.leaf Leaf describing the endpoint.\n * @param args.params Optional params used to build the path.\n * @param args.query Optional query payload.\n * @returns Tuple suitable for React Query cache keys.\n */\ntype SplitPath<P extends string> = P extends ''\n ? []\n : P extends `${infer A}/${infer B}`\n ? [A, ...SplitPath<B>]\n : [P];\nexport function buildCacheKey<L extends AnyLeaf>(args: {\n leaf: L;\n params?: ExtractParamsFromPath<L['path']>;\n query?: InferQuery<L>;\n}) {\n let p = args.leaf.path;\n if (args.params) {\n p = compilePath<L['path']>(p, args.params);\n }\n return [args.leaf.method, ...(p.split('/').filter(Boolean) as SplitPath<typeof p>), args.query ?? {}] as const;\n}\n\n/** Infer params either from the explicit params schema or from the path literal. */\nexport type InferParams<L extends AnyLeaf> = L['cfg']['paramsSchema'] extends ZodTypeAny\n ? z.infer<L['cfg']['paramsSchema']>\n : ExtractParamsFromPath<L['path']>;\n\n/** Infer query shape from a Zod schema when present. */\nexport type InferQuery<L extends AnyLeaf> = L['cfg']['querySchema'] extends ZodTypeAny\n ? z.infer<L['cfg']['querySchema']>\n : never;\n\n/** Infer request body shape from a Zod schema when present. */\nexport type InferBody<L extends AnyLeaf> = L['cfg']['bodySchema'] extends ZodTypeAny\n ? z.infer<L['cfg']['bodySchema']>\n : never;\n\n/** Infer handler output shape from a Zod schema. Defaults to unknown. */\nexport type InferOutput<L extends AnyLeaf> = L['cfg']['outputSchema'] extends ZodTypeAny\n ? z.infer<L['cfg']['outputSchema']>\n : unknown;\n\n/** Render a type as if it were a simple object literal. */\nexport type Prettify<T> = { [K in keyof T]: T[K] } & {};\n","import { AnyLeaf, HttpMethod, Prettify } from './routesV3.core';\n\n/** Build the key type for a leaf — distributive so method/path stay paired. */\nexport type KeyOf<L extends AnyLeaf> = L extends AnyLeaf\n ? `${Uppercase<L['method']>} ${L['path']}`\n : never;\n\n// From a tuple of leaves, get the union of keys (pairwise, no cartesian blow-up)\ntype KeysOf<Leaves extends readonly AnyLeaf[]> = KeyOf<Leaves[number]>;\n\n// Parse method & path out of a key\ntype MethodFromKey<K extends string> = K extends `${infer M} ${string}` ? Lowercase<M> : never;\ntype PathFromKey<K extends string> = K extends `${string} ${infer P}` ? P : never;\n\n// Given Leaves and a Key, pick the exact leaf that matches method+path\ntype LeafForKey<Leaves extends readonly AnyLeaf[], K extends string> = Extract<\n Leaves[number],\n { method: MethodFromKey<K> & HttpMethod; path: PathFromKey<K> }\n>;\n\n/**\n * Freeze a leaf tuple into a registry with typed key lookups.\n * @param leaves Readonly tuple of leaves produced by the builder DSL.\n * @returns Registry containing the leaves array and a `byKey` lookup map.\n */\nexport function finalize<const L extends readonly AnyLeaf[]>(leaves: L) {\n type Keys = KeysOf<L>;\n type MapByKey = { [K in Keys]: Prettify<LeafForKey<L, K>> };\n\n const byKey = Object.fromEntries(\n leaves.map((l) => [`${l.method.toUpperCase()} ${l.path}`, l] as const),\n ) as unknown as MapByKey;\n\n const log = (logger: { system: (...args: unknown[]) => void }) => {\n logger.system('Finalized routes:');\n (Object.keys(byKey) as Keys[]).forEach((k) => {\n const leaf = byKey[k];\n logger.system(`- ${k}`);\n });\n };\n\n return { all: leaves, byKey, log };\n}\n\n/** Nominal type alias for a finalized registry. */\nexport type Registry<R extends ReturnType<typeof finalize>> = R;\n\ntype FilterRoute<\n T extends readonly AnyLeaf[],\n F extends string,\n Acc extends readonly AnyLeaf[] = [],\n> = T extends readonly [infer First extends AnyLeaf, ...infer Rest extends AnyLeaf[]]\n ? First extends { path: `${string}${F}${string}` }\n ? FilterRoute<Rest, F, [...Acc, First]>\n : FilterRoute<Rest, F, Acc>\n : Acc;\n\ntype UpperCase<S extends string> = S extends `${infer First}${infer Rest}`\n ? `${Uppercase<First>}${UpperCase<Rest>}`\n : S;\n\ntype Routes<T extends readonly AnyLeaf[], F extends string> = FilterRoute<T, F>;\ntype ByKey<\n T extends readonly AnyLeaf[],\n Acc extends Record<string, AnyLeaf> = {},\n> = T extends readonly [infer First extends AnyLeaf, ...infer Rest extends AnyLeaf[]]\n ? ByKey<Rest, Acc & { [K in `${UpperCase<First['method']>} ${First['path']}`]: First }>\n : Acc;\n\n/**\n * Convenience helper for extracting a subset of routes by path fragment.\n * @param T Tuple of leaves produced by the DSL.\n * @param F String fragment to match against the route path.\n */\nexport type SubsetRoutes<T extends readonly AnyLeaf[], F extends string> = {\n byKey: ByKey<Routes<T, F>>;\n all: Routes<T, F>;\n};\n","// routesV3.crud.ts\n// -----------------------------------------------------------------------------\n// Add a first-class .crud() helper to the routesV3 DSL, without touching the\n// core builder. This file:\n// 1) Declares types + module augmentation to extend Branch<...> with .crud\n// 2) Provides a runtime decorator `withCrud(...)` that installs the method\n// 3) Exports a convenience `resourceWithCrud(...)` wrapper (optional)\n// -----------------------------------------------------------------------------\n\nimport { z, ZodType } from 'zod';\nimport {\n resource as baseResource,\n type Branch as _Branch, // import type so we can augment it\n} from '../core/routesV3.builder';\nimport { type AnyLeaf, type Leaf, type NodeCfg } from '../core/routesV3.core';\n\n// -----------------------------------------------------------------------------\n// Small utilities (runtime + types)\n// -----------------------------------------------------------------------------\n/** Default cursor pagination used by list (GET collection). */\nexport const CrudDefaultPagination = z.object({\n limit: z.coerce.number().min(1).max(100).default(20),\n cursor: z.string().optional(),\n});\n\n/**\n * Merge two Zod schemas at runtime; matches the typing pattern used in builder.\n * @param a Existing params schema inherited from parent branches.\n * @param b Schema introduced at the current branch.\n * @returns Intersection of schemas when both exist, otherwise whichever is defined.\n */\nexport function mergeSchemas<A extends ZodType | undefined, B extends ZodType | undefined>(\n a: A,\n b: B,\n): A extends ZodType ? (B extends ZodType ? ReturnType<typeof z.intersection<A, B>> : A) : B {\n if (a && b) return z.intersection(a as any, b as any) as any;\n return (a ?? b) as any;\n}\n\n/** Build { [Name]: S } Zod object at the type-level. */\nexport type ParamSchema<Name extends string, S extends ZodType> = z.ZodObject<{\n [K in Name]: S;\n}>;\n\n/** Inject active params schema into a leaf cfg (to match your Leaf typing). */\ntype WithParams<I, P> = P extends ZodType ? Omit<I, 'paramsSchema'> & { paramsSchema: P } : I;\n\n/** Resolve boolean flag: default D unless explicitly false. */\ntype Flag<E, D extends boolean> = E extends false ? false : D;\n\n// -----------------------------------------------------------------------------\n// CRUD config (few knobs, with DX comments)\n// -----------------------------------------------------------------------------\n\n/** Toggle individual CRUD methods; defaults enable all (create/update require body). */\nexport type CrudEnable = {\n /** GET /collection (feed). Defaults to true. */ list?: boolean;\n /** POST /collection. Defaults to true if `create` provided. */ create?: boolean;\n /** GET /collection/:id. Defaults to true. */ read?: boolean;\n /** PATCH /collection/:id. Defaults to true if `update` provided. */ update?: boolean;\n /** DELETE /collection/:id. Defaults to true. */ remove?: boolean;\n};\n\n/** Collection GET config. */\nexport type CrudListCfg = {\n /** Query schema (defaults to cursor pagination). */\n querySchema?: ZodType;\n /** Output schema (defaults to { items: Item[], nextCursor? }). */\n outputSchema?: ZodType;\n /** Optional description string. */\n description?: string;\n};\n\n/** Collection POST config. */\nexport type CrudCreateCfg = {\n /** Body schema for creating an item. */\n bodySchema: ZodType;\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType;\n /** Optional description. */\n description?: string;\n};\n\n/** Item GET config. */\nexport type CrudReadCfg = {\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType;\n /** Optional description. */\n description?: string;\n};\n\n/** Item PATCH config. */\nexport type CrudUpdateCfg = {\n /** Body schema for partial updates. */\n bodySchema: ZodType;\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType;\n /** Optional description. */\n description?: string;\n};\n\n/** Item DELETE config. */\nexport type CrudRemoveCfg = {\n /** Output schema (defaults to { ok: true }). */\n outputSchema?: ZodType;\n /** Optional description. */\n description?: string;\n};\n\n/**\n * CRUD config for `.crud(\"resource\", cfg, extras?)`.\n *\n * It synthesizes `:[resourceName]Id` as the param key and uses `paramSchema` for the value.\n * Prefer passing a **value schema** (e.g. `z.string().uuid()`).\n * As a convenience, a ZodObject of shape `{ [resourceName]Id: schema }` is accepted at runtime too.\n */\nexport type CrudCfg<Name extends string = string> = {\n /**\n * Zod schema for the ID *value* (e.g. `z.string().uuid()`).\n * The parameter key is always `:${name}Id`.\n * (If you pass `z.object({ [name]Id: ... })`, it's accepted at runtime.)\n */\n paramSchema: ZodType;\n\n /**\n * The single-item output shape used by read/create/update by default.\n * List defaults to `{ items: z.array(itemOutputSchema), nextCursor? }`.\n */\n itemOutputSchema: ZodType;\n\n /** Per-method toggles (all enabled by default; create/update require bodies). */\n enable?: CrudEnable;\n\n /** GET /collection configuration. */ list?: CrudListCfg;\n /** POST /collection configuration (enables create). */ create?: CrudCreateCfg;\n /** GET /collection/:id configuration. */ read?: CrudReadCfg;\n /** PATCH /collection/:id configuration (enables update). */ update?: CrudUpdateCfg;\n /** DELETE /collection/:id configuration. */ remove?: CrudRemoveCfg;\n};\n\n// -----------------------------------------------------------------------------\n// Type plumbing to expose generated leaves (so finalize().byKey sees them)\n// -----------------------------------------------------------------------------\n\ntype CrudLeavesTuple<\n Base extends string,\n I extends NodeCfg,\n PS extends ZodType | undefined,\n Name extends string,\n C extends CrudCfg<Name>,\n> = `${Name}Id` extends infer IdName extends string\n ? ParamSchema<IdName, C['paramSchema']> extends infer IdParamZ extends ZodType\n ? [\n // GET /collection\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['list'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'get',\n `${Base}/${Name}`,\n WithParams<\n Omit<I, never> & {\n feed: true;\n querySchema: C['list'] extends CrudListCfg\n ? C['list']['querySchema']\n : typeof CrudDefaultPagination;\n outputSchema: C['list'] extends CrudListCfg\n ? C['list']['outputSchema'] extends ZodType\n ? C['list']['outputSchema']\n : z.ZodObject<{\n items: z.ZodArray<C['itemOutputSchema']>;\n nextCursor: z.ZodOptional<z.ZodString>;\n }>\n : z.ZodObject<{\n items: z.ZodArray<C['itemOutputSchema']>;\n nextCursor: z.ZodOptional<z.ZodString>;\n }>;\n description?: string;\n },\n PS\n >\n >,\n ]\n : []),\n\n // POST /collection\n ...((C['create'] extends CrudCreateCfg ? true : false) extends true\n ? Flag<\n C['enable'] extends CrudEnable ? C['enable']['create'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'post',\n `${Base}/${Name}`,\n WithParams<\n Omit<I, never> & {\n bodySchema: C['create'] extends CrudCreateCfg\n ? C['create']['bodySchema']\n : never;\n outputSchema: C['create'] extends CrudCreateCfg\n ? C['create']['outputSchema'] extends ZodType\n ? C['create']['outputSchema']\n : C['itemOutputSchema']\n : never;\n description?: string;\n },\n PS\n >\n >,\n ]\n : []\n : []),\n\n // GET /collection/:id\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['read'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'get',\n `${Base}/${Name}/:${IdName}`,\n WithParams<\n Omit<I, never> & {\n outputSchema: C['read'] extends CrudReadCfg\n ? C['read']['outputSchema'] extends ZodType\n ? C['read']['outputSchema']\n : C['itemOutputSchema']\n : C['itemOutputSchema'];\n description?: string;\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >,\n ]\n : []),\n\n // PATCH /collection/:id\n ...((C['update'] extends CrudUpdateCfg ? true : false) extends true\n ? Flag<\n C['enable'] extends CrudEnable ? C['enable']['update'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'patch',\n `${Base}/${Name}/:${IdName}`,\n WithParams<\n Omit<I, never> & {\n bodySchema: C['update'] extends CrudUpdateCfg\n ? C['update']['bodySchema']\n : never;\n outputSchema: C['update'] extends CrudUpdateCfg\n ? C['update']['outputSchema'] extends ZodType\n ? C['update']['outputSchema']\n : C['itemOutputSchema']\n : never;\n description?: string;\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >,\n ]\n : []\n : []),\n\n // DELETE /collection/:id\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['remove'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'delete',\n `${Base}/${Name}/:${IdName}`,\n WithParams<\n Omit<I, never> & {\n outputSchema: C['remove'] extends CrudRemoveCfg\n ? C['remove']['outputSchema'] extends ZodType\n ? C['remove']['outputSchema']\n : z.ZodObject<{ ok: z.ZodLiteral<true> }>\n : z.ZodObject<{ ok: z.ZodLiteral<true> }>;\n description?: string;\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >,\n ]\n : []),\n ]\n : never\n : never;\n\n/** Merge generated leaves + extras into the branch accumulator. */\ntype CrudResultAcc<\n Base extends string,\n Acc extends readonly AnyLeaf[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeaf[],\n> = [...Acc, ...CrudLeavesTuple<Base, I, PS, Name, C>, ...Extras];\n\n// -----------------------------------------------------------------------------\n// Module augmentation: add the typed `.crud(...)` to Branch<...>\n// -----------------------------------------------------------------------------\n\ndeclare module './../core/routesV3.builder' {\n interface Branch<\n Base extends string,\n Acc extends readonly AnyLeaf[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n > {\n /**\n * Generate opinionated CRUD endpoints for a collection at `/.../<name>`\n * with an item at `/.../<name>/:<name>Id`.\n *\n * Creates (subject to `enable` + presence of create/update bodies):\n * - GET /<name> (feed list)\n * - POST /<name> (create)\n * - GET /<name>/:<name>Id (read item)\n * - PATCH /<name>/:<name>Id (update item)\n * - DELETE /<name>/:<name>Id (remove item)\n *\n * The `extras` callback receives live builders at both collection and item\n * levels so you can add custom subroutes; their leaves are included in the\n * returned Branch type.\n */\n crud<\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeaf[] = readonly [],\n >(\n name: Name,\n cfg: C,\n extras?: (ctx: {\n /** Builder at `/.../<name>` (collection scope). */\n collection: _Branch<`${Base}/${Name}`, readonly [], I, PS>;\n /** Builder at `/.../<name>/:<name>Id` (item scope). */\n item: _Branch<\n `${Base}/${Name}/:${`${Name}Id`}`,\n readonly [],\n I,\n ReturnType<typeof mergeSchemas<PS, ParamSchema<`${Name}Id`, C['paramSchema']>>>\n >;\n }) => Extras,\n ): _Branch<Base, CrudResultAcc<Base, Acc, I, PS, Name, C, Extras>, I, PS>;\n }\n}\n\n// -----------------------------------------------------------------------------\n// Runtime: install .crud on any Branch via decorator\n// -----------------------------------------------------------------------------\n\n/**\n * Decorate a Branch instance so `.crud(...)` is available at runtime.\n * Tip: wrap the root: `withCrud(resource('/v1'))`.\n * @param branch Branch returned by `resource(...)`.\n * @returns Same branch with `.crud(...)` installed.\n */\nexport function withCrud<\n Base extends string,\n Acc extends readonly AnyLeaf[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n>(branch: _Branch<Base, Acc, I, PS>): _Branch<Base, Acc, I, PS> {\n const b = branch as any;\n if (typeof b.crud === 'function') return branch;\n\n b.crud = function <\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeaf[] = readonly [],\n >(this: any, name: Name, cfg: C, extras?: (ctx: { collection: any; item: any }) => Extras) {\n // Build inside a sub-branch at `/.../<name>` and harvest its leaves.\n return this.sub(name, (collection: any) => {\n const idKey = `${name}Id`;\n\n // Accept a value schema (preferred); but if a z.object({[name]Id: ...}) is provided, use it.\n const s = cfg.paramSchema;\n const isObj =\n s &&\n typeof (s as any)._def === 'object' &&\n (s as any)._def.typeName === 'ZodObject' &&\n typeof (s as any).shape === 'function';\n\n const paramValueSchema =\n isObj && (s as any).shape()[idKey] ? ((s as any).shape()[idKey] as ZodType) : (s as ZodType);\n\n const itemOut = cfg.itemOutputSchema;\n const listOut =\n cfg.list?.outputSchema ??\n z.object({\n items: z.array(itemOut),\n nextCursor: z.string().optional(),\n });\n\n const want = {\n list: cfg.enable?.list !== false,\n create: cfg.enable?.create !== false && !!cfg.create?.bodySchema,\n read: cfg.enable?.read !== false,\n update: cfg.enable?.update !== false && !!cfg.update?.bodySchema,\n remove: cfg.enable?.remove !== false,\n } as const;\n\n // Collection routes\n if (want.list) {\n collection.get({\n feed: true,\n querySchema: cfg.list?.querySchema ?? CrudDefaultPagination,\n outputSchema: listOut,\n description: cfg.list?.description ?? 'List',\n });\n }\n\n if (want.create) {\n collection.post({\n bodySchema: cfg.create!.bodySchema,\n outputSchema: cfg.create?.outputSchema ?? itemOut,\n description: cfg.create?.description ?? 'Create',\n });\n }\n\n // Item routes via :<name>Id\n collection.routeParameter(idKey as any, paramValueSchema as any, (item: any) => {\n if (want.read) {\n item.get({\n outputSchema: cfg.read?.outputSchema ?? itemOut,\n description: cfg.read?.description ?? 'Read',\n });\n }\n if (want.update) {\n item.patch({\n bodySchema: cfg.update!.bodySchema,\n outputSchema: cfg.update?.outputSchema ?? itemOut,\n description: cfg.update?.description ?? 'Update',\n });\n }\n if (want.remove) {\n item.delete({\n outputSchema: cfg.remove?.outputSchema ?? z.object({ ok: z.literal(true) }),\n description: cfg.remove?.description ?? 'Delete',\n });\n }\n\n // Give extras fully-capable builders (decorate so extras can call .crud again)\n if (extras) extras({ collection: withCrud(collection), item: withCrud(item) });\n\n return item.done();\n });\n\n return collection.done();\n });\n };\n\n return branch;\n}\n\n// -----------------------------------------------------------------------------\n// Optional convenience: re-export a resource() that already has .crud installed\n// -----------------------------------------------------------------------------\n\n/**\n * Drop-in replacement for `resource(...)` that returns a Branch with `.crud()` installed.\n * You can either use this or call `withCrud(resource(...))`.\n * @param base Root path for the resource (e.g. `/v1`).\n * @param inherited Node configuration merged into every leaf.\n * @returns Branch builder that already includes the CRUD helper.\n */\nexport function resourceWithCrud<Base extends string, I extends NodeCfg = {}>(\n base: Base,\n inherited: I,\n) {\n return withCrud(baseResource(base, inherited));\n}\n\n// Re-export the original in case you want both styles from this module\nexport { baseResource as resource };\n","// socket.index.ts (shared client/server)\n// TODO:\n// 1. Automatic feed handling:\n// * Expand onReceive to be like a middleware chain. This would allow for automatic feed handling middleware to be added that would handle:\n// - 1. updating maps/dictionaries based on feed messages\n// - 2. handling join/leave rooms\n// 2. General helpers: \n// - Easy combine of routes and sockets in the client: Room joining onReceive handlers, map helpers that build dictionaries of the data from feeds for easy access, lifecycle handling)\n// - Custom route structure definitions (feed + information routes, get/put/patch/delete based on few central schemas, )\nimport { z } from 'zod';\n\nexport type SocketSchema<Output =unknown> = z.ZodType & {\n __out: Output;\n};\n\nexport type SocketSchemaOutput<Schema extends z.ZodTypeAny> = Schema extends {\n __out: infer Out;\n} ? Out : z.output<Schema>;\n\nexport type SocketEvent<Out = unknown> = {\n message: z.ZodTypeAny;\n /** phantom field, only for typing; not meant to be used at runtime */\n __out: Out;\n};\n\nexport type EventMap = Record<string, SocketEvent<any>>;\n\n/**\n * System event names – shared so server and client\n * don't drift on naming.\n */\nexport type SysEventName = 'sys:connect' | 'sys:disconnect' | 'sys:reconnect' | 'sys:connect_error' | 'sys:ping' | 'sys:pong' | 'sys:room_join' | 'sys:room_leave';\nexport function defineSocketEvents<const C extends SocketConnectionConfig, const Schemas extends Record<string, {\n message: z.ZodTypeAny;\n}>>(config: C, events: Schemas): {\n config: {\n [K in keyof C]: SocketSchema<z.output<C[K]>>;\n };\n events: {\n [K in keyof Schemas]: SocketEvent<z.output<Schemas[K]['message']>>;\n };\n};\n\nexport function defineSocketEvents(config: any, events: any) {\n return { config, events };\n}\n\n\n\nexport type Payload<T extends EventMap, K extends keyof T> = T[K] extends SocketEvent<infer Out> ? Out : never;\nexport type SocketConnectionConfig = {\n joinMetaMessage: z.ZodTypeAny;\n leaveMetaMessage: z.ZodTypeAny;\n pingPayload: z.ZodTypeAny;\n pongPayload: z.ZodTypeAny;\n};\n\nexport type SocketConnectionConfigOutput = {\n joinMetaMessage: SocketSchema<any>;\n leaveMetaMessage: SocketSchema<any>;\n pingPayload: SocketSchema<any>;\n pongPayload: SocketSchema<any>;\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAAA;AAAA,EAAA;AA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AI,MAAM,eAAe;AAAA,UACxC,CAAC;AAAA,QACH;AACA,YAAI,KAAK,QAAQ;AACf,eAAK,MAAM;AAAA,YACT,YAAY,IAAI,OAAQ;AAAA,YACxB,cAAc,IAAI,QAAQ,gBAAgB;AAAA,YAC1C,aAAa,IAAI,QAAQ,eAAe;AAAA,UAC1C,CAAC;AAAA,QACH;AACA,YAAI,KAAK,QAAQ;AACf,eAAK,OAAO;AAAA,YACV,cAAc,IAAI,QAAQ,gBAAgB,cAAE,OAAO,EAAE,IAAI,cAAE,QAAQ,IAAI,EAAE,CAAC;AAAA,YAC1E,aAAa,IAAI,QAAQ,eAAe;AAAA,UAC1C,CAAC;AAAA,QACH;AAGA,YAAI,OAAQ,QAAO,EAAE,YAAY,SAAS,UAAU,GAAG,MAAM,SAAS,IAAI,EAAE,CAAC;AAE7E,eAAO,KAAK,KAAK;AAAA,MACnB,CAAC;AAED,aAAO,WAAW,KAAK;AAAA,IACzB,CAAC;AAAA,EACH;AAEA,SAAO;AACT;AAaO,SAAS,iBACd,MACA,WACA;AACA,SAAO,SAAS,SAAa,MAAM,SAAS,CAAC;AAC/C;;;ACpbO,SAAS,mBAAmB,QAAa,QAAa;AAC3D,SAAO,EAAE,QAAQ,OAAO;AAC1B;","names":["mergeSchemas","import_zod","mergeSchemas"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/core/routesV3.builder.ts","../src/core/routesV3.core.ts","../src/core/routesV3.finalize.ts","../src/crud/routesV3.crud.ts","../src/sockets/socket.index.ts","../src/docs/docs.ts"],"sourcesContent":["export * from './core/routesV3.builder';\nexport * from './core/routesV3.core';\nexport * from './core/routesV3.finalize';\nexport * from './crud/routesV3.crud';\nexport * from './sockets/socket.index';\nexport * from './docs/docs';","import { z } from 'zod';\nimport {\n AnyLeaf,\n Append,\n HttpMethod,\n Leaf,\n Merge,\n MergeArray,\n MethodCfg,\n NodeCfg,\n Prettify,\n} from './routesV3.core';\n\nconst defaultFeedQuerySchema = z.object({\n cursor: z.string().optional(),\n limit: z.coerce.number().min(1).max(100).default(20),\n});\n\nconst paginationField = defaultFeedQuerySchema.optional().default(defaultFeedQuerySchema.parse({}));\ntype PaginationField = typeof paginationField;\n\ntype ZodTypeAny = z.ZodTypeAny;\ntype ParamZod<Name extends string, S extends ZodTypeAny> = z.ZodObject<{ [K in Name]: S }>;\ntype ZodArrayAny = z.ZodArray<ZodTypeAny>;\ntype ZodObjectAny = z.ZodObject<any>;\ntype AnyZodObject = z.ZodObject<any>;\ntype MergedParamsResult<PS, Name extends string, P extends ZodTypeAny> = PS extends ZodTypeAny\n ? z.ZodIntersection<PS, ParamZod<Name, P>>\n : ParamZod<Name, P>;\n\nconst defaultFeedOutputSchema = z.object({\n items: z.array(z.unknown()),\n nextCursor: z.string().optional(),\n});\n\nfunction augmentFeedQuerySchema<Q extends ZodTypeAny | undefined>(schema: Q) {\n if (schema && !(schema instanceof z.ZodObject)) {\n console.warn('Feed queries must be a ZodObject; default pagination applied.');\n return z.object({\n pagination: paginationField,\n });\n }\n\n const base = (schema as ZodObjectAny) ?? z.object({});\n return base.extend({\n pagination: paginationField,\n });\n}\n\nfunction augmentFeedOutputSchema<O extends ZodTypeAny | undefined>(schema: O) {\n if (!schema) return defaultFeedOutputSchema;\n if (schema instanceof z.ZodArray) {\n return z.object({\n items: schema,\n nextCursor: z.string().optional(),\n });\n }\n if (schema instanceof z.ZodObject) {\n const shape = (schema as any).shape ? (schema as any).shape : (schema as any)._def?.shape?.();\n const hasItems = Boolean(shape?.items);\n if (hasItems) {\n return schema.extend({ nextCursor: z.string().optional() });\n }\n return z.object({\n items: z.array(schema as ZodTypeAny),\n nextCursor: z.string().optional(),\n });\n }\n return z.object({\n items: z.array(schema as ZodTypeAny),\n nextCursor: z.string().optional(),\n });\n}\n\n/**\n * Runtime helper that mirrors the typed merge used by the builder.\n * @param a Previously merged params schema inherited from parent segments.\n * @param b Newly introduced params schema.\n * @returns Intersection of schemas when both exist, otherwise whichever is defined.\n */\nfunction mergeSchemas<A extends ZodTypeAny, B extends ZodTypeAny>(a: A, b: B): ZodTypeAny;\nfunction mergeSchemas<A extends ZodTypeAny>(a: A, b: undefined): A;\nfunction mergeSchemas<B extends ZodTypeAny>(a: undefined, b: B): B;\nfunction mergeSchemas(a: ZodTypeAny | undefined, b: ZodTypeAny | undefined): ZodTypeAny | undefined;\nfunction mergeSchemas(a: ZodTypeAny | undefined, b: ZodTypeAny | undefined) {\n if (a && b) return z.intersection(a as any, b as any);\n return (a ?? b) as ZodTypeAny | undefined;\n}\n\ntype FeedQuerySchema<C extends MethodCfg> = z.ZodObject<any>;\n\ntype FeedOutputSchema<C extends MethodCfg> = C['outputSchema'] extends ZodArrayAny\n ? z.ZodObject<{\n items: C['outputSchema'];\n nextCursor: z.ZodOptional<z.ZodString>;\n }>\n : C['outputSchema'] extends ZodTypeAny\n ? z.ZodObject<{\n items: z.ZodArray<C['outputSchema']>;\n nextCursor: z.ZodOptional<z.ZodString>;\n }>\n : typeof defaultFeedOutputSchema;\n\ntype BaseMethodCfg<C extends MethodCfg> = Merge<\n Omit<MethodCfg, 'querySchema' | 'outputSchema' | 'feed'>,\n Omit<C, 'querySchema' | 'outputSchema' | 'feed'>\n>;\n\ntype FeedField<C extends MethodCfg> = C['feed'] extends true ? { feed: true } : { feed?: boolean };\n\ntype AddPaginationToQuery<Q extends AnyZodObject | undefined> = Q extends z.ZodObject<\n infer Shape\n>\n ? z.ZodObject<Shape & { pagination: PaginationField }>\n : z.ZodObject<{ pagination: PaginationField }>;\n\ntype FeedQueryField<C extends MethodCfg> = {\n querySchema: AddPaginationToQuery<\n C['querySchema'] extends AnyZodObject ? C['querySchema'] : undefined\n >;\n};\n\ntype NonFeedQueryField<C extends MethodCfg> = C['querySchema'] extends ZodTypeAny\n ? { querySchema: C['querySchema'] }\n : { querySchema?: undefined };\n\ntype FeedOutputField<C extends MethodCfg> = { outputSchema: FeedOutputSchema<C> };\n\ntype NonFeedOutputField<C extends MethodCfg> = C['outputSchema'] extends ZodTypeAny\n ? { outputSchema: C['outputSchema'] }\n : { outputSchema?: undefined };\n\ntype ParamsField<C extends MethodCfg, PS> = C['paramsSchema'] extends ZodTypeAny\n ? { paramsSchema: C['paramsSchema'] }\n : { paramsSchema: PS };\n\ntype EffectiveFeedFields<C extends MethodCfg, PS> = C['feed'] extends true\n ? FeedField<C> & FeedQueryField<C> & FeedOutputField<C> & ParamsField<C, PS>\n : FeedField<C> & NonFeedQueryField<C> & NonFeedOutputField<C> & ParamsField<C, PS>;\n\ntype EffectiveCfg<C extends MethodCfg, PS> = Prettify<\n Merge<MethodCfg, BaseMethodCfg<C> & EffectiveFeedFields<C, PS>>\n>;\n\ntype BuiltLeaf<\n M extends HttpMethod,\n Base extends string,\n I extends NodeCfg,\n C extends MethodCfg,\n PS,\n> = Leaf<M, Base, Merge<I, EffectiveCfg<C, PS>>>;\n\n/** Builder surface used by `resource(...)` to accumulate leaves. */\nexport interface Branch<\n Base extends string,\n Acc extends readonly AnyLeaf[],\n I extends NodeCfg,\n PS extends ZodTypeAny | undefined,\n> {\n // --- structure ---\n /**\n * Enter or define a static child segment.\n * Optionally accepts extra config and/or a builder to populate nested routes.\n * @param name Child segment literal (no leading slash).\n * @param cfg Optional node configuration to merge for descendants.\n * @param builder Callback to produce leaves for the child branch.\n */\n sub<Name extends string, J extends NodeCfg>(\n name: Name,\n cfg?: J,\n ): Branch<`${Base}/${Name}`, Acc, Merge<I, NonNullable<J>>, PS>;\n\n sub<Name extends string, J extends NodeCfg | undefined, R extends readonly AnyLeaf[]>(\n name: Name,\n cfg: J,\n builder: (r: Branch<`${Base}/${Name}`, readonly [], Merge<I, NonNullable<J>>, PS>) => R,\n ): Branch<Base, Append<Acc, R[number]>, Merge<I, NonNullable<J>>, PS>;\n\n sub<Name extends string, R extends readonly AnyLeaf[]>(\n name: Name,\n builder: (r: Branch<`${Base}/${Name}`, readonly [], I, PS>) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, PS>;\n\n // --- parameterized segment (single signature) ---\n /**\n * Introduce a `:param` segment and merge its schema into downstream leaves.\n * @param name Parameter key (without leading colon).\n * @param paramsSchema Zod schema for the parameter value.\n * @param builder Callback that produces leaves beneath the parameterized segment.\n */\n routeParameter<Name extends string, P extends ZodTypeAny, R extends readonly AnyLeaf[]>(\n name: Name,\n paramsSchema: P,\n builder: (\n r: Branch<\n `${Base}/:${Name}`,\n readonly [],\n I,\n MergedParamsResult<PS, Name, P>\n >,\n ) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, MergedParamsResult<PS, Name, P>>;\n\n // --- flags inheritance ---\n /**\n * Merge additional node configuration that subsequent leaves will inherit.\n * @param cfg Partial node configuration.\n */\n with<J extends NodeCfg>(cfg: J): Branch<Base, Acc, Merge<I, J>, PS>;\n\n // --- methods (return Branch to keep chaining) ---\n /**\n * Register a GET leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n get<C extends MethodCfg>(\n cfg: C,\n ): Branch<\n Base,\n Append<Acc, Prettify<BuiltLeaf<'get', Base, I, C, PS>>>,\n I,\n PS\n >;\n\n /**\n * Register a POST leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n post<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'post', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >;\n\n /**\n * Register a PUT leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n put<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'put', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >;\n\n /**\n * Register a PATCH leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n patch<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'patch', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >;\n\n /**\n * Register a DELETE leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n delete<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'delete', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >;\n\n // --- finalize this subtree ---\n /**\n * Finish the branch and return the collected leaves.\n * @returns Readonly tuple of accumulated leaves.\n */\n done(): Readonly<Acc>;\n}\n\n/**\n * Start building a resource at the given base path.\n * @param base Root path for the resource (e.g. `/v1`).\n * @param inherited Optional node configuration applied to all descendants.\n * @returns Root `Branch` instance used to compose the route tree.\n */\nexport function resource<Base extends string, I extends NodeCfg = {}>(\n base: Base,\n inherited?: I,\n): Branch<Base, readonly [], I, undefined> {\n const rootBase = base;\n const rootInherited: NodeCfg = { ...(inherited as NodeCfg) };\n\n function makeBranch<Base2 extends string, I2 extends NodeCfg, PS2 extends ZodTypeAny | undefined>(\n base2: Base2,\n inherited2: I2,\n mergedParamsSchema?: PS2,\n ) {\n const stack: AnyLeaf[] = [];\n let currentBase: string = base2;\n let inheritedCfg: NodeCfg = { ...(inherited2 as NodeCfg) };\n let currentParamsSchema: PS2 = mergedParamsSchema as PS2;\n\n function add<M extends HttpMethod, C extends MethodCfg>(method: M, cfg: C) {\n // If the method didn’t provide a paramsSchema, inject the active merged one.\n const effectiveParamsSchema = (cfg.paramsSchema ?? currentParamsSchema) as PS2 | undefined;\n const effectiveQuerySchema =\n cfg.feed === true ? augmentFeedQuerySchema(cfg.querySchema) : cfg.querySchema;\n const effectiveOutputSchema =\n cfg.feed === true ? augmentFeedOutputSchema(cfg.outputSchema) : cfg.outputSchema;\n\n const fullCfg = (\n effectiveParamsSchema\n ? {\n ...inheritedCfg,\n ...cfg,\n paramsSchema: effectiveParamsSchema,\n ...(effectiveQuerySchema ? { querySchema: effectiveQuerySchema } : {}),\n ...(effectiveOutputSchema ? { outputSchema: effectiveOutputSchema } : {}),\n }\n : {\n ...inheritedCfg,\n ...cfg,\n ...(effectiveQuerySchema ? { querySchema: effectiveQuerySchema } : {}),\n ...(effectiveOutputSchema ? { outputSchema: effectiveOutputSchema } : {}),\n }\n ) as any;\n\n const leaf = {\n method,\n path: currentBase as Base2,\n cfg: fullCfg,\n } as const;\n\n stack.push(leaf as unknown as AnyLeaf);\n\n // Return same runtime obj, but with Acc including this new leaf\n return api as unknown as Branch<Base2, Append<readonly [], typeof leaf>, I2, PS2>;\n }\n\n const api: any = {\n // compose a plain subpath (optional cfg) with optional builder\n sub<Name extends string, J extends NodeCfg | undefined = undefined>(\n name: Name,\n cfgOrBuilder?: J | ((r: any) => readonly AnyLeaf[]),\n maybeBuilder?: (r: any) => readonly AnyLeaf[],\n ) {\n let cfg: NodeCfg | undefined;\n let builder: ((r: any) => readonly AnyLeaf[]) | undefined;\n\n if (typeof cfgOrBuilder === 'function') {\n builder = cfgOrBuilder as any;\n } else {\n cfg = cfgOrBuilder as NodeCfg | undefined;\n builder = maybeBuilder;\n }\n\n const childBase = `${currentBase}/${name}` as const;\n const childInherited = { ...inheritedCfg, ...(cfg ?? {}) } as Merge<I2, NonNullable<J>>;\n\n if (builder) {\n // params schema PS2 flows through unchanged on plain sub\n const child = makeBranch(childBase, childInherited, currentParamsSchema);\n const leaves = builder(child) as readonly AnyLeaf[];\n for (const l of leaves) stack.push(l);\n return api as Branch<\n Base2,\n Append<readonly [], (typeof leaves)[number]>,\n typeof childInherited,\n PS2\n >;\n } else {\n currentBase = childBase;\n inheritedCfg = childInherited;\n return api as Branch<`${Base2}/${Name}`, readonly [], typeof childInherited, PS2>;\n }\n },\n\n // the single param function: name + schema + builder\n routeParameter<Name extends string, P extends ZodTypeAny, R extends readonly AnyLeaf[]>(\n name: Name,\n paramsSchema: P,\n builder: (\n r: Branch<\n `${Base2}/:${Name}`,\n readonly [],\n I2,\n MergedParamsResult<PS2, Name, P>\n >,\n ) => R,\n ) {\n const childBase = `${currentBase}/:${name}` as const;\n // Wrap the value schema under the param name before merging with inherited params schema\n const paramObj: ParamZod<Name, P> = z.object({ [name]: paramsSchema } as Record<Name, P>);\n const childParams = (currentParamsSchema\n ? mergeSchemas(currentParamsSchema, paramObj)\n : paramObj) as MergedParamsResult<PS2, Name, P>;\n const child = makeBranch(childBase, inheritedCfg as I2, childParams);\n const leaves = builder(child) as readonly AnyLeaf[];\n for (const l of leaves) stack.push(l);\n return api as Branch<\n Base2,\n Append<readonly [], (typeof leaves)[number]>,\n I2,\n MergedParamsResult<PS2, Name, P>\n >;\n },\n\n with<J extends NodeCfg>(cfg: J) {\n inheritedCfg = { ...inheritedCfg, ...cfg };\n return api as Branch<Base2, readonly [], Merge<I2, J>, PS2>;\n },\n\n // methods (inject current params schema if missing)\n get<C extends MethodCfg>(cfg: C) {\n return add('get', cfg);\n },\n post<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('post', { ...cfg, feed: false });\n },\n put<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('put', { ...cfg, feed: false });\n },\n patch<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('patch', { ...cfg, feed: false });\n },\n delete<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('delete', { ...cfg, feed: false });\n },\n\n done() {\n return stack;\n },\n };\n\n return api as Branch<Base2, readonly [], I2, PS2>;\n }\n\n // Root branch starts with no params schema (PS = undefined)\n return makeBranch(rootBase, rootInherited, undefined);\n}\n\n/**\n * Merge two readonly tuples (preserves literal tuple information).\n * @param arr1 First tuple.\n * @param arr2 Second tuple.\n * @returns New tuple containing values from both inputs.\n */\nexport const mergeArrays = <T extends readonly any[], S extends readonly any[]>(\n arr1: T,\n arr2: S,\n) => {\n return [...arr1, ...arr2] as [...T, ...S];\n};\n","import { z, ZodTypeAny } from 'zod';\n\n/** Supported HTTP verbs for the routes DSL. */\nexport type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\n/** Declarative description of a multipart upload field. */\nexport type FileField = {\n /** Form field name used for uploads. */\n name: string;\n /** Maximum number of files accepted for this field. */\n maxCount: number;\n};\n\n/** Configuration that applies to an entire branch of the route tree. */\nexport type NodeCfg = {\n /** @deprecated. Does nothing. */\n authenticated?: boolean;\n};\n\n/** Per-method configuration merged with inherited node config. */\nexport type MethodCfg = {\n /** Zod schema describing the request body. */\n bodySchema?: ZodTypeAny;\n /** Zod schema describing the query string. */\n querySchema?: ZodTypeAny;\n /** Zod schema describing path params (overrides inferred params). */\n paramsSchema?: ZodTypeAny;\n /** Zod schema describing the response payload. */\n outputSchema?: ZodTypeAny;\n /** Multipart upload definitions for the route. */\n bodyFiles?: FileField[];\n /** Marks the route as an infinite feed (enables cursor helpers). */\n feed?: boolean;\n /** Optional human-readable description for docs/debugging. */\n description?: string;\n};\n\n/** Immutable representation of a single HTTP route in the tree. */\nexport type Leaf<M extends HttpMethod, P extends string, C extends MethodCfg> = {\n /** Lowercase HTTP method (get/post/...). */\n readonly method: M;\n /** Concrete path for the route (e.g. `/v1/users/:userId`). */\n readonly path: P;\n /** Readonly snapshot of route configuration. */\n readonly cfg: Readonly<C>;\n};\n\n/** Convenience union covering all generated leaves. */\nexport type AnyLeaf = Leaf<HttpMethod, string, MethodCfg>;\n\n/** Merge two object types while keeping nice IntelliSense output. */\nexport type Merge<A, B> = Prettify<Omit<A, keyof B> & B>;\n\n/** Append a new element to a readonly tuple type. */\nexport type Append<T extends readonly unknown[], X> = [...T, X];\n\n/** Concatenate two readonly tuple types. */\nexport type MergeArray<A extends readonly unknown[], B extends readonly unknown[]> = [\n ...A,\n ...B,\n];\n\n// helpers (optional)\ntype SegmentParams<S extends string> = S extends `:${infer P}` ? P : never;\ntype Split<S extends string> = S extends ''\n ? []\n : S extends `${infer A}/${infer B}`\n ? [A, ...Split<B>]\n : [S];\ntype ExtractParamNames<Path extends string> = SegmentParams<Split<Path>[number]>;\n\n/** Derive a params object type from a literal route string. */\nexport type ExtractParamsFromPath<Path extends string> =\n ExtractParamNames<Path> extends never ? never : Record<ExtractParamNames<Path>, string | number>;\n\n/**\n * Interpolate `:params` in a path using the given values.\n * @param path Literal route string containing `:param` segments.\n * @param params Object of parameter values to interpolate.\n * @returns Path string with parameters substituted.\n */\nexport function compilePath<Path extends string>(path: Path, params: ExtractParamsFromPath<Path>) {\n if (!params) return path;\n return path.replace(/:([A-Za-z0-9_]+)/g, (_, k) => {\n const v = (params as any)[k];\n if (v === undefined || v === null) throw new Error(`Missing param :${k}`);\n return String(v);\n });\n}\n\n/**\n * Build a deterministic cache key for the given leaf.\n * The key matches the shape consumed by React Query helpers.\n * @param args.leaf Leaf describing the endpoint.\n * @param args.params Optional params used to build the path.\n * @param args.query Optional query payload.\n * @returns Tuple suitable for React Query cache keys.\n */\ntype SplitPath<P extends string> = P extends ''\n ? []\n : P extends `${infer A}/${infer B}`\n ? [A, ...SplitPath<B>]\n : [P];\nexport function buildCacheKey<L extends AnyLeaf>(args: {\n leaf: L;\n params?: ExtractParamsFromPath<L['path']>;\n query?: InferQuery<L>;\n}) {\n let p = args.leaf.path;\n if (args.params) {\n p = compilePath<L['path']>(p, args.params);\n }\n return [args.leaf.method, ...(p.split('/').filter(Boolean) as SplitPath<typeof p>), args.query ?? {}] as const;\n}\n\n/** Infer params either from the explicit params schema or from the path literal. */\nexport type InferParams<L extends AnyLeaf> = L['cfg']['paramsSchema'] extends ZodTypeAny\n ? z.infer<L['cfg']['paramsSchema']>\n : ExtractParamsFromPath<L['path']>;\n\n/** Infer query shape from a Zod schema when present. */\nexport type InferQuery<L extends AnyLeaf> = L['cfg']['querySchema'] extends ZodTypeAny\n ? z.infer<L['cfg']['querySchema']>\n : never;\n\n/** Infer request body shape from a Zod schema when present. */\nexport type InferBody<L extends AnyLeaf> = L['cfg']['bodySchema'] extends ZodTypeAny\n ? z.infer<L['cfg']['bodySchema']>\n : never;\n\n/** Infer handler output shape from a Zod schema. Defaults to unknown. */\nexport type InferOutput<L extends AnyLeaf> = L['cfg']['outputSchema'] extends ZodTypeAny\n ? z.infer<L['cfg']['outputSchema']>\n : unknown;\n\n/** Render a type as if it were a simple object literal. */\nexport type Prettify<T> = { [K in keyof T]: T[K] } & {};\n","// TODO:\n// * use this as a transform that infers the types from Zod, to only pass the types around instead of the full schemas -> make converters that go both ways (data to schema, schema to data)\n// * consider moving to core package\n// * update server and client side to use this type instead of raw zod schemas \nimport { AnyLeaf, HttpMethod, Prettify } from './routesV3.core';\n\n/** Build the key type for a leaf — distributive so method/path stay paired. */\nexport type KeyOf<L extends AnyLeaf> = L extends AnyLeaf\n ? `${Uppercase<L['method']>} ${L['path']}`\n : never;\n\n// From a tuple of leaves, get the union of keys (pairwise, no cartesian blow-up)\ntype KeysOf<Leaves extends readonly AnyLeaf[]> = KeyOf<Leaves[number]>;\n\n// Parse method & path out of a key\ntype MethodFromKey<K extends string> = K extends `${infer M} ${string}` ? Lowercase<M> : never;\ntype PathFromKey<K extends string> = K extends `${string} ${infer P}` ? P : never;\n\n// Given Leaves and a Key, pick the exact leaf that matches method+path\ntype LeafForKey<Leaves extends readonly AnyLeaf[], K extends string> = Extract<\n Leaves[number],\n { method: MethodFromKey<K> & HttpMethod; path: PathFromKey<K> }\n>;\n\n/**\n * Freeze a leaf tuple into a registry with typed key lookups.\n * @param leaves Readonly tuple of leaves produced by the builder DSL.\n * @returns Registry containing the leaves array and a `byKey` lookup map.\n */\nexport function finalize<const L extends readonly AnyLeaf[]>(leaves: L) {\n type Keys = KeysOf<L>;\n type MapByKey = { [K in Keys]: Prettify<LeafForKey<L, K>> };\n\n const byKey = Object.fromEntries(\n leaves.map((l) => [`${l.method.toUpperCase()} ${l.path}`, l] as const),\n ) as unknown as MapByKey;\n\n const log = (logger: { system: (...args: unknown[]) => void }) => {\n logger.system('Finalized routes:');\n (Object.keys(byKey) as Keys[]).forEach((k) => {\n const leaf = byKey[k];\n logger.system(`- ${k}`);\n });\n };\n\n return { all: leaves, byKey, log };\n}\n\n/** Nominal type alias for a finalized registry. */\nexport type Registry<R extends ReturnType<typeof finalize>> = R;\n\ntype FilterRoute<\n T extends readonly AnyLeaf[],\n F extends string,\n Acc extends readonly AnyLeaf[] = [],\n> = T extends readonly [infer First extends AnyLeaf, ...infer Rest extends AnyLeaf[]]\n ? First extends { path: `${string}${F}${string}` }\n ? FilterRoute<Rest, F, [...Acc, First]>\n : FilterRoute<Rest, F, Acc>\n : Acc;\n\ntype UpperCase<S extends string> = S extends `${infer First}${infer Rest}`\n ? `${Uppercase<First>}${UpperCase<Rest>}`\n : S;\n\ntype Routes<T extends readonly AnyLeaf[], F extends string> = FilterRoute<T, F>;\ntype ByKey<\n T extends readonly AnyLeaf[],\n Acc extends Record<string, AnyLeaf> = {},\n> = T extends readonly [infer First extends AnyLeaf, ...infer Rest extends AnyLeaf[]]\n ? ByKey<Rest, Acc & { [K in `${UpperCase<First['method']>} ${First['path']}`]: First }>\n : Acc;\n\n/**\n * Convenience helper for extracting a subset of routes by path fragment.\n * @param T Tuple of leaves produced by the DSL.\n * @param F String fragment to match against the route path.\n */\nexport type SubsetRoutes<T extends readonly AnyLeaf[], F extends string> = {\n byKey: ByKey<Routes<T, F>>;\n all: Routes<T, F>;\n};\n","// routesV3.crud.ts\n// -----------------------------------------------------------------------------\n// Add a first-class .crud() helper to the routesV3 DSL, without touching the\n// core builder. This file:\n// 1) Declares types + module augmentation to extend Branch<...> with .crud\n// 2) Provides a runtime decorator `withCrud(...)` that installs the method\n// 3) Exports a convenience `resourceWithCrud(...)` wrapper (optional)\n// -----------------------------------------------------------------------------\n\nimport { z, ZodType } from 'zod';\nimport {\n resource as baseResource,\n type Branch as _Branch, // import type so we can augment it\n} from '../core/routesV3.builder';\nimport { type AnyLeaf, type Leaf, type NodeCfg } from '../core/routesV3.core';\n\n// -----------------------------------------------------------------------------\n// Small utilities (runtime + types)\n// -----------------------------------------------------------------------------\n/** Default cursor pagination used by list (GET collection). */\nexport const CrudDefaultPagination = z.object({\n limit: z.coerce.number().min(1).max(100).default(20),\n cursor: z.string().optional(),\n});\nconst CrudPaginationField = CrudDefaultPagination.optional().default(CrudDefaultPagination.parse({}));\ntype CrudPaginationField = typeof CrudPaginationField;\ntype AnyCrudZodObject = z.ZodObject<any>;\ntype AddCrudPagination<Q extends AnyCrudZodObject | undefined> = Q extends z.ZodObject<infer Shape>\n ? z.ZodObject<Shape & { pagination: CrudPaginationField }>\n : z.ZodObject<{ pagination: CrudPaginationField }>;\n\n/**\n * Merge two Zod schemas at runtime; matches the typing pattern used in builder.\n * @param a Existing params schema inherited from parent branches.\n * @param b Schema introduced at the current branch.\n * @returns Intersection of schemas when both exist, otherwise whichever is defined.\n */\nexport function mergeSchemas<A extends ZodType | undefined, B extends ZodType | undefined>(\n a: A,\n b: B,\n): A extends ZodType ? (B extends ZodType ? ReturnType<typeof z.intersection<A, B>> : A) : B {\n if (a && b) return z.intersection(a as any, b as any) as any;\n return (a ?? b) as any;\n}\n\n/** Build { [Name]: S } Zod object at the type-level. */\nexport type ParamSchema<Name extends string, S extends ZodType> = z.ZodObject<{\n [K in Name]: S;\n}>;\n\n/** Inject active params schema into a leaf cfg (to match your Leaf typing). */\ntype WithParams<I, P> = P extends ZodType ? Omit<I, 'paramsSchema'> & { paramsSchema: P } : I;\n\n/** Resolve boolean flag: default D unless explicitly false. */\ntype Flag<E, D extends boolean> = E extends false ? false : D;\n\n// -----------------------------------------------------------------------------\n// CRUD config (few knobs, with DX comments)\n// -----------------------------------------------------------------------------\n\n/** Toggle individual CRUD methods; defaults enable all (create/update require body). */\nexport type CrudEnable = {\n /** GET /collection (feed). Defaults to true. */ list?: boolean;\n /** POST /collection. Defaults to true if `create` provided. */ create?: boolean;\n /** GET /collection/:id. Defaults to true. */ read?: boolean;\n /** PATCH /collection/:id. Defaults to true if `update` provided. */ update?: boolean;\n /** DELETE /collection/:id. Defaults to true. */ remove?: boolean;\n};\n\n/** Collection GET config. */\nexport type CrudListCfg = {\n /** Query schema (defaults to cursor pagination). */\n querySchema?: ZodType;\n /** Output schema (defaults to { items: Item[], nextCursor? }). */\n outputSchema?: ZodType;\n /** Optional description string. */\n description?: string;\n};\n\n/** Collection POST config. */\nexport type CrudCreateCfg = {\n /** Body schema for creating an item. */\n bodySchema: ZodType;\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType;\n /** Optional description. */\n description?: string;\n};\n\n/** Item GET config. */\nexport type CrudReadCfg = {\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType;\n /** Optional description. */\n description?: string;\n};\n\n/** Item PATCH config. */\nexport type CrudUpdateCfg = {\n /** Body schema for partial updates. */\n bodySchema: ZodType;\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType;\n /** Optional description. */\n description?: string;\n};\n\n/** Item DELETE config. */\nexport type CrudRemoveCfg = {\n /** Output schema (defaults to { ok: true }). */\n outputSchema?: ZodType;\n /** Optional description. */\n description?: string;\n};\n\n/**\n * CRUD config for `.crud(\"resource\", cfg, extras?)`.\n *\n * It synthesizes `:[resourceName]Id` as the param key and uses `paramSchema` for the value.\n * Prefer passing a **value schema** (e.g. `z.string().uuid()`).\n * As a convenience, a ZodObject of shape `{ [resourceName]Id: schema }` is accepted at runtime too.\n */\nexport type CrudCfg<Name extends string = string> = {\n /**\n * Zod schema for the ID *value* (e.g. `z.string().uuid()`).\n * The parameter key is always `:${name}Id`.\n * (If you pass `z.object({ [name]Id: ... })`, it's accepted at runtime.)\n */\n paramSchema: ZodType;\n\n /**\n * The single-item output shape used by read/create/update by default.\n * List defaults to `{ items: z.array(itemOutputSchema), nextCursor? }`.\n */\n itemOutputSchema: ZodType;\n\n /** Per-method toggles (all enabled by default; create/update require bodies). */\n enable?: CrudEnable;\n\n /** GET /collection configuration. */ list?: CrudListCfg;\n /** POST /collection configuration (enables create). */ create?: CrudCreateCfg;\n /** GET /collection/:id configuration. */ read?: CrudReadCfg;\n /** PATCH /collection/:id configuration (enables update). */ update?: CrudUpdateCfg;\n /** DELETE /collection/:id configuration. */ remove?: CrudRemoveCfg;\n};\n\n// -----------------------------------------------------------------------------\n// Type plumbing to expose generated leaves (so finalize().byKey sees them)\n// -----------------------------------------------------------------------------\n\ntype CrudLeavesTuple<\n Base extends string,\n I extends NodeCfg,\n PS extends ZodType | undefined,\n Name extends string,\n C extends CrudCfg<Name>,\n> = `${Name}Id` extends infer IdName extends string\n ? ParamSchema<IdName, C['paramSchema']> extends infer IdParamZ extends ZodType\n ? [\n // GET /collection\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['list'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'get',\n `${Base}/${Name}`,\n WithParams<\n Omit<I, never> & {\n feed: true;\n querySchema: C['list'] extends CrudListCfg\n ? AddCrudPagination<\n C['list']['querySchema'] extends AnyCrudZodObject\n ? C['list']['querySchema']\n : undefined\n >\n : AddCrudPagination<undefined>;\n outputSchema: C['list'] extends CrudListCfg\n ? C['list']['outputSchema'] extends ZodType\n ? C['list']['outputSchema']\n : z.ZodObject<{\n items: z.ZodArray<C['itemOutputSchema']>;\n nextCursor: z.ZodOptional<z.ZodString>;\n }>\n : z.ZodObject<{\n items: z.ZodArray<C['itemOutputSchema']>;\n nextCursor: z.ZodOptional<z.ZodString>;\n }>;\n description?: string;\n },\n PS\n >\n >,\n ]\n : []),\n\n // POST /collection\n ...((C['create'] extends CrudCreateCfg ? true : false) extends true\n ? Flag<\n C['enable'] extends CrudEnable ? C['enable']['create'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'post',\n `${Base}/${Name}`,\n WithParams<\n Omit<I, never> & {\n bodySchema: C['create'] extends CrudCreateCfg\n ? C['create']['bodySchema']\n : never;\n outputSchema: C['create'] extends CrudCreateCfg\n ? C['create']['outputSchema'] extends ZodType\n ? C['create']['outputSchema']\n : C['itemOutputSchema']\n : never;\n description?: string;\n },\n PS\n >\n >,\n ]\n : []\n : []),\n\n // GET /collection/:id\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['read'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'get',\n `${Base}/${Name}/:${IdName}`,\n WithParams<\n Omit<I, never> & {\n outputSchema: C['read'] extends CrudReadCfg\n ? C['read']['outputSchema'] extends ZodType\n ? C['read']['outputSchema']\n : C['itemOutputSchema']\n : C['itemOutputSchema'];\n description?: string;\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >,\n ]\n : []),\n\n // PATCH /collection/:id\n ...((C['update'] extends CrudUpdateCfg ? true : false) extends true\n ? Flag<\n C['enable'] extends CrudEnable ? C['enable']['update'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'patch',\n `${Base}/${Name}/:${IdName}`,\n WithParams<\n Omit<I, never> & {\n bodySchema: C['update'] extends CrudUpdateCfg\n ? C['update']['bodySchema']\n : never;\n outputSchema: C['update'] extends CrudUpdateCfg\n ? C['update']['outputSchema'] extends ZodType\n ? C['update']['outputSchema']\n : C['itemOutputSchema']\n : never;\n description?: string;\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >,\n ]\n : []\n : []),\n\n // DELETE /collection/:id\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['remove'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'delete',\n `${Base}/${Name}/:${IdName}`,\n WithParams<\n Omit<I, never> & {\n outputSchema: C['remove'] extends CrudRemoveCfg\n ? C['remove']['outputSchema'] extends ZodType\n ? C['remove']['outputSchema']\n : z.ZodObject<{ ok: z.ZodLiteral<true> }>\n : z.ZodObject<{ ok: z.ZodLiteral<true> }>;\n description?: string;\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >,\n ]\n : []),\n ]\n : never\n : never;\n\n/** Merge generated leaves + extras into the branch accumulator. */\ntype CrudResultAcc<\n Base extends string,\n Acc extends readonly AnyLeaf[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeaf[],\n> = [...Acc, ...CrudLeavesTuple<Base, I, PS, Name, C>, ...Extras];\n\n// -----------------------------------------------------------------------------\n// Module augmentation: add the typed `.crud(...)` to Branch<...>\n// -----------------------------------------------------------------------------\n\ndeclare module './../core/routesV3.builder' {\n interface Branch<\n Base extends string,\n Acc extends readonly AnyLeaf[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n > {\n /**\n * Generate opinionated CRUD endpoints for a collection at `/.../<name>`\n * with an item at `/.../<name>/:<name>Id`.\n *\n * Creates (subject to `enable` + presence of create/update bodies):\n * - GET /<name> (feed list)\n * - POST /<name> (create)\n * - GET /<name>/:<name>Id (read item)\n * - PATCH /<name>/:<name>Id (update item)\n * - DELETE /<name>/:<name>Id (remove item)\n *\n * The `extras` callback receives live builders at both collection and item\n * levels so you can add custom subroutes; their leaves are included in the\n * returned Branch type.\n */\n crud<\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeaf[] = readonly [],\n >(\n name: Name,\n cfg: C,\n extras?: (ctx: {\n /** Builder at `/.../<name>` (collection scope). */\n collection: _Branch<`${Base}/${Name}`, readonly [], I, PS>;\n /** Builder at `/.../<name>/:<name>Id` (item scope). */\n item: _Branch<\n `${Base}/${Name}/:${`${Name}Id`}`,\n readonly [],\n I,\n ReturnType<typeof mergeSchemas<PS, ParamSchema<`${Name}Id`, C['paramSchema']>>>\n >;\n }) => Extras,\n ): _Branch<Base, CrudResultAcc<Base, Acc, I, PS, Name, C, Extras>, I, PS>;\n }\n}\n\n// -----------------------------------------------------------------------------\n// Runtime: install .crud on any Branch via decorator\n// -----------------------------------------------------------------------------\n\n/**\n * Decorate a Branch instance so `.crud(...)` is available at runtime.\n * Tip: wrap the root: `withCrud(resource('/v1'))`.\n * @param branch Branch returned by `resource(...)`.\n * @returns Same branch with `.crud(...)` installed.\n */\nexport function withCrud<\n Base extends string,\n Acc extends readonly AnyLeaf[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n>(branch: _Branch<Base, Acc, I, PS>): _Branch<Base, Acc, I, PS> {\n const b = branch as any;\n if (typeof b.crud === 'function') return branch;\n\n b.crud = function <\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeaf[] = readonly [],\n >(this: any, name: Name, cfg: C, extras?: (ctx: { collection: any; item: any }) => Extras) {\n // Build inside a sub-branch at `/.../<name>` and harvest its leaves.\n return this.sub(name, (collection: any) => {\n const idKey = `${name}Id`;\n\n // Accept a value schema (preferred); but if a z.object({[name]Id: ...}) is provided, use it.\n const s = cfg.paramSchema;\n const isObj =\n s &&\n typeof (s as any)._def === 'object' &&\n (s as any)._def.typeName === 'ZodObject' &&\n typeof (s as any).shape === 'function';\n\n const paramValueSchema =\n isObj && (s as any).shape()[idKey] ? ((s as any).shape()[idKey] as ZodType) : (s as ZodType);\n\n const itemOut = cfg.itemOutputSchema;\n const listOut =\n cfg.list?.outputSchema ??\n z.object({\n items: z.array(itemOut),\n nextCursor: z.string().optional(),\n });\n\n const want = {\n list: cfg.enable?.list !== false,\n create: cfg.enable?.create !== false && !!cfg.create?.bodySchema,\n read: cfg.enable?.read !== false,\n update: cfg.enable?.update !== false && !!cfg.update?.bodySchema,\n remove: cfg.enable?.remove !== false,\n } as const;\n\n // Collection routes\n if (want.list) {\n collection.get({\n feed: true,\n querySchema: cfg.list?.querySchema ?? CrudDefaultPagination,\n outputSchema: listOut,\n description: cfg.list?.description ?? 'List',\n });\n }\n\n if (want.create) {\n collection.post({\n bodySchema: cfg.create!.bodySchema,\n outputSchema: cfg.create?.outputSchema ?? itemOut,\n description: cfg.create?.description ?? 'Create',\n });\n }\n\n // Item routes via :<name>Id\n collection.routeParameter(idKey as any, paramValueSchema as any, (item: any) => {\n if (want.read) {\n item.get({\n outputSchema: cfg.read?.outputSchema ?? itemOut,\n description: cfg.read?.description ?? 'Read',\n });\n }\n if (want.update) {\n item.patch({\n bodySchema: cfg.update!.bodySchema,\n outputSchema: cfg.update?.outputSchema ?? itemOut,\n description: cfg.update?.description ?? 'Update',\n });\n }\n if (want.remove) {\n item.delete({\n outputSchema: cfg.remove?.outputSchema ?? z.object({ ok: z.literal(true) }),\n description: cfg.remove?.description ?? 'Delete',\n });\n }\n\n // Give extras fully-capable builders (decorate so extras can call .crud again)\n if (extras) extras({ collection: withCrud(collection), item: withCrud(item) });\n\n return item.done();\n });\n\n return collection.done();\n });\n };\n\n return branch;\n}\n\n// -----------------------------------------------------------------------------\n// Optional convenience: re-export a resource() that already has .crud installed\n// -----------------------------------------------------------------------------\n\n/**\n * Drop-in replacement for `resource(...)` that returns a Branch with `.crud()` installed.\n * You can either use this or call `withCrud(resource(...))`.\n * @param base Root path for the resource (e.g. `/v1`).\n * @param inherited Node configuration merged into every leaf.\n * @returns Branch builder that already includes the CRUD helper.\n */\nexport function resourceWithCrud<Base extends string, I extends NodeCfg = {}>(\n base: Base,\n inherited: I,\n) {\n return withCrud(baseResource(base, inherited));\n}\n\n// Re-export the original in case you want both styles from this module\nexport { baseResource as resource };\n","// socket.index.ts (shared client/server)\n\nimport { z } from 'zod';\n\nexport type SocketSchema<Output =unknown> = z.ZodType & {\n __out: Output;\n};\n\nexport type SocketSchemaOutput<Schema extends z.ZodTypeAny> = Schema extends {\n __out: infer Out;\n} ? Out : z.output<Schema>;\n\nexport type SocketEvent<Out = unknown> = {\n message: z.ZodTypeAny;\n /** phantom field, only for typing; not meant to be used at runtime */\n __out: Out;\n};\n\nexport type EventMap = Record<string, SocketEvent<any>>;\n\n/**\n * System event names – shared so server and client\n * don't drift on naming.\n */\nexport type SysEventName = 'sys:connect' | 'sys:disconnect' | 'sys:reconnect' | 'sys:connect_error' | 'sys:ping' | 'sys:pong' | 'sys:room_join' | 'sys:room_leave';\nexport function defineSocketEvents<const C extends SocketConnectionConfig, const Schemas extends Record<string, {\n message: z.ZodTypeAny;\n}>>(config: C, events: Schemas): {\n config: {\n [K in keyof C]: SocketSchema<z.output<C[K]>>;\n };\n events: {\n [K in keyof Schemas]: SocketEvent<z.output<Schemas[K]['message']>>;\n };\n};\n\nexport function defineSocketEvents(config: any, events: any) {\n return { config, events };\n}\n\n\n\nexport type Payload<T extends EventMap, K extends keyof T> = T[K] extends SocketEvent<infer Out> ? Out : never;\nexport type SocketConnectionConfig = {\n joinMetaMessage: z.ZodTypeAny;\n leaveMetaMessage: z.ZodTypeAny;\n pingPayload: z.ZodTypeAny;\n pongPayload: z.ZodTypeAny;\n};\n\nexport type SocketConnectionConfigOutput = {\n joinMetaMessage: SocketSchema<any>;\n leaveMetaMessage: SocketSchema<any>;\n pingPayload: SocketSchema<any>;\n pongPayload: SocketSchema<any>;\n}","// docs-generator.ts\nimport { z, ZodType, ZodObject, ZodArray } from \"zod\";\nimport { AnyLeaf, FileField } from \"../core/routesV3.core\";\n\n\n// ------------------------------------------------------------\n// Schema summarizer (lightweight introspection for Zod v4)\n// ------------------------------------------------------------\nfunction summarizeSchema(schema?: ZodType): unknown {\n if (!schema) return undefined;\n\n // ZodObject\n if (schema instanceof ZodObject) {\n const shape = schema.shape;\n return {\n type: \"object\",\n fields: Object.fromEntries(\n Object.entries(shape).map(([key, value]) => {\n const def: any = (value as any)._def;\n return [\n key,\n {\n typeName: def?.typeName,\n description: def?.description\n }\n ];\n })\n )\n };\n }\n\n // ZodArray\n if (schema instanceof ZodArray) {\n return {\n type: \"array\",\n // @ts-ignore\n element: summarizeSchema(schema.unwrap())\n };\n }\n\n // fallback for primitives and complex types\n const def: any = (schema as any)._def;\n return { typeName: def?.typeName ?? \"unknown\" };\n}\n\n// ------------------------------------------------------------\n// Build a structured doc model from AnyLeaf[]\n// ------------------------------------------------------------\ntype RouteDoc = {\n method: string;\n path: string;\n description?: string;\n feed?: boolean;\n body?: unknown;\n query?: unknown;\n params?: unknown;\n output?: unknown;\n files?: FileField[];\n};\n\nfunction leavesToDocs(leaves: AnyLeaf[]): RouteDoc[] {\n return leaves.map((leaf) => {\n const { method, path, cfg } = leaf;\n\n return {\n method,\n path,\n description: cfg.description,\n feed: cfg.feed,\n body: summarizeSchema(cfg.bodySchema),\n query: summarizeSchema(cfg.querySchema),\n params: summarizeSchema(cfg.paramsSchema),\n output: summarizeSchema(cfg.outputSchema),\n files: cfg.bodyFiles\n };\n });\n}\n\n// ------------------------------------------------------------\n// Markdown renderer for the docs\n// ------------------------------------------------------------\nexport function renderLeafDocsMarkdown(leaves: AnyLeaf[]): string {\n const docs = leavesToDocs(leaves);\n\n docs.sort((a, b) => {\n const p = a.path.localeCompare(b.path);\n return p !== 0 ? p : a.method.localeCompare(b.method);\n });\n\n return docs\n .map((d) => {\n const lines: string[] = [];\n\n lines.push(`### \\`${d.method.toUpperCase()} ${d.path}\\``);\n\n if (d.description) {\n lines.push(\"\", d.description);\n }\n\n if (d.feed) {\n lines.push(\"\", \"_Feed endpoint_\");\n }\n\n function pushJson(title: string, value: unknown | undefined) {\n if (!value) return;\n lines.push(\n \"\",\n `**${title}**`,\n \"```json\",\n JSON.stringify(value, null, 2),\n \"```\"\n );\n }\n\n pushJson(\"Query\", d.query);\n pushJson(\"Params\", d.params);\n pushJson(\"Body\", d.body);\n pushJson(\"Output\", d.output);\n\n if (d.files && d.files.length > 0) {\n lines.push(\"\", \"**Multipart files**\");\n d.files.forEach((f) => {\n lines.push(`- \\`${f.name}\\` (maxCount: ${f.maxCount})`);\n });\n }\n\n return lines.join(\"\\n\");\n })\n .join(\"\\n\\n\");\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAAkB;AAalB,IAAM,yBAAyB,aAAE,OAAO;AAAA,EACtC,QAAQ,aAAE,OAAO,EAAE,SAAS;AAAA,EAC5B,OAAO,aAAE,OAAO,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,QAAQ,EAAE;AACrD,CAAC;AAED,IAAM,kBAAkB,uBAAuB,SAAS,EAAE,QAAQ,uBAAuB,MAAM,CAAC,CAAC,CAAC;A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M,KAAK,SAAS,EAAE,OAAO,YAAY,CAAC,IAAI,EAAE,IAAI,IAAI;AAExD,QAAI,EAAE,aAAa;AACjB,YAAM,KAAK,IAAI,EAAE,WAAW;AAAA,IAC9B;AAEA,QAAI,EAAE,MAAM;AACV,YAAM,KAAK,IAAI,iBAAiB;AAAA,IAClC;AAEA,aAAS,SAAS,OAAe,OAA4B;AAC3D,UAAI,CAAC,MAAO;AACZ,YAAM;AAAA,QACJ;AAAA,QACA,KAAK,KAAK;AAAA,QACV;AAAA,QACA,KAAK,UAAU,OAAO,MAAM,CAAC;AAAA,QAC7B;AAAA,MACF;AAAA,IACF;AAEA,aAAS,SAAS,EAAE,KAAK;AACzB,aAAS,UAAU,EAAE,MAAM;AAC3B,aAAS,QAAQ,EAAE,IAAI;AACvB,aAAS,UAAU,EAAE,MAAM;AAE3B,QAAI,EAAE,SAAS,EAAE,MAAM,SAAS,GAAG;AACjC,YAAM,KAAK,IAAI,qBAAqB;AACpC,QAAE,MAAM,QAAQ,CAAC,MAAM;AACrB,cAAM,KAAK,OAAO,EAAE,IAAI,iBAAiB,EAAE,QAAQ,GAAG;AAAA,MACxD,CAAC;AAAA,IACH;AAEA,WAAO,MAAM,KAAK,IAAI;AAAA,EACxB,CAAC,EACA,KAAK,MAAM;AAChB;","names":["mergeSchemas","import_zod","mergeSchemas","import_zod","def"]}
package/dist/index.d.ts CHANGED
@@ -3,3 +3,4 @@ export * from './core/routesV3.core';
3
3
  export * from './core/routesV3.finalize';
4
4
  export * from './crud/routesV3.crud';
5
5
  export * from './sockets/socket.index';
6
+ export * from './docs/docs';
package/dist/index.mjs CHANGED
@@ -1,5 +1,50 @@
1
1
  // src/core/routesV3.builder.ts
2
2
  import { z } from "zod";
3
+ var defaultFeedQuerySchema = z.object({
4
+ cursor: z.string().optional(),
5
+ limit: z.coerce.number().min(1).max(100).default(20)
6
+ });
7
+ var paginationField = defaultFeedQuerySchema.optional().default(defaultFeedQuerySchema.parse({}));
8
+ var defaultFeedOutputSchema = z.object({
9
+ items: z.array(z.unknown()),
10
+ nextCursor: z.string().optional()
11
+ });
12
+ function augmentFeedQuerySchema(schema) {
13
+ if (schema && !(schema instanceof z.ZodObject)) {
14
+ console.warn("Feed queries must be a ZodObject; default pagination applied.");
15
+ return z.object({
16
+ pagination: paginationField
17
+ });
18
+ }
19
+ const base = schema ?? z.object({});
20
+ return base.extend({
21
+ pagination: paginationField
22
+ });
23
+ }
24
+ function augmentFeedOutputSchema(schema) {
25
+ if (!schema) return defaultFeedOutputSchema;
26
+ if (schema instanceof z.ZodArray) {
27
+ return z.object({
28
+ items: schema,
29
+ nextCursor: z.string().optional()
30
+ });
31
+ }
32
+ if (schema instanceof z.ZodObject) {
33
+ const shape = schema.shape ? schema.shape : schema._def?.shape?.();
34
+ const hasItems = Boolean(shape?.items);
35
+ if (hasItems) {
36
+ return schema.extend({ nextCursor: z.string().optional() });
37
+ }
38
+ return z.object({
39
+ items: z.array(schema),
40
+ nextCursor: z.string().optional()
41
+ });
42
+ }
43
+ return z.object({
44
+ items: z.array(schema),
45
+ nextCursor: z.string().optional()
46
+ });
47
+ }
3
48
  function mergeSchemas(a, b) {
4
49
  if (a && b) return z.intersection(a, b);
5
50
  return a ?? b;
@@ -14,7 +59,20 @@ function resource(base, inherited) {
14
59
  let currentParamsSchema = mergedParamsSchema;
15
60
  function add(method, cfg) {
16
61
  const effectiveParamsSchema = cfg.paramsSchema ?? currentParamsSchema;
17
- const fullCfg = effectiveParamsSchema ? { ...inheritedCfg, ...cfg, paramsSchema: effectiveParamsSchema } : { ...inheritedCfg, ...cfg };
62
+ const effectiveQuerySchema = cfg.feed === true ? augmentFeedQuerySchema(cfg.querySchema) : cfg.querySchema;
63
+ const effectiveOutputSchema = cfg.feed === true ? augmentFeedOutputSchema(cfg.outputSchema) : cfg.outputSchema;
64
+ const fullCfg = effectiveParamsSchema ? {
65
+ ...inheritedCfg,
66
+ ...cfg,
67
+ paramsSchema: effectiveParamsSchema,
68
+ ...effectiveQuerySchema ? { querySchema: effectiveQuerySchema } : {},
69
+ ...effectiveOutputSchema ? { outputSchema: effectiveOutputSchema } : {}
70
+ } : {
71
+ ...inheritedCfg,
72
+ ...cfg,
73
+ ...effectiveQuerySchema ? { querySchema: effectiveQuerySchema } : {},
74
+ ...effectiveOutputSchema ? { outputSchema: effectiveOutputSchema } : {}
75
+ };
18
76
  const leaf = {
19
77
  method,
20
78
  path: currentBase,
@@ -51,7 +109,7 @@ function resource(base, inherited) {
51
109
  routeParameter(name, paramsSchema, builder) {
52
110
  const childBase = `${currentBase}/:${name}`;
53
111
  const paramObj = z.object({ [name]: paramsSchema });
54
- const childParams = mergeSchemas(currentParamsSchema, paramObj);
112
+ const childParams = currentParamsSchema ? mergeSchemas(currentParamsSchema, paramObj) : paramObj;
55
113
  const child = makeBranch(childBase, inheritedCfg, childParams);
56
114
  const leaves = builder(child);
57
115
  for (const l of leaves) stack.push(l);
@@ -127,6 +185,7 @@ var CrudDefaultPagination = z2.object({
127
185
  limit: z2.coerce.number().min(1).max(100).default(20),
128
186
  cursor: z2.string().optional()
129
187
  });
188
+ var CrudPaginationField = CrudDefaultPagination.optional().default(CrudDefaultPagination.parse({}));
130
189
  function mergeSchemas2(a, b) {
131
190
  if (a && b) return z2.intersection(a, b);
132
191
  return a ?? b;
@@ -203,6 +262,93 @@ function resourceWithCrud(base, inherited) {
203
262
  function defineSocketEvents(config, events) {
204
263
  return { config, events };
205
264
  }
265
+
266
+ // src/docs/docs.ts
267
+ import { ZodObject, ZodArray } from "zod";
268
+ function summarizeSchema(schema) {
269
+ if (!schema) return void 0;
270
+ if (schema instanceof ZodObject) {
271
+ const shape = schema.shape;
272
+ return {
273
+ type: "object",
274
+ fields: Object.fromEntries(
275
+ Object.entries(shape).map(([key, value]) => {
276
+ const def2 = value._def;
277
+ return [
278
+ key,
279
+ {
280
+ typeName: def2?.typeName,
281
+ description: def2?.description
282
+ }
283
+ ];
284
+ })
285
+ )
286
+ };
287
+ }
288
+ if (schema instanceof ZodArray) {
289
+ return {
290
+ type: "array",
291
+ // @ts-ignore
292
+ element: summarizeSchema(schema.unwrap())
293
+ };
294
+ }
295
+ const def = schema._def;
296
+ return { typeName: def?.typeName ?? "unknown" };
297
+ }
298
+ function leavesToDocs(leaves) {
299
+ return leaves.map((leaf) => {
300
+ const { method, path, cfg } = leaf;
301
+ return {
302
+ method,
303
+ path,
304
+ description: cfg.description,
305
+ feed: cfg.feed,
306
+ body: summarizeSchema(cfg.bodySchema),
307
+ query: summarizeSchema(cfg.querySchema),
308
+ params: summarizeSchema(cfg.paramsSchema),
309
+ output: summarizeSchema(cfg.outputSchema),
310
+ files: cfg.bodyFiles
311
+ };
312
+ });
313
+ }
314
+ function renderLeafDocsMarkdown(leaves) {
315
+ const docs = leavesToDocs(leaves);
316
+ docs.sort((a, b) => {
317
+ const p = a.path.localeCompare(b.path);
318
+ return p !== 0 ? p : a.method.localeCompare(b.method);
319
+ });
320
+ return docs.map((d) => {
321
+ const lines = [];
322
+ lines.push(`### \`${d.method.toUpperCase()} ${d.path}\``);
323
+ if (d.description) {
324
+ lines.push("", d.description);
325
+ }
326
+ if (d.feed) {
327
+ lines.push("", "_Feed endpoint_");
328
+ }
329
+ function pushJson(title, value) {
330
+ if (!value) return;
331
+ lines.push(
332
+ "",
333
+ `**${title}**`,
334
+ "```json",
335
+ JSON.stringify(value, null, 2),
336
+ "```"
337
+ );
338
+ }
339
+ pushJson("Query", d.query);
340
+ pushJson("Params", d.params);
341
+ pushJson("Body", d.body);
342
+ pushJson("Output", d.output);
343
+ if (d.files && d.files.length > 0) {
344
+ lines.push("", "**Multipart files**");
345
+ d.files.forEach((f) => {
346
+ lines.push(`- \`${f.name}\` (maxCount: ${f.maxCount})`);
347
+ });
348
+ }
349
+ return lines.join("\n");
350
+ }).join("\n\n");
351
+ }
206
352
  export {
207
353
  CrudDefaultPagination,
208
354
  buildCacheKey,
@@ -211,6 +357,7 @@ export {
211
357
  finalize,
212
358
  mergeArrays,
213
359
  mergeSchemas2 as mergeSchemas,
360
+ renderLeafDocsMarkdown,
214
361
  resource,
215
362
  resourceWithCrud,
216
363
  withCrud
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/routesV3.builder.ts","../src/core/routesV3.core.ts","../src/core/routesV3.finalize.ts","../src/crud/routesV3.crud.ts","../src/sockets/socket.index.ts"],"sourcesContent":["import { z } from 'zod';\nimport {\n AnyLeaf,\n Append,\n HttpMethod,\n Leaf,\n Merge,\n MergeArray,\n MethodCfg,\n NodeCfg,\n Prettify,\n} from './routesV3.core';\n\ntype ZodTypeAny = z.ZodTypeAny;\ntype ParamZod<Name extends string, S extends ZodTypeAny> = z.ZodObject<{ [K in Name]: S }>;\n\n/**\n * Runtime helper that mirrors the typed merge used by the builder.\n * @param a Previously merged params schema inherited from parent segments.\n * @param b Newly introduced params schema.\n * @returns Intersection of schemas when both exist, otherwise whichever is defined.\n */\nfunction mergeSchemas<A extends ZodTypeAny | undefined, B extends ZodTypeAny | undefined>(\n a: A,\n b: B,\n): A extends ZodTypeAny ? (B extends ZodTypeAny ? ReturnType<typeof z.intersection<A, B>> : A) : B {\n if (a && b) return z.intersection(a as any, b as any) as any;\n return (a ?? b) as any;\n}\n\n/** Builder surface used by `resource(...)` to accumulate leaves. */\nexport interface Branch<\n Base extends string,\n Acc extends readonly AnyLeaf[],\n I extends NodeCfg,\n PS extends ZodTypeAny | undefined,\n> {\n // --- structure ---\n /**\n * Enter or define a static child segment.\n * Optionally accepts extra config and/or a builder to populate nested routes.\n * @param name Child segment literal (no leading slash).\n * @param cfg Optional node configuration to merge for descendants.\n * @param builder Callback to produce leaves for the child branch.\n */\n sub<Name extends string, J extends NodeCfg>(\n name: Name,\n cfg?: J,\n ): Branch<`${Base}/${Name}`, Acc, Merge<I, NonNullable<J>>, PS>;\n\n sub<Name extends string, J extends NodeCfg | undefined, R extends readonly AnyLeaf[]>(\n name: Name,\n cfg: J,\n builder: (r: Branch<`${Base}/${Name}`, readonly [], Merge<I, NonNullable<J>>, PS>) => R,\n ): Branch<Base, Append<Acc, R[number]>, Merge<I, NonNullable<J>>, PS>;\n\n sub<Name extends string, R extends readonly AnyLeaf[]>(\n name: Name,\n builder: (r: Branch<`${Base}/${Name}`, readonly [], I, PS>) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, PS>;\n\n // --- parameterized segment (single signature) ---\n /**\n * Introduce a `:param` segment and merge its schema into downstream leaves.\n * @param name Parameter key (without leading colon).\n * @param paramsSchema Zod schema for the parameter value.\n * @param builder Callback that produces leaves beneath the parameterized segment.\n */\n routeParameter<Name extends string, P extends ZodTypeAny, R extends readonly AnyLeaf[]>(\n name: Name,\n paramsSchema: P,\n builder: (\n r: Branch<\n `${Base}/:${Name}`,\n readonly [],\n I,\n ReturnType<typeof mergeSchemas<PS, ParamZod<Name, P>>>\n >,\n ) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, ReturnType<typeof mergeSchemas<PS, ParamZod<Name, P>>>>;\n\n // --- flags inheritance ---\n /**\n * Merge additional node configuration that subsequent leaves will inherit.\n * @param cfg Partial node configuration.\n */\n with<J extends NodeCfg>(cfg: J): Branch<Base, Acc, Merge<I, J>, PS>;\n\n // --- methods (return Branch to keep chaining) ---\n /**\n * Register a GET leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n get<C extends Omit<MethodCfg, 'paramsSchema'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<Acc, Prettify<Leaf<'get', Base, Merge<Merge<I, C>, { paramsSchema: PS }>>>>,\n I,\n PS\n >;\n\n /**\n * Register a POST leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n post<C extends Omit<MethodCfg, 'paramsSchema'>>(\n cfg: C,\n ): Branch<Base, Append<Acc, Leaf<'post', Base, Merge<Merge<I, C>, { paramsSchema: PS }>>>, I, PS>;\n\n /**\n * Register a PUT leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n put<C extends Omit<MethodCfg, 'paramsSchema'>>(\n cfg: C,\n ): Branch<Base, Append<Acc, Leaf<'put', Base, Merge<Merge<I, C>, { paramsSchema: PS }>>>, I, PS>;\n\n /**\n * Register a PATCH leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n patch<C extends Omit<MethodCfg, 'paramsSchema'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<Acc, Leaf<'patch', Base, Merge<Merge<I, C>, { paramsSchema: PS }>>>,\n I,\n PS\n >;\n\n /**\n * Register a DELETE leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n delete<C extends Omit<MethodCfg, 'paramsSchema'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<Acc, Leaf<'delete', Base, Merge<Merge<I, C>, { paramsSchema: PS }>>>,\n I,\n PS\n >;\n\n // --- finalize this subtree ---\n /**\n * Finish the branch and return the collected leaves.\n * @returns Readonly tuple of accumulated leaves.\n */\n done(): Readonly<Acc>;\n}\n\n/**\n * Start building a resource at the given base path.\n * @param base Root path for the resource (e.g. `/v1`).\n * @param inherited Optional node configuration applied to all descendants.\n * @returns Root `Branch` instance used to compose the route tree.\n */\nexport function resource<Base extends string, I extends NodeCfg = {}>(\n base: Base,\n inherited?: I,\n): Branch<Base, readonly [], I, undefined> {\n const rootBase = base;\n const rootInherited: NodeCfg = { ...(inherited as NodeCfg) };\n\n function makeBranch<Base2 extends string, I2 extends NodeCfg, PS2 extends ZodTypeAny | undefined>(\n base2: Base2,\n inherited2: I2,\n mergedParamsSchema?: PS2,\n ) {\n const stack: AnyLeaf[] = [];\n let currentBase: string = base2;\n let inheritedCfg: NodeCfg = { ...(inherited2 as NodeCfg) };\n let currentParamsSchema: PS2 = mergedParamsSchema as PS2;\n\n function add<M extends HttpMethod, C extends MethodCfg>(method: M, cfg: C) {\n // If the method didn’t provide a paramsSchema, inject the active merged one.\n const effectiveParamsSchema = (cfg.paramsSchema ?? currentParamsSchema) as PS2 | undefined;\n const fullCfg = (\n effectiveParamsSchema\n ? { ...inheritedCfg, ...cfg, paramsSchema: effectiveParamsSchema }\n : { ...inheritedCfg, ...cfg }\n ) as Merge<I2, C>;\n\n const leaf = {\n method,\n path: currentBase as Base2,\n cfg: fullCfg,\n } as const;\n\n stack.push(leaf as unknown as AnyLeaf);\n\n // Return same runtime obj, but with Acc including this new leaf\n return api as unknown as Branch<Base2, Append<readonly [], typeof leaf>, I2, PS2>;\n }\n\n const api: any = {\n // compose a plain subpath (optional cfg) with optional builder\n sub<Name extends string, J extends NodeCfg | undefined = undefined>(\n name: Name,\n cfgOrBuilder?: J | ((r: any) => readonly AnyLeaf[]),\n maybeBuilder?: (r: any) => readonly AnyLeaf[],\n ) {\n let cfg: NodeCfg | undefined;\n let builder: ((r: any) => readonly AnyLeaf[]) | undefined;\n\n if (typeof cfgOrBuilder === 'function') {\n builder = cfgOrBuilder as any;\n } else {\n cfg = cfgOrBuilder as NodeCfg | undefined;\n builder = maybeBuilder;\n }\n\n const childBase = `${currentBase}/${name}` as const;\n const childInherited = { ...inheritedCfg, ...(cfg ?? {}) } as Merge<I2, NonNullable<J>>;\n\n if (builder) {\n // params schema PS2 flows through unchanged on plain sub\n const child = makeBranch(childBase, childInherited, currentParamsSchema);\n const leaves = builder(child) as readonly AnyLeaf[];\n for (const l of leaves) stack.push(l);\n return api as Branch<\n Base2,\n Append<readonly [], (typeof leaves)[number]>,\n typeof childInherited,\n PS2\n >;\n } else {\n currentBase = childBase;\n inheritedCfg = childInherited;\n return api as Branch<`${Base2}/${Name}`, readonly [], typeof childInherited, PS2>;\n }\n },\n\n // the single param function: name + schema + builder\n routeParameter<Name extends string, P extends ZodTypeAny, R extends readonly AnyLeaf[]>(\n name: Name,\n paramsSchema: P,\n builder: (\n r: Branch<\n `${Base2}/:${Name}`,\n readonly [],\n I2,\n ReturnType<typeof mergeSchemas<PS2, ParamZod<Name, P>>>\n >,\n ) => R,\n ) {\n const childBase = `${currentBase}/:${name}` as const;\n // Wrap the value schema under the param name before merging with inherited params schema\n const paramObj: ParamZod<Name, P> = z.object({ [name]: paramsSchema } as Record<Name, P>);\n const childParams = mergeSchemas<PS2, ParamZod<Name, P>>(currentParamsSchema, paramObj);\n const child = makeBranch(childBase, inheritedCfg as I2, childParams);\n const leaves = builder(child) as readonly AnyLeaf[];\n for (const l of leaves) stack.push(l);\n return api as Branch<\n Base2,\n Append<readonly [], (typeof leaves)[number]>,\n I2,\n ReturnType<typeof mergeSchemas<PS2, ParamZod<Name, P>>>\n >;\n },\n\n with<J extends NodeCfg>(cfg: J) {\n inheritedCfg = { ...inheritedCfg, ...cfg };\n return api as Branch<Base2, readonly [], Merge<I2, J>, PS2>;\n },\n\n // methods (inject current params schema if missing)\n get<C extends MethodCfg>(cfg: C) {\n return add('get', cfg);\n },\n post<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('post', { ...cfg, feed: false });\n },\n put<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('put', { ...cfg, feed: false });\n },\n patch<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('patch', { ...cfg, feed: false });\n },\n delete<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('delete', { ...cfg, feed: false });\n },\n\n done() {\n return stack;\n },\n };\n\n return api as Branch<Base2, readonly [], I2, PS2>;\n }\n\n // Root branch starts with no params schema (PS = undefined)\n return makeBranch(rootBase, rootInherited, undefined);\n}\n\n/**\n * Merge two readonly tuples (preserves literal tuple information).\n * @param arr1 First tuple.\n * @param arr2 Second tuple.\n * @returns New tuple containing values from both inputs.\n */\nexport const mergeArrays = <T extends readonly any[], S extends readonly any[]>(\n arr1: T,\n arr2: S,\n) => {\n return [...arr1, ...arr2] as [...T, ...S];\n};\n","import { z, ZodTypeAny } from 'zod';\n\n/** Supported HTTP verbs for the routes DSL. */\nexport type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\n/** Declarative description of a multipart upload field. */\nexport type FileField = {\n /** Form field name used for uploads. */\n name: string;\n /** Maximum number of files accepted for this field. */\n maxCount: number;\n};\n\n/** Configuration that applies to an entire branch of the route tree. */\nexport type NodeCfg = {\n /** @deprecated. Does nothing. */\n authenticated?: boolean;\n};\n\n/** Per-method configuration merged with inherited node config. */\nexport type MethodCfg = {\n /** Zod schema describing the request body. */\n bodySchema?: ZodTypeAny;\n /** Zod schema describing the query string. */\n querySchema?: ZodTypeAny;\n /** Zod schema describing path params (overrides inferred params). */\n paramsSchema?: ZodTypeAny;\n /** Zod schema describing the response payload. */\n outputSchema?: ZodTypeAny;\n /** Multipart upload definitions for the route. */\n bodyFiles?: FileField[];\n /** Marks the route as an infinite feed (enables cursor helpers). */\n feed?: boolean;\n /** Optional human-readable description for docs/debugging. */\n description?: string;\n};\n\n/** Immutable representation of a single HTTP route in the tree. */\nexport type Leaf<M extends HttpMethod, P extends string, C extends MethodCfg> = {\n /** Lowercase HTTP method (get/post/...). */\n readonly method: M;\n /** Concrete path for the route (e.g. `/v1/users/:userId`). */\n readonly path: P;\n /** Readonly snapshot of route configuration. */\n readonly cfg: Readonly<C>;\n};\n\n/** Convenience union covering all generated leaves. */\nexport type AnyLeaf = Leaf<HttpMethod, string, MethodCfg>;\n\n/** Merge two object types while keeping nice IntelliSense output. */\nexport type Merge<A, B> = Prettify<Omit<A, keyof B> & B>;\n\n/** Append a new element to a readonly tuple type. */\nexport type Append<T extends readonly unknown[], X> = [...T, X];\n\n/** Concatenate two readonly tuple types. */\nexport type MergeArray<A extends readonly unknown[], B extends readonly unknown[]> = [\n ...A,\n ...B,\n];\n\n// helpers (optional)\ntype SegmentParams<S extends string> = S extends `:${infer P}` ? P : never;\ntype Split<S extends string> = S extends ''\n ? []\n : S extends `${infer A}/${infer B}`\n ? [A, ...Split<B>]\n : [S];\ntype ExtractParamNames<Path extends string> = SegmentParams<Split<Path>[number]>;\n\n/** Derive a params object type from a literal route string. */\nexport type ExtractParamsFromPath<Path extends string> =\n ExtractParamNames<Path> extends never ? never : Record<ExtractParamNames<Path>, string | number>;\n\n/**\n * Interpolate `:params` in a path using the given values.\n * @param path Literal route string containing `:param` segments.\n * @param params Object of parameter values to interpolate.\n * @returns Path string with parameters substituted.\n */\nexport function compilePath<Path extends string>(path: Path, params: ExtractParamsFromPath<Path>) {\n if (!params) return path;\n return path.replace(/:([A-Za-z0-9_]+)/g, (_, k) => {\n const v = (params as any)[k];\n if (v === undefined || v === null) throw new Error(`Missing param :${k}`);\n return String(v);\n });\n}\n\n/**\n * Build a deterministic cache key for the given leaf.\n * The key matches the shape consumed by React Query helpers.\n * @param args.leaf Leaf describing the endpoint.\n * @param args.params Optional params used to build the path.\n * @param args.query Optional query payload.\n * @returns Tuple suitable for React Query cache keys.\n */\ntype SplitPath<P extends string> = P extends ''\n ? []\n : P extends `${infer A}/${infer B}`\n ? [A, ...SplitPath<B>]\n : [P];\nexport function buildCacheKey<L extends AnyLeaf>(args: {\n leaf: L;\n params?: ExtractParamsFromPath<L['path']>;\n query?: InferQuery<L>;\n}) {\n let p = args.leaf.path;\n if (args.params) {\n p = compilePath<L['path']>(p, args.params);\n }\n return [args.leaf.method, ...(p.split('/').filter(Boolean) as SplitPath<typeof p>), args.query ?? {}] as const;\n}\n\n/** Infer params either from the explicit params schema or from the path literal. */\nexport type InferParams<L extends AnyLeaf> = L['cfg']['paramsSchema'] extends ZodTypeAny\n ? z.infer<L['cfg']['paramsSchema']>\n : ExtractParamsFromPath<L['path']>;\n\n/** Infer query shape from a Zod schema when present. */\nexport type InferQuery<L extends AnyLeaf> = L['cfg']['querySchema'] extends ZodTypeAny\n ? z.infer<L['cfg']['querySchema']>\n : never;\n\n/** Infer request body shape from a Zod schema when present. */\nexport type InferBody<L extends AnyLeaf> = L['cfg']['bodySchema'] extends ZodTypeAny\n ? z.infer<L['cfg']['bodySchema']>\n : never;\n\n/** Infer handler output shape from a Zod schema. Defaults to unknown. */\nexport type InferOutput<L extends AnyLeaf> = L['cfg']['outputSchema'] extends ZodTypeAny\n ? z.infer<L['cfg']['outputSchema']>\n : unknown;\n\n/** Render a type as if it were a simple object literal. */\nexport type Prettify<T> = { [K in keyof T]: T[K] } & {};\n","import { AnyLeaf, HttpMethod, Prettify } from './routesV3.core';\n\n/** Build the key type for a leaf — distributive so method/path stay paired. */\nexport type KeyOf<L extends AnyLeaf> = L extends AnyLeaf\n ? `${Uppercase<L['method']>} ${L['path']}`\n : never;\n\n// From a tuple of leaves, get the union of keys (pairwise, no cartesian blow-up)\ntype KeysOf<Leaves extends readonly AnyLeaf[]> = KeyOf<Leaves[number]>;\n\n// Parse method & path out of a key\ntype MethodFromKey<K extends string> = K extends `${infer M} ${string}` ? Lowercase<M> : never;\ntype PathFromKey<K extends string> = K extends `${string} ${infer P}` ? P : never;\n\n// Given Leaves and a Key, pick the exact leaf that matches method+path\ntype LeafForKey<Leaves extends readonly AnyLeaf[], K extends string> = Extract<\n Leaves[number],\n { method: MethodFromKey<K> & HttpMethod; path: PathFromKey<K> }\n>;\n\n/**\n * Freeze a leaf tuple into a registry with typed key lookups.\n * @param leaves Readonly tuple of leaves produced by the builder DSL.\n * @returns Registry containing the leaves array and a `byKey` lookup map.\n */\nexport function finalize<const L extends readonly AnyLeaf[]>(leaves: L) {\n type Keys = KeysOf<L>;\n type MapByKey = { [K in Keys]: Prettify<LeafForKey<L, K>> };\n\n const byKey = Object.fromEntries(\n leaves.map((l) => [`${l.method.toUpperCase()} ${l.path}`, l] as const),\n ) as unknown as MapByKey;\n\n const log = (logger: { system: (...args: unknown[]) => void }) => {\n logger.system('Finalized routes:');\n (Object.keys(byKey) as Keys[]).forEach((k) => {\n const leaf = byKey[k];\n logger.system(`- ${k}`);\n });\n };\n\n return { all: leaves, byKey, log };\n}\n\n/** Nominal type alias for a finalized registry. */\nexport type Registry<R extends ReturnType<typeof finalize>> = R;\n\ntype FilterRoute<\n T extends readonly AnyLeaf[],\n F extends string,\n Acc extends readonly AnyLeaf[] = [],\n> = T extends readonly [infer First extends AnyLeaf, ...infer Rest extends AnyLeaf[]]\n ? First extends { path: `${string}${F}${string}` }\n ? FilterRoute<Rest, F, [...Acc, First]>\n : FilterRoute<Rest, F, Acc>\n : Acc;\n\ntype UpperCase<S extends string> = S extends `${infer First}${infer Rest}`\n ? `${Uppercase<First>}${UpperCase<Rest>}`\n : S;\n\ntype Routes<T extends readonly AnyLeaf[], F extends string> = FilterRoute<T, F>;\ntype ByKey<\n T extends readonly AnyLeaf[],\n Acc extends Record<string, AnyLeaf> = {},\n> = T extends readonly [infer First extends AnyLeaf, ...infer Rest extends AnyLeaf[]]\n ? ByKey<Rest, Acc & { [K in `${UpperCase<First['method']>} ${First['path']}`]: First }>\n : Acc;\n\n/**\n * Convenience helper for extracting a subset of routes by path fragment.\n * @param T Tuple of leaves produced by the DSL.\n * @param F String fragment to match against the route path.\n */\nexport type SubsetRoutes<T extends readonly AnyLeaf[], F extends string> = {\n byKey: ByKey<Routes<T, F>>;\n all: Routes<T, F>;\n};\n","// routesV3.crud.ts\n// -----------------------------------------------------------------------------\n// Add a first-class .crud() helper to the routesV3 DSL, without touching the\n// core builder. This file:\n// 1) Declares types + module augmentation to extend Branch<...> with .crud\n// 2) Provides a runtime decorator `withCrud(...)` that installs the method\n// 3) Exports a convenience `resourceWithCrud(...)` wrapper (optional)\n// -----------------------------------------------------------------------------\n\nimport { z, ZodType } from 'zod';\nimport {\n resource as baseResource,\n type Branch as _Branch, // import type so we can augment it\n} from '../core/routesV3.builder';\nimport { type AnyLeaf, type Leaf, type NodeCfg } from '../core/routesV3.core';\n\n// -----------------------------------------------------------------------------\n// Small utilities (runtime + types)\n// -----------------------------------------------------------------------------\n/** Default cursor pagination used by list (GET collection). */\nexport const CrudDefaultPagination = z.object({\n limit: z.coerce.number().min(1).max(100).default(20),\n cursor: z.string().optional(),\n});\n\n/**\n * Merge two Zod schemas at runtime; matches the typing pattern used in builder.\n * @param a Existing params schema inherited from parent branches.\n * @param b Schema introduced at the current branch.\n * @returns Intersection of schemas when both exist, otherwise whichever is defined.\n */\nexport function mergeSchemas<A extends ZodType | undefined, B extends ZodType | undefined>(\n a: A,\n b: B,\n): A extends ZodType ? (B extends ZodType ? ReturnType<typeof z.intersection<A, B>> : A) : B {\n if (a && b) return z.intersection(a as any, b as any) as any;\n return (a ?? b) as any;\n}\n\n/** Build { [Name]: S } Zod object at the type-level. */\nexport type ParamSchema<Name extends string, S extends ZodType> = z.ZodObject<{\n [K in Name]: S;\n}>;\n\n/** Inject active params schema into a leaf cfg (to match your Leaf typing). */\ntype WithParams<I, P> = P extends ZodType ? Omit<I, 'paramsSchema'> & { paramsSchema: P } : I;\n\n/** Resolve boolean flag: default D unless explicitly false. */\ntype Flag<E, D extends boolean> = E extends false ? false : D;\n\n// -----------------------------------------------------------------------------\n// CRUD config (few knobs, with DX comments)\n// -----------------------------------------------------------------------------\n\n/** Toggle individual CRUD methods; defaults enable all (create/update require body). */\nexport type CrudEnable = {\n /** GET /collection (feed). Defaults to true. */ list?: boolean;\n /** POST /collection. Defaults to true if `create` provided. */ create?: boolean;\n /** GET /collection/:id. Defaults to true. */ read?: boolean;\n /** PATCH /collection/:id. Defaults to true if `update` provided. */ update?: boolean;\n /** DELETE /collection/:id. Defaults to true. */ remove?: boolean;\n};\n\n/** Collection GET config. */\nexport type CrudListCfg = {\n /** Query schema (defaults to cursor pagination). */\n querySchema?: ZodType;\n /** Output schema (defaults to { items: Item[], nextCursor? }). */\n outputSchema?: ZodType;\n /** Optional description string. */\n description?: string;\n};\n\n/** Collection POST config. */\nexport type CrudCreateCfg = {\n /** Body schema for creating an item. */\n bodySchema: ZodType;\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType;\n /** Optional description. */\n description?: string;\n};\n\n/** Item GET config. */\nexport type CrudReadCfg = {\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType;\n /** Optional description. */\n description?: string;\n};\n\n/** Item PATCH config. */\nexport type CrudUpdateCfg = {\n /** Body schema for partial updates. */\n bodySchema: ZodType;\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType;\n /** Optional description. */\n description?: string;\n};\n\n/** Item DELETE config. */\nexport type CrudRemoveCfg = {\n /** Output schema (defaults to { ok: true }). */\n outputSchema?: ZodType;\n /** Optional description. */\n description?: string;\n};\n\n/**\n * CRUD config for `.crud(\"resource\", cfg, extras?)`.\n *\n * It synthesizes `:[resourceName]Id` as the param key and uses `paramSchema` for the value.\n * Prefer passing a **value schema** (e.g. `z.string().uuid()`).\n * As a convenience, a ZodObject of shape `{ [resourceName]Id: schema }` is accepted at runtime too.\n */\nexport type CrudCfg<Name extends string = string> = {\n /**\n * Zod schema for the ID *value* (e.g. `z.string().uuid()`).\n * The parameter key is always `:${name}Id`.\n * (If you pass `z.object({ [name]Id: ... })`, it's accepted at runtime.)\n */\n paramSchema: ZodType;\n\n /**\n * The single-item output shape used by read/create/update by default.\n * List defaults to `{ items: z.array(itemOutputSchema), nextCursor? }`.\n */\n itemOutputSchema: ZodType;\n\n /** Per-method toggles (all enabled by default; create/update require bodies). */\n enable?: CrudEnable;\n\n /** GET /collection configuration. */ list?: CrudListCfg;\n /** POST /collection configuration (enables create). */ create?: CrudCreateCfg;\n /** GET /collection/:id configuration. */ read?: CrudReadCfg;\n /** PATCH /collection/:id configuration (enables update). */ update?: CrudUpdateCfg;\n /** DELETE /collection/:id configuration. */ remove?: CrudRemoveCfg;\n};\n\n// -----------------------------------------------------------------------------\n// Type plumbing to expose generated leaves (so finalize().byKey sees them)\n// -----------------------------------------------------------------------------\n\ntype CrudLeavesTuple<\n Base extends string,\n I extends NodeCfg,\n PS extends ZodType | undefined,\n Name extends string,\n C extends CrudCfg<Name>,\n> = `${Name}Id` extends infer IdName extends string\n ? ParamSchema<IdName, C['paramSchema']> extends infer IdParamZ extends ZodType\n ? [\n // GET /collection\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['list'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'get',\n `${Base}/${Name}`,\n WithParams<\n Omit<I, never> & {\n feed: true;\n querySchema: C['list'] extends CrudListCfg\n ? C['list']['querySchema']\n : typeof CrudDefaultPagination;\n outputSchema: C['list'] extends CrudListCfg\n ? C['list']['outputSchema'] extends ZodType\n ? C['list']['outputSchema']\n : z.ZodObject<{\n items: z.ZodArray<C['itemOutputSchema']>;\n nextCursor: z.ZodOptional<z.ZodString>;\n }>\n : z.ZodObject<{\n items: z.ZodArray<C['itemOutputSchema']>;\n nextCursor: z.ZodOptional<z.ZodString>;\n }>;\n description?: string;\n },\n PS\n >\n >,\n ]\n : []),\n\n // POST /collection\n ...((C['create'] extends CrudCreateCfg ? true : false) extends true\n ? Flag<\n C['enable'] extends CrudEnable ? C['enable']['create'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'post',\n `${Base}/${Name}`,\n WithParams<\n Omit<I, never> & {\n bodySchema: C['create'] extends CrudCreateCfg\n ? C['create']['bodySchema']\n : never;\n outputSchema: C['create'] extends CrudCreateCfg\n ? C['create']['outputSchema'] extends ZodType\n ? C['create']['outputSchema']\n : C['itemOutputSchema']\n : never;\n description?: string;\n },\n PS\n >\n >,\n ]\n : []\n : []),\n\n // GET /collection/:id\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['read'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'get',\n `${Base}/${Name}/:${IdName}`,\n WithParams<\n Omit<I, never> & {\n outputSchema: C['read'] extends CrudReadCfg\n ? C['read']['outputSchema'] extends ZodType\n ? C['read']['outputSchema']\n : C['itemOutputSchema']\n : C['itemOutputSchema'];\n description?: string;\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >,\n ]\n : []),\n\n // PATCH /collection/:id\n ...((C['update'] extends CrudUpdateCfg ? true : false) extends true\n ? Flag<\n C['enable'] extends CrudEnable ? C['enable']['update'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'patch',\n `${Base}/${Name}/:${IdName}`,\n WithParams<\n Omit<I, never> & {\n bodySchema: C['update'] extends CrudUpdateCfg\n ? C['update']['bodySchema']\n : never;\n outputSchema: C['update'] extends CrudUpdateCfg\n ? C['update']['outputSchema'] extends ZodType\n ? C['update']['outputSchema']\n : C['itemOutputSchema']\n : never;\n description?: string;\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >,\n ]\n : []\n : []),\n\n // DELETE /collection/:id\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['remove'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'delete',\n `${Base}/${Name}/:${IdName}`,\n WithParams<\n Omit<I, never> & {\n outputSchema: C['remove'] extends CrudRemoveCfg\n ? C['remove']['outputSchema'] extends ZodType\n ? C['remove']['outputSchema']\n : z.ZodObject<{ ok: z.ZodLiteral<true> }>\n : z.ZodObject<{ ok: z.ZodLiteral<true> }>;\n description?: string;\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >,\n ]\n : []),\n ]\n : never\n : never;\n\n/** Merge generated leaves + extras into the branch accumulator. */\ntype CrudResultAcc<\n Base extends string,\n Acc extends readonly AnyLeaf[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeaf[],\n> = [...Acc, ...CrudLeavesTuple<Base, I, PS, Name, C>, ...Extras];\n\n// -----------------------------------------------------------------------------\n// Module augmentation: add the typed `.crud(...)` to Branch<...>\n// -----------------------------------------------------------------------------\n\ndeclare module './../core/routesV3.builder' {\n interface Branch<\n Base extends string,\n Acc extends readonly AnyLeaf[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n > {\n /**\n * Generate opinionated CRUD endpoints for a collection at `/.../<name>`\n * with an item at `/.../<name>/:<name>Id`.\n *\n * Creates (subject to `enable` + presence of create/update bodies):\n * - GET /<name> (feed list)\n * - POST /<name> (create)\n * - GET /<name>/:<name>Id (read item)\n * - PATCH /<name>/:<name>Id (update item)\n * - DELETE /<name>/:<name>Id (remove item)\n *\n * The `extras` callback receives live builders at both collection and item\n * levels so you can add custom subroutes; their leaves are included in the\n * returned Branch type.\n */\n crud<\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeaf[] = readonly [],\n >(\n name: Name,\n cfg: C,\n extras?: (ctx: {\n /** Builder at `/.../<name>` (collection scope). */\n collection: _Branch<`${Base}/${Name}`, readonly [], I, PS>;\n /** Builder at `/.../<name>/:<name>Id` (item scope). */\n item: _Branch<\n `${Base}/${Name}/:${`${Name}Id`}`,\n readonly [],\n I,\n ReturnType<typeof mergeSchemas<PS, ParamSchema<`${Name}Id`, C['paramSchema']>>>\n >;\n }) => Extras,\n ): _Branch<Base, CrudResultAcc<Base, Acc, I, PS, Name, C, Extras>, I, PS>;\n }\n}\n\n// -----------------------------------------------------------------------------\n// Runtime: install .crud on any Branch via decorator\n// -----------------------------------------------------------------------------\n\n/**\n * Decorate a Branch instance so `.crud(...)` is available at runtime.\n * Tip: wrap the root: `withCrud(resource('/v1'))`.\n * @param branch Branch returned by `resource(...)`.\n * @returns Same branch with `.crud(...)` installed.\n */\nexport function withCrud<\n Base extends string,\n Acc extends readonly AnyLeaf[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n>(branch: _Branch<Base, Acc, I, PS>): _Branch<Base, Acc, I, PS> {\n const b = branch as any;\n if (typeof b.crud === 'function') return branch;\n\n b.crud = function <\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeaf[] = readonly [],\n >(this: any, name: Name, cfg: C, extras?: (ctx: { collection: any; item: any }) => Extras) {\n // Build inside a sub-branch at `/.../<name>` and harvest its leaves.\n return this.sub(name, (collection: any) => {\n const idKey = `${name}Id`;\n\n // Accept a value schema (preferred); but if a z.object({[name]Id: ...}) is provided, use it.\n const s = cfg.paramSchema;\n const isObj =\n s &&\n typeof (s as any)._def === 'object' &&\n (s as any)._def.typeName === 'ZodObject' &&\n typeof (s as any).shape === 'function';\n\n const paramValueSchema =\n isObj && (s as any).shape()[idKey] ? ((s as any).shape()[idKey] as ZodType) : (s as ZodType);\n\n const itemOut = cfg.itemOutputSchema;\n const listOut =\n cfg.list?.outputSchema ??\n z.object({\n items: z.array(itemOut),\n nextCursor: z.string().optional(),\n });\n\n const want = {\n list: cfg.enable?.list !== false,\n create: cfg.enable?.create !== false && !!cfg.create?.bodySchema,\n read: cfg.enable?.read !== false,\n update: cfg.enable?.update !== false && !!cfg.update?.bodySchema,\n remove: cfg.enable?.remove !== false,\n } as const;\n\n // Collection routes\n if (want.list) {\n collection.get({\n feed: true,\n querySchema: cfg.list?.querySchema ?? CrudDefaultPagination,\n outputSchema: listOut,\n description: cfg.list?.description ?? 'List',\n });\n }\n\n if (want.create) {\n collection.post({\n bodySchema: cfg.create!.bodySchema,\n outputSchema: cfg.create?.outputSchema ?? itemOut,\n description: cfg.create?.description ?? 'Create',\n });\n }\n\n // Item routes via :<name>Id\n collection.routeParameter(idKey as any, paramValueSchema as any, (item: any) => {\n if (want.read) {\n item.get({\n outputSchema: cfg.read?.outputSchema ?? itemOut,\n description: cfg.read?.description ?? 'Read',\n });\n }\n if (want.update) {\n item.patch({\n bodySchema: cfg.update!.bodySchema,\n outputSchema: cfg.update?.outputSchema ?? itemOut,\n description: cfg.update?.description ?? 'Update',\n });\n }\n if (want.remove) {\n item.delete({\n outputSchema: cfg.remove?.outputSchema ?? z.object({ ok: z.literal(true) }),\n description: cfg.remove?.description ?? 'Delete',\n });\n }\n\n // Give extras fully-capable builders (decorate so extras can call .crud again)\n if (extras) extras({ collection: withCrud(collection), item: withCrud(item) });\n\n return item.done();\n });\n\n return collection.done();\n });\n };\n\n return branch;\n}\n\n// -----------------------------------------------------------------------------\n// Optional convenience: re-export a resource() that already has .crud installed\n// -----------------------------------------------------------------------------\n\n/**\n * Drop-in replacement for `resource(...)` that returns a Branch with `.crud()` installed.\n * You can either use this or call `withCrud(resource(...))`.\n * @param base Root path for the resource (e.g. `/v1`).\n * @param inherited Node configuration merged into every leaf.\n * @returns Branch builder that already includes the CRUD helper.\n */\nexport function resourceWithCrud<Base extends string, I extends NodeCfg = {}>(\n base: Base,\n inherited: I,\n) {\n return withCrud(baseResource(base, inherited));\n}\n\n// Re-export the original in case you want both styles from this module\nexport { baseResource as resource };\n","// socket.index.ts (shared client/server)\n// TODO:\n// 1. Automatic feed handling:\n// * Expand onReceive to be like a middleware chain. This would allow for automatic feed handling middleware to be added that would handle:\n// - 1. updating maps/dictionaries based on feed messages\n// - 2. handling join/leave rooms\n// 2. General helpers: \n// - Easy combine of routes and sockets in the client: Room joining onReceive handlers, map helpers that build dictionaries of the data from feeds for easy access, lifecycle handling)\n// - Custom route structure definitions (feed + information routes, get/put/patch/delete based on few central schemas, )\nimport { z } from 'zod';\n\nexport type SocketSchema<Output =unknown> = z.ZodType & {\n __out: Output;\n};\n\nexport type SocketSchemaOutput<Schema extends z.ZodTypeAny> = Schema extends {\n __out: infer Out;\n} ? Out : z.output<Schema>;\n\nexport type SocketEvent<Out = unknown> = {\n message: z.ZodTypeAny;\n /** phantom field, only for typing; not meant to be used at runtime */\n __out: Out;\n};\n\nexport type EventMap = Record<string, SocketEvent<any>>;\n\n/**\n * System event names – shared so server and client\n * don't drift on naming.\n */\nexport type SysEventName = 'sys:connect' | 'sys:disconnect' | 'sys:reconnect' | 'sys:connect_error' | 'sys:ping' | 'sys:pong' | 'sys:room_join' | 'sys:room_leave';\nexport function defineSocketEvents<const C extends SocketConnectionConfig, const Schemas extends Record<string, {\n message: z.ZodTypeAny;\n}>>(config: C, events: Schemas): {\n config: {\n [K in keyof C]: SocketSchema<z.output<C[K]>>;\n };\n events: {\n [K in keyof Schemas]: SocketEvent<z.output<Schemas[K]['message']>>;\n };\n};\n\nexport function defineSocketEvents(config: any, events: any) {\n return { config, events };\n}\n\n\n\nexport type Payload<T extends EventMap, K extends keyof T> = T[K] extends SocketEvent<infer Out> ? Out : never;\nexport type SocketConnectionConfig = {\n joinMetaMessage: z.ZodTypeAny;\n leaveMetaMessage: z.ZodTypeAny;\n pingPayload: z.ZodTypeAny;\n pongPayload: z.ZodTypeAny;\n};\n\nexport type SocketConnectionConfigOutput = {\n joinMetaMessage: SocketSchema<any>;\n leaveMetaMessage: SocketSchema<any>;\n pingPayload: SocketSchema<any>;\n pongPayload: SocketSchema<any>;\n}"],"mappings":";AAAA,SAAS,SAAS;AAsBlB,SAAS,aACP,GACA,GACiG;AACjG,MAAI,KAAK,EAAG,QAAO,EAAE,aAAa,GAAU,CAAQ;AACpD,SAAQ,KAAK;AACf;AAkIO,SAAS,SACd,MACA,WACyC;AACzC,QAAM,WAAW;AACjB,QAAM,gBAAyB,EAAE,GAAI,UAAsB;AAE3D,WAAS,WACP,OACA,YACA,oBACA;AACA,UAAM,QAAmB,CAAC;AAC1B,QAAI,cAAsB;AAC1B,QAAI,eAAwB,EAAE,GAAI,WAAuB;AACzD,QAAI,sBAA2B;AAE/B,aAAS,IAA+C,QAAW,KAAQ;AAEzE,YAAM,wBAAyB,IAAI,gBAAgB;AACnD,YAAM,UACJ,wBACI,EAAE,GAAG,cAAc,GAAG,KAAK,cAAc,sBAAsB,IAC/D,EAAE,GAAG,cAAc,GAAG,IAAI;AAGhC,YAAM,OAAO;AAAA,QACX;AAAA,QACA,MAAM;AAAA,QACN,KAAK;AAAA,MACP;AAEA,YAAM,KAAK,IAA0B;AAGrC,aAAO;AAAA,IACT;AAEA,UAAM,MAAW;AAAA;AAAA,MAEf,IACE,MACA,cACA,cACA;AACA,YAAI;AACJ,YAAI;AAEJ,YAAI,OAAO,iBAAiB,YAAY;AACtC,oBAAU;AAAA,QACZ,OAAO;AACL,gBAAM;AACN,oBAAU;AAAA,QACZ;AAEA,cAAM,YAAY,GAAG,WAAW,IAAI,IAAI;AACxC,cAAM,iBAAiB,EAAE,GAAG,cAAc,GAAI,OAAO,CAAC,EAAG;AAEzD,YAAI,SAAS;AAEX,gBAAM,QAAQ,WAAW,WAAW,gBAAgB,mBAAmB;AACvE,gBAAM,SAAS,QAAQ,KAAK;AAC5B,qBAAW,KAAK,OAAQ,OAAM,KAAK,CAAC;AACpC,iBAAO;AAAA,QAMT,OAAO;AACL,wBAAc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AAC9E,YAAI,KAAK,MAAM;AACb,eAAK,IAAI;AAAA,YACP,cAAc,IAAI,MAAM,gBAAgB;AAAA,YACxC,aAAa,IAAI,MAAM,eAAe;AAAA,UACxC,CAAC;AAAA,QACH;AACA,YAAI,KAAK,QAAQ;AACf,eAAK,MAAM;AAAA,YACT,YAAY,IAAI,OAAQ;AAAA,YACxB,cAAc,IAAI,QAAQ,gBAAgB;AAAA,YAC1C,aAAa,IAAI,QAAQ,eAAe;AAAA,UAC1C,CAAC;AAAA,QACH;AACA,YAAI,KAAK,QAAQ;AACf,eAAK,OAAO;AAAA,YACV,cAAc,IAAI,QAAQ,gBAAgBA,GAAE,OAAO,EAAE,IAAIA,GAAE,QAAQ,IAAI,EAAE,CAAC;AAAA,YAC1E,aAAa,IAAI,QAAQ,eAAe;AAAA,UAC1C,CAAC;AAAA,QACH;AAGA,YAAI,OAAQ,QAAO,EAAE,YAAY,SAAS,UAAU,GAAG,MAAM,SAAS,IAAI,EAAE,CAAC;AAE7E,eAAO,KAAK,KAAK;AAAA,MACnB,CAAC;AAED,aAAO,WAAW,KAAK;AAAA,IACzB,CAAC;AAAA,EACH;AAEA,SAAO;AACT;AAaO,SAAS,iBACd,MACA,WACA;AACA,SAAO,SAAS,SAAa,MAAM,SAAS,CAAC;AAC/C;;;ACpbO,SAAS,mBAAmB,QAAa,QAAa;AAC3D,SAAO,EAAE,QAAQ,OAAO;AAC1B;","names":["z","z","mergeSchemas"]}
1
+ {"version":3,"sources":["../src/core/routesV3.builder.ts","../src/core/routesV3.core.ts","../src/core/routesV3.finalize.ts","../src/crud/routesV3.crud.ts","../src/sockets/socket.index.ts","../src/docs/docs.ts"],"sourcesContent":["import { z } from 'zod';\nimport {\n AnyLeaf,\n Append,\n HttpMethod,\n Leaf,\n Merge,\n MergeArray,\n MethodCfg,\n NodeCfg,\n Prettify,\n} from './routesV3.core';\n\nconst defaultFeedQuerySchema = z.object({\n cursor: z.string().optional(),\n limit: z.coerce.number().min(1).max(100).default(20),\n});\n\nconst paginationField = defaultFeedQuerySchema.optional().default(defaultFeedQuerySchema.parse({}));\ntype PaginationField = typeof paginationField;\n\ntype ZodTypeAny = z.ZodTypeAny;\ntype ParamZod<Name extends string, S extends ZodTypeAny> = z.ZodObject<{ [K in Name]: S }>;\ntype ZodArrayAny = z.ZodArray<ZodTypeAny>;\ntype ZodObjectAny = z.ZodObject<any>;\ntype AnyZodObject = z.ZodObject<any>;\ntype MergedParamsResult<PS, Name extends string, P extends ZodTypeAny> = PS extends ZodTypeAny\n ? z.ZodIntersection<PS, ParamZod<Name, P>>\n : ParamZod<Name, P>;\n\nconst defaultFeedOutputSchema = z.object({\n items: z.array(z.unknown()),\n nextCursor: z.string().optional(),\n});\n\nfunction augmentFeedQuerySchema<Q extends ZodTypeAny | undefined>(schema: Q) {\n if (schema && !(schema instanceof z.ZodObject)) {\n console.warn('Feed queries must be a ZodObject; default pagination applied.');\n return z.object({\n pagination: paginationField,\n });\n }\n\n const base = (schema as ZodObjectAny) ?? z.object({});\n return base.extend({\n pagination: paginationField,\n });\n}\n\nfunction augmentFeedOutputSchema<O extends ZodTypeAny | undefined>(schema: O) {\n if (!schema) return defaultFeedOutputSchema;\n if (schema instanceof z.ZodArray) {\n return z.object({\n items: schema,\n nextCursor: z.string().optional(),\n });\n }\n if (schema instanceof z.ZodObject) {\n const shape = (schema as any).shape ? (schema as any).shape : (schema as any)._def?.shape?.();\n const hasItems = Boolean(shape?.items);\n if (hasItems) {\n return schema.extend({ nextCursor: z.string().optional() });\n }\n return z.object({\n items: z.array(schema as ZodTypeAny),\n nextCursor: z.string().optional(),\n });\n }\n return z.object({\n items: z.array(schema as ZodTypeAny),\n nextCursor: z.string().optional(),\n });\n}\n\n/**\n * Runtime helper that mirrors the typed merge used by the builder.\n * @param a Previously merged params schema inherited from parent segments.\n * @param b Newly introduced params schema.\n * @returns Intersection of schemas when both exist, otherwise whichever is defined.\n */\nfunction mergeSchemas<A extends ZodTypeAny, B extends ZodTypeAny>(a: A, b: B): ZodTypeAny;\nfunction mergeSchemas<A extends ZodTypeAny>(a: A, b: undefined): A;\nfunction mergeSchemas<B extends ZodTypeAny>(a: undefined, b: B): B;\nfunction mergeSchemas(a: ZodTypeAny | undefined, b: ZodTypeAny | undefined): ZodTypeAny | undefined;\nfunction mergeSchemas(a: ZodTypeAny | undefined, b: ZodTypeAny | undefined) {\n if (a && b) return z.intersection(a as any, b as any);\n return (a ?? b) as ZodTypeAny | undefined;\n}\n\ntype FeedQuerySchema<C extends MethodCfg> = z.ZodObject<any>;\n\ntype FeedOutputSchema<C extends MethodCfg> = C['outputSchema'] extends ZodArrayAny\n ? z.ZodObject<{\n items: C['outputSchema'];\n nextCursor: z.ZodOptional<z.ZodString>;\n }>\n : C['outputSchema'] extends ZodTypeAny\n ? z.ZodObject<{\n items: z.ZodArray<C['outputSchema']>;\n nextCursor: z.ZodOptional<z.ZodString>;\n }>\n : typeof defaultFeedOutputSchema;\n\ntype BaseMethodCfg<C extends MethodCfg> = Merge<\n Omit<MethodCfg, 'querySchema' | 'outputSchema' | 'feed'>,\n Omit<C, 'querySchema' | 'outputSchema' | 'feed'>\n>;\n\ntype FeedField<C extends MethodCfg> = C['feed'] extends true ? { feed: true } : { feed?: boolean };\n\ntype AddPaginationToQuery<Q extends AnyZodObject | undefined> = Q extends z.ZodObject<\n infer Shape\n>\n ? z.ZodObject<Shape & { pagination: PaginationField }>\n : z.ZodObject<{ pagination: PaginationField }>;\n\ntype FeedQueryField<C extends MethodCfg> = {\n querySchema: AddPaginationToQuery<\n C['querySchema'] extends AnyZodObject ? C['querySchema'] : undefined\n >;\n};\n\ntype NonFeedQueryField<C extends MethodCfg> = C['querySchema'] extends ZodTypeAny\n ? { querySchema: C['querySchema'] }\n : { querySchema?: undefined };\n\ntype FeedOutputField<C extends MethodCfg> = { outputSchema: FeedOutputSchema<C> };\n\ntype NonFeedOutputField<C extends MethodCfg> = C['outputSchema'] extends ZodTypeAny\n ? { outputSchema: C['outputSchema'] }\n : { outputSchema?: undefined };\n\ntype ParamsField<C extends MethodCfg, PS> = C['paramsSchema'] extends ZodTypeAny\n ? { paramsSchema: C['paramsSchema'] }\n : { paramsSchema: PS };\n\ntype EffectiveFeedFields<C extends MethodCfg, PS> = C['feed'] extends true\n ? FeedField<C> & FeedQueryField<C> & FeedOutputField<C> & ParamsField<C, PS>\n : FeedField<C> & NonFeedQueryField<C> & NonFeedOutputField<C> & ParamsField<C, PS>;\n\ntype EffectiveCfg<C extends MethodCfg, PS> = Prettify<\n Merge<MethodCfg, BaseMethodCfg<C> & EffectiveFeedFields<C, PS>>\n>;\n\ntype BuiltLeaf<\n M extends HttpMethod,\n Base extends string,\n I extends NodeCfg,\n C extends MethodCfg,\n PS,\n> = Leaf<M, Base, Merge<I, EffectiveCfg<C, PS>>>;\n\n/** Builder surface used by `resource(...)` to accumulate leaves. */\nexport interface Branch<\n Base extends string,\n Acc extends readonly AnyLeaf[],\n I extends NodeCfg,\n PS extends ZodTypeAny | undefined,\n> {\n // --- structure ---\n /**\n * Enter or define a static child segment.\n * Optionally accepts extra config and/or a builder to populate nested routes.\n * @param name Child segment literal (no leading slash).\n * @param cfg Optional node configuration to merge for descendants.\n * @param builder Callback to produce leaves for the child branch.\n */\n sub<Name extends string, J extends NodeCfg>(\n name: Name,\n cfg?: J,\n ): Branch<`${Base}/${Name}`, Acc, Merge<I, NonNullable<J>>, PS>;\n\n sub<Name extends string, J extends NodeCfg | undefined, R extends readonly AnyLeaf[]>(\n name: Name,\n cfg: J,\n builder: (r: Branch<`${Base}/${Name}`, readonly [], Merge<I, NonNullable<J>>, PS>) => R,\n ): Branch<Base, Append<Acc, R[number]>, Merge<I, NonNullable<J>>, PS>;\n\n sub<Name extends string, R extends readonly AnyLeaf[]>(\n name: Name,\n builder: (r: Branch<`${Base}/${Name}`, readonly [], I, PS>) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, PS>;\n\n // --- parameterized segment (single signature) ---\n /**\n * Introduce a `:param` segment and merge its schema into downstream leaves.\n * @param name Parameter key (without leading colon).\n * @param paramsSchema Zod schema for the parameter value.\n * @param builder Callback that produces leaves beneath the parameterized segment.\n */\n routeParameter<Name extends string, P extends ZodTypeAny, R extends readonly AnyLeaf[]>(\n name: Name,\n paramsSchema: P,\n builder: (\n r: Branch<\n `${Base}/:${Name}`,\n readonly [],\n I,\n MergedParamsResult<PS, Name, P>\n >,\n ) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, MergedParamsResult<PS, Name, P>>;\n\n // --- flags inheritance ---\n /**\n * Merge additional node configuration that subsequent leaves will inherit.\n * @param cfg Partial node configuration.\n */\n with<J extends NodeCfg>(cfg: J): Branch<Base, Acc, Merge<I, J>, PS>;\n\n // --- methods (return Branch to keep chaining) ---\n /**\n * Register a GET leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n get<C extends MethodCfg>(\n cfg: C,\n ): Branch<\n Base,\n Append<Acc, Prettify<BuiltLeaf<'get', Base, I, C, PS>>>,\n I,\n PS\n >;\n\n /**\n * Register a POST leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n post<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'post', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >;\n\n /**\n * Register a PUT leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n put<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'put', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >;\n\n /**\n * Register a PATCH leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n patch<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'patch', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >;\n\n /**\n * Register a DELETE leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n delete<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'delete', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >;\n\n // --- finalize this subtree ---\n /**\n * Finish the branch and return the collected leaves.\n * @returns Readonly tuple of accumulated leaves.\n */\n done(): Readonly<Acc>;\n}\n\n/**\n * Start building a resource at the given base path.\n * @param base Root path for the resource (e.g. `/v1`).\n * @param inherited Optional node configuration applied to all descendants.\n * @returns Root `Branch` instance used to compose the route tree.\n */\nexport function resource<Base extends string, I extends NodeCfg = {}>(\n base: Base,\n inherited?: I,\n): Branch<Base, readonly [], I, undefined> {\n const rootBase = base;\n const rootInherited: NodeCfg = { ...(inherited as NodeCfg) };\n\n function makeBranch<Base2 extends string, I2 extends NodeCfg, PS2 extends ZodTypeAny | undefined>(\n base2: Base2,\n inherited2: I2,\n mergedParamsSchema?: PS2,\n ) {\n const stack: AnyLeaf[] = [];\n let currentBase: string = base2;\n let inheritedCfg: NodeCfg = { ...(inherited2 as NodeCfg) };\n let currentParamsSchema: PS2 = mergedParamsSchema as PS2;\n\n function add<M extends HttpMethod, C extends MethodCfg>(method: M, cfg: C) {\n // If the method didn’t provide a paramsSchema, inject the active merged one.\n const effectiveParamsSchema = (cfg.paramsSchema ?? currentParamsSchema) as PS2 | undefined;\n const effectiveQuerySchema =\n cfg.feed === true ? augmentFeedQuerySchema(cfg.querySchema) : cfg.querySchema;\n const effectiveOutputSchema =\n cfg.feed === true ? augmentFeedOutputSchema(cfg.outputSchema) : cfg.outputSchema;\n\n const fullCfg = (\n effectiveParamsSchema\n ? {\n ...inheritedCfg,\n ...cfg,\n paramsSchema: effectiveParamsSchema,\n ...(effectiveQuerySchema ? { querySchema: effectiveQuerySchema } : {}),\n ...(effectiveOutputSchema ? { outputSchema: effectiveOutputSchema } : {}),\n }\n : {\n ...inheritedCfg,\n ...cfg,\n ...(effectiveQuerySchema ? { querySchema: effectiveQuerySchema } : {}),\n ...(effectiveOutputSchema ? { outputSchema: effectiveOutputSchema } : {}),\n }\n ) as any;\n\n const leaf = {\n method,\n path: currentBase as Base2,\n cfg: fullCfg,\n } as const;\n\n stack.push(leaf as unknown as AnyLeaf);\n\n // Return same runtime obj, but with Acc including this new leaf\n return api as unknown as Branch<Base2, Append<readonly [], typeof leaf>, I2, PS2>;\n }\n\n const api: any = {\n // compose a plain subpath (optional cfg) with optional builder\n sub<Name extends string, J extends NodeCfg | undefined = undefined>(\n name: Name,\n cfgOrBuilder?: J | ((r: any) => readonly AnyLeaf[]),\n maybeBuilder?: (r: any) => readonly AnyLeaf[],\n ) {\n let cfg: NodeCfg | undefined;\n let builder: ((r: any) => readonly AnyLeaf[]) | undefined;\n\n if (typeof cfgOrBuilder === 'function') {\n builder = cfgOrBuilder as any;\n } else {\n cfg = cfgOrBuilder as NodeCfg | undefined;\n builder = maybeBuilder;\n }\n\n const childBase = `${currentBase}/${name}` as const;\n const childInherited = { ...inheritedCfg, ...(cfg ?? {}) } as Merge<I2, NonNullable<J>>;\n\n if (builder) {\n // params schema PS2 flows through unchanged on plain sub\n const child = makeBranch(childBase, childInherited, currentParamsSchema);\n const leaves = builder(child) as readonly AnyLeaf[];\n for (const l of leaves) stack.push(l);\n return api as Branch<\n Base2,\n Append<readonly [], (typeof leaves)[number]>,\n typeof childInherited,\n PS2\n >;\n } else {\n currentBase = childBase;\n inheritedCfg = childInherited;\n return api as Branch<`${Base2}/${Name}`, readonly [], typeof childInherited, PS2>;\n }\n },\n\n // the single param function: name + schema + builder\n routeParameter<Name extends string, P extends ZodTypeAny, R extends readonly AnyLeaf[]>(\n name: Name,\n paramsSchema: P,\n builder: (\n r: Branch<\n `${Base2}/:${Name}`,\n readonly [],\n I2,\n MergedParamsResult<PS2, Name, P>\n >,\n ) => R,\n ) {\n const childBase = `${currentBase}/:${name}` as const;\n // Wrap the value schema under the param name before merging with inherited params schema\n const paramObj: ParamZod<Name, P> = z.object({ [name]: paramsSchema } as Record<Name, P>);\n const childParams = (currentParamsSchema\n ? mergeSchemas(currentParamsSchema, paramObj)\n : paramObj) as MergedParamsResult<PS2, Name, P>;\n const child = makeBranch(childBase, inheritedCfg as I2, childParams);\n const leaves = builder(child) as readonly AnyLeaf[];\n for (const l of leaves) stack.push(l);\n return api as Branch<\n Base2,\n Append<readonly [], (typeof leaves)[number]>,\n I2,\n MergedParamsResult<PS2, Name, P>\n >;\n },\n\n with<J extends NodeCfg>(cfg: J) {\n inheritedCfg = { ...inheritedCfg, ...cfg };\n return api as Branch<Base2, readonly [], Merge<I2, J>, PS2>;\n },\n\n // methods (inject current params schema if missing)\n get<C extends MethodCfg>(cfg: C) {\n return add('get', cfg);\n },\n post<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('post', { ...cfg, feed: false });\n },\n put<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('put', { ...cfg, feed: false });\n },\n patch<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('patch', { ...cfg, feed: false });\n },\n delete<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('delete', { ...cfg, feed: false });\n },\n\n done() {\n return stack;\n },\n };\n\n return api as Branch<Base2, readonly [], I2, PS2>;\n }\n\n // Root branch starts with no params schema (PS = undefined)\n return makeBranch(rootBase, rootInherited, undefined);\n}\n\n/**\n * Merge two readonly tuples (preserves literal tuple information).\n * @param arr1 First tuple.\n * @param arr2 Second tuple.\n * @returns New tuple containing values from both inputs.\n */\nexport const mergeArrays = <T extends readonly any[], S extends readonly any[]>(\n arr1: T,\n arr2: S,\n) => {\n return [...arr1, ...arr2] as [...T, ...S];\n};\n","import { z, ZodTypeAny } from 'zod';\n\n/** Supported HTTP verbs for the routes DSL. */\nexport type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\n/** Declarative description of a multipart upload field. */\nexport type FileField = {\n /** Form field name used for uploads. */\n name: string;\n /** Maximum number of files accepted for this field. */\n maxCount: number;\n};\n\n/** Configuration that applies to an entire branch of the route tree. */\nexport type NodeCfg = {\n /** @deprecated. Does nothing. */\n authenticated?: boolean;\n};\n\n/** Per-method configuration merged with inherited node config. */\nexport type MethodCfg = {\n /** Zod schema describing the request body. */\n bodySchema?: ZodTypeAny;\n /** Zod schema describing the query string. */\n querySchema?: ZodTypeAny;\n /** Zod schema describing path params (overrides inferred params). */\n paramsSchema?: ZodTypeAny;\n /** Zod schema describing the response payload. */\n outputSchema?: ZodTypeAny;\n /** Multipart upload definitions for the route. */\n bodyFiles?: FileField[];\n /** Marks the route as an infinite feed (enables cursor helpers). */\n feed?: boolean;\n /** Optional human-readable description for docs/debugging. */\n description?: string;\n};\n\n/** Immutable representation of a single HTTP route in the tree. */\nexport type Leaf<M extends HttpMethod, P extends string, C extends MethodCfg> = {\n /** Lowercase HTTP method (get/post/...). */\n readonly method: M;\n /** Concrete path for the route (e.g. `/v1/users/:userId`). */\n readonly path: P;\n /** Readonly snapshot of route configuration. */\n readonly cfg: Readonly<C>;\n};\n\n/** Convenience union covering all generated leaves. */\nexport type AnyLeaf = Leaf<HttpMethod, string, MethodCfg>;\n\n/** Merge two object types while keeping nice IntelliSense output. */\nexport type Merge<A, B> = Prettify<Omit<A, keyof B> & B>;\n\n/** Append a new element to a readonly tuple type. */\nexport type Append<T extends readonly unknown[], X> = [...T, X];\n\n/** Concatenate two readonly tuple types. */\nexport type MergeArray<A extends readonly unknown[], B extends readonly unknown[]> = [\n ...A,\n ...B,\n];\n\n// helpers (optional)\ntype SegmentParams<S extends string> = S extends `:${infer P}` ? P : never;\ntype Split<S extends string> = S extends ''\n ? []\n : S extends `${infer A}/${infer B}`\n ? [A, ...Split<B>]\n : [S];\ntype ExtractParamNames<Path extends string> = SegmentParams<Split<Path>[number]>;\n\n/** Derive a params object type from a literal route string. */\nexport type ExtractParamsFromPath<Path extends string> =\n ExtractParamNames<Path> extends never ? never : Record<ExtractParamNames<Path>, string | number>;\n\n/**\n * Interpolate `:params` in a path using the given values.\n * @param path Literal route string containing `:param` segments.\n * @param params Object of parameter values to interpolate.\n * @returns Path string with parameters substituted.\n */\nexport function compilePath<Path extends string>(path: Path, params: ExtractParamsFromPath<Path>) {\n if (!params) return path;\n return path.replace(/:([A-Za-z0-9_]+)/g, (_, k) => {\n const v = (params as any)[k];\n if (v === undefined || v === null) throw new Error(`Missing param :${k}`);\n return String(v);\n });\n}\n\n/**\n * Build a deterministic cache key for the given leaf.\n * The key matches the shape consumed by React Query helpers.\n * @param args.leaf Leaf describing the endpoint.\n * @param args.params Optional params used to build the path.\n * @param args.query Optional query payload.\n * @returns Tuple suitable for React Query cache keys.\n */\ntype SplitPath<P extends string> = P extends ''\n ? []\n : P extends `${infer A}/${infer B}`\n ? [A, ...SplitPath<B>]\n : [P];\nexport function buildCacheKey<L extends AnyLeaf>(args: {\n leaf: L;\n params?: ExtractParamsFromPath<L['path']>;\n query?: InferQuery<L>;\n}) {\n let p = args.leaf.path;\n if (args.params) {\n p = compilePath<L['path']>(p, args.params);\n }\n return [args.leaf.method, ...(p.split('/').filter(Boolean) as SplitPath<typeof p>), args.query ?? {}] as const;\n}\n\n/** Infer params either from the explicit params schema or from the path literal. */\nexport type InferParams<L extends AnyLeaf> = L['cfg']['paramsSchema'] extends ZodTypeAny\n ? z.infer<L['cfg']['paramsSchema']>\n : ExtractParamsFromPath<L['path']>;\n\n/** Infer query shape from a Zod schema when present. */\nexport type InferQuery<L extends AnyLeaf> = L['cfg']['querySchema'] extends ZodTypeAny\n ? z.infer<L['cfg']['querySchema']>\n : never;\n\n/** Infer request body shape from a Zod schema when present. */\nexport type InferBody<L extends AnyLeaf> = L['cfg']['bodySchema'] extends ZodTypeAny\n ? z.infer<L['cfg']['bodySchema']>\n : never;\n\n/** Infer handler output shape from a Zod schema. Defaults to unknown. */\nexport type InferOutput<L extends AnyLeaf> = L['cfg']['outputSchema'] extends ZodTypeAny\n ? z.infer<L['cfg']['outputSchema']>\n : unknown;\n\n/** Render a type as if it were a simple object literal. */\nexport type Prettify<T> = { [K in keyof T]: T[K] } & {};\n","// TODO:\n// * use this as a transform that infers the types from Zod, to only pass the types around instead of the full schemas -> make converters that go both ways (data to schema, schema to data)\n// * consider moving to core package\n// * update server and client side to use this type instead of raw zod schemas \nimport { AnyLeaf, HttpMethod, Prettify } from './routesV3.core';\n\n/** Build the key type for a leaf — distributive so method/path stay paired. */\nexport type KeyOf<L extends AnyLeaf> = L extends AnyLeaf\n ? `${Uppercase<L['method']>} ${L['path']}`\n : never;\n\n// From a tuple of leaves, get the union of keys (pairwise, no cartesian blow-up)\ntype KeysOf<Leaves extends readonly AnyLeaf[]> = KeyOf<Leaves[number]>;\n\n// Parse method & path out of a key\ntype MethodFromKey<K extends string> = K extends `${infer M} ${string}` ? Lowercase<M> : never;\ntype PathFromKey<K extends string> = K extends `${string} ${infer P}` ? P : never;\n\n// Given Leaves and a Key, pick the exact leaf that matches method+path\ntype LeafForKey<Leaves extends readonly AnyLeaf[], K extends string> = Extract<\n Leaves[number],\n { method: MethodFromKey<K> & HttpMethod; path: PathFromKey<K> }\n>;\n\n/**\n * Freeze a leaf tuple into a registry with typed key lookups.\n * @param leaves Readonly tuple of leaves produced by the builder DSL.\n * @returns Registry containing the leaves array and a `byKey` lookup map.\n */\nexport function finalize<const L extends readonly AnyLeaf[]>(leaves: L) {\n type Keys = KeysOf<L>;\n type MapByKey = { [K in Keys]: Prettify<LeafForKey<L, K>> };\n\n const byKey = Object.fromEntries(\n leaves.map((l) => [`${l.method.toUpperCase()} ${l.path}`, l] as const),\n ) as unknown as MapByKey;\n\n const log = (logger: { system: (...args: unknown[]) => void }) => {\n logger.system('Finalized routes:');\n (Object.keys(byKey) as Keys[]).forEach((k) => {\n const leaf = byKey[k];\n logger.system(`- ${k}`);\n });\n };\n\n return { all: leaves, byKey, log };\n}\n\n/** Nominal type alias for a finalized registry. */\nexport type Registry<R extends ReturnType<typeof finalize>> = R;\n\ntype FilterRoute<\n T extends readonly AnyLeaf[],\n F extends string,\n Acc extends readonly AnyLeaf[] = [],\n> = T extends readonly [infer First extends AnyLeaf, ...infer Rest extends AnyLeaf[]]\n ? First extends { path: `${string}${F}${string}` }\n ? FilterRoute<Rest, F, [...Acc, First]>\n : FilterRoute<Rest, F, Acc>\n : Acc;\n\ntype UpperCase<S extends string> = S extends `${infer First}${infer Rest}`\n ? `${Uppercase<First>}${UpperCase<Rest>}`\n : S;\n\ntype Routes<T extends readonly AnyLeaf[], F extends string> = FilterRoute<T, F>;\ntype ByKey<\n T extends readonly AnyLeaf[],\n Acc extends Record<string, AnyLeaf> = {},\n> = T extends readonly [infer First extends AnyLeaf, ...infer Rest extends AnyLeaf[]]\n ? ByKey<Rest, Acc & { [K in `${UpperCase<First['method']>} ${First['path']}`]: First }>\n : Acc;\n\n/**\n * Convenience helper for extracting a subset of routes by path fragment.\n * @param T Tuple of leaves produced by the DSL.\n * @param F String fragment to match against the route path.\n */\nexport type SubsetRoutes<T extends readonly AnyLeaf[], F extends string> = {\n byKey: ByKey<Routes<T, F>>;\n all: Routes<T, F>;\n};\n","// routesV3.crud.ts\n// -----------------------------------------------------------------------------\n// Add a first-class .crud() helper to the routesV3 DSL, without touching the\n// core builder. This file:\n// 1) Declares types + module augmentation to extend Branch<...> with .crud\n// 2) Provides a runtime decorator `withCrud(...)` that installs the method\n// 3) Exports a convenience `resourceWithCrud(...)` wrapper (optional)\n// -----------------------------------------------------------------------------\n\nimport { z, ZodType } from 'zod';\nimport {\n resource as baseResource,\n type Branch as _Branch, // import type so we can augment it\n} from '../core/routesV3.builder';\nimport { type AnyLeaf, type Leaf, type NodeCfg } from '../core/routesV3.core';\n\n// -----------------------------------------------------------------------------\n// Small utilities (runtime + types)\n// -----------------------------------------------------------------------------\n/** Default cursor pagination used by list (GET collection). */\nexport const CrudDefaultPagination = z.object({\n limit: z.coerce.number().min(1).max(100).default(20),\n cursor: z.string().optional(),\n});\nconst CrudPaginationField = CrudDefaultPagination.optional().default(CrudDefaultPagination.parse({}));\ntype CrudPaginationField = typeof CrudPaginationField;\ntype AnyCrudZodObject = z.ZodObject<any>;\ntype AddCrudPagination<Q extends AnyCrudZodObject | undefined> = Q extends z.ZodObject<infer Shape>\n ? z.ZodObject<Shape & { pagination: CrudPaginationField }>\n : z.ZodObject<{ pagination: CrudPaginationField }>;\n\n/**\n * Merge two Zod schemas at runtime; matches the typing pattern used in builder.\n * @param a Existing params schema inherited from parent branches.\n * @param b Schema introduced at the current branch.\n * @returns Intersection of schemas when both exist, otherwise whichever is defined.\n */\nexport function mergeSchemas<A extends ZodType | undefined, B extends ZodType | undefined>(\n a: A,\n b: B,\n): A extends ZodType ? (B extends ZodType ? ReturnType<typeof z.intersection<A, B>> : A) : B {\n if (a && b) return z.intersection(a as any, b as any) as any;\n return (a ?? b) as any;\n}\n\n/** Build { [Name]: S } Zod object at the type-level. */\nexport type ParamSchema<Name extends string, S extends ZodType> = z.ZodObject<{\n [K in Name]: S;\n}>;\n\n/** Inject active params schema into a leaf cfg (to match your Leaf typing). */\ntype WithParams<I, P> = P extends ZodType ? Omit<I, 'paramsSchema'> & { paramsSchema: P } : I;\n\n/** Resolve boolean flag: default D unless explicitly false. */\ntype Flag<E, D extends boolean> = E extends false ? false : D;\n\n// -----------------------------------------------------------------------------\n// CRUD config (few knobs, with DX comments)\n// -----------------------------------------------------------------------------\n\n/** Toggle individual CRUD methods; defaults enable all (create/update require body). */\nexport type CrudEnable = {\n /** GET /collection (feed). Defaults to true. */ list?: boolean;\n /** POST /collection. Defaults to true if `create` provided. */ create?: boolean;\n /** GET /collection/:id. Defaults to true. */ read?: boolean;\n /** PATCH /collection/:id. Defaults to true if `update` provided. */ update?: boolean;\n /** DELETE /collection/:id. Defaults to true. */ remove?: boolean;\n};\n\n/** Collection GET config. */\nexport type CrudListCfg = {\n /** Query schema (defaults to cursor pagination). */\n querySchema?: ZodType;\n /** Output schema (defaults to { items: Item[], nextCursor? }). */\n outputSchema?: ZodType;\n /** Optional description string. */\n description?: string;\n};\n\n/** Collection POST config. */\nexport type CrudCreateCfg = {\n /** Body schema for creating an item. */\n bodySchema: ZodType;\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType;\n /** Optional description. */\n description?: string;\n};\n\n/** Item GET config. */\nexport type CrudReadCfg = {\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType;\n /** Optional description. */\n description?: string;\n};\n\n/** Item PATCH config. */\nexport type CrudUpdateCfg = {\n /** Body schema for partial updates. */\n bodySchema: ZodType;\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType;\n /** Optional description. */\n description?: string;\n};\n\n/** Item DELETE config. */\nexport type CrudRemoveCfg = {\n /** Output schema (defaults to { ok: true }). */\n outputSchema?: ZodType;\n /** Optional description. */\n description?: string;\n};\n\n/**\n * CRUD config for `.crud(\"resource\", cfg, extras?)`.\n *\n * It synthesizes `:[resourceName]Id` as the param key and uses `paramSchema` for the value.\n * Prefer passing a **value schema** (e.g. `z.string().uuid()`).\n * As a convenience, a ZodObject of shape `{ [resourceName]Id: schema }` is accepted at runtime too.\n */\nexport type CrudCfg<Name extends string = string> = {\n /**\n * Zod schema for the ID *value* (e.g. `z.string().uuid()`).\n * The parameter key is always `:${name}Id`.\n * (If you pass `z.object({ [name]Id: ... })`, it's accepted at runtime.)\n */\n paramSchema: ZodType;\n\n /**\n * The single-item output shape used by read/create/update by default.\n * List defaults to `{ items: z.array(itemOutputSchema), nextCursor? }`.\n */\n itemOutputSchema: ZodType;\n\n /** Per-method toggles (all enabled by default; create/update require bodies). */\n enable?: CrudEnable;\n\n /** GET /collection configuration. */ list?: CrudListCfg;\n /** POST /collection configuration (enables create). */ create?: CrudCreateCfg;\n /** GET /collection/:id configuration. */ read?: CrudReadCfg;\n /** PATCH /collection/:id configuration (enables update). */ update?: CrudUpdateCfg;\n /** DELETE /collection/:id configuration. */ remove?: CrudRemoveCfg;\n};\n\n// -----------------------------------------------------------------------------\n// Type plumbing to expose generated leaves (so finalize().byKey sees them)\n// -----------------------------------------------------------------------------\n\ntype CrudLeavesTuple<\n Base extends string,\n I extends NodeCfg,\n PS extends ZodType | undefined,\n Name extends string,\n C extends CrudCfg<Name>,\n> = `${Name}Id` extends infer IdName extends string\n ? ParamSchema<IdName, C['paramSchema']> extends infer IdParamZ extends ZodType\n ? [\n // GET /collection\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['list'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'get',\n `${Base}/${Name}`,\n WithParams<\n Omit<I, never> & {\n feed: true;\n querySchema: C['list'] extends CrudListCfg\n ? AddCrudPagination<\n C['list']['querySchema'] extends AnyCrudZodObject\n ? C['list']['querySchema']\n : undefined\n >\n : AddCrudPagination<undefined>;\n outputSchema: C['list'] extends CrudListCfg\n ? C['list']['outputSchema'] extends ZodType\n ? C['list']['outputSchema']\n : z.ZodObject<{\n items: z.ZodArray<C['itemOutputSchema']>;\n nextCursor: z.ZodOptional<z.ZodString>;\n }>\n : z.ZodObject<{\n items: z.ZodArray<C['itemOutputSchema']>;\n nextCursor: z.ZodOptional<z.ZodString>;\n }>;\n description?: string;\n },\n PS\n >\n >,\n ]\n : []),\n\n // POST /collection\n ...((C['create'] extends CrudCreateCfg ? true : false) extends true\n ? Flag<\n C['enable'] extends CrudEnable ? C['enable']['create'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'post',\n `${Base}/${Name}`,\n WithParams<\n Omit<I, never> & {\n bodySchema: C['create'] extends CrudCreateCfg\n ? C['create']['bodySchema']\n : never;\n outputSchema: C['create'] extends CrudCreateCfg\n ? C['create']['outputSchema'] extends ZodType\n ? C['create']['outputSchema']\n : C['itemOutputSchema']\n : never;\n description?: string;\n },\n PS\n >\n >,\n ]\n : []\n : []),\n\n // GET /collection/:id\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['read'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'get',\n `${Base}/${Name}/:${IdName}`,\n WithParams<\n Omit<I, never> & {\n outputSchema: C['read'] extends CrudReadCfg\n ? C['read']['outputSchema'] extends ZodType\n ? C['read']['outputSchema']\n : C['itemOutputSchema']\n : C['itemOutputSchema'];\n description?: string;\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >,\n ]\n : []),\n\n // PATCH /collection/:id\n ...((C['update'] extends CrudUpdateCfg ? true : false) extends true\n ? Flag<\n C['enable'] extends CrudEnable ? C['enable']['update'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'patch',\n `${Base}/${Name}/:${IdName}`,\n WithParams<\n Omit<I, never> & {\n bodySchema: C['update'] extends CrudUpdateCfg\n ? C['update']['bodySchema']\n : never;\n outputSchema: C['update'] extends CrudUpdateCfg\n ? C['update']['outputSchema'] extends ZodType\n ? C['update']['outputSchema']\n : C['itemOutputSchema']\n : never;\n description?: string;\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >,\n ]\n : []\n : []),\n\n // DELETE /collection/:id\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['remove'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'delete',\n `${Base}/${Name}/:${IdName}`,\n WithParams<\n Omit<I, never> & {\n outputSchema: C['remove'] extends CrudRemoveCfg\n ? C['remove']['outputSchema'] extends ZodType\n ? C['remove']['outputSchema']\n : z.ZodObject<{ ok: z.ZodLiteral<true> }>\n : z.ZodObject<{ ok: z.ZodLiteral<true> }>;\n description?: string;\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >,\n ]\n : []),\n ]\n : never\n : never;\n\n/** Merge generated leaves + extras into the branch accumulator. */\ntype CrudResultAcc<\n Base extends string,\n Acc extends readonly AnyLeaf[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeaf[],\n> = [...Acc, ...CrudLeavesTuple<Base, I, PS, Name, C>, ...Extras];\n\n// -----------------------------------------------------------------------------\n// Module augmentation: add the typed `.crud(...)` to Branch<...>\n// -----------------------------------------------------------------------------\n\ndeclare module './../core/routesV3.builder' {\n interface Branch<\n Base extends string,\n Acc extends readonly AnyLeaf[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n > {\n /**\n * Generate opinionated CRUD endpoints for a collection at `/.../<name>`\n * with an item at `/.../<name>/:<name>Id`.\n *\n * Creates (subject to `enable` + presence of create/update bodies):\n * - GET /<name> (feed list)\n * - POST /<name> (create)\n * - GET /<name>/:<name>Id (read item)\n * - PATCH /<name>/:<name>Id (update item)\n * - DELETE /<name>/:<name>Id (remove item)\n *\n * The `extras` callback receives live builders at both collection and item\n * levels so you can add custom subroutes; their leaves are included in the\n * returned Branch type.\n */\n crud<\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeaf[] = readonly [],\n >(\n name: Name,\n cfg: C,\n extras?: (ctx: {\n /** Builder at `/.../<name>` (collection scope). */\n collection: _Branch<`${Base}/${Name}`, readonly [], I, PS>;\n /** Builder at `/.../<name>/:<name>Id` (item scope). */\n item: _Branch<\n `${Base}/${Name}/:${`${Name}Id`}`,\n readonly [],\n I,\n ReturnType<typeof mergeSchemas<PS, ParamSchema<`${Name}Id`, C['paramSchema']>>>\n >;\n }) => Extras,\n ): _Branch<Base, CrudResultAcc<Base, Acc, I, PS, Name, C, Extras>, I, PS>;\n }\n}\n\n// -----------------------------------------------------------------------------\n// Runtime: install .crud on any Branch via decorator\n// -----------------------------------------------------------------------------\n\n/**\n * Decorate a Branch instance so `.crud(...)` is available at runtime.\n * Tip: wrap the root: `withCrud(resource('/v1'))`.\n * @param branch Branch returned by `resource(...)`.\n * @returns Same branch with `.crud(...)` installed.\n */\nexport function withCrud<\n Base extends string,\n Acc extends readonly AnyLeaf[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n>(branch: _Branch<Base, Acc, I, PS>): _Branch<Base, Acc, I, PS> {\n const b = branch as any;\n if (typeof b.crud === 'function') return branch;\n\n b.crud = function <\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeaf[] = readonly [],\n >(this: any, name: Name, cfg: C, extras?: (ctx: { collection: any; item: any }) => Extras) {\n // Build inside a sub-branch at `/.../<name>` and harvest its leaves.\n return this.sub(name, (collection: any) => {\n const idKey = `${name}Id`;\n\n // Accept a value schema (preferred); but if a z.object({[name]Id: ...}) is provided, use it.\n const s = cfg.paramSchema;\n const isObj =\n s &&\n typeof (s as any)._def === 'object' &&\n (s as any)._def.typeName === 'ZodObject' &&\n typeof (s as any).shape === 'function';\n\n const paramValueSchema =\n isObj && (s as any).shape()[idKey] ? ((s as any).shape()[idKey] as ZodType) : (s as ZodType);\n\n const itemOut = cfg.itemOutputSchema;\n const listOut =\n cfg.list?.outputSchema ??\n z.object({\n items: z.array(itemOut),\n nextCursor: z.string().optional(),\n });\n\n const want = {\n list: cfg.enable?.list !== false,\n create: cfg.enable?.create !== false && !!cfg.create?.bodySchema,\n read: cfg.enable?.read !== false,\n update: cfg.enable?.update !== false && !!cfg.update?.bodySchema,\n remove: cfg.enable?.remove !== false,\n } as const;\n\n // Collection routes\n if (want.list) {\n collection.get({\n feed: true,\n querySchema: cfg.list?.querySchema ?? CrudDefaultPagination,\n outputSchema: listOut,\n description: cfg.list?.description ?? 'List',\n });\n }\n\n if (want.create) {\n collection.post({\n bodySchema: cfg.create!.bodySchema,\n outputSchema: cfg.create?.outputSchema ?? itemOut,\n description: cfg.create?.description ?? 'Create',\n });\n }\n\n // Item routes via :<name>Id\n collection.routeParameter(idKey as any, paramValueSchema as any, (item: any) => {\n if (want.read) {\n item.get({\n outputSchema: cfg.read?.outputSchema ?? itemOut,\n description: cfg.read?.description ?? 'Read',\n });\n }\n if (want.update) {\n item.patch({\n bodySchema: cfg.update!.bodySchema,\n outputSchema: cfg.update?.outputSchema ?? itemOut,\n description: cfg.update?.description ?? 'Update',\n });\n }\n if (want.remove) {\n item.delete({\n outputSchema: cfg.remove?.outputSchema ?? z.object({ ok: z.literal(true) }),\n description: cfg.remove?.description ?? 'Delete',\n });\n }\n\n // Give extras fully-capable builders (decorate so extras can call .crud again)\n if (extras) extras({ collection: withCrud(collection), item: withCrud(item) });\n\n return item.done();\n });\n\n return collection.done();\n });\n };\n\n return branch;\n}\n\n// -----------------------------------------------------------------------------\n// Optional convenience: re-export a resource() that already has .crud installed\n// -----------------------------------------------------------------------------\n\n/**\n * Drop-in replacement for `resource(...)` that returns a Branch with `.crud()` installed.\n * You can either use this or call `withCrud(resource(...))`.\n * @param base Root path for the resource (e.g. `/v1`).\n * @param inherited Node configuration merged into every leaf.\n * @returns Branch builder that already includes the CRUD helper.\n */\nexport function resourceWithCrud<Base extends string, I extends NodeCfg = {}>(\n base: Base,\n inherited: I,\n) {\n return withCrud(baseResource(base, inherited));\n}\n\n// Re-export the original in case you want both styles from this module\nexport { baseResource as resource };\n","// socket.index.ts (shared client/server)\n\nimport { z } from 'zod';\n\nexport type SocketSchema<Output =unknown> = z.ZodType & {\n __out: Output;\n};\n\nexport type SocketSchemaOutput<Schema extends z.ZodTypeAny> = Schema extends {\n __out: infer Out;\n} ? Out : z.output<Schema>;\n\nexport type SocketEvent<Out = unknown> = {\n message: z.ZodTypeAny;\n /** phantom field, only for typing; not meant to be used at runtime */\n __out: Out;\n};\n\nexport type EventMap = Record<string, SocketEvent<any>>;\n\n/**\n * System event names – shared so server and client\n * don't drift on naming.\n */\nexport type SysEventName = 'sys:connect' | 'sys:disconnect' | 'sys:reconnect' | 'sys:connect_error' | 'sys:ping' | 'sys:pong' | 'sys:room_join' | 'sys:room_leave';\nexport function defineSocketEvents<const C extends SocketConnectionConfig, const Schemas extends Record<string, {\n message: z.ZodTypeAny;\n}>>(config: C, events: Schemas): {\n config: {\n [K in keyof C]: SocketSchema<z.output<C[K]>>;\n };\n events: {\n [K in keyof Schemas]: SocketEvent<z.output<Schemas[K]['message']>>;\n };\n};\n\nexport function defineSocketEvents(config: any, events: any) {\n return { config, events };\n}\n\n\n\nexport type Payload<T extends EventMap, K extends keyof T> = T[K] extends SocketEvent<infer Out> ? Out : never;\nexport type SocketConnectionConfig = {\n joinMetaMessage: z.ZodTypeAny;\n leaveMetaMessage: z.ZodTypeAny;\n pingPayload: z.ZodTypeAny;\n pongPayload: z.ZodTypeAny;\n};\n\nexport type SocketConnectionConfigOutput = {\n joinMetaMessage: SocketSchema<any>;\n leaveMetaMessage: SocketSchema<any>;\n pingPayload: SocketSchema<any>;\n pongPayload: SocketSchema<any>;\n}","// docs-generator.ts\nimport { z, ZodType, ZodObject, ZodArray } from \"zod\";\nimport { AnyLeaf, FileField } from \"../core/routesV3.core\";\n\n\n// ------------------------------------------------------------\n// Schema summarizer (lightweight introspection for Zod v4)\n// ------------------------------------------------------------\nfunction summarizeSchema(schema?: ZodType): unknown {\n if (!schema) return undefined;\n\n // ZodObject\n if (schema instanceof ZodObject) {\n const shape = schema.shape;\n return {\n type: \"object\",\n fields: Object.fromEntries(\n Object.entries(shape).map(([key, value]) => {\n const def: any = (value as any)._def;\n return [\n key,\n {\n typeName: def?.typeName,\n description: def?.description\n }\n ];\n })\n )\n };\n }\n\n // ZodArray\n if (schema instanceof ZodArray) {\n return {\n type: \"array\",\n // @ts-ignore\n element: summarizeSchema(schema.unwrap())\n };\n }\n\n // fallback for primitives and complex types\n const def: any = (schema as any)._def;\n return { typeName: def?.typeName ?? \"unknown\" };\n}\n\n// ------------------------------------------------------------\n// Build a structured doc model from AnyLeaf[]\n// ------------------------------------------------------------\ntype RouteDoc = {\n method: string;\n path: string;\n description?: string;\n feed?: boolean;\n body?: unknown;\n query?: unknown;\n params?: unknown;\n output?: unknown;\n files?: FileField[];\n};\n\nfunction leavesToDocs(leaves: AnyLeaf[]): RouteDoc[] {\n return leaves.map((leaf) => {\n const { method, path, cfg } = leaf;\n\n return {\n method,\n path,\n description: cfg.description,\n feed: cfg.feed,\n body: summarizeSchema(cfg.bodySchema),\n query: summarizeSchema(cfg.querySchema),\n params: summarizeSchema(cfg.paramsSchema),\n output: summarizeSchema(cfg.outputSchema),\n files: cfg.bodyFiles\n };\n });\n}\n\n// ------------------------------------------------------------\n// Markdown renderer for the docs\n// ------------------------------------------------------------\nexport function renderLeafDocsMarkdown(leaves: AnyLeaf[]): string {\n const docs = leavesToDocs(leaves);\n\n docs.sort((a, b) => {\n const p = a.path.localeCompare(b.path);\n return p !== 0 ? p : a.method.localeCompare(b.method);\n });\n\n return docs\n .map((d) => {\n const lines: string[] = [];\n\n lines.push(`### \\`${d.method.toUpperCase()} ${d.path}\\``);\n\n if (d.description) {\n lines.push(\"\", d.description);\n }\n\n if (d.feed) {\n lines.push(\"\", \"_Feed endpoint_\");\n }\n\n function pushJson(title: string, value: unknown | undefined) {\n if (!value) return;\n lines.push(\n \"\",\n `**${title}**`,\n \"```json\",\n JSON.stringify(value, null, 2),\n \"```\"\n );\n }\n\n pushJson(\"Query\", d.query);\n pushJson(\"Params\", d.params);\n pushJson(\"Body\", d.body);\n pushJson(\"Output\", d.output);\n\n if (d.files && d.files.length > 0) {\n lines.push(\"\", \"**Multipart files**\");\n d.files.forEach((f) => {\n lines.push(`- \\`${f.name}\\` (maxCount: ${f.maxCount})`);\n });\n }\n\n return lines.join(\"\\n\");\n })\n .join(\"\\n\\n\");\n}"],"mappings":";AAAA,SAAS,SAAS;AAalB,IAAM,yBAAyB,EAAE,OAAO;AAAA,EACtC,QAAQ,EAAE,OAAO,EAAE,SAAS;AAAA,EAC5B,OAAO,EAAE,OAAO,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,QAAQ,EAAE;AACrD,CAAC;AAED,IAAM,kBAAkB,uBAAuB,SAAS,EAAE,QAAQ,uBAAuB,MAAM,CAAC,CAAC,CAAC;AAYlG,IAAM,0BAA0B,EAAE,OAAO;AAAA,EACvC,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC;AAAA,EAC1B,YAAY,EAAE,OAAO,EAAE,SAAS;AAClC,CAAC;AAED,SAAS,uBAAyD,QAA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,QAAI,EAAE,MAAM;AACV,YAAM,KAAK,IAAI,iBAAiB;AAAA,IAClC;AAEA,aAAS,SAAS,OAAe,OAA4B;AAC3D,UAAI,CAAC,MAAO;AACZ,YAAM;AAAA,QACJ;AAAA,QACA,KAAK,KAAK;AAAA,QACV;AAAA,QACA,KAAK,UAAU,OAAO,MAAM,CAAC;AAAA,QAC7B;AAAA,MACF;AAAA,IACF;AAEA,aAAS,SAAS,EAAE,KAAK;AACzB,aAAS,UAAU,EAAE,MAAM;AAC3B,aAAS,QAAQ,EAAE,IAAI;AACvB,aAAS,UAAU,EAAE,MAAM;AAE3B,QAAI,EAAE,SAAS,EAAE,MAAM,SAAS,GAAG;AACjC,YAAM,KAAK,IAAI,qBAAqB;AACpC,QAAE,MAAM,QAAQ,CAAC,MAAM;AACrB,cAAM,KAAK,OAAO,EAAE,IAAI,iBAAiB,EAAE,QAAQ,GAAG;AAAA,MACxD,CAAC;AAAA,IACH;AAEA,WAAO,MAAM,KAAK,IAAI;AAAA,EACxB,CAAC,EACA,KAAK,MAAM;AAChB;","names":["z","z","mergeSchemas","def"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@emeryld/rrroutes-contract",
3
3
  "description": "TypeScript contract definitions for RRRoutes",
4
- "version": "2.1.7",
4
+ "version": "2.1.9",
5
5
  "private": false,
6
6
  "type": "module",
7
7
  "main": "dist/index.cjs",