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,110 @@
1
+ import { pointerGet } from './core/resolve.js';
2
+ const isDict = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
3
+ const dict = (value) => (isDict(value) ? value : {});
4
+ const METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'];
5
+ const PLACES = ['path', 'query', 'header', 'cookie'];
6
+ const STYLES = {
7
+ path: ['simple'],
8
+ query: ['form', 'spaceDelimited', 'pipeDelimited', 'deepObject'],
9
+ header: ['simple'],
10
+ cookie: ['form'],
11
+ };
12
+ const SENDABLE = ['application/json', 'application/x-www-form-urlencoded', 'multipart/form-data'];
13
+ const decodeToken = (token) => token.replaceAll('~1', '/').replaceAll('~0', '~');
14
+ const pascal = (id) => {
15
+ const name = id.split(/[^A-Za-z0-9]/u).map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join('');
16
+ return /^[A-Za-z]/u.test(name) ? name : `Op${name}`;
17
+ };
18
+ export const routesOf = (contract) => {
19
+ const root = contract.document;
20
+ const findings = [];
21
+ const note = (code, pointer, message, fix) => {
22
+ findings.push({ code, pointer, message, fix });
23
+ };
24
+ const deref = (value) => {
25
+ let node = value;
26
+ const seen = new Set();
27
+ while (isDict(node) && typeof node.$ref === 'string' && !seen.has(node.$ref)) {
28
+ seen.add(node.$ref);
29
+ node = pointerGet(root, node.$ref);
30
+ }
31
+ return dict(node);
32
+ };
33
+ const parameterOf = (entry, at) => {
34
+ const declared = deref(entry);
35
+ const place = String(declared.in);
36
+ if (!PLACES.includes(place)) {
37
+ note('parameter-skipped', at, `the parameter "${String(declared.name)}" is in "${place}", which the client does not send`, 'declare it in path, query, header or cookie');
38
+ return undefined;
39
+ }
40
+ const where = place;
41
+ const [fallback] = STYLES[where];
42
+ const asked = typeof declared.style === 'string' ? declared.style : fallback;
43
+ const style = STYLES[where].includes(asked) ? asked : fallback;
44
+ if (style !== asked)
45
+ note('style-translated', at, `the ${where} style "${asked}" is sent as "${style}"`, `declare \`style: ${style}\`, or send the parameter yourself`);
46
+ const explode = typeof declared.explode === 'boolean' ? declared.explode : style === 'form';
47
+ return { name: String(declared.name), in: where, style, explode, required: where === 'path' || declared.required === true };
48
+ };
49
+ const routeOf = (id, source) => {
50
+ const [, token, method] = /^#\/paths\/([^/]+)\/([^/]+)$/u.exec(source) ?? [];
51
+ if (!METHODS.includes(method)) {
52
+ note('operation-skipped', source, `"${id}" is not a request a client sends`, 'call it yourself; the client covers operations under `paths` with a standard method');
53
+ return undefined;
54
+ }
55
+ const path = decodeToken(token);
56
+ const declared = dict(pointerGet(root, source));
57
+ const item = dict(pointerGet(root, `#/paths/${token}`));
58
+ const byPlace = new Map();
59
+ const lists = [
60
+ [item.parameters, `#/paths/${token}/parameters`],
61
+ [declared.parameters, `${source}/parameters`],
62
+ ];
63
+ for (const [list, at] of lists) {
64
+ for (const [index, entry] of (Array.isArray(list) ? list : []).entries()) {
65
+ const parameter = parameterOf(entry, `${at}/${String(index)}`);
66
+ if (parameter !== undefined)
67
+ byPlace.set(`${parameter.in}:${parameter.name}`, parameter);
68
+ }
69
+ }
70
+ const route = {
71
+ id,
72
+ method: method,
73
+ path,
74
+ parameters: [...byPlace.values()],
75
+ responses: Object.entries(dict(declared.responses)).map(([key, response]) => ({
76
+ key,
77
+ media: Object.entries(dict(deref(response).content)).map(([type, media]) => ({
78
+ type,
79
+ schema: (dict(media).schema ?? true),
80
+ pointer: `${source}/responses/${key}/content/${type.replaceAll('~', '~0').replaceAll('/', '~1')}`,
81
+ declared: dict(media),
82
+ })),
83
+ })),
84
+ };
85
+ if (declared.requestBody !== undefined) {
86
+ const body = deref(declared.requestBody);
87
+ const types = Object.keys(dict(body.content));
88
+ const type = SENDABLE.find((candidate) => types.includes(candidate)) ?? types[0] ?? 'application/json';
89
+ for (const dropped of types.filter((candidate) => candidate !== type)) {
90
+ note('media-type-skipped', `${source}/requestBody`, `the body is sent as ${type}; ${dropped} is not offered`, `call the operation with fetch yourself to send ${dropped}`);
91
+ }
92
+ route.body = { type, required: body.required === true };
93
+ }
94
+ return route;
95
+ };
96
+ const routes = contract.operations
97
+ .map((operation) => routeOf(operation.id, operation.source))
98
+ .filter((route) => route !== undefined)
99
+ .toSorted((a, b) => (a.id < b.id ? -1 : 1));
100
+ const taken = new Set();
101
+ const named = routes.map((route) => {
102
+ const base = pascal(route.id);
103
+ let name = base;
104
+ for (let suffix = 2; taken.has(name); suffix += 1)
105
+ name = `${base}${String(suffix)}`;
106
+ taken.add(name);
107
+ return { ...route, name };
108
+ });
109
+ return { routes: named, findings };
110
+ };
@@ -0,0 +1,155 @@
1
+ export const document = { "openapi": "3.1.0", "paths": { "/pets/{petId}": { "get": { "operationId": "getPet", "parameters": [{ "name": "petId", "in": "path" }, { "name": "fields", "in": "query", "explode": false }], "responses": { "200": { "content": { "application/json": {} } }, "404": {} } } } } };
2
+ export const SAMPLE_CLIENT = `import type { paths } from "./types.js";
3
+
4
+ /** A declared response: the status as the spec writes it, the status received, the body and the headers. */
5
+ export interface Answer<S, B> {
6
+ readonly status: S;
7
+ readonly code: number;
8
+ readonly body: B;
9
+ readonly headers: Headers;
10
+ }
11
+
12
+ /** A status the operation does not declare, or a body \`validate\` refused. Never thrown. */
13
+ export interface Unexpected extends Answer<'unexpected', unknown> {
14
+ /** What \`validate\` reported. */
15
+ readonly errors?: readonly unknown[];
16
+ }
17
+
18
+ type BodyOf<R> = R extends { content: infer C } ? C[keyof C] : undefined;
19
+
20
+ export interface ClientOptions {
21
+ /** Where the API is, e.g. \`https://api.example.com/v1\`. */
22
+ readonly baseUrl: string;
23
+ /** Defaults to the platform \`fetch\`. */
24
+ readonly fetch?: (url: string, init: RequestInit) => Promise<Response>;
25
+ /** Sent with every request. */
26
+ readonly headers?: Readonly<Record<string, string>>;
27
+ /** Checks a declared response body; any error turns the result into \`unexpected\`. */
28
+ readonly validate?: (check: { readonly operation: string; readonly status: string; readonly body: unknown }) => readonly unknown[] | undefined;
29
+ }
30
+
31
+ type Place = 'path' | 'query' | 'header' | 'cookie';
32
+
33
+ interface Param {
34
+ readonly name: string;
35
+ readonly in: Place;
36
+ readonly style: string;
37
+ readonly explode: boolean;
38
+ }
39
+
40
+ interface Route {
41
+ readonly id: string;
42
+ readonly method: string;
43
+ readonly path: string;
44
+ readonly params: readonly Param[];
45
+ readonly body?: string;
46
+ readonly responses: Readonly<Record<string, 'json' | 'text' | 'blob' | 'none'>>;
47
+ }
48
+
49
+ type Bag = Readonly<Record<string, unknown>>;
50
+
51
+ const isBag = (value: unknown): value is Bag => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Blob);
52
+ const atom = (value: unknown): string => (typeof value === "object" && value !== null ? JSON.stringify(value) : String(value));
53
+ const present = (value: Bag): [string, unknown][] => Object.entries(value).filter((entry) => entry[1] !== undefined);
54
+
55
+ /** The \`simple\` style (path and header), each piece through \`encode\`. */
56
+ const simple = (value: unknown, explode: boolean, encode: (text: string) => string): string => {
57
+ if (Array.isArray(value)) return value.map((item) => encode(atom(item))).join(",");
58
+ if (!isBag(value)) return encode(atom(value));
59
+ return present(value).map(([name, item]) => \`\${encode(name)}\${explode ? "=" : ","}\${encode(atom(item))}\`).join(",");
60
+ };
61
+
62
+ const DELIMITERS: Readonly<Record<string, string>> = { spaceDelimited: "%20", pipeDelimited: "|" };
63
+
64
+ /** One query parameter as \`name=value\` pairs, already encoded. */
65
+ const query = (param: Param, value: unknown): string[] => {
66
+ const name = encodeURIComponent(param.name);
67
+ const one = (item: unknown): string => encodeURIComponent(atom(item));
68
+ if (Array.isArray(value)) {
69
+ if (param.explode) return value.map((item) => \`\${name}=\${one(item)}\`);
70
+ return [\`\${name}=\${value.map(one).join(DELIMITERS[param.style] ?? ",")}\`];
71
+ }
72
+ if (!isBag(value)) return [\`\${name}=\${one(value)}\`];
73
+ const entries = present(value);
74
+ if (param.style === "deepObject") return entries.map(([inner, item]) => \`\${name}%5B\${encodeURIComponent(inner)}%5D=\${one(item)}\`);
75
+ if (param.explode) return entries.map(([inner, item]) => \`\${encodeURIComponent(inner)}=\${one(item)}\`);
76
+ return [\`\${name}=\${entries.map(([inner, item]) => \`\${encodeURIComponent(inner)},\${one(item)}\`).join(",")}\`];
77
+ };
78
+
79
+ /** A body as the media type the operation sends. */
80
+ const encodeBody = (type: string, body: unknown): BodyInit => {
81
+ if (/[/+]json(?:;|$)/u.test(type)) return JSON.stringify(body);
82
+ const fields = isBag(body) ? present(body).flatMap(([name, value]) => (Array.isArray(value) ? value : [value]).map((item): [string, unknown] => [name, item])) : [];
83
+ if (type === "application/x-www-form-urlencoded") return new URLSearchParams(fields.map(([name, item]) => [name, atom(item)]));
84
+ if (type !== "multipart/form-data") return body as BodyInit;
85
+ const form = new FormData();
86
+ for (const [name, item] of fields) {
87
+ if (item instanceof Blob) form.append(name, item);
88
+ else form.append(name, atom(item));
89
+ }
90
+ return form;
91
+ };
92
+
93
+ /** The body of a response; an undeclared one is JSON when it parses and text when it does not. */
94
+ const read = async (response: Response, kind: 'json' | 'text' | 'blob' | 'none' | undefined): Promise<unknown> => {
95
+ if (kind === "none") return undefined;
96
+ if (kind === "blob") return response.blob();
97
+ const text = await response.text();
98
+ if (kind === "text" || text === "") return kind === "text" ? text : undefined;
99
+ try {
100
+ return JSON.parse(text) as unknown;
101
+ } catch {
102
+ return text;
103
+ }
104
+ };
105
+
106
+ const call = async (options: ClientOptions, route: Route, input: object): Promise<unknown> => {
107
+ const sent = input as Partial<Record<Place, Bag>> & { readonly body?: unknown };
108
+ const headers = new Headers(options.headers);
109
+ const pairs: string[] = [];
110
+ const cookies: string[] = [];
111
+ let path = route.path;
112
+ for (const param of route.params) {
113
+ const value = sent[param.in]?.[param.name];
114
+ if (value === undefined) continue;
115
+ if (param.in === "path") path = path.replaceAll(\`{\${param.name}}\`, simple(value, param.explode, encodeURIComponent));
116
+ else if (param.in === "query") pairs.push(...query(param, value));
117
+ else if (param.in === "header") headers.set(param.name, simple(value, param.explode, String));
118
+ else cookies.push(\`\${param.name}=\${simple(value, false, encodeURIComponent)}\`);
119
+ }
120
+ if (cookies.length > 0) headers.set("cookie", cookies.join("; "));
121
+ const init: RequestInit = { method: route.method, headers };
122
+ if (route.body !== undefined && sent.body !== undefined) {
123
+ if (route.body !== "multipart/form-data") headers.set("content-type", route.body);
124
+ init.body = encodeBody(route.body, sent.body);
125
+ }
126
+ const search = pairs.length === 0 ? "" : \`?\${pairs.join("&")}\`;
127
+ const response = await (options.fetch ?? fetch)(\`\${options.baseUrl.replace(/\\/+$/u, "")}\${path}\${search}\`, init);
128
+ const code = String(response.status);
129
+ const status = [code, \`\${code.charAt(0)}XX\`, "default"].find((candidate) => Object.hasOwn(route.responses, candidate));
130
+ const body = await read(response, status === undefined ? undefined : route.responses[status]);
131
+ const answer = { code: response.status, body, headers: response.headers };
132
+ if (status === undefined) return { status: "unexpected", ...answer };
133
+ const errors = options.validate?.({ operation: route.id, status, body }) ?? [];
134
+ if (errors.length > 0) return { status: "unexpected", ...answer, errors };
135
+ return { status: /^\\d+$/u.test(status) ? Number(status) : status, ...answer };
136
+ };
137
+
138
+ const routes = {
139
+ "getPet": {"id":"getPet","method":"GET","path":"/pets/{petId}","params":[{"name":"petId","in":"path","style":"simple","explode":false},{"name":"fields","in":"query","style":"form","explode":false}],"responses":{"200":"json","404":"none"}},
140
+ } as const satisfies Readonly<Record<string, Route>>;
141
+
142
+ type GetPet = paths["/pets/{petId}"]["get"];
143
+ export type GetPetInput = GetPet["parameters"] & { readonly body?: never };
144
+ export type GetPetResult =
145
+ | Answer<200, BodyOf<GetPet["responses"][200]>>
146
+ | Answer<404, BodyOf<GetPet["responses"][404]>>
147
+ | Unexpected;
148
+
149
+ /** One method per operation. A method resolves to the response whatever its status; only a failed request rejects. */
150
+ export const createClient = (options: ClientOptions) => ({
151
+ getPet: async (input: GetPetInput): Promise<GetPetResult> => (await call(options, routes["getPet"], input)) as GetPetResult,
152
+ });
153
+
154
+ export type Client = ReturnType<typeof createClient>;
155
+ `;
@@ -0,0 +1,5 @@
1
+ const UNSAFE = { '<': '\\u003C', '>': '\\u003E', '\u2028': '\\u2028', '\u2029': '\\u2029' };
2
+ export const literal = (value) => JSON.stringify(value).replaceAll(/[<>\u2028\u2029]/gu, (character) => UNSAFE[character]);
3
+ export const lines = (...text) => `${text.join('\n')}\n`;
4
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/u;
5
+ export const key = (name) => (IDENTIFIER.test(name) ? name : literal(name));
@@ -0,0 +1,19 @@
1
+ import { clientFile } from './plugin-fetch-client.js';
2
+ import { routesOf } from './plugin-fetch-routes.js';
3
+ import { document, SAMPLE_CLIENT } from './plugin-fetch-sample.js';
4
+ export const CLIENT_FILE = 'client.ts';
5
+ const run = (contract, options) => {
6
+ const { routes, findings } = routesOf(contract);
7
+ const types = typeof options.types === 'string' ? options.types : './types.js';
8
+ const files = [
9
+ { path: CLIENT_FILE, owner: 'generated', content: clientFile(routes, types), symbols: routes.map((route) => ({ operation: route.id, symbol: route.name })) },
10
+ ];
11
+ return { files, findings };
12
+ };
13
+ const fetchTarget = {
14
+ description: 'A typed client over the platform fetch: one method per operation, every response a typed result, nothing thrown on a non-2xx',
15
+ inputs: ['openapi'],
16
+ sample: { document, files: [{ path: CLIENT_FILE, owner: 'generated', content: SAMPLE_CLIENT }] },
17
+ run,
18
+ };
19
+ export const plugin = { name: 'fetch', generators: { fetch: fetchTarget } };
@@ -0,0 +1,42 @@
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 HONO = {
7
+ target: 'hono',
8
+ name: 'Hono',
9
+ path: colonPath,
10
+ imports: ["import { type Env, type Hono } from 'hono';"],
11
+ register: [
12
+ '/** Register every route on `app`: each reads and checks the request, calls its handler, and checks what it answers. */',
13
+ 'export const registerRoutes = <E extends Env>(app: Hono<E>, handlers: Handlers): void => {',
14
+ ' for (const route of routes) {',
15
+ ' app.on(route.method, route.path, async (c) => {',
16
+ ' const answer = await handle(route, handlers, { path: c.req.param(), query: c.req.queries(), header: c.req.header(), body: route.body === undefined ? undefined : await c.req.text() });',
17
+ ' return new Response(answer.body ?? null, { status: answer.status, headers: answer.headers });',
18
+ ' });',
19
+ ' }',
20
+ '};',
21
+ ],
22
+ usage: 'Serve them with `registerRoutes(app, handlers)` from routes.ts.',
23
+ harness: {
24
+ framework: ["import { Hono } from 'hono';"],
25
+ hooks: [],
26
+ local: ["import { handlers } from './handlers.js';", "import { registerRoutes } from './routes.js';"],
27
+ setup: [' const app = new Hono();', ' registerRoutes(app, handlers);', ''],
28
+ call: (url, init) => `app.request(${url}, ${init})`,
29
+ },
30
+ };
31
+ export const run = (contract, options) => runRouter(HONO, contract, options);
32
+ const hono = {
33
+ description: 'Hono routes: a generated route table and registerRoutes(app, handlers) that validate requests and responses, handlers you own, and a contract test per operation',
34
+ inputs: ['openapi'],
35
+ options: SERVER_OPTIONS,
36
+ sample: {
37
+ document: SAMPLE_DOCUMENT,
38
+ files: run(read(SAMPLE_DOCUMENT), {}).files,
39
+ },
40
+ run,
41
+ };
42
+ export const plugin = { name: 'hono', generators: { hono } };
@@ -0,0 +1,289 @@
1
+ import { pointerGet } from './core/resolve.js';
2
+ import { unique } from './plugin-validator-names.js';
3
+ const isDict = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
4
+ export const URI_2020 = 'https://json-schema.org/draft/2020-12/schema';
5
+ export const URI_07 = 'http://json-schema.org/draft-07/schema#';
6
+ export const KEYWORDS = new Map([
7
+ ['additionalProperties', 'schema'],
8
+ ['propertyNames', 'schema'],
9
+ ['items', 'schema'],
10
+ ['contains', 'schema'],
11
+ ['not', 'schema'],
12
+ ['if', 'schema'],
13
+ ['then', 'schema'],
14
+ ['else', 'schema'],
15
+ ['unevaluatedItems', 'schema'],
16
+ ['unevaluatedProperties', 'schema'],
17
+ ['contentSchema', 'schema'],
18
+ ['allOf', 'list'],
19
+ ['anyOf', 'list'],
20
+ ['oneOf', 'list'],
21
+ ['prefixItems', 'list'],
22
+ ['properties', 'map'],
23
+ ['patternProperties', 'map'],
24
+ ['dependentSchemas', 'map'],
25
+ ['type', 'data'],
26
+ ['enum', 'data'],
27
+ ['const', 'data'],
28
+ ['required', 'data'],
29
+ ['multipleOf', 'data'],
30
+ ['maximum', 'data'],
31
+ ['exclusiveMaximum', 'data'],
32
+ ['minimum', 'data'],
33
+ ['exclusiveMinimum', 'data'],
34
+ ['maxLength', 'data'],
35
+ ['minLength', 'data'],
36
+ ['pattern', 'data'],
37
+ ['maxItems', 'data'],
38
+ ['minItems', 'data'],
39
+ ['uniqueItems', 'data'],
40
+ ['maxContains', 'data'],
41
+ ['minContains', 'data'],
42
+ ['maxProperties', 'data'],
43
+ ['minProperties', 'data'],
44
+ ['dependentRequired', 'data'],
45
+ ['format', 'data'],
46
+ ['contentEncoding', 'data'],
47
+ ['contentMediaType', 'data'],
48
+ ['title', 'data'],
49
+ ['description', 'data'],
50
+ ['default', 'data'],
51
+ ['deprecated', 'data'],
52
+ ['readOnly', 'data'],
53
+ ['writeOnly', 'data'],
54
+ ['examples', 'data'],
55
+ ['$comment', 'data'],
56
+ ]);
57
+ const DEFS = new Set(['$defs', 'definitions']);
58
+ export const sourceOf = (contract) => {
59
+ const document = isDict(contract.document) ? contract.document : {};
60
+ if (contract.format === 'openapi')
61
+ return String(document.openapi).startsWith('3.0') ? 'oas30' : '2020-12';
62
+ if (contract.format === 'swagger2')
63
+ return 'oas30';
64
+ if (contract.format === 'asyncapi')
65
+ return '07';
66
+ return typeof document.$schema === 'string' && /draft-0[467]/u.test(document.$schema) ? '07' : '2020-12';
67
+ };
68
+ const token = (key) => key.replaceAll('~', '~0').replaceAll('/', '~1');
69
+ const quoted = (keys) => keys.map((key) => `\`${key}\``).join(', ');
70
+ const report = (state) => (code, pointer, message, fix) => {
71
+ state.findings.push({ code, pointer, message: `${state.options.label}: ${message}`, fix });
72
+ };
73
+ const invalid = (state, at, what) => {
74
+ throw new Error(`cannot generate ${state.options.label}: the schema at "${at}" ${what}. fix: correct the document, or validate it against its dialect's meta-schema first`);
75
+ };
76
+ const without = (schema, ...keys) => Object.fromEntries(Object.entries(schema).filter(([key]) => !keys.includes(key)));
77
+ const lone = (state, schema, at) => {
78
+ const beside = Object.keys(schema).filter((key) => key !== '$ref');
79
+ if (beside.length > 0) {
80
+ report(state)('keyword-dropped', at, `${quoted(beside)} beside \`$ref\` ${beside.length === 1 ? 'is' : 'are'} ignored by the source's dialect, and left out`, 'move them into the referenced schema, or put the `$ref` under `allOf` beside them');
81
+ }
82
+ return { $ref: schema.$ref };
83
+ };
84
+ const exclusive = (state, schema, at) => {
85
+ let out = schema;
86
+ for (const [flag, bound] of [
87
+ ['exclusiveMinimum', 'minimum'],
88
+ ['exclusiveMaximum', 'maximum'],
89
+ ]) {
90
+ const on = out[flag];
91
+ if (typeof on !== 'boolean')
92
+ continue;
93
+ const value = out[bound];
94
+ out = without(out, flag, bound);
95
+ if (value === undefined) {
96
+ report(state)('keyword-dropped', `${at}/${flag}`, `\`${flag}: ${String(on)}\` is the boolean form of draft-04, and there is no \`${bound}\` beside it: it is left out`, 'nothing to do: it says nothing without the bound');
97
+ continue;
98
+ }
99
+ out = { ...out, [on ? flag : bound]: value };
100
+ report(state)('keyword-rewritten', `${at}/${flag}`, `\`${flag}: ${String(on)}\` is the boolean form of draft-04: written as ${on ? `\`${flag}: ${String(value)}\`` : `\`${bound}\` alone`}`, 'nothing to do: the document means the same');
101
+ }
102
+ return out;
103
+ };
104
+ const nullable = (state, schema, at) => {
105
+ const rest = without(schema, 'nullable');
106
+ if (schema.nullable !== true)
107
+ return rest;
108
+ if (typeof rest.type === 'string') {
109
+ report(state)('keyword-rewritten', `${at}/nullable`, `\`nullable: true\` is written as \`type: ["${rest.type}", "null"]\``, 'nothing to do: the document means the same');
110
+ return { ...rest, type: [rest.type, 'null'] };
111
+ }
112
+ report(state)('keyword-dropped', `${at}/nullable`, '`nullable: true` without a `type` adds nothing in OpenAPI 3.0.3, and is left out', 'give the schema a `type`, or write `type: [..., "null"]` once on OpenAPI 3.1');
113
+ return rest;
114
+ };
115
+ const example = (state, schema, at) => {
116
+ if (!('example' in schema))
117
+ return schema;
118
+ const rest = without(schema, 'example');
119
+ if (rest.examples === undefined) {
120
+ report(state)('keyword-rewritten', `${at}/example`, '`example` is written as `examples: [example]`', 'nothing to do: the document means the same');
121
+ return { ...rest, examples: [schema.example] };
122
+ }
123
+ report(state)('keyword-dropped', `${at}/example`, '`example` beside `examples` is left out', 'move the example into `examples`');
124
+ return rest;
125
+ };
126
+ const fromDraft07 = (state, schema, at) => {
127
+ let out = schema;
128
+ if (Array.isArray(out.items)) {
129
+ report(state)('keyword-rewritten', `${at}/items`, 'draft-07\'s list of `items` is written as `prefixItems`, and `additionalItems` as `items`', 'nothing to do: the document means the same');
130
+ const rest = without(out, 'items', 'additionalItems');
131
+ out = { ...rest, prefixItems: out.items, ...(out.additionalItems !== undefined && { items: out.additionalItems }) };
132
+ }
133
+ if (isDict(out.dependencies)) {
134
+ report(state)('keyword-rewritten', `${at}/dependencies`, '`dependencies` is written as `dependentRequired` (lists of keys) and `dependentSchemas` (schemas)', 'nothing to do: the document means the same');
135
+ const entries = Object.entries(out.dependencies);
136
+ const keys = entries.filter(([, value]) => Array.isArray(value));
137
+ const schemas = entries.filter(([, value]) => !Array.isArray(value));
138
+ out = {
139
+ ...without(out, 'dependencies'),
140
+ ...(keys.length > 0 && { dependentRequired: Object.fromEntries(keys) }),
141
+ ...(schemas.length > 0 && { dependentSchemas: Object.fromEntries(schemas) }),
142
+ };
143
+ }
144
+ return out;
145
+ };
146
+ const normalise = (state, schema, at) => {
147
+ const { source } = state.options;
148
+ if (typeof schema.$ref === 'string' && source !== '2020-12')
149
+ return lone(state, schema, at);
150
+ let out = example(state, exclusive(state, schema, at), at);
151
+ if (source === 'oas30')
152
+ out = nullable(state, out, at);
153
+ if (source === '07')
154
+ out = fromDraft07(state, out, at);
155
+ return out;
156
+ };
157
+ const define = (state, ref, target) => {
158
+ const known = state.defs.get(ref);
159
+ if (known !== undefined)
160
+ return known.name;
161
+ const last = ref.split('/').at(-1).replaceAll('~1', '/').replaceAll('~0', '~');
162
+ const base = ref === '#' ? 'root' : decodeURIComponent(last).replaceAll(/[^\w.-]/gu, '_') || 'def';
163
+ const name = unique(base, state.names);
164
+ const def = { name, schema: true };
165
+ state.defs.set(ref, def);
166
+ def.schema = walk(state, target, { at: ref, open: new Set([ref]) });
167
+ return name;
168
+ };
169
+ const referenced = (state, ref, beside, { at, open }) => {
170
+ if (typeof ref !== 'string')
171
+ return invalid(state, at, 'has a `$ref` that is not a string');
172
+ if (ref !== '#' && !ref.startsWith('#/')) {
173
+ report(state)('ref-unresolved', `${at}/$ref`, `\`$ref: ${JSON.stringify(ref)}\` is not a JSON Pointer into this document, and is left out: the document accepts any value there`, 'bundle the document first, so every `$ref` is a `#/…` pointer');
174
+ return beside;
175
+ }
176
+ const target = pointerGet(state.document, ref);
177
+ const inline = state.options.refs !== 'keep';
178
+ if (inline && !open.has(ref)) {
179
+ const inlined = walk(state, target, { at: ref, open: new Set(open).add(ref) });
180
+ if (Object.keys(beside).length === 0)
181
+ return inlined;
182
+ return { ...beside, allOf: [inlined, ...(Array.isArray(beside.allOf) ? beside.allOf : [])] };
183
+ }
184
+ if (inline && !state.cut.has(ref)) {
185
+ state.cut.add(ref);
186
+ report(state)('ref-cycle-kept', ref, `\`${ref}\` refers to itself, so it cannot be inlined: it is kept under \`$defs\``, 'nothing to do; or generate with `refs: keep`');
187
+ }
188
+ return { $ref: `#/$defs/${define(state, ref, target)}`, ...beside };
189
+ };
190
+ const child = (state, kind, value, { at, open }) => {
191
+ if (kind === 'data')
192
+ return value;
193
+ if (kind === 'schema')
194
+ return walk(state, value, { at, open });
195
+ if (kind === 'list') {
196
+ if (!Array.isArray(value))
197
+ return invalid(state, at, 'is not a list of schemas');
198
+ return value.map((item, index) => walk(state, item, { at: `${at}/${String(index)}`, open }));
199
+ }
200
+ if (!isDict(value))
201
+ return invalid(state, at, 'is not an object of schemas');
202
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, walk(state, item, { at: `${at}/${token(key)}`, open })]));
203
+ };
204
+ function walk(state, schema, place, root = false) {
205
+ const { at, open } = place;
206
+ if (typeof schema === 'boolean')
207
+ return schema;
208
+ if (!isDict(schema))
209
+ return invalid(state, at, 'is neither an object nor a boolean');
210
+ const normal = normalise(state, schema, at);
211
+ const entries = Object.entries(normal);
212
+ const out = Object.fromEntries(entries.flatMap(([key, value]) => {
213
+ const kind = KEYWORDS.get(key);
214
+ return kind === undefined ? [] : [[key, child(state, kind, value, { at: `${at}/${token(key)}`, open })]];
215
+ }));
216
+ const dropped = entries.map(([key]) => key).filter((key) => !KEYWORDS.has(key) && key !== '$ref' && !DEFS.has(key) && !(root && key === '$schema'));
217
+ if (dropped.length > 0) {
218
+ report(state)('keyword-dropped', at, `${quoted(dropped)} ${dropped.length === 1 ? 'is not a keyword' : 'are not keywords'} a JSON Schema validator applies here, and ${dropped.length === 1 ? 'is' : 'are'} left out`, 'move what it means into a keyword the dialect has, or into `description`');
219
+ }
220
+ return '$ref' in normal ? referenced(state, normal.$ref, out, place) : out;
221
+ }
222
+ const body = (schema) => {
223
+ if (schema === true)
224
+ return {};
225
+ return schema === false ? { not: {} } : schema;
226
+ };
227
+ const tuple07 = (out, say) => {
228
+ if (!('prefixItems' in out))
229
+ return out;
230
+ say('keyword-rewritten', '`prefixItems` is written as draft-07\'s list of `items`, and `items` as `additionalItems`', 'nothing to do: the document means the same');
231
+ return { ...without(out, 'prefixItems'), items: out.prefixItems, ...(out.items !== undefined && { additionalItems: out.items }) };
232
+ };
233
+ const dependencies07 = (out, say) => {
234
+ if (!('dependentRequired' in out || 'dependentSchemas' in out))
235
+ return out;
236
+ say('keyword-rewritten', '`dependentRequired` and `dependentSchemas` are written as `dependencies`', 'nothing to do: the document means the same');
237
+ return { ...without(out, 'dependentRequired', 'dependentSchemas'), dependencies: { ...out.dependentRequired, ...out.dependentSchemas } };
238
+ };
239
+ const missing07 = (out, say) => {
240
+ const missing = ['minContains', 'maxContains', 'unevaluatedItems', 'unevaluatedProperties'].filter((key) => key in out);
241
+ if (missing.length === 0)
242
+ return out;
243
+ say('keyword-dropped', `draft-07 has no ${quoted(missing)}, and ${missing.length === 1 ? 'it is' : 'they are'} left out: the document accepts more than the schema`, 'generate with `draft: 2020-12`');
244
+ return without(out, ...missing);
245
+ };
246
+ const ref07 = (out, say) => {
247
+ const beside = Object.keys(out).filter((key) => !['$ref', '$schema', '$defs'].includes(key));
248
+ if (!('$ref' in out) || beside.length === 0)
249
+ return out;
250
+ say('keyword-rewritten', '`$ref` with keywords beside it is written under `allOf`, which draft-07 does not ignore', 'nothing to do: the document means the same');
251
+ const rest = without(out, '$ref');
252
+ return { ...rest, allOf: [{ $ref: out.$ref }, ...(Array.isArray(rest.allOf) ? rest.allOf : [])] };
253
+ };
254
+ const value07 = (state, key, value, path) => {
255
+ const kind = key === '$defs' ? 'map' : KEYWORDS.get(key);
256
+ if (key === '$ref')
257
+ return value.replace('#/$defs/', '#/definitions/');
258
+ if (kind === 'schema')
259
+ return toDraft07(state, value, `${path}/${key}`);
260
+ if (kind === 'list')
261
+ return value.map((item, index) => toDraft07(state, item, `${path}/${key}/${String(index)}`));
262
+ if (kind === 'map')
263
+ return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, toDraft07(state, item, `${path}/${key}/${token(name)}`)]));
264
+ return value;
265
+ };
266
+ function toDraft07(state, schema, path) {
267
+ if (!isDict(schema))
268
+ return schema;
269
+ const say = (code, message, fix) => {
270
+ report(state)(code, state.options.at, `at "${path}" in the document, ${message}`, fix);
271
+ };
272
+ const out = Object.fromEntries(Object.entries(schema).map(([key, value]) => [key, value07(state, key, value, path)]));
273
+ return ref07(missing07(dependencies07(tuple07(out, say), say), say), say);
274
+ }
275
+ export const build = (document, schema, options) => {
276
+ const state = { document, options, findings: [], defs: new Map(), names: new Set(), cut: new Set() };
277
+ const top = body(walk(state, schema, { at: options.at, open: new Set() }, true));
278
+ const defs = state.defs.size === 0 ? {} : { $defs: Object.fromEntries([...state.defs.values()].map((def) => [def.name, def.schema])) };
279
+ const whole = { $schema: URI_2020, ...top, ...defs };
280
+ if (options.draft === '2020-12')
281
+ return { schema: whole, findings: state.findings };
282
+ const down = toDraft07(state, whole, '');
283
+ const shared = down.$defs;
284
+ const rest = without(down, '$defs', '$schema');
285
+ if (shared !== undefined) {
286
+ report(state)('keyword-rewritten', options.at, '`$defs` is written as draft-07\'s `definitions`', 'nothing to do: the document means the same');
287
+ }
288
+ return { schema: { $schema: URI_07, ...rest, ...(shared !== undefined && { definitions: shared }) }, findings: state.findings };
289
+ };