@emeryld/rrroutes-contract 2.0.2 → 2.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/sockets/socket.index.d.ts +15 -1
- package/package.json +1 -1
package/dist/index.cjs.map
CHANGED
|
@@ -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;\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<`${Base}/:${Name}`, readonly [], I, ReturnType<typeof mergeSchemas<PS, P>>>,\n ) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, ReturnType<typeof mergeSchemas<PS, 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<`${Base2}/:${Name}`, readonly [], I2, ReturnType<typeof mergeSchemas<PS2, P>>>,\n ) => R,\n ) {\n const childBase = `${currentBase}/:${name}` as const;\n // Merge existing PS2 with P to create the child’s active params schema\n const childParams = mergeSchemas(currentParamsSchema, paramsSchema);\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, 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 */\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), 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 paramObj =\n isObj && (s as any).shape()[idKey]\n ? (s as ZodType)\n : z.object({ [idKey]: s } as Record<string, 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, paramObj 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","import { z } from 'zod';\n\nexport type SocketEvent = {\n message: z.ZodTypeAny;\n};\n\nexport function defineSocketEvents<const T extends Record<string, SocketEvent>>(events: T): T { \n return events;\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAAkB;AAqBlB,SAAS,aACP,GACA,GACiG;AACjG,MAAI,KAAK,EAAG,QAAO,aAAE,aAAa,GAAU,CAAQ;AACpD,SAAQ,KAAK;AACf;AA6HO,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,YA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gB;AAAA,UAC1C,aAAa,IAAI,QAAQ,eAAe;AAAA,QAC1C,CAAC;AAAA,MACH;AAGA,iBAAW,eAAe,OAAc,UAAiB,CAAC,SAAc;AACtE,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,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;;;AC3dO,SAAS,mBAAgE,QAAc;AAC5F,SAAO;AACT;","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"],"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;\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<`${Base}/:${Name}`, readonly [], I, ReturnType<typeof mergeSchemas<PS, P>>>,\n ) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, ReturnType<typeof mergeSchemas<PS, 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<`${Base2}/:${Name}`, readonly [], I2, ReturnType<typeof mergeSchemas<PS2, P>>>,\n ) => R,\n ) {\n const childBase = `${currentBase}/:${name}` as const;\n // Merge existing PS2 with P to create the child’s active params schema\n const childParams = mergeSchemas(currentParamsSchema, paramsSchema);\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, 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 */\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), 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 paramObj =\n isObj && (s as any).shape()[idKey]\n ? (s as ZodType)\n : z.object({ [idKey]: s } as Record<string, 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, paramObj 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 SocketEvent = {\n message: z.ZodTypeAny;\n};\n\n/**\n * Base event map type for app events.\n * Client and server should both use/extend this.\n */\nexport type EventMap = Record<string, SocketEvent>;\n\n/**\n * System event names – shared so server and client\n * don't drift on naming.\n */\nexport type SysEventName =\n | 'sys:connect'\n | 'sys:disconnect'\n | 'sys:reconnect'\n | 'sys:connect_error'\n | 'sys:ping'\n | 'sys:pong'\n | 'sys:room_join'\n | 'sys:room_leave';\n\n/**\n * Helper for declaring event maps in a type-safe way,\n * usable both on client and server.\n */\nexport function defineSocketEvents<const T extends EventMap>(events: T): T {\n return events;\n}\n"],"mappings":";;;;;;;;;;;;;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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,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;;;ACjcO,SAAS,mBAA6C,QAAc;AACzE,SAAO;AACT;","names":["mergeSchemas","import_zod","mergeSchemas"]}
|
package/dist/index.mjs.map
CHANGED
|
@@ -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;\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<`${Base}/:${Name}`, readonly [], I, ReturnType<typeof mergeSchemas<PS, P>>>,\n ) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, ReturnType<typeof mergeSchemas<PS, 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<`${Base2}/:${Name}`, readonly [], I2, ReturnType<typeof mergeSchemas<PS2, P>>>,\n ) => R,\n ) {\n const childBase = `${currentBase}/:${name}` as const;\n // Merge existing PS2 with P to create the child’s active params schema\n const childParams = mergeSchemas(currentParamsSchema, paramsSchema);\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, 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 */\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), 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 paramObj =\n isObj && (s as any).shape()[idKey]\n ? (s as ZodType)\n : z.object({ [idKey]: s } as Record<string, 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, paramObj 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","import { z } from 'zod';\n\nexport type SocketEvent = {\n message: z.ZodTypeAny;\n};\n\nexport function defineSocketEvents<const T extends Record<string, SocketEvent>>(events: T): T { \n return events;\n}"],"mappings":";AAAA,SAAS,SAAS;AAqBlB,SAAS,aACP,GACA,GACiG;AACjG,MAAI,KAAK,EAAG,QAAO,EAAE,aAAa,GAAU,CAAQ;AACpD,SAAQ,KAAK;AACf;AA6HO,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,Q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AACT;AAaO,SAAS,iBACd,MACA,WACA;AACA,SAAO,SAAS,SAAa,MAAM,SAAS,CAAC;AAC/C;;;AC3dO,SAAS,mBAAgE,QAAc;AAC5F,SAAO;AACT;","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"],"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;\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<`${Base}/:${Name}`, readonly [], I, ReturnType<typeof mergeSchemas<PS, P>>>,\n ) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, ReturnType<typeof mergeSchemas<PS, 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<`${Base2}/:${Name}`, readonly [], I2, ReturnType<typeof mergeSchemas<PS2, P>>>,\n ) => R,\n ) {\n const childBase = `${currentBase}/:${name}` as const;\n // Merge existing PS2 with P to create the child’s active params schema\n const childParams = mergeSchemas(currentParamsSchema, paramsSchema);\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, 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 */\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), 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 paramObj =\n isObj && (s as any).shape()[idKey]\n ? (s as ZodType)\n : z.object({ [idKey]: s } as Record<string, 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, paramObj 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 SocketEvent = {\n message: z.ZodTypeAny;\n};\n\n/**\n * Base event map type for app events.\n * Client and server should both use/extend this.\n */\nexport type EventMap = Record<string, SocketEvent>;\n\n/**\n * System event names – shared so server and client\n * don't drift on naming.\n */\nexport type SysEventName =\n | 'sys:connect'\n | 'sys:disconnect'\n | 'sys:reconnect'\n | 'sys:connect_error'\n | 'sys:ping'\n | 'sys:pong'\n | 'sys:room_join'\n | 'sys:room_leave';\n\n/**\n * Helper for declaring event maps in a type-safe way,\n * usable both on client and server.\n */\nexport function defineSocketEvents<const T extends EventMap>(events: T): T {\n return events;\n}\n"],"mappings":";AAAA,SAAS,SAAS;AAqBlB,SAAS,aACP,GACA,GACiG;AACjG,MAAI,KAAK,EAAG,QAAO,EAAE,aAAa,GAAU,CAAQ;AACpD,SAAQ,KAAK;AACf;AA6HO,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,Q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UAC1C,aAAa,IAAI,QAAQ,eAAe;AAAA,QAC1C,CAAC;AAAA,MACH;AAGA,iBAAW,eAAe,OAAc,UAAiB,CAAC,SAAc;AACtE,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;;;ACjcO,SAAS,mBAA6C,QAAc;AACzE,SAAO;AACT;","names":["z","z","mergeSchemas"]}
|
|
@@ -2,4 +2,18 @@ import { z } from 'zod';
|
|
|
2
2
|
export type SocketEvent = {
|
|
3
3
|
message: z.ZodTypeAny;
|
|
4
4
|
};
|
|
5
|
-
|
|
5
|
+
/**
|
|
6
|
+
* Base event map type for app events.
|
|
7
|
+
* Client and server should both use/extend this.
|
|
8
|
+
*/
|
|
9
|
+
export type EventMap = Record<string, SocketEvent>;
|
|
10
|
+
/**
|
|
11
|
+
* System event names – shared so server and client
|
|
12
|
+
* don't drift on naming.
|
|
13
|
+
*/
|
|
14
|
+
export type SysEventName = 'sys:connect' | 'sys:disconnect' | 'sys:reconnect' | 'sys:connect_error' | 'sys:ping' | 'sys:pong' | 'sys:room_join' | 'sys:room_leave';
|
|
15
|
+
/**
|
|
16
|
+
* Helper for declaring event maps in a type-safe way,
|
|
17
|
+
* usable both on client and server.
|
|
18
|
+
*/
|
|
19
|
+
export declare function defineSocketEvents<const T extends EventMap>(events: T): T;
|