contractdiff 0.0.0-stage → 0.4.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.
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 +408 -0
  150. package/dist/props-judge.js +30 -0
  151. package/dist/props-mutate.js +144 -0
  152. package/dist/props-random.js +25 -0
  153. package/dist/props-run.js +170 -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,159 @@
1
+ import { parse as parseYaml } from 'seniority/yaml';
2
+ import { camel, commandParts, editScripts, finding, scripts } from './migrate-shared.js';
3
+ const CARRIED = new Set([
4
+ 'additional-properties',
5
+ 'alphabetize',
6
+ 'array-length',
7
+ 'default-non-nullable',
8
+ 'properties-required-by-default',
9
+ 'empty-objects-unknown',
10
+ 'enum',
11
+ 'enum-values',
12
+ 'conditional-enums',
13
+ 'dedupe-enums',
14
+ 'exclude-deprecated',
15
+ 'export-type',
16
+ 'immutable',
17
+ 'path-params-as-types',
18
+ 'root-types',
19
+ 'root-types-no-schema-prefix',
20
+ 'root-types-keep-casing',
21
+ 'make-paths-enum',
22
+ 'generate-path-params',
23
+ 'read-write-markers',
24
+ ]);
25
+ const ALIASES = new Map([
26
+ ['-o', '--output'],
27
+ ['-t', '--export-type'],
28
+ ]);
29
+ const RUNNERS = new Set(['npx', 'bunx', 'pnpx', 'pnpm', 'yarn', 'npm', 'exec', 'dlx']);
30
+ export const STDOUT_OUT = 'schema.ts';
31
+ const words = (command) => [...command.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/gu)].map((match) => match[1] ?? match[2] ?? match[3]);
32
+ const flagValue = (value) => {
33
+ if (value === undefined || value === 'true')
34
+ return true;
35
+ return value === 'false' ? false : value;
36
+ };
37
+ const parseArgs = (args, pointer) => {
38
+ let input;
39
+ let out;
40
+ let check = false;
41
+ const options = new Map();
42
+ const findings = [];
43
+ for (let index = 0; index < args.length; index += 1) {
44
+ const word = args[index];
45
+ const equals = word.indexOf('=');
46
+ const rawName = equals === -1 ? word : word.slice(0, equals);
47
+ const inline = equals === -1 ? undefined : word.slice(equals + 1);
48
+ const name = ALIASES.get(rawName) ?? rawName;
49
+ const next = () => {
50
+ if (inline !== undefined)
51
+ return inline;
52
+ index += 1;
53
+ return args[index];
54
+ };
55
+ if (name === '>')
56
+ out = next();
57
+ else if (name === '--output')
58
+ out = next();
59
+ else if (name === '--check')
60
+ check = true;
61
+ else if (name.startsWith('--') && CARRIED.has(name.slice(2)))
62
+ options.set(camel(name.slice(2)), flagValue(inline));
63
+ else if (name === '--redocly') {
64
+ findings.push(finding('option-dropped', pointer, `\`--redocly ${String(next())}\` names a config this migration did not read`, 'move its `apis` into `redocly.yaml` at the project root and run the migration again'));
65
+ }
66
+ else if (name.startsWith('-')) {
67
+ findings.push(finding('option-dropped', pointer, `\`${word}\` is not an openapi-typescript flag contractdiff carries`, 'remove it; `contractdiff gen --help` lists what the types target takes'));
68
+ }
69
+ else
70
+ input ??= word;
71
+ }
72
+ return { run: { input, out, options: Object.fromEntries(options), pointer, findings }, check };
73
+ };
74
+ const fromScripts = (files) => {
75
+ const runs = [];
76
+ const replaced = new Map();
77
+ for (const [name, command] of Object.entries(scripts(files))) {
78
+ const parts = commandParts(command);
79
+ const rewritten = parts.map((part) => {
80
+ const list = words(part);
81
+ const at = list.indexOf('openapi-typescript');
82
+ if (at === -1)
83
+ return part;
84
+ const { run, check } = parseArgs(list.slice(at + 1), `package.json#/scripts/${name}`);
85
+ runs.push(run);
86
+ const before = list.slice(0, at);
87
+ while (RUNNERS.has(before.at(-1)))
88
+ before.pop();
89
+ return [...before, 'contractdiff', 'gen', ...(check ? ['--check'] : [])].join(' ');
90
+ });
91
+ if (rewritten.join('') !== command)
92
+ replaced.set(name, rewritten.join(''));
93
+ }
94
+ return { runs, replaced: Object.fromEntries(replaced) };
95
+ };
96
+ const isDict = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
97
+ const fromApi = (name, api) => {
98
+ const pointer = `redocly.yaml#/apis/${name}`;
99
+ if (!isDict(api) || !isDict(api['x-openapi-ts']))
100
+ return [];
101
+ const { output, ...flags } = api['x-openapi-ts'];
102
+ const options = new Map();
103
+ const dropped = [];
104
+ for (const [flag, value] of Object.entries(flags)) {
105
+ const kebab = flag.replaceAll(/[A-Z]/gu, (letter) => `-${letter.toLowerCase()}`);
106
+ if (CARRIED.has(kebab))
107
+ options.set(camel(kebab), value);
108
+ else
109
+ dropped.push(finding('option-dropped', `${pointer}/x-openapi-ts/${flag}`, `\`${flag}\` is not an openapi-typescript option contractdiff carries`, 'remove it; `contractdiff gen --help` lists what the types target takes'));
110
+ }
111
+ return [{ input: typeof api.root === 'string' ? api.root : undefined, out: typeof output === 'string' ? output : undefined, options: Object.fromEntries(options), pointer, findings: dropped }];
112
+ };
113
+ const fromRedocly = (text) => {
114
+ const findings = [];
115
+ let parsed;
116
+ try {
117
+ parsed = parseYaml(text);
118
+ }
119
+ catch (error) {
120
+ return { runs: [], findings: [finding('config-unreadable', 'redocly.yaml', `redocly.yaml is not YAML this migration reads: ${error.message}`, 'fix the YAML, or write contractdiff.config.json by hand')] };
121
+ }
122
+ const root = isDict(parsed) ? parsed : {};
123
+ for (const key of Object.keys(root).filter((name) => name !== 'apis')) {
124
+ findings.push(finding('option-dropped', `redocly.yaml#/${key}`, `\`${key}\` configures Redocly, not the types`, 'keep redocly.yaml for `redocly lint`; contractdiff does not read it'));
125
+ }
126
+ const runs = Object.entries(isDict(root.apis) ? root.apis : {}).flatMap(([name, api]) => fromApi(name, api));
127
+ return { runs, findings };
128
+ };
129
+ const assemble = (runs) => {
130
+ const findings = runs.flatMap((run) => run.findings);
131
+ const input = runs.find((run) => run.input !== undefined)?.input;
132
+ if (input === undefined) {
133
+ findings.push(finding('nothing-to-migrate', 'package.json#/scripts', 'no script runs openapi-typescript on a document, and redocly.yaml names no api with `x-openapi-ts`', 'run `contractdiff plugin new` or write contractdiff.config.json by hand'));
134
+ return { config: undefined, findings };
135
+ }
136
+ if (/^https?:\/\//u.test(input)) {
137
+ findings.push(finding('remote-input', 'contractdiff.config.json#/input', `${input} is fetched over the network, and contractdiff reads local files`, 'download the document into the project and point `input` at it'));
138
+ }
139
+ const targets = new Map();
140
+ for (const run of runs.filter((one) => one.input !== undefined)) {
141
+ if (run.input !== input) {
142
+ findings.push(finding('second-input', run.pointer, `${run.input} is a second input, and one contractdiff.config.json reads one`, 'write a second contractdiff.config.json for it in its own folder'));
143
+ continue;
144
+ }
145
+ if (run.out === undefined) {
146
+ findings.push(finding('stdout-output', run.pointer, 'openapi-typescript printed to stdout, and contractdiff writes a file', `the target writes ${STDOUT_OUT}: change \`out\` to where the types belong`));
147
+ }
148
+ const name = targets.size === 0 ? 'types' : `types-${String(targets.size + 1)}`;
149
+ targets.set(name, { generator: 'types', out: run.out ?? STDOUT_OUT, options: { compat: 'openapi-typescript', ...run.options } });
150
+ }
151
+ return { config: { input, targets: Object.fromEntries(targets) }, findings };
152
+ };
153
+ export const migrate = (configText, files) => {
154
+ const scripted = fromScripts(files);
155
+ const redocly = configText === undefined ? { runs: [], findings: [] } : fromRedocly(configText);
156
+ const { config, findings } = assemble([...scripted.runs, ...redocly.runs]);
157
+ const { edits, findings: unwritten } = editScripts(files, scripted.replaced);
158
+ return { config, edits, findings: [...redocly.findings, ...findings, ...unwritten], uninstall: 'npm uninstall openapi-typescript' };
159
+ };
@@ -0,0 +1,119 @@
1
+ import { isUnreadable, readExport } from './migrate-literal.js';
2
+ import { commandParts, editScripts, finding, scripts } from './migrate-shared.js';
3
+ const CLIENTS = new Map([
4
+ ['fetch', ['fetch']],
5
+ ['axios', ['fetch']],
6
+ ['axios-functions', ['fetch']],
7
+ ['react-query', ['fetch', 'tanstack-query']],
8
+ ['swr', ['fetch', 'swr']],
9
+ ['zod', ['validator']],
10
+ ['hono', ['hono']],
11
+ ['mcp', ['mcp']],
12
+ ]);
13
+ const TRANSLATED = new Map([
14
+ ['axios-functions', 'the `fetch` target, which calls `fetch` and not axios'],
15
+ ['axios', 'the `fetch` target, which calls `fetch` and not axios'],
16
+ ['zod', "the `validator` target, contractdiff's own validators and not Zod"],
17
+ ]);
18
+ const DEFAULT_CLIENT = 'axios-functions';
19
+ const READ = new Set(['target', 'schemas', 'client', 'mock']);
20
+ const isDict = (value) => typeof value === 'object' && value !== null && !Array.isArray(value) && !isUnreadable(value);
21
+ const text = (value) => (isUnreadable(value) ? value.unreadable : JSON.stringify(value));
22
+ const dropped = (pointer, key) => finding('option-dropped', `${pointer}/${key}`, `\`${key}\` has no counterpart in contractdiff`, 'remove it, or carry it over by hand; `contractdiff gen --help` lists what each target takes');
23
+ const unreadable = (pointer, value) => finding('unreadable', pointer, `\`${text(value)}\` is not data this migration can read`, 'write the value out as a literal, or carry it over by hand');
24
+ const targetOf = (value, pointer, findings, read) => {
25
+ if (typeof value === 'string')
26
+ return value;
27
+ if (!isDict(value)) {
28
+ if (value !== undefined)
29
+ findings.push(unreadable(pointer, value));
30
+ return undefined;
31
+ }
32
+ for (const key of Object.keys(value).filter((name) => !read.has(name)))
33
+ findings.push(dropped(pointer, key));
34
+ return targetOf(value.target, `${pointer}/target`, findings, read);
35
+ };
36
+ const targetsOf = (settings, out, pointer, findings) => {
37
+ const targets = new Map([['types', { generator: 'types', out: typeof settings.schemas === 'string' ? settings.schemas : out }]]);
38
+ const client = settings.client ?? DEFAULT_CLIENT;
39
+ const generators = CLIENTS.get(client) ?? [];
40
+ const translated = TRANSLATED.get(client);
41
+ if (typeof client !== 'string')
42
+ findings.push(unreadable(`${pointer}/output/client`, client));
43
+ else if (translated !== undefined)
44
+ findings.push(finding('client-translated', `${pointer}/output/client`, `the \`${client}\` client becomes ${translated}`, `check the call sites after \`contractdiff gen\`, or keep orval for ${client}`));
45
+ else if (generators.length === 0)
46
+ findings.push(finding('client-dropped', `${pointer}/output/client`, `the \`${client}\` client has no contractdiff target`, 'keep orval for it, or write the plugin: `contractdiff plugin new`'));
47
+ for (const generator of generators)
48
+ targets.set(generator, { generator, out });
49
+ if (settings.mock === true)
50
+ targets.set('msw', { generator: 'msw', out });
51
+ else if (settings.mock !== undefined && settings.mock !== false)
52
+ findings.push(finding('option-dropped', `${pointer}/output/mock`, 'mock options other than `true` have no counterpart in contractdiff', 'set `mock: true` and run the migration again, or carry the options over by hand'));
53
+ findings.push(finding('imports-change', `${pointer}/output`, `the files under ${out} are written with contractdiff's module names, not orval's`, `after \`contractdiff gen\`, point imports of ${out} at the targets' files`));
54
+ return Object.fromEntries(targets);
55
+ };
56
+ const project = (name, value, findings) => {
57
+ const pointer = `orval.config#/${name}`;
58
+ if (!isDict(value)) {
59
+ findings.push(unreadable(pointer, value));
60
+ return undefined;
61
+ }
62
+ const { input, output, ...rest } = value;
63
+ for (const key of Object.keys(rest))
64
+ findings.push(dropped(pointer, key));
65
+ const path = targetOf(input, `${pointer}/input`, findings, new Set(['target']));
66
+ const out = targetOf(output, `${pointer}/output`, findings, READ);
67
+ if (path === undefined || out === undefined) {
68
+ findings.push(finding('nothing-to-migrate', pointer, `the \`${name}\` project names no input or no output`, 'set `input` and `output` and run the migration again'));
69
+ return undefined;
70
+ }
71
+ if (/^https?:\/\//u.test(path))
72
+ findings.push(finding('remote-input', 'contractdiff.config.json#/input', `${path} is fetched over the network, and contractdiff reads local files`, 'download the document into the project and point `input` at it'));
73
+ return { input: path, targets: targetsOf(isDict(output) ? output : {}, out, pointer, findings) };
74
+ };
75
+ const BINARY = /^(\s*)(?:npx\s+)?orval((?:\s.*)?)$/u;
76
+ const fromFlags = (args) => {
77
+ const pairs = [];
78
+ for (let index = 0; index + 1 < args.length; index += 2)
79
+ pairs.push([args[index].replace(/^-+/u, ''), args[index + 1]]);
80
+ const { input, output, client, ...rest } = Object.fromEntries(pairs);
81
+ if (input === undefined)
82
+ return undefined;
83
+ return { cli: { input, output: { target: output, client }, ...rest } };
84
+ };
85
+ export const migrate = (configText, files) => {
86
+ const findings = [];
87
+ const replaced = new Map();
88
+ let args;
89
+ for (const [name, command] of Object.entries(scripts(files))) {
90
+ const parts = commandParts(command);
91
+ const rewritten = parts
92
+ .map((part) => {
93
+ const found = BINARY.exec(part);
94
+ if (found === null)
95
+ return part;
96
+ args ??= found[2].trim().split(/\s+/u);
97
+ return `${found[1]}contractdiff gen`;
98
+ })
99
+ .join('');
100
+ if (rewritten !== command)
101
+ replaced.set(name, rewritten);
102
+ }
103
+ const flags = args === undefined ? undefined : fromFlags(args);
104
+ const value = configText === undefined ? flags : readExport(configText);
105
+ let config;
106
+ if (isDict(value)) {
107
+ const [first, ...rest] = Object.entries(value);
108
+ for (const [name] of rest)
109
+ findings.push(finding('second-input', `orval.config#/${name}`, `the \`${name}\` project is a second input, and one contractdiff.config.json reads one`, 'write a second contractdiff.config.json for it in its own folder'));
110
+ config = first === undefined ? undefined : project(first[0], first[1], findings);
111
+ if (first === undefined)
112
+ findings.push(finding('nothing-to-migrate', 'orval.config', 'the config names no project', 'add a project and run the migration again'));
113
+ }
114
+ else {
115
+ findings.push(value === undefined ? finding('config-unreadable', 'orval.config', 'no orval.config file, or no `export default` in it', 'write contractdiff.config.json by hand') : unreadable('orval.config', value));
116
+ }
117
+ const { edits, findings: unwritten } = editScripts(files, Object.fromEntries(replaced));
118
+ return { config, edits, findings: [...findings, ...unwritten], uninstall: 'npm uninstall orval' };
119
+ };
@@ -0,0 +1,31 @@
1
+ export const finding = (code, pointer, message, fix) => ({ code, pointer, message, fix });
2
+ export const scripts = (files) => {
3
+ try {
4
+ const { scripts: found } = JSON.parse(files['package.json']);
5
+ if (Object(found) !== found)
6
+ return {};
7
+ return Object.fromEntries(Object.entries(found).filter((entry) => typeof entry[1] === 'string'));
8
+ }
9
+ catch {
10
+ return {};
11
+ }
12
+ };
13
+ export const editScripts = (files, replaced) => {
14
+ const before = files['package.json'];
15
+ const found = scripts(files);
16
+ let after = before;
17
+ const findings = [];
18
+ for (const [name, command] of Object.entries(replaced)) {
19
+ const old = `${JSON.stringify(name)}: ${JSON.stringify(found[name])}`;
20
+ if (after.includes(old)) {
21
+ after = after.replace(old, `${JSON.stringify(name)}: ${JSON.stringify(command)}`);
22
+ }
23
+ else {
24
+ findings.push(finding('script-not-rewritten', `package.json#/scripts/${name}`, `the \`${name}\` script is not written as \`"${name}": "…"\` on one line`, `set it to \`${command}\` by hand`));
25
+ }
26
+ }
27
+ return { edits: after === before ? [] : [{ path: 'package.json', before, after }], findings };
28
+ };
29
+ export const commandParts = (command) => command.split(/(\s*(?:&&|\|\||;|\|)\s*)/u);
30
+ export const camel = (name) => name.replaceAll(/-([a-z])/gu, (_match, letter) => letter.toUpperCase());
31
+ export const configText = (config) => `${JSON.stringify(config, undefined, 2)}\n`;
@@ -0,0 +1,9 @@
1
+ import { Readable } from 'node:stream';
2
+ import { type GenerateOptions } from './gen-ts-index.js';
3
+ /** What `openapiTS` reads: a parsed document, YAML or JSON text, a `file:` address, or a stream of text. */
4
+ export type Source = string | URL | Buffer | Readable | object;
5
+ /** Prints what `openapiTS` returned. It is already text. */
6
+ export declare const astToString: (value: unknown) => string;
7
+ /** Converts an OpenAPI 3.x document to TypeScript, as the text `openapi-typescript` 7.13.0 writes. */
8
+ export default function openapiTS(source: Source, options?: GenerateOptions): Promise<string>;
9
+ export { COMMENT_HEADER, createRef, isEnumSchema, makeApiPathsEnum, resolveRef, scanDiscriminators, transformComponentsObject, transformHeaderObject, transformOperationObject, transformPathItemObject, transformPathsObject, transformRequestBodyObject, transformResponseObject, transformSchema, transformSchemaObject, transformWebhooksObject, type GenerateOptions as OpenAPITSOptions, } from './gen-ts-index.js';
@@ -0,0 +1,36 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { Readable } from 'node:stream';
3
+ import { text as textOf } from 'node:stream/consumers';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { parse as parseYaml } from 'seniority/yaml';
6
+ import { bundle } from './gen-ts-bundle.js';
7
+ import { generate, unresolvedRefs } from './gen-ts-index.js';
8
+ export const astToString = (value) => String(value);
9
+ const remote = (address) => {
10
+ throw new Error(`\`${address}\` is a remote address, and this package does not fetch.\nfix: download the document and pass its text, its parsed value or a \`file:\` URL`);
11
+ };
12
+ const parse = (source) => {
13
+ const trimmed = source.trimStart();
14
+ if (/^https?:\/\//u.test(trimmed))
15
+ return remote(trimmed);
16
+ return trimmed.startsWith('{') ? JSON.parse(source) : parseYaml(source);
17
+ };
18
+ const read = async (source) => {
19
+ if (typeof source === 'string')
20
+ return parse(source);
21
+ if (source instanceof URL)
22
+ return source.protocol === 'file:' ? bundle(parse(readFileSync(source, 'utf8')), fileURLToPath(source)) : remote(source.href);
23
+ if (Buffer.isBuffer(source))
24
+ return parse(source.toString('utf8'));
25
+ return source instanceof Readable ? parse(await textOf(source)) : source;
26
+ };
27
+ export default async function openapiTS(source, options = {}) {
28
+ if (source === undefined || source === null || source === '') {
29
+ throw new Error('Empty schema.\nfix: pass a document, its YAML or JSON text, or a `file:` URL');
30
+ }
31
+ const document = await read(source);
32
+ for (const at of unresolvedRefs(document))
33
+ console.error(`✘ Can't resolve $ref at ${at}`);
34
+ return generate(document, options);
35
+ }
36
+ export { COMMENT_HEADER, createRef, isEnumSchema, makeApiPathsEnum, resolveRef, scanDiscriminators, transformComponentsObject, transformHeaderObject, transformOperationObject, transformPathItemObject, transformPathsObject, transformRequestBodyObject, transformResponseObject, transformSchema, transformSchemaObject, transformWebhooksObject, } from './gen-ts-index.js';
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The OpenAPI input format (spec.md R1, R2): an OpenAPI 3.0, 3.1 or 3.2 document read into the
3
+ * model. It imports only `contractdiff/core`, and the core never imports it.
4
+ */
5
+ import { type Contract } from './core/model.js';
6
+ /** A document this adapter does not read. The message ends in a `fix:` line. */
7
+ export declare class OpenApiError extends Error {
8
+ constructor(reason: string, fix: string);
9
+ }
10
+ /** Whether `document` declares itself as OpenAPI 3.x. */
11
+ export declare const detect: (document: unknown) => boolean;
12
+ /** Read an OpenAPI 3.x document into the model. */
13
+ export declare const read: (document: unknown) => Contract;
14
+ /** The adapter as the plugin host will register it (spec.md R-PL1). */
15
+ export declare const openapi: Readonly<{
16
+ name: "openapi";
17
+ description: "OpenAPI 3.0, 3.1 and 3.2 documents, including webhooks";
18
+ detect: (document: unknown) => boolean;
19
+ read: (document: unknown) => Contract;
20
+ }>;
@@ -0,0 +1,94 @@
1
+ import { pointerGet } from './core/resolve.js';
2
+ const METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace', 'query'];
3
+ const isDict = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
4
+ const dict = (value) => (isDict(value) ? value : {});
5
+ const token = (key) => key.replaceAll('~', '~0').replaceAll('/', '~1');
6
+ const schemaOf = (holder) => (holder.schema === undefined ? true : holder.schema);
7
+ const parameterSchema = (parameter) => {
8
+ if (parameter.schema !== undefined || !isDict(parameter.content))
9
+ return schemaOf(parameter);
10
+ const [media] = Object.values(parameter.content);
11
+ return schemaOf(dict(media));
12
+ };
13
+ export class OpenApiError extends Error {
14
+ constructor(reason, fix) {
15
+ super(`not an OpenAPI 3 document: ${reason}. fix: ${fix}`);
16
+ this.name = 'OpenApiError';
17
+ }
18
+ }
19
+ export const detect = (document) => isDict(document) && typeof document.openapi === 'string' && document.openapi.startsWith('3.');
20
+ const content = (holder, prefix, direction, required) => {
21
+ const types = Object.entries(dict(holder.content));
22
+ if (types.length === 0)
23
+ return [{ name: prefix, direction, schema: false, required }];
24
+ return types.flatMap(([type, media]) => {
25
+ const declared = dict(media);
26
+ const name = `${prefix}:${type}`;
27
+ const whole = declared.itemSchema === undefined || declared.schema !== undefined ? [{ name, direction, schema: schemaOf(declared), required }] : [];
28
+ const items = declared.itemSchema === undefined ? [] : [{ name: `${name}:item`, direction, schema: declared.itemSchema, required }];
29
+ return [...whole, ...items];
30
+ });
31
+ };
32
+ export const read = (document) => {
33
+ if (isDict(document) && typeof document.swagger === 'string') {
34
+ throw new OpenApiError(`it is Swagger ${document.swagger}`, 'convert it to OpenAPI 3.1 first');
35
+ }
36
+ if (!detect(document)) {
37
+ throw new OpenApiError('it has no `openapi: 3.x` member', 'pass an OpenAPI 3.0, 3.1 or 3.2 document');
38
+ }
39
+ const root = document;
40
+ const deref = (value) => {
41
+ let node = value;
42
+ const seen = new Set();
43
+ while (isDict(node) && typeof node.$ref === 'string' && !seen.has(node.$ref)) {
44
+ seen.add(node.$ref);
45
+ node = pointerGet(root, node.$ref);
46
+ }
47
+ return dict(node);
48
+ };
49
+ const operation = ({ id, source, declared, shared }, sends, receives) => {
50
+ const parameters = new Map();
51
+ for (const entry of [...(Array.isArray(shared) ? shared : []), ...(Array.isArray(declared.parameters) ? declared.parameters : [])]) {
52
+ const parameter = deref(entry);
53
+ const name = `param:${String(parameter.in)}:${String(parameter.name)}`;
54
+ const required = parameter.in === 'path' || parameter.required === true;
55
+ parameters.set(name, { name, direction: sends, schema: parameterSchema(parameter), required });
56
+ }
57
+ const payloads = [...parameters.values()];
58
+ if (declared.requestBody !== undefined) {
59
+ const body = deref(declared.requestBody);
60
+ payloads.push(...content(body, 'body', sends, body.required === true));
61
+ }
62
+ for (const [status, response] of Object.entries(dict(declared.responses))) {
63
+ payloads.push(...content(deref(response), `response:${status}`, receives, true));
64
+ }
65
+ return { id, source, payloads };
66
+ };
67
+ const operations = [];
68
+ const section = (name, sends, receives) => {
69
+ for (const [key, entry] of Object.entries(dict(root[name]))) {
70
+ const item = deref(entry);
71
+ const declaredMethods = [
72
+ ...METHODS.map((method) => [method, item[method], method]),
73
+ ...Object.entries(dict(item.additionalOperations)).map(([method, declared]) => [method, declared, `additionalOperations/${token(method)}`]),
74
+ ];
75
+ for (const [method, declared, at] of declaredMethods) {
76
+ if (!isDict(declared))
77
+ continue;
78
+ const fallback = name === 'paths' ? `${method} ${key}` : `webhook ${method} ${key}`;
79
+ const id = typeof declared.operationId === 'string' ? declared.operationId : fallback;
80
+ const source = `#/${name}/${token(key)}/${at}`;
81
+ operations.push(operation({ id, source, declared, shared: item.parameters }, sends, receives));
82
+ }
83
+ }
84
+ };
85
+ section('paths', 'request', 'response');
86
+ section('webhooks', 'publish', 'subscribe');
87
+ return { format: 'openapi', document, operations };
88
+ };
89
+ export const openapi = Object.freeze({
90
+ name: 'openapi',
91
+ description: 'OpenAPI 3.0, 3.1 and 3.2 documents, including webhooks',
92
+ detect,
93
+ read,
94
+ });
@@ -0,0 +1,66 @@
1
+ import { read } from './openapi.js';
2
+ import { routePath } 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 EXPRESS = {
7
+ target: 'express',
8
+ name: 'Express',
9
+ path: routePath,
10
+ imports: ["import { Router, text } from 'express';"],
11
+ register: [
12
+ '/**',
13
+ ' * An Express 5 router serving every route: each reads and checks the request, calls its handler,',
14
+ ' * and checks what it answers. A body arrives as text, unless a parser before the router read it.',
15
+ ' */',
16
+ 'export const createRouter = (handlers: Handlers): Router => {',
17
+ ' const router = Router();',
18
+ ' for (const route of routes) {',
19
+ ' router[route.method](route.path, text({ type: () => true }), async (request, response) => {',
20
+ ' const answer = await handle(route, handlers, { path: request.params, query: request.query, header: request.headers, body: request.body as unknown });',
21
+ ' response.status(answer.status).set(answer.headers);',
22
+ ' if (answer.body === undefined) response.end();',
23
+ ' else response.send(answer.body);',
24
+ ' });',
25
+ ' }',
26
+ ' return router;',
27
+ '};',
28
+ ],
29
+ usage: 'Serve them with `app.use(createRouter(handlers))` from routes.ts.',
30
+ harness: {
31
+ framework: ["import { type Server } from 'node:http';", "import { type AddressInfo } from 'node:net';", '', "import express from 'express';"],
32
+ hooks: ['afterAll', 'beforeAll'],
33
+ local: ["import { handlers } from './handlers.js';", "import { createRouter } from './routes.js';"],
34
+ setup: [
35
+ ' let server: Server;',
36
+ ' let base: string;',
37
+ '',
38
+ ' beforeAll(async () => {',
39
+ ' const app = express();',
40
+ ' app.use(createRouter(handlers));',
41
+ ' server = await new Promise<Server>((resolve) => {',
42
+ " const listening = app.listen(0, '127.0.0.1', () => resolve(listening));",
43
+ ' });',
44
+ ' base = `http://127.0.0.1:${String((server.address() as AddressInfo).port)}`;',
45
+ ' });',
46
+ '',
47
+ ' afterAll(async () => {',
48
+ ' await new Promise((resolve) => server.close(resolve));',
49
+ ' });',
50
+ '',
51
+ ],
52
+ call: (url, init) => `fetch(new URL(${url}, base), ${init})`,
53
+ },
54
+ };
55
+ export const run = (contract, options) => runRouter(EXPRESS, contract, options);
56
+ const express = {
57
+ description: 'Express 5 routes: a generated router that validates requests and responses per operation, handlers you own, and a contract test per operation',
58
+ inputs: ['openapi'],
59
+ options: SERVER_OPTIONS,
60
+ sample: {
61
+ document: SAMPLE_DOCUMENT,
62
+ files: run(read(SAMPLE_DOCUMENT), {}).files,
63
+ },
64
+ run,
65
+ };
66
+ export const plugin = { name: 'express', generators: { express } };
@@ -0,0 +1 @@
1
+ export const plugin = undefined;
@@ -0,0 +1 @@
1
+ export const plugin = undefined;