contractdiff 0.0.0-stage → 0.4.2

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.
Files changed (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +228 -2
  3. package/dist/bin.js +4 -0
  4. package/dist/cli.d.ts +3 -0
  5. package/dist/cli.js +24 -0
  6. package/dist/command-diff.js +310 -0
  7. package/dist/command-explain-cap.js +36 -0
  8. package/dist/command-explain-inline.js +17 -0
  9. package/dist/command-explain-name.js +31 -0
  10. package/dist/command-explain-operation.js +85 -0
  11. package/dist/command-explain-text.js +21 -0
  12. package/dist/command-explain.js +54 -0
  13. package/dist/command-lint.js +280 -0
  14. package/dist/command-migrate.js +70 -0
  15. package/dist/command-plugin.js +32 -0
  16. package/dist/command-props.js +116 -0
  17. package/dist/commands.js +7 -0
  18. package/dist/core/index.d.ts +2 -0
  19. package/dist/core/index.js +2 -0
  20. package/dist/core/model.d.ts +46 -0
  21. package/dist/core/model.js +1 -0
  22. package/dist/core/resolve.d.ts +22 -0
  23. package/dist/core/resolve.js +71 -0
  24. package/dist/diff-classify.js +30 -0
  25. package/dist/diff-contract.js +176 -0
  26. package/dist/diff-decisions.js +446 -0
  27. package/dist/diff-normalise.js +143 -0
  28. package/dist/diff-rules.js +109 -0
  29. package/dist/diff-schema.js +335 -0
  30. package/dist/diff-security.js +33 -0
  31. package/dist/diff-transitive.js +26 -0
  32. package/dist/diff-usage.js +59 -0
  33. package/dist/extract-normalise.js +85 -0
  34. package/dist/extract-roundtrip.js +28 -0
  35. package/dist/extract-standard.js +79 -0
  36. package/dist/gen-ts-ast.d.ts +135 -0
  37. package/dist/gen-ts-ast.js +52 -0
  38. package/dist/gen-ts-bundle.js +233 -0
  39. package/dist/gen-ts-comment.js +48 -0
  40. package/dist/gen-ts-context.d.ts +83 -0
  41. package/dist/gen-ts-context.js +45 -0
  42. package/dist/gen-ts-dict.d.ts +14 -0
  43. package/dist/gen-ts-dict.js +14 -0
  44. package/dist/gen-ts-discriminators.d.ts +7 -0
  45. package/dist/gen-ts-discriminators.js +117 -0
  46. package/dist/gen-ts-document.d.ts +12 -0
  47. package/dist/gen-ts-document.js +82 -0
  48. package/dist/gen-ts-enums.js +139 -0
  49. package/dist/gen-ts-helpers.js +30 -0
  50. package/dist/gen-ts-index.d.ts +49 -0
  51. package/dist/gen-ts-index.js +110 -0
  52. package/dist/gen-ts-operations.js +277 -0
  53. package/dist/gen-ts-print.js +113 -0
  54. package/dist/gen-ts-ref.d.ts +30 -0
  55. package/dist/gen-ts-ref.js +75 -0
  56. package/dist/gen-ts-schema.js +283 -0
  57. package/dist/gen-ts-text.d.ts +24 -0
  58. package/dist/gen-ts-text.js +98 -0
  59. package/dist/host.d.ts +145 -0
  60. package/dist/host.js +273 -0
  61. package/dist/index.d.ts +6 -0
  62. package/dist/index.js +5 -0
  63. package/dist/input-asyncapi.js +167 -0
  64. package/dist/input-buf.js +58 -0
  65. package/dist/input-jsonschema.js +165 -0
  66. package/dist/input-mcp.js +111 -0
  67. package/dist/input-overlay-jsonpath.js +265 -0
  68. package/dist/input-overlay.js +138 -0
  69. package/dist/input-protobuf.js +212 -0
  70. package/dist/input-swagger2.js +331 -0
  71. package/dist/inputs.js +8 -0
  72. package/dist/lint-code-read.js +129 -0
  73. package/dist/lint-code.d.ts +56 -0
  74. package/dist/lint-code.js +64 -0
  75. package/dist/lint-engine.d.ts +93 -0
  76. package/dist/lint-engine.js +87 -0
  77. package/dist/lint-functions.js +95 -0
  78. package/dist/lint-history.js +133 -0
  79. package/dist/lint-jsonpath.js +92 -0
  80. package/dist/lint-names.d.ts +11 -0
  81. package/dist/lint-names.js +2 -0
  82. package/dist/lint-redocly.js +141 -0
  83. package/dist/lint-rules.js +189 -0
  84. package/dist/lint-select.d.ts +33 -0
  85. package/dist/lint-select.js +129 -0
  86. package/dist/lint-since.js +20 -0
  87. package/dist/lint-spectral.js +167 -0
  88. package/dist/lint-stats.js +58 -0
  89. package/dist/migrate-hey-api.js +144 -0
  90. package/dist/migrate-literal.js +139 -0
  91. package/dist/migrate-openapi-fetch.js +62 -0
  92. package/dist/migrate-openapi-typescript.js +159 -0
  93. package/dist/migrate-orval.js +119 -0
  94. package/dist/migrate-shared.js +31 -0
  95. package/dist/openapi-typescript.d.ts +9 -0
  96. package/dist/openapi-typescript.js +36 -0
  97. package/dist/openapi.d.ts +20 -0
  98. package/dist/openapi.js +94 -0
  99. package/dist/plugin-express.js +66 -0
  100. package/dist/plugin-extract-hono.js +1 -0
  101. package/dist/plugin-extract-nest.js +1 -0
  102. package/dist/plugin-extract-openapi.js +246 -0
  103. package/dist/plugin-extract-standard-schema.js +42 -0
  104. package/dist/plugin-extract-trpc.js +1 -0
  105. package/dist/plugin-extract-ts-rest.js +77 -0
  106. package/dist/plugin-fastify.js +68 -0
  107. package/dist/plugin-fetch-client.js +172 -0
  108. package/dist/plugin-fetch-routes.js +110 -0
  109. package/dist/plugin-fetch-sample.js +155 -0
  110. package/dist/plugin-fetch-text.js +5 -0
  111. package/dist/plugin-fetch.js +19 -0
  112. package/dist/plugin-hono.js +42 -0
  113. package/dist/plugin-json-schema-build.js +289 -0
  114. package/dist/plugin-json-schema-dialect-anthropic.js +41 -0
  115. package/dist/plugin-json-schema-dialect-gemini.js +29 -0
  116. package/dist/plugin-json-schema-dialect-mcp-elicitation.js +32 -0
  117. package/dist/plugin-json-schema-dialect-mcp.js +13 -0
  118. package/dist/plugin-json-schema-dialect-openai.js +37 -0
  119. package/dist/plugin-json-schema-dialect.js +180 -0
  120. package/dist/plugin-json-schema.js +125 -0
  121. package/dist/plugin-markdown.js +114 -0
  122. package/dist/plugin-mcp-code.js +28 -0
  123. package/dist/plugin-mcp-tools.js +152 -0
  124. package/dist/plugin-mcp.js +107 -0
  125. package/dist/plugin-msw-files.js +50 -0
  126. package/dist/plugin-msw-sample.js +45 -0
  127. package/dist/plugin-msw-synth.js +116 -0
  128. package/dist/plugin-msw.js +30 -0
  129. package/dist/plugin-nest-code.js +68 -0
  130. package/dist/plugin-nest-contract.js +23 -0
  131. package/dist/plugin-nest.js +44 -0
  132. package/dist/plugin-server-code.js +61 -0
  133. package/dist/plugin-server-contract.js +48 -0
  134. package/dist/plugin-server-example.js +62 -0
  135. package/dist/plugin-server-router.js +77 -0
  136. package/dist/plugin-server-routes.js +155 -0
  137. package/dist/plugin-server-runtime.js +3 -0
  138. package/dist/plugin-server-sample.js +40 -0
  139. package/dist/plugin-swr-sample.js +21 -0
  140. package/dist/plugin-swr.js +40 -0
  141. package/dist/plugin-tanstack-query-sample.js +21 -0
  142. package/dist/plugin-tanstack-query.js +59 -0
  143. package/dist/plugin-types.js +80 -0
  144. package/dist/plugin-validator-code.js +41 -0
  145. package/dist/plugin-validator-names.js +27 -0
  146. package/dist/plugin-validator.js +103 -0
  147. package/dist/plugins.js +21 -0
  148. package/dist/props-emit.js +194 -0
  149. package/dist/props-generate.js +409 -0
  150. package/dist/props-judge.js +61 -0
  151. package/dist/props-mutate.js +144 -0
  152. package/dist/props-random.js +25 -0
  153. package/dist/props-run.js +176 -0
  154. package/dist/props-shrink.js +75 -0
  155. package/dist/run-apply.js +25 -0
  156. package/dist/run-command.js +31 -0
  157. package/dist/run-commit.d.ts +51 -0
  158. package/dist/run-commit.js +48 -0
  159. package/dist/run-config.d.ts +193 -0
  160. package/dist/run-config.js +256 -0
  161. package/dist/run-diff.js +24 -0
  162. package/dist/run-extract.d.ts +13 -0
  163. package/dist/run-extract.js +21 -0
  164. package/dist/run-gen.d.ts +15 -0
  165. package/dist/run-gen.js +43 -0
  166. package/dist/run-header.js +37 -0
  167. package/dist/run-input.js +31 -0
  168. package/dist/run-load.js +32 -0
  169. package/dist/run-map.d.ts +41 -0
  170. package/dist/run-map.js +52 -0
  171. package/dist/run-plan.d.ts +31 -0
  172. package/dist/run-plan.js +35 -0
  173. package/dist/scaffold-seed.js +43 -0
  174. package/dist/scaffold-write.js +17 -0
  175. package/dist/scaffold.js +196 -0
  176. package/dist/testing-lint.js +43 -0
  177. package/dist/testing-owner.js +17 -0
  178. package/dist/testing-probe.js +25 -0
  179. package/dist/testing-rules.d.ts +65 -0
  180. package/dist/testing-rules.js +115 -0
  181. package/dist/testing.d.ts +32 -0
  182. package/dist/testing.js +79 -0
  183. package/package.json +108 -4
@@ -0,0 +1,246 @@
1
+ import { STATUS_CODES } from 'node:http';
2
+ import { string } from 'truefit';
3
+ import { standardJson } from 'truefit/json-schema';
4
+ import { stable } from './extract-normalise.js';
5
+ import { escape, finding, isRecord, isStandard, loadModule, placeAt, relocate, sideOf, toJsonSchema } from './extract-standard.js';
6
+ const BASE = '#/components/schemas/';
7
+ const METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'];
8
+ const BODY = new Set(['post', 'put', 'patch']);
9
+ const JSON_MEDIA = 'application/json';
10
+ export const openapiPath = (path) => path.replaceAll(/:([A-Za-z_][\w]*)/gu, '{$1}');
11
+ const pathNames = (path) => [...path.matchAll(/\{([^}]+)\}/gu)].map((match) => match[1]);
12
+ export const docsOf = (value) => {
13
+ const docs = {};
14
+ if (typeof value.summary === 'string')
15
+ docs.summary = value.summary;
16
+ if (typeof value.description === 'string')
17
+ docs.description = value.description;
18
+ if (Array.isArray(value.tags) && value.tags.every((tag) => typeof tag === 'string'))
19
+ docs.tags = value.tags;
20
+ if (typeof value.deprecated === 'boolean')
21
+ docs.deprecated = value.deprecated;
22
+ return docs;
23
+ };
24
+ const ref = (name) => ({ $ref: `${BASE}${escape(name)}` });
25
+ const placed = (schema, name, build) => {
26
+ const moved = relocate(schema, name, build.place);
27
+ if (stable(moved).includes(JSON.stringify(ref(name).$ref)))
28
+ build.place.defs.set(name, moved);
29
+ return moved;
30
+ };
31
+ const converted = (wanted, build) => {
32
+ const result = toJsonSchema(wanted.value, wanted.side, wanted.pointer);
33
+ if ('schema' in result)
34
+ return result.schema;
35
+ build.place.findings.push(result.finding);
36
+ return undefined;
37
+ };
38
+ const schemaOf = (wanted, build) => {
39
+ const schema = converted(wanted, build);
40
+ if (schema === undefined)
41
+ return undefined;
42
+ const exported = build.names.get(wanted.value);
43
+ if (exported === undefined) {
44
+ const moved = placed(schema, wanted.fallback, build);
45
+ return build.place.defs.has(wanted.fallback) ? ref(wanted.fallback) : moved;
46
+ }
47
+ const candidate = relocate(schema, exported, placeAt(BASE));
48
+ const first = build.place.defs.get(exported);
49
+ const name = first === undefined || stable(first) === stable(candidate) ? exported : `${exported}.${wanted.side}`;
50
+ build.place.defs.set(name, relocate(schema, name, build.place));
51
+ return ref(name);
52
+ };
53
+ const objectOf = (wanted, build) => {
54
+ const schema = converted(wanted, build);
55
+ if (schema === undefined)
56
+ return undefined;
57
+ if (!isRecord(schema.properties)) {
58
+ build.place.findings.push(finding('not-an-object', wanted.pointer, `${wanted.pointer} is not an object schema, so it cannot be split into parameters`, 'describe the parameters with an object schema, one property each'));
59
+ return undefined;
60
+ }
61
+ return placed(schema, wanted.fallback, build);
62
+ };
63
+ const parametersOf = (schema, location, only) => {
64
+ const { required } = schema;
65
+ return Object.entries(schema.properties)
66
+ .filter(([name]) => only(name))
67
+ .map(([name, property]) => ({ name, in: location, required: location === 'path' || (Array.isArray(required) && required.includes(name)), schema: property }));
68
+ };
69
+ const without = (schema, names) => {
70
+ const properties = Object.fromEntries(Object.entries(schema.properties).filter(([name]) => !names.includes(name)));
71
+ const required = Array.isArray(schema.required) ? schema.required.filter((name) => !names.includes(name)) : [];
72
+ const { required: _required, ...rest } = schema;
73
+ return { ...rest, properties, ...(required.length === 0 ? {} : { required }) };
74
+ };
75
+ const fromInput = (route, names, build) => {
76
+ const wanted = { value: route.input, side: 'input', pointer: `${route.pointer}/input`, fallback: `${route.id}.input` };
77
+ if (BODY.has(route.method) && names.length === 0)
78
+ return { parameters: [], body: schemaOf(wanted, build) };
79
+ const schema = objectOf(wanted, build);
80
+ if (schema === undefined)
81
+ return { parameters: [] };
82
+ const inPath = parametersOf(schema, 'path', (name) => names.includes(name));
83
+ if (BODY.has(route.method))
84
+ return { parameters: inPath, body: without(schema, names) };
85
+ return { parameters: [...inPath, ...parametersOf(schema, 'query', (name) => !names.includes(name))] };
86
+ };
87
+ const LOCATIONS = [
88
+ ['params', 'path'],
89
+ ['query', 'query'],
90
+ ['headers', 'header'],
91
+ ];
92
+ const requestOf = (route, build) => {
93
+ const names = pathNames(route.path);
94
+ const shorthand = route.input === undefined ? { parameters: [] } : fromInput(route, names, build);
95
+ const parameters = [...shorthand.parameters];
96
+ for (const [key, location] of LOCATIONS) {
97
+ if (route[key] === undefined)
98
+ continue;
99
+ const schema = objectOf({ value: route[key], side: 'input', pointer: `${route.pointer}/${key}`, fallback: `${route.id}.${key}` }, build);
100
+ if (schema !== undefined)
101
+ parameters.push(...parametersOf(schema, location, () => true));
102
+ }
103
+ for (const name of names) {
104
+ if (!parameters.some((parameter) => parameter.in === 'path' && parameter.name === name))
105
+ parameters.push({ name, in: 'path', required: true, schema: { type: 'string' } });
106
+ }
107
+ const body = route.body === undefined ? shorthand.body : schemaOf({ value: route.body, side: 'input', pointer: `${route.pointer}/body`, fallback: `${route.id}.body` }, build);
108
+ return { parameters, body };
109
+ };
110
+ const responseOf = (route, response, side, build) => {
111
+ const description = STATUS_CODES[response.status] ?? 'Response';
112
+ if (response.schema === undefined)
113
+ return { description };
114
+ const schema = schemaOf({ value: response.schema, side, pointer: `${route.pointer}/responses/${response.status}`, fallback: `${route.id}.${response.status}` }, build);
115
+ return schema === undefined ? { description } : { description, content: { [response.contentType ?? JSON_MEDIA]: { schema } } };
116
+ };
117
+ const responsesOf = (route, side, build) => Object.fromEntries(route.responses.map((response) => [response.status, responseOf(route, response, side, build)]));
118
+ const operationOf = (route, side, build) => {
119
+ const { parameters, body } = requestOf(route, build);
120
+ return {
121
+ operationId: route.id,
122
+ ...route.docs,
123
+ ...(parameters.length === 0 ? {} : { parameters }),
124
+ ...(body === undefined ? {} : { requestBody: { required: true, content: { [route.contentType ?? JSON_MEDIA]: { schema: body } } } }),
125
+ responses: responsesOf(route, side, build),
126
+ };
127
+ };
128
+ export const toOpenApi = (routes, names, options) => {
129
+ const side = sideOf(options.responseSide ?? 'output');
130
+ const build = { place: placeAt(BASE), names };
131
+ const paths = new Map();
132
+ for (const route of routes.toSorted((a, b) => a.id.localeCompare(b.id, 'en'))) {
133
+ if (!METHODS.includes(route.method)) {
134
+ build.place.findings.push(finding('unknown-method', route.pointer, `${route.id} has the method "${route.method}", which OpenAPI does not have`, `use one of ${METHODS.join(', ')}`));
135
+ continue;
136
+ }
137
+ const item = paths.get(route.path) ?? new Map();
138
+ paths.set(route.path, item);
139
+ if (item.has(route.method)) {
140
+ build.place.findings.push(finding('duplicate-route', route.pointer, `${route.id} is ${route.method.toUpperCase()} ${route.path} again; the first is kept`, 'give each operation a path and method of its own'));
141
+ continue;
142
+ }
143
+ item.set(route.method, operationOf(route, side, build));
144
+ }
145
+ const ordered = Object.fromEntries([...paths.keys()].toSorted().map((path) => {
146
+ const item = paths.get(path);
147
+ return [path, Object.fromEntries(METHODS.filter((method) => item.has(method)).map((method) => [method, item.get(method)]))];
148
+ }));
149
+ const schemas = Object.fromEntries([...build.place.defs.keys()].toSorted().map((name) => [name, build.place.defs.get(name)]));
150
+ const document = {
151
+ openapi: '3.1.0',
152
+ info: { title: typeof options.title === 'string' ? options.title : 'API', version: typeof options.version === 'string' ? options.version : '0.0.0' },
153
+ paths: ordered,
154
+ ...(Object.keys(schemas).length === 0 ? {} : { components: { schemas } }),
155
+ };
156
+ return { document, findings: build.place.findings };
157
+ };
158
+ export const namesOf = (namespace) => {
159
+ const names = new Map();
160
+ for (const name of Object.keys(namespace).toSorted())
161
+ if (isStandard(namespace[name]) && !names.has(namespace[name]))
162
+ names.set(namespace[name], name);
163
+ return names;
164
+ };
165
+ export const exported = (namespace, wanted) => Object.entries(namespace).find(([name]) => name === wanted)?.[1];
166
+ const isOperation = (value) => isRecord(value) && typeof value.method === 'string' && typeof value.path === 'string';
167
+ const routeOf = (id, operation, findings) => {
168
+ const pointer = `/${escape(id)}`;
169
+ const responses = [];
170
+ if (operation.output !== undefined)
171
+ responses.push({ status: '200', schema: operation.output });
172
+ if (isRecord(operation.responses)) {
173
+ for (const [status, schema] of Object.entries(operation.responses)) {
174
+ if (schema === null)
175
+ responses.push({ status });
176
+ else if (isStandard(schema))
177
+ responses.push({ status, schema });
178
+ else
179
+ findings.push(finding('unknown-response', `${pointer}/responses/${status}`, `${id}'s ${status} response is neither a schema nor null`, 'give a Standard Schema for a body, or null for none'));
180
+ }
181
+ }
182
+ if (responses.length === 0)
183
+ responses.push({ status: '204' });
184
+ return {
185
+ id,
186
+ pointer,
187
+ method: operation.method.toLowerCase(),
188
+ path: openapiPath(operation.path),
189
+ input: operation.input,
190
+ params: operation.params,
191
+ query: operation.query,
192
+ headers: operation.headers,
193
+ body: operation.body,
194
+ responses,
195
+ docs: docsOf(operation),
196
+ };
197
+ };
198
+ export const operationsOf = (namespace, wanted) => {
199
+ const findings = [];
200
+ const all = wanted === undefined || wanted === '*';
201
+ const map = all ? namespace : exported(namespace, wanted);
202
+ if (!isRecord(map)) {
203
+ throw new TypeError(`the module has no operation map ${JSON.stringify(wanted)}. fix: name the export that holds \`{ [operationId]: { method, path, input, output } }\`, or write "*"`);
204
+ }
205
+ const routes = [];
206
+ for (const [id, value] of Object.entries(map)) {
207
+ if (isOperation(value))
208
+ routes.push(routeOf(id, value, findings));
209
+ else if (!all)
210
+ findings.push(finding('not-an-operation', `/${escape(id)}`, `${id} has no method and path`, 'write `{ method, path, input, output }`'));
211
+ }
212
+ return { routes, findings };
213
+ };
214
+ export const withFindings = (written, more) => ({ document: written.document, findings: [...more, ...written.findings] });
215
+ export const WRITER_OPTIONS = {
216
+ module: { type: 'string', description: 'the module to import, relative to the working folder; its code runs' },
217
+ title: { type: 'string', description: 'info.title (default "API")' },
218
+ version: { type: 'string', description: 'info.version (default "0.0.0")' },
219
+ responseSide: { type: 'string', description: '"output" (default): responses as the schema hands them out; "input": as a client parses them' },
220
+ };
221
+ export const extractOpenApi = (namespace, options) => {
222
+ const { routes, findings } = operationsOf(namespace, options.export);
223
+ return withFindings(toOpenApi(routes, namesOf(namespace), options), findings);
224
+ };
225
+ const extractor = {
226
+ description: 'An OpenAPI 3.1 document from a module exporting `{ [operationId]: { method, path, input, output } }` of Standard Schema values',
227
+ options: { ...WRITER_OPTIONS, export: { type: 'string', description: 'the export holding the operation map, or "*" when the module\'s own exports are the operations (default)' } },
228
+ sample: {
229
+ options: { module: { getPet: { method: 'GET', path: '/pets/:id', output: standardJson(string()) } } },
230
+ document: {
231
+ openapi: '3.1.0',
232
+ info: { title: 'API', version: '0.0.0' },
233
+ paths: {
234
+ '/pets/{id}': {
235
+ get: {
236
+ operationId: 'getPet',
237
+ parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
238
+ responses: { '200': { description: 'OK', content: { [JSON_MEDIA]: { schema: { type: 'string' } } } } },
239
+ },
240
+ },
241
+ },
242
+ },
243
+ },
244
+ run: async (options) => extractOpenApi(await loadModule(options.module), options),
245
+ };
246
+ export const plugin = { name: 'extract-openapi', extractors: { 'openapi-from-schemas': extractor } };
@@ -0,0 +1,42 @@
1
+ import { optional, number, object, string } from 'truefit';
2
+ import { standardJson } from 'truefit/json-schema';
3
+ import { definitions, escape, isStandard, loadModule, placeAt, relocate, sideOf, toJsonSchema } from './extract-standard.js';
4
+ export const DIALECT = 'https://json-schema.org/draft/2020-12/schema';
5
+ export const exportsOf = (namespace, wanted) => {
6
+ if (wanted === undefined || wanted === '*')
7
+ return Object.keys(namespace).filter((name) => isStandard(namespace[name])).toSorted();
8
+ if (!Object.keys(namespace).includes(wanted)) {
9
+ throw new TypeError(`the module has no export ${JSON.stringify(wanted)}. fix: name one of ${Object.keys(namespace).toSorted().join(', ') || 'its exports'}, or write "*"`);
10
+ }
11
+ return [wanted];
12
+ };
13
+ export const extractSchemas = (namespace, options) => {
14
+ const side = sideOf(options.side);
15
+ const place = placeAt('#/$defs/');
16
+ for (const name of exportsOf(namespace, options.export)) {
17
+ const result = toJsonSchema(namespace[name], side, `/${escape(name)}`);
18
+ if ('finding' in result)
19
+ place.findings.push(result.finding);
20
+ else
21
+ place.defs.set(name, relocate(result.schema, name, place));
22
+ }
23
+ return { document: { $schema: DIALECT, $defs: definitions(place) }, findings: place.findings };
24
+ };
25
+ const Pet = standardJson(object({ id: number(), name: optional(string()) }));
26
+ const extractor = {
27
+ description: 'Every Standard JSON Schema export of a module (Zod 4, Valibot, ArkType, validator) as one JSON Schema document',
28
+ options: {
29
+ module: { type: 'string', description: 'the module to import, relative to the working folder; its code runs' },
30
+ export: { type: 'string', description: 'the export to read, or "*" for every schema it exports (default)' },
31
+ side: { type: 'string', description: '"input" (default): what parse reads; "output": what it hands out' },
32
+ },
33
+ sample: {
34
+ options: { module: { Pet } },
35
+ document: {
36
+ $schema: DIALECT,
37
+ $defs: { Pet: { type: 'object', properties: { id: { type: 'number' }, name: { type: 'string' } }, required: ['id'] } },
38
+ },
39
+ },
40
+ run: async (options) => extractSchemas(await loadModule(options.module), options),
41
+ };
42
+ export const plugin = { name: 'extract-standard-schema', extractors: { 'standard-schema': extractor } };
@@ -0,0 +1 @@
1
+ export const plugin = undefined;
@@ -0,0 +1,77 @@
1
+ import { escape, finding, isStandard, loadModule } from './extract-standard.js';
2
+ import { docsOf, exported, namesOf, openapiPath, toOpenApi, withFindings, WRITER_OPTIONS } from './plugin-extract-openapi.js';
3
+ const NO_BODY = 'ContractNoBody';
4
+ const isPlain = (value) => {
5
+ if (typeof value !== 'object' || value === null || isStandard(value))
6
+ return false;
7
+ const prototype = Object.getPrototypeOf(value);
8
+ return prototype === Object.prototype || prototype === null;
9
+ };
10
+ const isRoute = (value) => typeof value.method === 'string' && typeof value.path === 'string';
11
+ const typeOnly = (pointer, what) => finding('type-only', pointer, `${what} is \`c.type<T>()\`, which has no schema at run time, so OpenAPI gets no schema for it`, 'give it a Standard Schema (a Zod 4 schema, for one) in place of `c.type<T>()`');
12
+ const bodyOf = (value, pointer, what, findings) => {
13
+ if (value === undefined || isStandard(value))
14
+ return value;
15
+ if (typeof value === 'symbol' && value.description === NO_BODY)
16
+ return undefined;
17
+ findings.push(typeof value === 'symbol' ? typeOnly(pointer, what) : finding('unknown-body', pointer, `${what} is neither a schema, \`c.noBody()\` nor \`c.type<T>()\``, 'give a Standard Schema, or `c.noBody()`'));
18
+ return undefined;
19
+ };
20
+ const responseOf = (status, value, pointer, findings) => {
21
+ if (isPlain(value) && typeof value.contentType === 'string') {
22
+ return { status, schema: bodyOf(value.body, `${pointer}/body`, `the ${status} response`, findings), contentType: value.contentType };
23
+ }
24
+ return { status, schema: bodyOf(value, pointer, `the ${status} response`, findings) };
25
+ };
26
+ const routeOf = (keys, route, findings) => {
27
+ const id = keys.join('.');
28
+ const pointer = keys.map((key) => `/${escape(key)}`).join('');
29
+ const responses = Object.entries(isPlain(route.responses) ? route.responses : {}).map(([status, value]) => responseOf(status, value, `${pointer}/responses/${status}`, findings));
30
+ return {
31
+ id,
32
+ pointer,
33
+ method: route.method.toLowerCase(),
34
+ path: openapiPath(route.path),
35
+ params: route.pathParams,
36
+ query: route.query,
37
+ headers: route.headers,
38
+ body: bodyOf(route.body, `${pointer}/body`, `${id}'s body`, findings),
39
+ ...(typeof route.contentType === 'string' ? { contentType: route.contentType } : {}),
40
+ responses: responses.length === 0 ? [{ status: '204' }] : responses,
41
+ docs: docsOf(route),
42
+ };
43
+ };
44
+ export const routesOf = (router, keys = [], findings = []) => {
45
+ const routes = [];
46
+ for (const [key, value] of Object.entries(router)) {
47
+ if (!isPlain(value))
48
+ continue;
49
+ if (isRoute(value))
50
+ routes.push(routeOf([...keys, key], value, findings));
51
+ else
52
+ routes.push(...routesOf(value, [...keys, key], findings).routes);
53
+ }
54
+ return { routes, findings };
55
+ };
56
+ export const contractOf = (namespace, wanted) => {
57
+ if (wanted === undefined || wanted === '*')
58
+ return namespace;
59
+ const found = exported(namespace, wanted);
60
+ if (!isPlain(found))
61
+ throw new TypeError(`the module has no ts-rest contract ${JSON.stringify(wanted)}. fix: name the export that \`c.router(…)\` made, or write "*"`);
62
+ return found;
63
+ };
64
+ export const extractTsRest = (namespace, options) => {
65
+ const { routes, findings } = routesOf(contractOf(namespace, options.export));
66
+ return withFindings(toOpenApi(routes, namesOf(namespace), options), findings);
67
+ };
68
+ const extractor = {
69
+ description: 'An OpenAPI 3.1 document from a ts-rest contract (`c.router(…)`), read as data: ts-rest need not be installed',
70
+ options: { ...WRITER_OPTIONS, export: { type: 'string', description: 'the export holding the contract, or "*" when the module\'s own exports are its routers (default)' } },
71
+ sample: {
72
+ options: { module: { contract: { health: { method: 'GET', path: '/health', responses: { 200: Symbol(NO_BODY) } } } }, export: 'contract' },
73
+ document: { openapi: '3.1.0', info: { title: 'API', version: '0.0.0' }, paths: { '/health': { get: { operationId: 'health', responses: { '200': { description: 'OK' } } } } } },
74
+ },
75
+ run: async (options) => extractTsRest(await loadModule(options.module), options),
76
+ };
77
+ export const plugin = { name: 'extract-ts-rest', extractors: { 'ts-rest': extractor } };
@@ -0,0 +1,68 @@
1
+ import { read } from './openapi.js';
2
+ import { colonPath } from './plugin-server-code.js';
3
+ import { SERVER_OPTIONS } from './plugin-server-contract.js';
4
+ import { runRouter } from './plugin-server-router.js';
5
+ import { SAMPLE_DOCUMENT } from './plugin-server-sample.js';
6
+ export const FASTIFY = {
7
+ target: 'fastify',
8
+ name: 'Fastify',
9
+ path: colonPath,
10
+ imports: ["import { type FastifyPluginAsync } from 'fastify';"],
11
+ register: [
12
+ '/**',
13
+ ' * A Fastify plugin registering every route: each reads and checks the request, calls its handler,',
14
+ ' * and checks what it answers. Inside it every body arrives as text, which `handle` parses.',
15
+ ' */',
16
+ 'export const registerRoutes: FastifyPluginAsync<{ readonly handlers: Handlers }> = async (fastify, { handlers }) => {',
17
+ ' fastify.removeAllContentTypeParsers();',
18
+ " fastify.addContentTypeParser('*', { parseAs: 'string' }, (_request, body, done) => {",
19
+ ' done(null, body);',
20
+ ' });',
21
+ ' for (const route of routes) {',
22
+ ' fastify.route({',
23
+ ' method: route.method,',
24
+ ' url: route.path,',
25
+ ' exposeHeadRoute: false,',
26
+ ' handler: async (request, reply) => {',
27
+ ' const answer = await handle(route, handlers, { path: request.params as Readonly<Record<string, unknown>>, query: request.query as Readonly<Record<string, unknown>>, header: request.headers, body: request.body });',
28
+ ' return reply.code(answer.status).headers(answer.headers).send(answer.body);',
29
+ ' },',
30
+ ' });',
31
+ ' }',
32
+ '};',
33
+ ],
34
+ usage: 'Serve them with `app.register(registerRoutes, { handlers })` from routes.ts.',
35
+ harness: {
36
+ framework: ["import Fastify, { type FastifyInstance } from 'fastify';"],
37
+ hooks: ['afterAll', 'beforeAll'],
38
+ local: ["import { handlers } from './handlers.js';", "import { registerRoutes } from './routes.js';"],
39
+ setup: [
40
+ ' let app: FastifyInstance;',
41
+ ' let base: string;',
42
+ '',
43
+ ' beforeAll(async () => {',
44
+ ' app = Fastify();',
45
+ ' await app.register(registerRoutes, { handlers });',
46
+ " base = await app.listen({ port: 0, host: '127.0.0.1' });",
47
+ ' });',
48
+ '',
49
+ ' afterAll(async () => {',
50
+ ' await app.close();',
51
+ ' });',
52
+ '',
53
+ ],
54
+ call: (url, init) => `fetch(new URL(${url}, base), ${init})`,
55
+ },
56
+ };
57
+ export const run = (contract, options) => runRouter(FASTIFY, contract, options);
58
+ const fastify = {
59
+ description: 'Fastify routes: a generated plugin that registers every route and validates requests and responses, handlers you own, and a contract test per operation',
60
+ inputs: ['openapi'],
61
+ options: SERVER_OPTIONS,
62
+ sample: {
63
+ document: SAMPLE_DOCUMENT,
64
+ files: run(read(SAMPLE_DOCUMENT), {}).files,
65
+ },
66
+ run,
67
+ };
68
+ export const plugin = { name: 'fastify', generators: { fastify } };
@@ -0,0 +1,172 @@
1
+ import { key, lines, literal } from './plugin-fetch-text.js';
2
+ const kindOf = (type) => {
3
+ if (type === undefined)
4
+ return 'none';
5
+ if (/[/+]json(?:;|$)/u.test(type))
6
+ return 'json';
7
+ return type.startsWith('text/') ? 'text' : 'blob';
8
+ };
9
+ const RUNTIME = [
10
+ '/** A declared response: the status as the spec writes it, the status received, the body and the headers. */',
11
+ 'export interface Answer<S, B> {',
12
+ ' readonly status: S;',
13
+ ' readonly code: number;',
14
+ ' readonly body: B;',
15
+ ' readonly headers: Headers;',
16
+ '}',
17
+ '',
18
+ '/** A status the operation does not declare, or a body `validate` refused. Never thrown. */',
19
+ "export interface Unexpected extends Answer<'unexpected', unknown> {",
20
+ ' /** What `validate` reported. */',
21
+ ' readonly errors?: readonly unknown[];',
22
+ '}',
23
+ '',
24
+ 'type BodyOf<R> = R extends { content: infer C } ? C[keyof C] : undefined;',
25
+ '',
26
+ 'export interface ClientOptions {',
27
+ ' /** Where the API is, e.g. `https://api.example.com/v1`. */',
28
+ ' readonly baseUrl: string;',
29
+ ' /** Defaults to the platform `fetch`. */',
30
+ ' readonly fetch?: (url: string, init: RequestInit) => Promise<Response>;',
31
+ ' /** Sent with every request. */',
32
+ ' readonly headers?: Readonly<Record<string, string>>;',
33
+ ' /** Checks a declared response body; any error turns the result into `unexpected`. */',
34
+ ' readonly validate?: (check: { readonly operation: string; readonly status: string; readonly body: unknown }) => readonly unknown[] | undefined;',
35
+ '}',
36
+ '',
37
+ "type Place = 'path' | 'query' | 'header' | 'cookie';",
38
+ '',
39
+ 'interface Param {',
40
+ ' readonly name: string;',
41
+ ' readonly in: Place;',
42
+ ' readonly style: string;',
43
+ ' readonly explode: boolean;',
44
+ '}',
45
+ '',
46
+ 'interface Route {',
47
+ ' readonly id: string;',
48
+ ' readonly method: string;',
49
+ ' readonly path: string;',
50
+ ' readonly params: readonly Param[];',
51
+ ' readonly body?: string;',
52
+ " readonly responses: Readonly<Record<string, 'json' | 'text' | 'blob' | 'none'>>;",
53
+ '}',
54
+ '',
55
+ 'type Bag = Readonly<Record<string, unknown>>;',
56
+ '',
57
+ 'const isBag = (value: unknown): value is Bag => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Blob);',
58
+ 'const atom = (value: unknown): string => (typeof value === "object" && value !== null ? JSON.stringify(value) : String(value));',
59
+ 'const present = (value: Bag): [string, unknown][] => Object.entries(value).filter((entry) => entry[1] !== undefined);',
60
+ '',
61
+ '/** The `simple` style (path and header), each piece through `encode`. */',
62
+ 'const simple = (value: unknown, explode: boolean, encode: (text: string) => string): string => {',
63
+ ' if (Array.isArray(value)) return value.map((item) => encode(atom(item))).join(",");',
64
+ ' if (!isBag(value)) return encode(atom(value));',
65
+ ' return present(value).map(([name, item]) => `${encode(name)}${explode ? "=" : ","}${encode(atom(item))}`).join(",");',
66
+ '};',
67
+ '',
68
+ 'const DELIMITERS: Readonly<Record<string, string>> = { spaceDelimited: "%20", pipeDelimited: "|" };',
69
+ '',
70
+ '/** One query parameter as `name=value` pairs, already encoded. */',
71
+ 'const query = (param: Param, value: unknown): string[] => {',
72
+ ' const name = encodeURIComponent(param.name);',
73
+ ' const one = (item: unknown): string => encodeURIComponent(atom(item));',
74
+ ' if (Array.isArray(value)) {',
75
+ ' if (param.explode) return value.map((item) => `${name}=${one(item)}`);',
76
+ ' return [`${name}=${value.map(one).join(DELIMITERS[param.style] ?? ",")}`];',
77
+ ' }',
78
+ ' if (!isBag(value)) return [`${name}=${one(value)}`];',
79
+ ' const entries = present(value);',
80
+ ' if (param.style === "deepObject") return entries.map(([inner, item]) => `${name}%5B${encodeURIComponent(inner)}%5D=${one(item)}`);',
81
+ ' if (param.explode) return entries.map(([inner, item]) => `${encodeURIComponent(inner)}=${one(item)}`);',
82
+ ' return [`${name}=${entries.map(([inner, item]) => `${encodeURIComponent(inner)},${one(item)}`).join(",")}`];',
83
+ '};',
84
+ '',
85
+ '/** A body as the media type the operation sends. */',
86
+ 'const encodeBody = (type: string, body: unknown): BodyInit => {',
87
+ ' if (/[/+]json(?:;|$)/u.test(type)) return JSON.stringify(body);',
88
+ ' const fields = isBag(body) ? present(body).flatMap(([name, value]) => (Array.isArray(value) ? value : [value]).map((item): [string, unknown] => [name, item])) : [];',
89
+ ' if (type === "application/x-www-form-urlencoded") return new URLSearchParams(fields.map(([name, item]) => [name, atom(item)]));',
90
+ ' if (type !== "multipart/form-data") return body as BodyInit;',
91
+ ' const form = new FormData();',
92
+ ' for (const [name, item] of fields) {',
93
+ ' if (item instanceof Blob) form.append(name, item);',
94
+ ' else form.append(name, atom(item));',
95
+ ' }',
96
+ ' return form;',
97
+ '};',
98
+ '',
99
+ '/** The body of a response; an undeclared one is JSON when it parses and text when it does not. */',
100
+ "const read = async (response: Response, kind: 'json' | 'text' | 'blob' | 'none' | undefined): Promise<unknown> => {",
101
+ ' if (kind === "none") return undefined;',
102
+ ' if (kind === "blob") return response.blob();',
103
+ ' const text = await response.text();',
104
+ ' if (kind === "text" || text === "") return kind === "text" ? text : undefined;',
105
+ ' try {',
106
+ ' return JSON.parse(text) as unknown;',
107
+ ' } catch {',
108
+ ' return text;',
109
+ ' }',
110
+ '};',
111
+ '',
112
+ 'const call = async (options: ClientOptions, route: Route, input: object): Promise<unknown> => {',
113
+ ' const sent = input as Partial<Record<Place, Bag>> & { readonly body?: unknown };',
114
+ ' const headers = new Headers(options.headers);',
115
+ ' const pairs: string[] = [];',
116
+ ' const cookies: string[] = [];',
117
+ ' let path = route.path;',
118
+ ' for (const param of route.params) {',
119
+ ' const value = sent[param.in]?.[param.name];',
120
+ ' if (value === undefined) continue;',
121
+ ' if (param.in === "path") path = path.replaceAll(`{${param.name}}`, simple(value, param.explode, encodeURIComponent));',
122
+ ' else if (param.in === "query") pairs.push(...query(param, value));',
123
+ ' else if (param.in === "header") headers.set(param.name, simple(value, param.explode, String));',
124
+ ' else cookies.push(`${param.name}=${simple(value, false, encodeURIComponent)}`);',
125
+ ' }',
126
+ ' if (cookies.length > 0) headers.set("cookie", cookies.join("; "));',
127
+ ' const init: RequestInit = { method: route.method, headers };',
128
+ ' if (route.body !== undefined && sent.body !== undefined) {',
129
+ ' if (route.body !== "multipart/form-data") headers.set("content-type", route.body);',
130
+ ' init.body = encodeBody(route.body, sent.body);',
131
+ ' }',
132
+ ' const search = pairs.length === 0 ? "" : `?${pairs.join("&")}`;',
133
+ ' const response = await (options.fetch ?? fetch)(`${options.baseUrl.replace(/\\/+$/u, "")}${path}${search}`, init);',
134
+ ' const code = String(response.status);',
135
+ ' const status = [code, `${code.charAt(0)}XX`, "default"].find((candidate) => Object.hasOwn(route.responses, candidate));',
136
+ ' const body = await read(response, status === undefined ? undefined : route.responses[status]);',
137
+ ' const answer = { code: response.status, body, headers: response.headers };',
138
+ ' if (status === undefined) return { status: "unexpected", ...answer };',
139
+ ' const errors = options.validate?.({ operation: route.id, status, body }) ?? [];',
140
+ ' if (errors.length > 0) return { status: "unexpected", ...answer, errors };',
141
+ ' return { status: /^\\d+$/u.test(status) ? Number(status) : status, ...answer };',
142
+ '};',
143
+ ];
144
+ const statusType = (status) => (/^\d+$/u.test(status) ? status : literal(status));
145
+ const routeData = (route) => {
146
+ const data = {
147
+ id: route.id,
148
+ method: route.method.toUpperCase(),
149
+ path: route.path,
150
+ params: route.parameters.map((parameter) => ({ name: parameter.name, in: parameter.in, style: parameter.style, explode: parameter.explode })),
151
+ ...(route.body === undefined ? {} : { body: route.body.type }),
152
+ responses: Object.fromEntries(route.responses.map((response) => [response.key, kindOf(response.media[0]?.type)])),
153
+ };
154
+ return ` ${literal(route.id)}: ${literal(data)},`;
155
+ };
156
+ export const optional = (route) => !route.parameters.some((parameter) => parameter.required) && route.body?.required !== true;
157
+ const bodyType = (route) => {
158
+ if (route.body === undefined)
159
+ return '{ readonly body?: never }';
160
+ const type = `NonNullable<${route.name}["requestBody"]>["content"][${literal(route.body.type)}]`;
161
+ return route.body.required ? `{ readonly body: ${type} }` : `{ readonly body?: ${type} }`;
162
+ };
163
+ const operationTypes = (route) => [
164
+ `type ${route.name} = paths[${literal(route.path)}][${literal(route.method)}];`,
165
+ `export type ${route.name}Input = ${route.name}["parameters"] & ${bodyType(route)};`,
166
+ `export type ${route.name}Result =`,
167
+ ...route.responses.map((response) => ` | Answer<${statusType(response.key)}, BodyOf<${route.name}["responses"][${statusType(response.key)}]>>`),
168
+ ' | Unexpected;',
169
+ '',
170
+ ];
171
+ const method = (route) => ` ${key(route.id)}: async (input: ${route.name}Input${optional(route) ? ' = {}' : ''}): Promise<${route.name}Result> => (await call(options, routes[${literal(route.id)}], input)) as ${route.name}Result,`;
172
+ export const clientFile = (routes, types) => lines(`import type { paths } from ${literal(types)};`, '', ...RUNTIME, '', 'const routes = {', ...routes.map((route) => routeData(route)), '} as const satisfies Readonly<Record<string, Route>>;', '', ...routes.flatMap((route) => operationTypes(route)), '/** One method per operation. A method resolves to the response whatever its status; only a failed request rejects. */', 'export const createClient = (options: ClientOptions) => ({', ...routes.map((route) => method(route)), '});', '', 'export type Client = ReturnType<typeof createClient>;');