@rexezuge/contracts 0.0.0-stage → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,130 @@
1
- # Temporary Holding Version
1
+ # @rexezuge/contracts
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ One endpoint definition shared by a family API and its SPA. The backend registers it
4
+ as a chanfana route, and the SPA calls it as a typed function. There is no code
5
+ generation.
6
+
7
+ ## Why this package exists
8
+
9
+ Twelve repos hand-copied their API's shapes into `apps/web/src/types.ts`. A copy
10
+ compiles on both sides when a field is renamed on one, and fails only in a browser.
11
+ A contract is the single source: the same zod schemas validate the request on the
12
+ Worker, document it at `/docs`, and type the call in the SPA.
13
+
14
+ ```bash
15
+ pnpm add @rexezuge/contracts zod
16
+ ```
17
+
18
+ `zod` 4 is a peer, the same major chanfana 3 uses. It is optional because this
19
+ package imports nothing from zod at runtime, but you need it to write a schema.
20
+ The package has no runtime dependencies and is framework-free.
21
+
22
+ ## Usage
23
+
24
+ A repo's `packages/contracts` (imported by both `apps/api` and `apps/web`):
25
+
26
+ ```ts
27
+ import { defineContract, defineEndpoint } from '@rexezuge/contracts';
28
+ import { z } from 'zod';
29
+
30
+ const Item = z.object({ id: z.string(), name: z.string() });
31
+
32
+ export const itemsContract = defineContract({
33
+ getItem: defineEndpoint({
34
+ method: 'GET',
35
+ path: '/user/items/:id',
36
+ summary: 'Read one item',
37
+ tags: ['items'],
38
+ auth: 'access',
39
+ params: z.object({ id: z.string() }),
40
+ response: Item,
41
+ errors: { 404: 'No such item' },
42
+ }),
43
+ renameItem: defineEndpoint({
44
+ method: 'PUT',
45
+ path: '/user/items/:id',
46
+ auth: 'access',
47
+ params: z.object({ id: z.string() }),
48
+ body: z.object({ name: z.string().min(1) }),
49
+ response: null, // 204 No Content; the client resolves null
50
+ }),
51
+ });
52
+ ```
53
+
54
+ Backend (`@rexezuge/http/hono`):
55
+
56
+ ```ts
57
+ createApiApp<Env>({
58
+ auth: { '/user/*': accessAuth({ ... }) },
59
+ routes: (app) =>
60
+ registerContract(app, itemsContract, {
61
+ getItem: async ({ params }, c) => new ItemDAO(c.env.DB).get(c.get('AuthenticatedUserId'), params.id),
62
+ renameItem: async ({ params, body }, c) => (await rename(c, params.id, body.name), null),
63
+ }),
64
+ });
65
+ ```
66
+
67
+ SPA (`@rexezuge/web`):
68
+
69
+ ```ts
70
+ const api = createContractClient(itemsContract, { baseUrl: '' });
71
+ const item = await api.getItem({ params: { id } }); // typed { id, name }
72
+ ```
73
+
74
+ ## Where the adapters live, and why
75
+
76
+ | Adapter | Package | Reason |
77
+ | --------------------------------------- | --------------------- | --------------------------------------------------------------------------------------------- |
78
+ | `registerContract`, `routeFromEndpoint` | `@rexezuge/http/hono` | chanfana may be imported only under `http/src/hono`; `http` depends on `contracts` |
79
+ | `createContractClient` | `@rexezuge/web` | it is `createApiClient` with types: same errors, credentials, envelope decoding, D1 bookmarks |
80
+
81
+ The direction is `errors`/`shared` → `contracts` → `http` → `web`. `contracts`
82
+ imports neither adapter, so the graph stays acyclic and the definitions load in
83
+ both a Worker and a browser.
84
+
85
+ ## Closed
86
+
87
+ - **Validated at definition.** These throw a `TypeError` when the module loads: a
88
+ path not starting with `/`, Hono's regex or optional `:param` syntax, a `:param`
89
+ without a `params` entry (also a type error), `params` keys that differ from the
90
+ path's, a `GET` with a body, an error status outside 400–599, an unknown method
91
+ or auth surface, and a missing `response`.
92
+ - **Frozen and branded.** Only `defineEndpoint` makes an endpoint (`isEndpoint`),
93
+ and `defineContract` refuses a spread copy, non-identifier names, and two
94
+ endpoints with the same method and path.
95
+ - **Implied errors.** `400` when the endpoint validates input, `401`/`403` on an
96
+ authenticated surface, and `500` always. `errors` only adds to that list.
97
+ - **Fail-closed auth on the backend.** An `access`/`apiKey` endpoint answers `401`
98
+ when no auth middleware ran on its path.
99
+
100
+ ## Extending
101
+
102
+ | You want | Door |
103
+ | ----------------------------------------------------- | -------------------------------------------------------------------------- |
104
+ | Your shapes | any zod 4 schema for `params` / `query` / `body` / `response` |
105
+ | Extra documented errors, your own wording | `errors: [409]` or `errors: { 404: 'No such item' }` |
106
+ | A 204 endpoint | `response: null` |
107
+ | Docs grouping | `summary`, `description`, `tags` |
108
+ | Compose contracts | `defineContract({ ...a, ...b })` |
109
+ | A hand-written route (errorMapping, a raw `Response`) | `schemaFromEndpoint(endpoint)` in your own `FamilyRoute` subclass |
110
+ | Types elsewhere | `EndpointInput`, `EndpointOutput`, `EndpointServerInput`, `EndpointResult` |
111
+ | Build a URL yourself | `buildPath(endpoint.path, params)` |
112
+
113
+ ## Types
114
+
115
+ | Type | Is |
116
+ | ------------------------ | -------------------------------------------------------------------------- |
117
+ | `EndpointInput<E>` | what the client passes: `params`, `query`, `body` (zod input), as declared |
118
+ | `EndpointOutput<E>` | what the client resolves: the response's zod output, or `null` |
119
+ | `EndpointServerInput<E>` | what the handler receives: validated zod output |
120
+ | `EndpointResult<E>` | what the handler returns: the response's zod input, or `null` |
121
+ | `PathParamNames<P>` | `'id' \| 'sub'` for `'/a/:id/b/:sub'` |
122
+
123
+ A slot whose input accepts `{}` or `undefined` (an all-optional query) is optional
124
+ in `EndpointInput`. Keep response schemas JSON-safe: the client receives JSON, so a
125
+ transform that produces a `Date` is a lie unless `validateResponses` is on.
126
+
127
+ ## Null and undefined
128
+
129
+ `null` means absent: `response: null` is "no body", and the client resolves it to
130
+ `null`. An omitted slot (`query?`) means not supplied. See the kit's `AGENTS.md`.
@@ -0,0 +1,14 @@
1
+ import type { Endpoint } from './endpoint.ts';
2
+ type ContractEndpoints = Readonly<Record<string, Endpoint>>;
3
+ /**
4
+ A defined contract: your endpoint record, frozen.
5
+ */
6
+ type Contract<C extends ContractEndpoints = ContractEndpoints> = Readonly<C>;
7
+ /**
8
+ * Group endpoints. Spread one contract into another to compose them:
9
+ * `defineContract({ ...itemsContract, ...settingsContract })`.
10
+ */
11
+ declare function defineContract<const C extends ContractEndpoints>(endpoints: C): Contract<C>;
12
+ export { defineContract };
13
+ export type { Contract, ContractEndpoints };
14
+ //# sourceMappingURL=contract.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../src/contract.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C,KAAK,iBAAiB,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;AAE5D;;EAEE;AACF,KAAK,QAAQ,CAAC,CAAC,SAAS,iBAAiB,GAAG,iBAAiB,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC;AAI7E;;;GAGG;AACH,iBAAS,cAAc,CAAC,KAAK,CAAC,CAAC,SAAS,iBAAiB,EAAE,SAAS,EAAE,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAWpF;AAED,OAAO,EAAE,cAAc,EAAE,CAAC;AAC1B,YAAY,EAAE,QAAQ,EAAE,iBAAiB,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var d=Object.defineProperty;var a=(e,n)=>d(e,"name",{value:n,configurable:!0});import{isEndpoint as c}from"./endpoint.js";const s=/^[a-z_$][\w$]*$/i;function f(e){const n=new Map;for(const[t,o]of Object.entries(e)){if(!s.test(t))throw new TypeError(`Contract endpoint name must be an identifier: ${t}`);if(!c(o))throw new TypeError(`Contract endpoint "${t}" was not made by defineEndpoint`);const r=`${o.method} ${o.path}`,i=n.get(r);if(i!==void 0)throw new TypeError(`Contract endpoints "${i}" and "${t}" both declare ${r}`);n.set(r,t)}return Object.freeze({...e})}a(f,"defineContract");export{f as defineContract};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/contract.ts"],
4
+ "sourcesContent": ["/**\n * `defineContract`: a repo's endpoints, by name.\n *\n * The name is the client's method (`client.getItem(input)`) and the key of the\n * backend's handler map (`registerContract(app, contract, { getItem })`), so the\n * map type-checks complete against the contract.\n *\n * Closed: the contract is frozen, every value must come from `defineEndpoint`,\n * names must be identifiers, and two endpoints may not share a method and path.\n * Hono would register both and silently serve the first.\n */\nimport { isEndpoint } from './endpoint.ts';\nimport type { Endpoint } from './endpoint.ts';\n\ntype ContractEndpoints = Readonly<Record<string, Endpoint>>;\n\n/**\nA defined contract: your endpoint record, frozen.\n*/\ntype Contract<C extends ContractEndpoints = ContractEndpoints> = Readonly<C>;\n\nconst IDENTIFIER = /^[a-z_$][\\w$]*$/i;\n\n/**\n * Group endpoints. Spread one contract into another to compose them:\n * `defineContract({ ...itemsContract, ...settingsContract })`.\n */\nfunction defineContract<const C extends ContractEndpoints>(endpoints: C): Contract<C> {\n const routes = new Map<string, string>();\n for (const [name, endpoint] of Object.entries(endpoints)) {\n if (!IDENTIFIER.test(name)) throw new TypeError(`Contract endpoint name must be an identifier: ${name}`);\n if (!isEndpoint(endpoint)) throw new TypeError(`Contract endpoint \"${name}\" was not made by defineEndpoint`);\n const route = `${endpoint.method} ${endpoint.path}`;\n const existing = routes.get(route);\n if (existing !== undefined) throw new TypeError(`Contract endpoints \"${existing}\" and \"${name}\" both declare ${route}`);\n routes.set(route, name);\n }\n return Object.freeze({ ...endpoints });\n}\n\nexport { defineContract };\nexport type { Contract, ContractEndpoints };\n"],
5
+ "mappings": "+EAWA,OAAS,cAAAA,MAAkB,gBAU3B,MAAMC,EAAa,mBAMnB,SAASC,EAAkDC,EAAY,CACrE,MAAMC,EAAS,IAAI,IACnB,SAAW,CAACC,EAAMC,CAAQ,IAAK,OAAO,QAAQH,CAAS,EAAG,CACxD,GAAI,CAACF,EAAW,KAAKI,CAAI,EAAG,MAAM,IAAI,UAAU,iDAAiDA,CAAI,EAAE,EACvG,GAAI,CAACL,EAAWM,CAAQ,EAAG,MAAM,IAAI,UAAU,sBAAsBD,CAAI,kCAAkC,EAC3G,MAAME,EAAQ,GAAGD,EAAS,MAAM,IAAIA,EAAS,IAAI,GAC3CE,EAAWJ,EAAO,IAAIG,CAAK,EACjC,GAAIC,IAAa,OAAW,MAAM,IAAI,UAAU,uBAAuBA,CAAQ,UAAUH,CAAI,kBAAkBE,CAAK,EAAE,EACtHH,EAAO,IAAIG,EAAOF,CAAI,CACxB,CACA,OAAO,OAAO,OAAO,CAAE,GAAGF,CAAS,CAAE,CACvC,CAXSM,EAAAP,EAAA",
6
+ "names": ["isEndpoint", "IDENTIFIER", "defineContract", "endpoints", "routes", "name", "endpoint", "route", "existing", "__name"]
7
+ }
@@ -0,0 +1,185 @@
1
+ /**
2
+ * `defineEndpoint`: one object that describes a route to both ends.
3
+ *
4
+ * Twelve repos hand-copied their API's request and response shapes into
5
+ * `apps/web/src/types.ts`, and a copy is the half of a contract nobody checks:
6
+ * a renamed field compiled on both sides and failed only in a browser. An
7
+ * endpoint here is the single source. The backend turns it into a chanfana
8
+ * route (`@rexezuge/http/hono`'s `routeFromEndpoint`), whose schema validates the
9
+ * request and documents the responses. The SPA turns it into a typed call
10
+ * (`@rexezuge/web`'s `createContractClient`). There is no code generation, so
11
+ * there is no generated file to go stale.
12
+ *
13
+ * ## Closed
14
+ *
15
+ * - The definition is **validated once**, at module load: a malformed path, a
16
+ * `:param` without a schema entry (or a schema entry without a `:param`), a
17
+ * `GET` with a body, an error status outside 400–599. Each throws a
18
+ * `TypeError`, so a bad contract fails every test that imports it.
19
+ * - The result is **frozen**, and only `defineEndpoint` makes one
20
+ * (`isEndpoint` checks a private brand), so a contract cannot be patched
21
+ * after the backend registered it.
22
+ * - The errors every endpoint can produce are **implied**, never forgotten:
23
+ * `400` when it validates input, `401`/`403` on an authenticated surface,
24
+ * `500` always. `errors` adds to that set.
25
+ *
26
+ * ## Open
27
+ *
28
+ * Your schemas (zod 4, the major chanfana 3 uses), `summary`/`description`/
29
+ * `tags`, the auth surface, and the extra error statuses with your own wording.
30
+ *
31
+ * This module imports nothing from zod at runtime. It only reads `.shape` from
32
+ * a params object, so zod is a peer you need to *write* a contract, and the
33
+ * client bundle carries no second copy.
34
+ */
35
+ import type * as z from 'zod';
36
+ import type { PathParamNames, PathValue } from './path.ts';
37
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
38
+ /**
39
+ * Which authenticated surface serves the endpoint.
40
+ *
41
+ * - `access`: Cloudflare Access (`accessAuth`), the SPA's `/user/*` surface.
42
+ * - `apiKey`: a key or token surface (`apiKeyAuth`).
43
+ * - `public`: no authentication.
44
+ *
45
+ * The backend adapter fails closed on it. An `access` or `apiKey` endpoint
46
+ * served without an authenticated user answers `401`, even if the app forgot
47
+ * to mount the auth middleware on its path.
48
+ */
49
+ type AuthSurface = 'access' | 'apiKey' | 'public';
50
+ /**
51
+ Extra error statuses: a list (catalog wording) or status → description.
52
+ */
53
+ type EndpointErrors = readonly number[] | Readonly<Record<number, string>>;
54
+ /**
55
+ * What you write. `response: null` declares a `204 No Content` endpoint, and
56
+ * the client resolves it to `null`.
57
+ */
58
+ interface EndpointDefinition {
59
+ method: HttpMethod;
60
+ path: string;
61
+ summary?: string;
62
+ description?: string;
63
+ tags?: readonly string[];
64
+ auth: AuthSurface;
65
+ /**
66
+ Required when `path` has `:params`; its keys must be exactly those names.
67
+ */
68
+ params?: z.ZodObject;
69
+ query?: z.ZodObject;
70
+ body?: z.ZodType;
71
+ response: z.ZodType | null;
72
+ errors?: EndpointErrors;
73
+ }
74
+ /**
75
+ One documented error status. `description` is `null` for the catalog wording.
76
+ */
77
+ interface EndpointError {
78
+ status: number;
79
+ description: string | null;
80
+ }
81
+ declare const ENDPOINT_BRAND: unique symbol;
82
+ /**
83
+ * A defined endpoint: your definition, frozen, plus the derived facts both
84
+ * adapters read.
85
+ */
86
+ type Endpoint<D extends EndpointDefinition = EndpointDefinition> = Readonly<D> & {
87
+ readonly [ENDPOINT_BRAND]: true;
88
+ /**
89
+ The template's parameter names, in order.
90
+ */
91
+ readonly pathParams: readonly string[];
92
+ /**
93
+ Every error status the endpoint documents: implied ones first, then yours.
94
+ */
95
+ readonly errorResponses: readonly EndpointError[];
96
+ };
97
+ /**
98
+ `params` is required by the type as soon as the template has a `:name`.
99
+ */
100
+ type RequireParams<D extends EndpointDefinition> = [PathParamNames<D['path']>] extends [never] ? unknown : {
101
+ params: z.ZodObject<Record<PathParamNames<D['path']>, z.ZodType>>;
102
+ };
103
+ /**
104
+ The empty slot set: an endpoint that takes no input.
105
+ */
106
+ type NoSlots = Record<never, never>;
107
+ type Simplify<T> = {
108
+ [K in keyof T]: T[K];
109
+ };
110
+ /**
111
+ `{ key: T }` when `T` must be given, `{ key?: T }` when it may be omitted.
112
+ */
113
+ type Slot<K extends string, T> = undefined extends T ? {
114
+ [P in K]?: T;
115
+ } : NoSlots extends T ? {
116
+ [P in K]?: T;
117
+ } : {
118
+ [P in K]: T;
119
+ };
120
+ /**
121
+ * What a caller passes: `params` (typed from the schema, or from the template's
122
+ * names), `query` and `body` (each a zod *input*), each present only when the
123
+ * endpoint declares it.
124
+ */
125
+ type EndpointInput<E extends EndpointDefinition> = Simplify<(E extends {
126
+ params: infer P extends z.ZodType;
127
+ } ? {
128
+ params: z.input<P>;
129
+ } : [PathParamNames<E['path']>] extends [never] ? NoSlots : {
130
+ params: Record<PathParamNames<E['path']>, PathValue>;
131
+ }) & (E extends {
132
+ query: infer Q extends z.ZodType;
133
+ } ? Slot<'query', z.input<Q>> : NoSlots) & (E extends {
134
+ body: infer B extends z.ZodType;
135
+ } ? Slot<'body', z.input<B>> : NoSlots)>;
136
+ /**
137
+ What the handler receives: the same slots, as validated zod *output*.
138
+ */
139
+ type EndpointServerInput<E extends EndpointDefinition> = Simplify<(E extends {
140
+ params: infer P extends z.ZodType;
141
+ } ? {
142
+ params: z.output<P>;
143
+ } : NoSlots) & (E extends {
144
+ query: infer Q extends z.ZodType;
145
+ } ? {
146
+ query: z.output<Q>;
147
+ } : NoSlots) & (E extends {
148
+ body: infer B extends z.ZodType;
149
+ } ? {
150
+ body: z.output<B>;
151
+ } : NoSlots)>;
152
+ /**
153
+ What the client resolves to: the response schema's output, or `null` for a 204.
154
+ */
155
+ type EndpointOutput<E extends EndpointDefinition> = E extends {
156
+ response: infer R extends z.ZodType;
157
+ } ? z.output<R> : null;
158
+ /**
159
+ What a handler returns for serialization: the response schema's *input*, or `null`.
160
+ */
161
+ type EndpointResult<E extends EndpointDefinition> = E extends {
162
+ response: infer R extends z.ZodType;
163
+ } ? z.input<R> : null;
164
+ /**
165
+ * Define one endpoint.
166
+ *
167
+ * ```ts
168
+ * const getItem = defineEndpoint({
169
+ * method: 'GET',
170
+ * path: '/user/items/:id',
171
+ * auth: 'access',
172
+ * params: z.object({ id: z.string() }),
173
+ * response: Item,
174
+ * errors: { 404: 'No such item' },
175
+ * });
176
+ * ```
177
+ */
178
+ declare function defineEndpoint<const D extends EndpointDefinition>(definition: D & RequireParams<D>): Endpoint<D>;
179
+ /**
180
+ Whether `value` came from `defineEndpoint`.
181
+ */
182
+ declare function isEndpoint(value: unknown): value is Endpoint;
183
+ export { defineEndpoint, isEndpoint };
184
+ export type { AuthSurface, Endpoint, EndpointDefinition, EndpointError, EndpointErrors, EndpointInput, EndpointOutput, EndpointResult, EndpointServerInput, HttpMethod, };
185
+ //# sourceMappingURL=endpoint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"endpoint.d.ts","sourceRoot":"","sources":["../src/endpoint.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,OAAO,KAAK,KAAK,CAAC,MAAM,KAAK,CAAC;AAE9B,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAE3D,KAAK,UAAU,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,OAAO,GAAG,QAAQ,CAAC;AAE9D;;;;;;;;;;GAUG;AACH,KAAK,WAAW,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAElD;;EAEE;AACF,KAAK,cAAc,GAAG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I,CAAC;AAmD1H;;;;;;;;;;;;;GAaG;AACH,iBAAS,cAAc,CAAC,KAAK,CAAC,CAAC,SAAS,kBAAkB,EAAE,UAAU,EAAE,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAsBzG;AAED;;EAEE;AACF,iBAAS,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,QAAQ,CAErD;AAED,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,CAAC;AACtC,YAAY,EACV,WAAW,EACX,QAAQ,EACR,kBAAkB,EAClB,aAAa,EACb,cAAc,EACd,aAAa,EACb,cAAc,EACd,cAAc,EACd,mBAAmB,EACnB,UAAU,GACX,CAAC"}
@@ -0,0 +1 @@
1
+ var l=Object.defineProperty;var u=(e,r)=>l(e,"name",{value:r,configurable:!0});import{pathParamNames as b}from"./path.js";const m=["GET","POST","PUT","PATCH","DELETE"],n=["access","apiKey","public"],h=new WeakSet;function o(e,r){throw new TypeError(`Invalid endpoint ${String(e.method)} ${String(e.path)}: ${r}`)}u(o,"fail");function j(e,r){if(e.params===void 0){r.length>0&&o(e,`path declares ${r.map(a=>`:${a}`).join(", ")} but no params schema`);return}const t=e.params.shape;(typeof t!="object"||t===null)&&o(e,"params must be a zod object schema");const c=Object.keys(t).sort((a,p)=>a.localeCompare(p)),s=[...r].sort((a,p)=>a.localeCompare(p));c.join(",")!==s.join(",")&&o(e,`params keys [${c.join(", ")}] must match the path's [${s.join(", ")}]`)}u(j,"checkParams");function f(e){const r=[];(e.params!==void 0||e.query!==void 0||e.body!==void 0)&&r.push(400),e.auth!=="public"&&r.push(401,403),r.push(500);const t=Array.isArray(e.errors)?e.errors.map(s=>({status:s,description:null})):Object.entries(e.errors??{}).map(([s,a])=>({status:Number(s),description:a}));for(const{status:s}of t)(!Number.isInteger(s)||s<400||s>599)&&o(e,`error status ${s} is not 400\u2013599`);const c=new Map;for(const s of r)c.set(s,{status:s,description:null});for(const s of t)c.set(s.status,Object.freeze({...s}));return[...c.values()].sort((s,a)=>s.status-a.status).map(s=>Object.freeze(s))}u(f,"normalizeErrors");function y(e){m.includes(e.method)||o(e,`method must be one of ${m.join(", ")}`),n.includes(e.auth)||o(e,`auth must be one of ${n.join(", ")}`),e.response===void 0&&o(e,"response is required (a schema, or null for 204)"),e.method==="GET"&&e.body!==void 0&&o(e,"a GET endpoint cannot declare a body");let r;try{r=b(e.path)}catch(c){o(e,c.message)}j(e,r);const t={...e,...e.tags!==void 0&&{tags:Object.freeze([...e.tags])},pathParams:Object.freeze(r),errorResponses:Object.freeze(f(e))};return Object.freeze(t),h.add(t),t}u(y,"defineEndpoint");function E(e){return typeof e=="object"&&e!==null&&h.has(e)}u(E,"isEndpoint");export{y as defineEndpoint,E as isEndpoint};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/endpoint.ts"],
4
+ "sourcesContent": ["/**\n * `defineEndpoint`: one object that describes a route to both ends.\n *\n * Twelve repos hand-copied their API's request and response shapes into\n * `apps/web/src/types.ts`, and a copy is the half of a contract nobody checks:\n * a renamed field compiled on both sides and failed only in a browser. An\n * endpoint here is the single source. The backend turns it into a chanfana\n * route (`@rexezuge/http/hono`'s `routeFromEndpoint`), whose schema validates the\n * request and documents the responses. The SPA turns it into a typed call\n * (`@rexezuge/web`'s `createContractClient`). There is no code generation, so\n * there is no generated file to go stale.\n *\n * ## Closed\n *\n * - The definition is **validated once**, at module load: a malformed path, a\n * `:param` without a schema entry (or a schema entry without a `:param`), a\n * `GET` with a body, an error status outside 400–599. Each throws a\n * `TypeError`, so a bad contract fails every test that imports it.\n * - The result is **frozen**, and only `defineEndpoint` makes one\n * (`isEndpoint` checks a private brand), so a contract cannot be patched\n * after the backend registered it.\n * - The errors every endpoint can produce are **implied**, never forgotten:\n * `400` when it validates input, `401`/`403` on an authenticated surface,\n * `500` always. `errors` adds to that set.\n *\n * ## Open\n *\n * Your schemas (zod 4, the major chanfana 3 uses), `summary`/`description`/\n * `tags`, the auth surface, and the extra error statuses with your own wording.\n *\n * This module imports nothing from zod at runtime. It only reads `.shape` from\n * a params object, so zod is a peer you need to *write* a contract, and the\n * client bundle carries no second copy.\n */\nimport type * as z from 'zod';\nimport { pathParamNames } from './path.ts';\nimport type { PathParamNames, PathValue } from './path.ts';\n\ntype HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * Which authenticated surface serves the endpoint.\n *\n * - `access`: Cloudflare Access (`accessAuth`), the SPA's `/user/*` surface.\n * - `apiKey`: a key or token surface (`apiKeyAuth`).\n * - `public`: no authentication.\n *\n * The backend adapter fails closed on it. An `access` or `apiKey` endpoint\n * served without an authenticated user answers `401`, even if the app forgot\n * to mount the auth middleware on its path.\n */\ntype AuthSurface = 'access' | 'apiKey' | 'public';\n\n/**\nExtra error statuses: a list (catalog wording) or status → description.\n*/\ntype EndpointErrors = readonly number[] | Readonly<Record<number, string>>;\n\n/**\n * What you write. `response: null` declares a `204 No Content` endpoint, and\n * the client resolves it to `null`.\n */\ninterface EndpointDefinition {\n method: HttpMethod;\n path: string;\n summary?: string;\n description?: string;\n tags?: readonly string[];\n auth: AuthSurface;\n /**\n Required when `path` has `:params`; its keys must be exactly those names.\n */\n params?: z.ZodObject;\n query?: z.ZodObject;\n body?: z.ZodType;\n response: z.ZodType | null;\n errors?: EndpointErrors;\n}\n\n/**\nOne documented error status. `description` is `null` for the catalog wording.\n*/\ninterface EndpointError {\n status: number;\n description: string | null;\n}\n\ndeclare const ENDPOINT_BRAND: unique symbol;\n\n/**\n * A defined endpoint: your definition, frozen, plus the derived facts both\n * adapters read.\n */\ntype Endpoint<D extends EndpointDefinition = EndpointDefinition> = Readonly<D> & {\n readonly [ENDPOINT_BRAND]: true;\n /**\n The template's parameter names, in order.\n */\n readonly pathParams: readonly string[];\n /**\n Every error status the endpoint documents: implied ones first, then yours.\n */\n readonly errorResponses: readonly EndpointError[];\n};\n\n/**\n`params` is required by the type as soon as the template has a `:name`.\n*/\ntype RequireParams<D extends EndpointDefinition> = [PathParamNames<D['path']>] extends [never]\n ? unknown\n : { params: z.ZodObject<Record<PathParamNames<D['path']>, z.ZodType>> };\n\n/**\nThe empty slot set: an endpoint that takes no input.\n*/\ntype NoSlots = Record<never, never>;\n\ntype Simplify<T> = { [K in keyof T]: T[K] };\n\n/**\n`{ key: T }` when `T` must be given, `{ key?: T }` when it may be omitted.\n*/\ntype Slot<K extends string, T> = undefined extends T ? { [P in K]?: T } : NoSlots extends T ? { [P in K]?: T } : { [P in K]: T };\n\n/**\n * What a caller passes: `params` (typed from the schema, or from the template's\n * names), `query` and `body` (each a zod *input*), each present only when the\n * endpoint declares it.\n */\ntype EndpointInput<E extends EndpointDefinition> = Simplify<\n (E extends { params: infer P extends z.ZodType }\n ? { params: z.input<P> }\n : [PathParamNames<E['path']>] extends [never]\n ? NoSlots\n : { params: Record<PathParamNames<E['path']>, PathValue> }) &\n (E extends { query: infer Q extends z.ZodType } ? Slot<'query', z.input<Q>> : NoSlots) &\n (E extends { body: infer B extends z.ZodType } ? Slot<'body', z.input<B>> : NoSlots)\n>;\n\n/**\nWhat the handler receives: the same slots, as validated zod *output*.\n*/\ntype EndpointServerInput<E extends EndpointDefinition> = Simplify<\n (E extends { params: infer P extends z.ZodType } ? { params: z.output<P> } : NoSlots) &\n (E extends { query: infer Q extends z.ZodType } ? { query: z.output<Q> } : NoSlots) &\n (E extends { body: infer B extends z.ZodType } ? { body: z.output<B> } : NoSlots)\n>;\n\n/**\nWhat the client resolves to: the response schema's output, or `null` for a 204.\n*/\ntype EndpointOutput<E extends EndpointDefinition> = E extends { response: infer R extends z.ZodType } ? z.output<R> : null;\n\n/**\nWhat a handler returns for serialization: the response schema's *input*, or `null`.\n*/\ntype EndpointResult<E extends EndpointDefinition> = E extends { response: infer R extends z.ZodType } ? z.input<R> : null;\n\nconst METHODS: readonly HttpMethod[] = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];\nconst AUTH_SURFACES: readonly AuthSurface[] = ['access', 'apiKey', 'public'];\n\n/**\nEndpoints `defineEndpoint` made: the brand that cannot be forged by spreading.\n*/\nconst DEFINED = new WeakSet<object>();\n\nfunction fail(definition: { method?: unknown; path?: unknown }, problem: string): never {\n throw new TypeError(`Invalid endpoint ${String(definition.method)} ${String(definition.path)}: ${problem}`);\n}\n\nfunction checkParams(definition: EndpointDefinition, names: readonly string[]): void {\n if (definition.params === undefined) {\n if (names.length > 0) fail(definition, `path declares ${names.map((name) => `:${name}`).join(', ')} but no params schema`);\n return;\n }\n const shape = (definition.params as { shape?: unknown }).shape;\n if (typeof shape !== 'object' || shape === null) fail(definition, 'params must be a zod object schema');\n const keys = Object.keys(shape).sort((left, right) => left.localeCompare(right));\n const expected = [...names].sort((left, right) => left.localeCompare(right));\n if (keys.join(',') !== expected.join(',')) {\n fail(definition, `params keys [${keys.join(', ')}] must match the path's [${expected.join(', ')}]`);\n }\n}\n\nfunction normalizeErrors(definition: EndpointDefinition): EndpointError[] {\n const implied: number[] = [];\n if (definition.params !== undefined || definition.query !== undefined || definition.body !== undefined) implied.push(400);\n if (definition.auth !== 'public') implied.push(401, 403);\n implied.push(500);\n\n const given: EndpointError[] = Array.isArray(definition.errors)\n ? (definition.errors as readonly number[]).map((status) => ({ status, description: null }))\n : Object.entries((definition.errors ?? {}) as Readonly<Record<number, string>>).map(([status, description]) => ({\n status: Number(status),\n description,\n }));\n for (const { status } of given) {\n if (!Number.isInteger(status) || status < 400 || status > 599) fail(definition, `error status ${status} is not 400–599`);\n }\n\n const byStatus = new Map<number, EndpointError>();\n for (const status of implied) byStatus.set(status, { status, description: null });\n // Yours win: the same status with your wording replaces the catalog one.\n for (const entry of given) byStatus.set(entry.status, Object.freeze({ ...entry }));\n return [...byStatus.values()].sort((left, right) => left.status - right.status).map((entry) => Object.freeze(entry));\n}\n\n/**\n * Define one endpoint.\n *\n * ```ts\n * const getItem = defineEndpoint({\n * method: 'GET',\n * path: '/user/items/:id',\n * auth: 'access',\n * params: z.object({ id: z.string() }),\n * response: Item,\n * errors: { 404: 'No such item' },\n * });\n * ```\n */\nfunction defineEndpoint<const D extends EndpointDefinition>(definition: D & RequireParams<D>): Endpoint<D> {\n if (!METHODS.includes(definition.method)) fail(definition, `method must be one of ${METHODS.join(', ')}`);\n if (!AUTH_SURFACES.includes(definition.auth)) fail(definition, `auth must be one of ${AUTH_SURFACES.join(', ')}`);\n if (definition.response === undefined) fail(definition, 'response is required (a schema, or null for 204)');\n if (definition.method === 'GET' && definition.body !== undefined) fail(definition, 'a GET endpoint cannot declare a body');\n let names: string[];\n try {\n names = pathParamNames(definition.path);\n } catch (error: unknown) {\n fail(definition, (error as Error).message);\n }\n checkParams(definition, names);\n\n const endpoint = {\n ...definition,\n ...(definition.tags !== undefined && { tags: Object.freeze([...definition.tags]) }),\n pathParams: Object.freeze(names),\n errorResponses: Object.freeze(normalizeErrors(definition)),\n };\n Object.freeze(endpoint);\n DEFINED.add(endpoint);\n return endpoint as unknown as Endpoint<D>;\n}\n\n/**\nWhether `value` came from `defineEndpoint`.\n*/\nfunction isEndpoint(value: unknown): value is Endpoint {\n return typeof value === 'object' && value !== null && DEFINED.has(value);\n}\n\nexport { defineEndpoint, isEndpoint };\nexport type {\n AuthSurface,\n Endpoint,\n EndpointDefinition,\n EndpointError,\n EndpointErrors,\n EndpointInput,\n EndpointOutput,\n EndpointResult,\n EndpointServerInput,\n HttpMethod,\n};\n"],
5
+ "mappings": "+EAmCA,OAAS,kBAAAA,MAAsB,YA2H/B,MAAMC,EAAiC,CAAC,MAAO,OAAQ,MAAO,QAAS,QAAQ,EACzEC,EAAwC,CAAC,SAAU,SAAU,QAAQ,EAKrEC,EAAU,IAAI,QAEpB,SAASC,EAAKC,EAAkDC,EAAe,CAC7E,MAAM,IAAI,UAAU,oBAAoB,OAAOD,EAAW,MAAM,CAAC,IAAI,OAAOA,EAAW,IAAI,CAAC,KAAKC,CAAO,EAAE,CAC5G,CAFSC,EAAAH,EAAA,QAIT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AAOA,GAAU,UAAYA,IAAU,MAAQxB,EAAQ,IAAIwB,CAAK,CACzE,CAFSpB,EAAAmB,EAAA",
6
+ "names": ["pathParamNames", "METHODS", "AUTH_SURFACES", "DEFINED", "fail", "definition", "problem", "__name", "checkParams", "names", "name", "shape", "keys", "left", "right", "expected", "normalizeErrors", "implied", "given", "status", "description", "byStatus", "entry", "defineEndpoint", "error", "endpoint", "isEndpoint", "value"]
7
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * `@rexezuge/contracts`: endpoint definitions shared by a family API and its SPA.
3
+ *
4
+ * Framework-free and runtime-dependency-free. The two adapters live where their
5
+ * frameworks already are: the chanfana route in `@rexezuge/http/hono`
6
+ * (`routeFromEndpoint`, `registerContract`) and the typed client in
7
+ * `@rexezuge/web` (`createContractClient`). Both depend on this package, and
8
+ * it depends on neither, so the layer order stays
9
+ * `errors`/`shared` → `contracts` → `http` → `web`.
10
+ */
11
+ export { defineContract } from './contract.ts';
12
+ export type { Contract, ContractEndpoints } from './contract.ts';
13
+ export { defineEndpoint, isEndpoint } from './endpoint.ts';
14
+ export type { AuthSurface, Endpoint, EndpointDefinition, EndpointError, EndpointErrors, EndpointInput, EndpointOutput, EndpointResult, EndpointServerInput, HttpMethod, } from './endpoint.ts';
15
+ export { buildPath, pathParamNames } from './path.ts';
16
+ export type { PathParamNames, PathValue } from './path.ts';
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,YAAY,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAEjE,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3D,YAAY,EACV,WAAW,EACX,QAAQ,EACR,kBAAkB,EAClB,aAAa,EACb,cAAc,EACd,aAAa,EACb,cAAc,EACd,cAAc,EACd,mBAAmB,EACnB,UAAU,GACX,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACtD,YAAY,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import{defineContract as e}from"./contract.js";import{defineEndpoint as n,isEndpoint as a}from"./endpoint.js";import{buildPath as p,pathParamNames as d}from"./path.js";export{p as buildPath,e as defineContract,n as defineEndpoint,a as isEndpoint,d as pathParamNames};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts"],
4
+ "sourcesContent": ["/**\n * `@rexezuge/contracts`: endpoint definitions shared by a family API and its SPA.\n *\n * Framework-free and runtime-dependency-free. The two adapters live where their\n * frameworks already are: the chanfana route in `@rexezuge/http/hono`\n * (`routeFromEndpoint`, `registerContract`) and the typed client in\n * `@rexezuge/web` (`createContractClient`). Both depend on this package, and\n * it depends on neither, so the layer order stays\n * `errors`/`shared` → `contracts` → `http` → `web`.\n */\nexport { defineContract } from './contract.ts';\nexport type { Contract, ContractEndpoints } from './contract.ts';\n\nexport { defineEndpoint, isEndpoint } from './endpoint.ts';\nexport type {\n AuthSurface,\n Endpoint,\n EndpointDefinition,\n EndpointError,\n EndpointErrors,\n EndpointInput,\n EndpointOutput,\n EndpointResult,\n EndpointServerInput,\n HttpMethod,\n} from './endpoint.ts';\n\nexport { buildPath, pathParamNames } from './path.ts';\nexport type { PathParamNames, PathValue } from './path.ts';\n"],
5
+ "mappings": "AAUA,OAAS,kBAAAA,MAAsB,gBAG/B,OAAS,kBAAAC,EAAgB,cAAAC,MAAkB,gBAc3C,OAAS,aAAAC,EAAW,kBAAAC,MAAsB",
6
+ "names": ["defineContract", "defineEndpoint", "isEndpoint", "buildPath", "pathParamNames"]
7
+ }
package/dist/path.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Path templates: `/user/items/:id`, the Hono/chanfana spelling, so one string
3
+ * is both the route the backend registers and the URL the client builds.
4
+ *
5
+ * Only plain `:name` segments are accepted. Hono's regex (`:id{[0-9]+}`) and
6
+ * optional (`:id?`) forms are refused at definition: the client would have to
7
+ * re-implement Hono's matcher to build those URLs, and a contract whose two
8
+ * ends disagree about a URL is the bug this package exists to remove.
9
+ */
10
+ /**
11
+ * The parameter names in a template, as a union: `PathParamNames<'/a/:id/b/:sub'>`
12
+ * is `'id' | 'sub'`, and `never` for a template with none.
13
+ */
14
+ type PathParamNames<P extends string> = P extends `${string}:${infer Rest}` ? Rest extends `${infer Name}/${infer Tail}` ? Name | PathParamNames<`/${Tail}`> : Rest : never;
15
+ /**
16
+ A value a path segment may be built from. Encoded with `encodeURIComponent`.
17
+ */
18
+ type PathValue = string | number;
19
+ /**
20
+ * The parameter names of a template, in order. Throws a `TypeError` for a
21
+ * template the client could not build: not starting with `/`, a malformed or
22
+ * repeated name, or Hono's regex/optional syntax.
23
+ */
24
+ declare function pathParamNames(template: string): string[];
25
+ /**
26
+ * Fills a template. Every value is `encodeURIComponent`-encoded, so an id with
27
+ * a `/` or `?` stays one segment. A missing or empty value throws rather than
28
+ * producing `/user/items/` or `/user/items/undefined`.
29
+ */
30
+ declare function buildPath(template: string, params?: Readonly<Record<string, PathValue>>): string;
31
+ export { buildPath, pathParamNames };
32
+ export type { PathParamNames, PathValue };
33
+ //# sourceMappingURL=path.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"path.d.ts","sourceRoot":"","sources":["../src/path.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;;GAGG;AACH,KAAK,cAAc,CAAC,CAAC,SAAS,MAAM,IAAI,CAAC,SAAS,GAAG,MAAM,IAAI,MAAM,IAAI,EAAE,GACvE,IAAI,SAAS,GAAG,MAAM,IAAI,IAAI,MAAM,IAAI,EAAE,GACxC,IAAI,GAAG,cAAc,CAAC,IAAI,IAAI,EAAE,CAAC,GACjC,IAAI,GACN,KAAK,CAAC;AAEV;;EAEE;AACF,KAAK,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC;AAIjC;;;;GAIG;AACH,iBAAS,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,EAAE,CAiBlD;AAED;;;;GAIG;AACH,iBAAS,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAM,GAAG,MAAM,CAa7F;AAED,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,CAAC;AACrC,YAAY,EAAE,cAAc,EAAE,SAAS,EAAE,CAAC"}
package/dist/path.js ADDED
@@ -0,0 +1 @@
1
+ var s=Object.defineProperty;var o=(t,r)=>s(t,"name",{value:r,configurable:!0});const a=/^[a-z_]\w*$/i;function c(t){if(!t.startsWith("/"))throw new TypeError(`Contract path must start with "/": ${t}`);const r=[];for(const e of t.split("/")){if(!e.startsWith(":"))continue;const n=e.slice(1);if(!a.test(n))throw new TypeError(`Contract path parameter must be a plain ":name" segment: ${t}`);if(r.includes(n))throw new TypeError(`Contract path repeats parameter "${n}": ${t}`);r.push(n)}return r}o(c,"pathParamNames");function h(t,r={}){return t.split("/").map(e=>{if(!e.startsWith(":"))return e;const n=e.slice(1),i=Object.hasOwn(r,n)?r[n]:void 0;if(i==null||String(i)==="")throw new TypeError(`Missing path parameter "${n}" for ${t}`);return encodeURIComponent(String(i))}).join("/")}o(h,"buildPath");export{h as buildPath,c as pathParamNames};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/path.ts"],
4
+ "sourcesContent": ["/**\n * Path templates: `/user/items/:id`, the Hono/chanfana spelling, so one string\n * is both the route the backend registers and the URL the client builds.\n *\n * Only plain `:name` segments are accepted. Hono's regex (`:id{[0-9]+}`) and\n * optional (`:id?`) forms are refused at definition: the client would have to\n * re-implement Hono's matcher to build those URLs, and a contract whose two\n * ends disagree about a URL is the bug this package exists to remove.\n */\n\n/**\n * The parameter names in a template, as a union: `PathParamNames<'/a/:id/b/:sub'>`\n * is `'id' | 'sub'`, and `never` for a template with none.\n */\ntype PathParamNames<P extends string> = P extends `${string}:${infer Rest}`\n ? Rest extends `${infer Name}/${infer Tail}`\n ? Name | PathParamNames<`/${Tail}`>\n : Rest\n : never;\n\n/**\nA value a path segment may be built from. Encoded with `encodeURIComponent`.\n*/\ntype PathValue = string | number;\n\nconst PARAM_NAME = /^[a-z_]\\w*$/i;\n\n/**\n * The parameter names of a template, in order. Throws a `TypeError` for a\n * template the client could not build: not starting with `/`, a malformed or\n * repeated name, or Hono's regex/optional syntax.\n */\nfunction pathParamNames(template: string): string[] {\n if (!template.startsWith('/')) {\n throw new TypeError(`Contract path must start with \"/\": ${template}`);\n }\n const names: string[] = [];\n for (const segment of template.split('/')) {\n if (!segment.startsWith(':')) continue;\n const name = segment.slice(1);\n if (!PARAM_NAME.test(name)) {\n throw new TypeError(`Contract path parameter must be a plain \":name\" segment: ${template}`);\n }\n if (names.includes(name)) {\n throw new TypeError(`Contract path repeats parameter \"${name}\": ${template}`);\n }\n names.push(name);\n }\n return names;\n}\n\n/**\n * Fills a template. Every value is `encodeURIComponent`-encoded, so an id with\n * a `/` or `?` stays one segment. A missing or empty value throws rather than\n * producing `/user/items/` or `/user/items/undefined`.\n */\nfunction buildPath(template: string, params: Readonly<Record<string, PathValue>> = {}): string {\n return template\n .split('/')\n .map((segment) => {\n if (!segment.startsWith(':')) return segment;\n const name = segment.slice(1);\n const value = Object.hasOwn(params, name) ? params[name] : undefined;\n if (value === undefined || value === null || String(value) === '') {\n throw new TypeError(`Missing path parameter \"${name}\" for ${template}`);\n }\n return encodeURIComponent(String(value));\n })\n .join('/');\n}\n\nexport { buildPath, pathParamNames };\nexport type { PathParamNames, PathValue };\n"],
5
+ "mappings": "+EAyBA,MAAMA,EAAa,eAOnB,SAASC,EAAeC,EAAgB,CACtC,GAAI,CAACA,EAAS,WAAW,GAAG,EAC1B,MAAM,IAAI,UAAU,sCAAsCA,CAAQ,EAAE,EAEtE,MAAMC,EAAkB,CAAA,EACxB,UAAWC,KAAWF,EAAS,MAAM,GAAG,EAAG,CACzC,GAAI,CAACE,EAAQ,WAAW,GAAG,EAAG,SAC9B,MAAMC,EAAOD,EAAQ,MAAM,CAAC,EAC5B,GAAI,CAACJ,EAAW,KAAKK,CAAI,EACvB,MAAM,IAAI,UAAU,4DAA4DH,CAAQ,EAAE,EAE5F,GAAIC,EAAM,SAASE,CAAI,EACrB,MAAM,IAAI,UAAU,oCAAoCA,CAAI,MAAMH,CAAQ,EAAE,EAE9EC,EAAM,KAAKE,CAAI,CACjB,CACA,OAAOF,CACT,CAjBSG,EAAAL,EAAA,kBAwBT,SAASM,EAAUL,EAAkBM,EAA8C,CAAA,EAAE,CACnF,OAAON,EACJ,MAAM,GAAG,EACT,IAAKE,GAAW,CACf,GAAI,CAACA,EAAQ,WAAW,GAAG,EAAG,OAAOA,EACrC,MAAMC,EAAOD,EAAQ,MAAM,CAAC,EACtBK,EAAQ,OAAO,OAAOD,EAAQH,CAAI,EAAIG,EAAOH,CAAI,EAAI,OAC3D,GAA2BI,GAAU,MAAQ,OAAOA,CAAK,IAAM,GAC7D,MAAM,IAAI,UAAU,2BAA2BJ,CAAI,SAASH,CAAQ,EAAE,EAExE,OAAO,mBAAmB,OAAOO,CAAK,CAAC,CACzC,CAAC,EACA,KAAK,GAAG,CACb,CAbSH,EAAAC,EAAA",
6
+ "names": ["PARAM_NAME", "pathParamNames", "template", "names", "segment", "name", "__name", "buildPath", "params", "value"]
7
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@rexezuge/contracts",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.12.0",
4
+ "private": false,
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Rexezuge-CloudflareWorkers/SDK.git",
9
+ "directory": "packages/contracts"
10
+ },
11
+ "type": "module",
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "./*": {
20
+ "types": "./dist/*.d.ts",
21
+ "default": "./dist/*.js"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "scripts": {
28
+ "build": "tsc -p tsconfig.json && node ../../scripts/minify-dist.mjs",
29
+ "typecheck": "tsc -p tsconfig.test.json --noEmit",
30
+ "test": "vitest run",
31
+ "test:coverage": "vitest run --coverage"
32
+ },
33
+ "peerDependencies": {
34
+ "zod": "^4.4.3"
35
+ },
36
+ "peerDependenciesMeta": {
37
+ "zod": {
38
+ "optional": true
39
+ }
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "26.6.4",
43
+ "typescript": "6.0.3",
44
+ "vitest": "4.1.11",
45
+ "zod": "^4.6.5"
46
+ },
47
+ "description": "Endpoint contracts shared by a Rexezuge family API and its SPA: one zod-typed definition drives the chanfana route and the typed client."
48
+ }