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.
- package/LICENSE +21 -0
- package/README.md +228 -2
- package/dist/bin.js +4 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.js +24 -0
- package/dist/command-diff.js +310 -0
- package/dist/command-explain-cap.js +36 -0
- package/dist/command-explain-inline.js +17 -0
- package/dist/command-explain-name.js +31 -0
- package/dist/command-explain-operation.js +85 -0
- package/dist/command-explain-text.js +21 -0
- package/dist/command-explain.js +54 -0
- package/dist/command-lint.js +280 -0
- package/dist/command-migrate.js +70 -0
- package/dist/command-plugin.js +32 -0
- package/dist/command-props.js +116 -0
- package/dist/commands.js +7 -0
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.js +2 -0
- package/dist/core/model.d.ts +46 -0
- package/dist/core/model.js +1 -0
- package/dist/core/resolve.d.ts +22 -0
- package/dist/core/resolve.js +71 -0
- package/dist/diff-classify.js +30 -0
- package/dist/diff-contract.js +176 -0
- package/dist/diff-decisions.js +446 -0
- package/dist/diff-normalise.js +143 -0
- package/dist/diff-rules.js +109 -0
- package/dist/diff-schema.js +335 -0
- package/dist/diff-security.js +33 -0
- package/dist/diff-transitive.js +26 -0
- package/dist/diff-usage.js +59 -0
- package/dist/extract-normalise.js +85 -0
- package/dist/extract-roundtrip.js +28 -0
- package/dist/extract-standard.js +79 -0
- package/dist/gen-ts-ast.d.ts +135 -0
- package/dist/gen-ts-ast.js +52 -0
- package/dist/gen-ts-bundle.js +233 -0
- package/dist/gen-ts-comment.js +48 -0
- package/dist/gen-ts-context.d.ts +83 -0
- package/dist/gen-ts-context.js +45 -0
- package/dist/gen-ts-dict.d.ts +14 -0
- package/dist/gen-ts-dict.js +14 -0
- package/dist/gen-ts-discriminators.d.ts +7 -0
- package/dist/gen-ts-discriminators.js +117 -0
- package/dist/gen-ts-document.d.ts +12 -0
- package/dist/gen-ts-document.js +82 -0
- package/dist/gen-ts-enums.js +139 -0
- package/dist/gen-ts-helpers.js +30 -0
- package/dist/gen-ts-index.d.ts +49 -0
- package/dist/gen-ts-index.js +110 -0
- package/dist/gen-ts-operations.js +277 -0
- package/dist/gen-ts-print.js +113 -0
- package/dist/gen-ts-ref.d.ts +30 -0
- package/dist/gen-ts-ref.js +75 -0
- package/dist/gen-ts-schema.js +283 -0
- package/dist/gen-ts-text.d.ts +24 -0
- package/dist/gen-ts-text.js +98 -0
- package/dist/host.d.ts +145 -0
- package/dist/host.js +273 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/input-asyncapi.js +167 -0
- package/dist/input-buf.js +58 -0
- package/dist/input-jsonschema.js +165 -0
- package/dist/input-mcp.js +111 -0
- package/dist/input-overlay-jsonpath.js +265 -0
- package/dist/input-overlay.js +138 -0
- package/dist/input-protobuf.js +212 -0
- package/dist/input-swagger2.js +331 -0
- package/dist/inputs.js +8 -0
- package/dist/lint-code-read.js +129 -0
- package/dist/lint-code.d.ts +56 -0
- package/dist/lint-code.js +64 -0
- package/dist/lint-engine.d.ts +93 -0
- package/dist/lint-engine.js +87 -0
- package/dist/lint-functions.js +95 -0
- package/dist/lint-history.js +133 -0
- package/dist/lint-jsonpath.js +92 -0
- package/dist/lint-names.d.ts +11 -0
- package/dist/lint-names.js +2 -0
- package/dist/lint-redocly.js +141 -0
- package/dist/lint-rules.js +189 -0
- package/dist/lint-select.d.ts +33 -0
- package/dist/lint-select.js +129 -0
- package/dist/lint-since.js +20 -0
- package/dist/lint-spectral.js +167 -0
- package/dist/lint-stats.js +58 -0
- package/dist/migrate-hey-api.js +144 -0
- package/dist/migrate-literal.js +139 -0
- package/dist/migrate-openapi-fetch.js +62 -0
- package/dist/migrate-openapi-typescript.js +159 -0
- package/dist/migrate-orval.js +119 -0
- package/dist/migrate-shared.js +31 -0
- package/dist/openapi-typescript.d.ts +9 -0
- package/dist/openapi-typescript.js +36 -0
- package/dist/openapi.d.ts +20 -0
- package/dist/openapi.js +94 -0
- package/dist/plugin-express.js +66 -0
- package/dist/plugin-extract-hono.js +1 -0
- package/dist/plugin-extract-nest.js +1 -0
- package/dist/plugin-extract-openapi.js +246 -0
- package/dist/plugin-extract-standard-schema.js +42 -0
- package/dist/plugin-extract-trpc.js +1 -0
- package/dist/plugin-extract-ts-rest.js +77 -0
- package/dist/plugin-fastify.js +68 -0
- package/dist/plugin-fetch-client.js +172 -0
- package/dist/plugin-fetch-routes.js +110 -0
- package/dist/plugin-fetch-sample.js +155 -0
- package/dist/plugin-fetch-text.js +5 -0
- package/dist/plugin-fetch.js +19 -0
- package/dist/plugin-hono.js +42 -0
- package/dist/plugin-json-schema-build.js +289 -0
- package/dist/plugin-json-schema-dialect-anthropic.js +41 -0
- package/dist/plugin-json-schema-dialect-gemini.js +29 -0
- package/dist/plugin-json-schema-dialect-mcp-elicitation.js +32 -0
- package/dist/plugin-json-schema-dialect-mcp.js +13 -0
- package/dist/plugin-json-schema-dialect-openai.js +37 -0
- package/dist/plugin-json-schema-dialect.js +180 -0
- package/dist/plugin-json-schema.js +125 -0
- package/dist/plugin-markdown.js +114 -0
- package/dist/plugin-mcp-code.js +28 -0
- package/dist/plugin-mcp-tools.js +152 -0
- package/dist/plugin-mcp.js +107 -0
- package/dist/plugin-msw-files.js +50 -0
- package/dist/plugin-msw-sample.js +45 -0
- package/dist/plugin-msw-synth.js +116 -0
- package/dist/plugin-msw.js +30 -0
- package/dist/plugin-nest-code.js +68 -0
- package/dist/plugin-nest-contract.js +23 -0
- package/dist/plugin-nest.js +44 -0
- package/dist/plugin-server-code.js +61 -0
- package/dist/plugin-server-contract.js +48 -0
- package/dist/plugin-server-example.js +62 -0
- package/dist/plugin-server-router.js +77 -0
- package/dist/plugin-server-routes.js +155 -0
- package/dist/plugin-server-runtime.js +3 -0
- package/dist/plugin-server-sample.js +40 -0
- package/dist/plugin-swr-sample.js +21 -0
- package/dist/plugin-swr.js +40 -0
- package/dist/plugin-tanstack-query-sample.js +21 -0
- package/dist/plugin-tanstack-query.js +59 -0
- package/dist/plugin-types.js +80 -0
- package/dist/plugin-validator-code.js +41 -0
- package/dist/plugin-validator-names.js +27 -0
- package/dist/plugin-validator.js +103 -0
- package/dist/plugins.js +21 -0
- package/dist/props-emit.js +194 -0
- package/dist/props-generate.js +408 -0
- package/dist/props-judge.js +30 -0
- package/dist/props-mutate.js +144 -0
- package/dist/props-random.js +25 -0
- package/dist/props-run.js +170 -0
- package/dist/props-shrink.js +75 -0
- package/dist/run-apply.js +25 -0
- package/dist/run-command.js +31 -0
- package/dist/run-commit.d.ts +51 -0
- package/dist/run-commit.js +48 -0
- package/dist/run-config.d.ts +193 -0
- package/dist/run-config.js +256 -0
- package/dist/run-diff.js +24 -0
- package/dist/run-extract.d.ts +13 -0
- package/dist/run-extract.js +21 -0
- package/dist/run-gen.d.ts +15 -0
- package/dist/run-gen.js +43 -0
- package/dist/run-header.js +37 -0
- package/dist/run-input.js +31 -0
- package/dist/run-load.js +32 -0
- package/dist/run-map.d.ts +41 -0
- package/dist/run-map.js +52 -0
- package/dist/run-plan.d.ts +31 -0
- package/dist/run-plan.js +35 -0
- package/dist/scaffold-seed.js +43 -0
- package/dist/scaffold-write.js +17 -0
- package/dist/scaffold.js +196 -0
- package/dist/testing-lint.js +43 -0
- package/dist/testing-owner.js +17 -0
- package/dist/testing-probe.js +25 -0
- package/dist/testing-rules.d.ts +65 -0
- package/dist/testing-rules.js +115 -0
- package/dist/testing.d.ts +32 -0
- package/dist/testing.js +79 -0
- package/package.json +108 -4
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { CASINGS } from './lint-functions.js';
|
|
2
|
+
import { parse } from './lint-jsonpath.js';
|
|
3
|
+
import { FUNCTIONS } from './lint-names.js';
|
|
4
|
+
export const SPECTRAL_OAS = {
|
|
5
|
+
'info-description': { id: 'info-description', level: 'warn' },
|
|
6
|
+
'operation-description': { id: 'operation-description', level: 'warn' },
|
|
7
|
+
'operation-operationId': { id: 'operation-operation-id', level: 'warn' },
|
|
8
|
+
'operation-operationId-unique': { id: 'operation-operation-id-unique', level: 'error' },
|
|
9
|
+
'operation-success-response': { id: 'operation-success-response', level: 'warn' },
|
|
10
|
+
'operation-tags': { id: 'operation-tags', level: 'warn' },
|
|
11
|
+
'path-keys-no-trailing-slash': { id: 'path-no-trailing-slash', level: 'warn' },
|
|
12
|
+
'oas3-unused-component': { id: 'no-unused-component', level: 'warn' },
|
|
13
|
+
'oas3-valid-media-example': { id: 'example-valid', level: 'warn' },
|
|
14
|
+
};
|
|
15
|
+
const FORMATS = {
|
|
16
|
+
oas2: 'swagger2',
|
|
17
|
+
oas3: 'openapi',
|
|
18
|
+
oas3_0: 'openapi',
|
|
19
|
+
'oas3.0': 'openapi',
|
|
20
|
+
oas3_1: 'openapi',
|
|
21
|
+
'oas3.1': 'openapi',
|
|
22
|
+
asyncapi: 'asyncapi',
|
|
23
|
+
asyncapi2: 'asyncapi',
|
|
24
|
+
'asyncapi2.0': 'asyncapi',
|
|
25
|
+
};
|
|
26
|
+
const SEVERITIES = new Map([
|
|
27
|
+
['error', 'error'],
|
|
28
|
+
['warn', 'warn'],
|
|
29
|
+
['info', 'warn'],
|
|
30
|
+
['hint', 'warn'],
|
|
31
|
+
['off', 'off'],
|
|
32
|
+
[false, 'off'],
|
|
33
|
+
[true, 'warn'],
|
|
34
|
+
]);
|
|
35
|
+
const NUMBERED = ['error', 'warn', 'info', 'hint'];
|
|
36
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
37
|
+
const token = (key) => key.replaceAll('~', '~0').replaceAll('/', '~1');
|
|
38
|
+
export const uncarried = (reason) => {
|
|
39
|
+
throw new Error(`${reason}`);
|
|
40
|
+
};
|
|
41
|
+
export const plainMessage = (message) => (typeof message === 'string' && !message.includes('{{') ? message : undefined);
|
|
42
|
+
export const patternOf = (value, key) => {
|
|
43
|
+
if (typeof value !== 'string')
|
|
44
|
+
return uncarried(`\`pattern\`'s \`${key}\` is not a string`);
|
|
45
|
+
const slashed = /^\/(.*)\/([a-z]*)$/su.exec(value);
|
|
46
|
+
if (slashed !== null && slashed[2] !== '')
|
|
47
|
+
uncarried(`\`pattern\`'s \`${key}\` has the flags \`${slashed[2]}\`, which are not carried`);
|
|
48
|
+
const source = slashed === null ? value : slashed[1];
|
|
49
|
+
try {
|
|
50
|
+
new RegExp(source, 'u');
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
uncarried(`\`pattern\`'s \`${key}\` does not compile as a Unicode regular expression`);
|
|
54
|
+
}
|
|
55
|
+
return source;
|
|
56
|
+
};
|
|
57
|
+
const optionsOf = (name, options) => {
|
|
58
|
+
if (options === undefined)
|
|
59
|
+
return undefined;
|
|
60
|
+
if (!isRecord(options))
|
|
61
|
+
return uncarried('`functionOptions` is not an object');
|
|
62
|
+
if (name === 'casing') {
|
|
63
|
+
if (!CASINGS.includes(options.type))
|
|
64
|
+
uncarried(`\`casing\` type \`${String(options.type)}\` is not one of ${CASINGS.join(', ')}`);
|
|
65
|
+
const extra = Object.keys(options).filter((key) => key !== 'type');
|
|
66
|
+
if (extra.length > 0)
|
|
67
|
+
uncarried(`\`casing\` options ${extra.map((key) => `\`${key}\``).join(', ')} are not carried`);
|
|
68
|
+
}
|
|
69
|
+
if (name === 'pattern') {
|
|
70
|
+
return { ...(options.match === undefined ? {} : { match: patternOf(options.match, 'match') }), ...(options.notMatch === undefined ? {} : { notMatch: patternOf(options.notMatch, 'notMatch') }) };
|
|
71
|
+
}
|
|
72
|
+
return options;
|
|
73
|
+
};
|
|
74
|
+
const thenOf = (then) => {
|
|
75
|
+
if (!isRecord(then))
|
|
76
|
+
return uncarried('a `then` entry is not an object');
|
|
77
|
+
const name = then.function;
|
|
78
|
+
if (!FUNCTIONS.includes(name))
|
|
79
|
+
return uncarried(`function \`${String(name)}\` is not a core function contractdiff carries (${FUNCTIONS.join(', ')})`);
|
|
80
|
+
const { field } = then;
|
|
81
|
+
if (field !== undefined && (typeof field !== 'string' || field.startsWith('@') || field.startsWith('$')))
|
|
82
|
+
uncarried(`\`field\` \`${String(field)}\` is not a member name; \`@key\` and JSONPath fields are not carried`);
|
|
83
|
+
const options = optionsOf(name, then.functionOptions);
|
|
84
|
+
return { function: name, ...(field === undefined ? {} : { field: field }), ...(options === undefined ? {} : { functionOptions: options }) };
|
|
85
|
+
};
|
|
86
|
+
const pathsOf = (given) => {
|
|
87
|
+
const paths = [given].flat();
|
|
88
|
+
if (paths.length === 0 || !paths.every((path) => typeof path === 'string'))
|
|
89
|
+
return uncarried('`given` is not a JSONPath or a list of them');
|
|
90
|
+
for (const path of paths) {
|
|
91
|
+
try {
|
|
92
|
+
parse(path);
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
uncarried(error.message);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return paths;
|
|
99
|
+
};
|
|
100
|
+
const namedOf = (severity) => (severity < 0 ? 'off' : NUMBERED.at(severity));
|
|
101
|
+
const levelOf = (severity) => SEVERITIES.get(typeof severity === 'number' ? namedOf(severity) : (severity ?? 'warn')) ??
|
|
102
|
+
uncarried(`severity \`${String(severity)}\` is not error, warn, info, hint or off`);
|
|
103
|
+
const ruleOf = (id, value, file) => {
|
|
104
|
+
const formats = value.formats === undefined ? undefined : [value.formats].flat().map((format) => FORMATS[String(format)] ?? uncarried(`format \`${String(format)}\` is not one contractdiff reads`));
|
|
105
|
+
const paths = pathsOf(value.given);
|
|
106
|
+
const thens = [value.then].flat().map((then) => thenOf(then));
|
|
107
|
+
const description = [value.description, plainMessage(value.message), id].find((text) => typeof text === 'string');
|
|
108
|
+
return {
|
|
109
|
+
rule: {
|
|
110
|
+
description,
|
|
111
|
+
given: { select: 'path', path: paths.length === 1 ? paths[0] : paths, ...(formats === undefined ? {} : { formats: [...new Set(formats)] }) },
|
|
112
|
+
then: thens.length === 1 ? thens[0] : thens,
|
|
113
|
+
fix: `make it hold, as \`${id}\` in ${file} asks: ${description}`,
|
|
114
|
+
},
|
|
115
|
+
level: levelOf(value.severity),
|
|
116
|
+
};
|
|
117
|
+
};
|
|
118
|
+
const extendsOf = (value, file) => {
|
|
119
|
+
const levels = new Map();
|
|
120
|
+
const notCarried = [];
|
|
121
|
+
const entries = value === undefined ? [] : [value].flat().map((entry) => (Array.isArray(entry) ? entry : [entry]));
|
|
122
|
+
for (const [index, [name, mode]] of entries.entries()) {
|
|
123
|
+
const pointer = `#/extends/${String(index)}`;
|
|
124
|
+
if (mode === 'off')
|
|
125
|
+
continue;
|
|
126
|
+
if (name !== 'spectral:oas') {
|
|
127
|
+
notCarried.push({ id: String(name), file, pointer, reason: `extends \`${String(name)}\`, which contractdiff does not read`, fix: `copy the rules you need from \`${String(name)}\` into ${file}, inside the JSONPath subset` });
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
for (const { id, level } of Object.values(SPECTRAL_OAS))
|
|
131
|
+
levels.set(id, level);
|
|
132
|
+
notCarried.push({
|
|
133
|
+
id: 'spectral:oas',
|
|
134
|
+
file,
|
|
135
|
+
pointer,
|
|
136
|
+
reason: `carries ${String(Object.keys(SPECTRAL_OAS).length)} of its rules as contractdiff equivalents (${Object.keys(SPECTRAL_OAS).join(', ')}); the others are not carried`,
|
|
137
|
+
fix: 'add the others you rely on as rules in this file, or run `contractdiff lint --ruleset recommended` for the built-in set',
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
return { levels, notCarried };
|
|
141
|
+
};
|
|
142
|
+
const overrideOf = (id, severity, known) => {
|
|
143
|
+
const target = SPECTRAL_OAS[id]?.id ?? (known.has(id) ? id : uncarried(`it sets the level of \`${id}\`, which no carried ruleset defines`));
|
|
144
|
+
return [target, levelOf(severity)];
|
|
145
|
+
};
|
|
146
|
+
export const readSpectral = (document, file, known) => {
|
|
147
|
+
const value = isRecord(document) ? document : {};
|
|
148
|
+
const { levels, notCarried } = extendsOf(value.extends, file);
|
|
149
|
+
const rules = new Map();
|
|
150
|
+
for (const [id, definition] of Object.entries(isRecord(value.rules) ? value.rules : {})) {
|
|
151
|
+
try {
|
|
152
|
+
if (isRecord(definition)) {
|
|
153
|
+
const carried = ruleOf(id, definition, file);
|
|
154
|
+
rules.set(id, carried.rule);
|
|
155
|
+
levels.set(id, carried.level);
|
|
156
|
+
}
|
|
157
|
+
else {
|
|
158
|
+
const [target, level] = overrideOf(id, definition, known);
|
|
159
|
+
levels.set(target, level);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
notCarried.push({ id, file, pointer: `#/rules/${token(id)}`, reason: error.message, fix: 'rewrite it with core functions and a `given` inside the JSONPath subset, or turn it off here and keep it in Spectral' });
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return { rules: Object.fromEntries(rules), levels: Object.fromEntries(levels), notCarried };
|
|
167
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { WARN_FOR } from './lint-history.js';
|
|
2
|
+
import { UsageError } from './run-config.js';
|
|
3
|
+
const EMPTY = { version: 1, rules: {} };
|
|
4
|
+
const DAY = 86_400_000;
|
|
5
|
+
function isRecord(value) {
|
|
6
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
7
|
+
}
|
|
8
|
+
const isCount = (value) => Number.isInteger(value) && value >= 0;
|
|
9
|
+
const isDate = (value) => typeof value === 'string' && !Number.isNaN(Date.parse(value));
|
|
10
|
+
const isRuleStats = (value) => isRecord(value) && isDate(value.firstRun) && isCount(value.runs) && isCount(value.findings) && (value.lastFinding === undefined || isDate(value.lastFinding));
|
|
11
|
+
function isStats(value) {
|
|
12
|
+
return isRecord(value) && value.version === 1 && (value.lastRun === undefined || typeof value.lastRun === 'string') && isRecord(value.rules) && Object.values(value.rules).every((entry) => isRuleStats(entry));
|
|
13
|
+
}
|
|
14
|
+
const parsed = (text) => {
|
|
15
|
+
try {
|
|
16
|
+
return JSON.parse(text);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
export const statsOf = (text, file) => {
|
|
23
|
+
if (text === undefined)
|
|
24
|
+
return EMPTY;
|
|
25
|
+
const value = parsed(text);
|
|
26
|
+
if (isStats(value))
|
|
27
|
+
return value;
|
|
28
|
+
throw new UsageError(`\`--stats ${file}\` is not a stats file lint wrote. fix: delete it, or name another file; the next run starts it again`);
|
|
29
|
+
};
|
|
30
|
+
export const countRun = (stats, result, run) => {
|
|
31
|
+
if (stats.lastRun === run.key)
|
|
32
|
+
return stats;
|
|
33
|
+
const today = run.now.toISOString();
|
|
34
|
+
const rules = new Map(Object.entries(stats.rules));
|
|
35
|
+
for (const id of Object.keys(result.counts)) {
|
|
36
|
+
const found = result.findings.filter((finding) => finding.rule === id).length;
|
|
37
|
+
const was = rules.get(id) ?? { firstRun: today, runs: 0, findings: 0 };
|
|
38
|
+
rules.set(id, { ...was, runs: was.runs + 1, findings: was.findings + found, ...(found > 0 ? { lastFinding: today } : {}) });
|
|
39
|
+
}
|
|
40
|
+
return { version: 1, lastRun: run.key, rules: Object.fromEntries([...rules].sort(([a], [b]) => a.localeCompare(b, 'en'))) };
|
|
41
|
+
};
|
|
42
|
+
export const idleDays = (idle) => {
|
|
43
|
+
const days = WARN_FOR.exec(idle)?.[1];
|
|
44
|
+
if (days === undefined)
|
|
45
|
+
throw new UsageError(`\`--idle ${idle}\` is not a number of days. fix: write \`--idle 90d\``);
|
|
46
|
+
return Number(days);
|
|
47
|
+
};
|
|
48
|
+
export const idleOf = (stats, ran, cutoff) => {
|
|
49
|
+
const rules = new Map(Object.entries(stats.rules));
|
|
50
|
+
return [...ran].sort().flatMap((id) => {
|
|
51
|
+
const entry = rules.get(id);
|
|
52
|
+
if (entry === undefined)
|
|
53
|
+
return [];
|
|
54
|
+
const since = entry.lastFinding ?? entry.firstRun;
|
|
55
|
+
return Date.parse(since) <= cutoff.getTime() ? [{ id, runs: entry.runs, since, found: entry.lastFinding !== undefined }] : [];
|
|
56
|
+
});
|
|
57
|
+
};
|
|
58
|
+
export const idleCutoff = (days, now) => new Date(now.getTime() - days * DAY);
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { isUnreadable, readExport } from './migrate-literal.js';
|
|
2
|
+
import { commandParts, editScripts, finding, scripts } from './migrate-shared.js';
|
|
3
|
+
const MAPPED = new Map([
|
|
4
|
+
['@hey-api/typescript', 'types'],
|
|
5
|
+
['@hey-api/sdk', 'fetch'],
|
|
6
|
+
['@hey-api/client-fetch', 'fetch'],
|
|
7
|
+
['@hey-api/schemas', 'json-schema'],
|
|
8
|
+
['@tanstack/react-query', 'tanstack-query'],
|
|
9
|
+
['swr', 'swr'],
|
|
10
|
+
['msw', 'msw'],
|
|
11
|
+
['fastify', 'fastify'],
|
|
12
|
+
['hono', 'hono'],
|
|
13
|
+
['nest', 'nest'],
|
|
14
|
+
['express', 'express'],
|
|
15
|
+
]);
|
|
16
|
+
const VALIDATORS = new Set(['zod', 'valibot', 'arktype', 'joi', 'yup', 'typebox', 'superstruct', 'ajv']);
|
|
17
|
+
const DEFAULT_PLUGINS = ['@hey-api/typescript', '@hey-api/sdk'];
|
|
18
|
+
const POINTER = 'openapi-ts.config';
|
|
19
|
+
const isDict = (value) => typeof value === 'object' && value !== null && !Array.isArray(value) && !isUnreadable(value);
|
|
20
|
+
const unreadable = (pointer, value) => finding('unreadable', pointer, `\`${isUnreadable(value) ? value.unreadable : JSON.stringify(value)}\` is not data this migration can read`, 'write the value out as a literal, or carry it over by hand');
|
|
21
|
+
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');
|
|
22
|
+
const pathOf = (value, pointer, findings, what) => {
|
|
23
|
+
if (typeof value === 'string')
|
|
24
|
+
return value;
|
|
25
|
+
if (Array.isArray(value)) {
|
|
26
|
+
const [first, ...rest] = value;
|
|
27
|
+
rest.forEach((other, index) => findings.push(finding(`second-${what}`, `${pointer}/${String(index + 1)}`, `${JSON.stringify(other)} is a second ${what}, and one contractdiff.config.json has one`, 'write a second contractdiff.config.json for it in its own folder')));
|
|
28
|
+
return pathOf(first, `${pointer}/0`, findings, what);
|
|
29
|
+
}
|
|
30
|
+
if (isDict(value)) {
|
|
31
|
+
const { path, ...rest } = value;
|
|
32
|
+
for (const key of Object.keys(rest))
|
|
33
|
+
findings.push(dropped(pointer, key));
|
|
34
|
+
return pathOf(path, `${pointer}/path`, findings, what);
|
|
35
|
+
}
|
|
36
|
+
if (value !== undefined)
|
|
37
|
+
findings.push(unreadable(pointer, value));
|
|
38
|
+
return undefined;
|
|
39
|
+
};
|
|
40
|
+
const plugins = (list, output, findings) => {
|
|
41
|
+
const targets = new Map();
|
|
42
|
+
list.forEach((entry, index) => {
|
|
43
|
+
const pointer = `${POINTER}#/plugins/${String(index)}`;
|
|
44
|
+
let name = entry;
|
|
45
|
+
if (isDict(entry)) {
|
|
46
|
+
const { name: named, ...options } = entry;
|
|
47
|
+
name = named;
|
|
48
|
+
for (const key of Object.keys(options))
|
|
49
|
+
findings.push(dropped(pointer, key));
|
|
50
|
+
}
|
|
51
|
+
if (typeof name !== 'string') {
|
|
52
|
+
findings.push(unreadable(pointer, entry));
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const generator = MAPPED.get(name) ?? (VALIDATORS.has(name) ? 'validator' : undefined);
|
|
56
|
+
if (generator === undefined) {
|
|
57
|
+
findings.push(finding('plugin-dropped', pointer, `the \`${name}\` plugin has no contractdiff target`, 'keep Hey API for it, or write the plugin: `contractdiff plugin new`'));
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (VALIDATORS.has(name)) {
|
|
61
|
+
findings.push(finding('plugin-translated', pointer, `\`${name}\` schemas become the \`validator\` target, contractdiff's own validators, not ${name}'s`, `import the validators from the \`validator\` target's output, or keep Hey API for ${name}`));
|
|
62
|
+
}
|
|
63
|
+
targets.set(generator, { generator, out: output });
|
|
64
|
+
});
|
|
65
|
+
return Object.fromEntries(targets);
|
|
66
|
+
};
|
|
67
|
+
const fromFlags = (args) => {
|
|
68
|
+
const config = new Map();
|
|
69
|
+
const list = [];
|
|
70
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
71
|
+
const flag = args[index];
|
|
72
|
+
const value = args[index + 1] ?? '';
|
|
73
|
+
if (flag === '-i' || flag === '--input')
|
|
74
|
+
config.set('input', value);
|
|
75
|
+
else if (flag === '-o' || flag === '--output')
|
|
76
|
+
config.set('output', value);
|
|
77
|
+
else if (flag === '-c' || flag === '--client' || flag === '-p' || flag === '--plugins')
|
|
78
|
+
list.push(...value.split(','));
|
|
79
|
+
else {
|
|
80
|
+
config.set(flag, flag);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
index += 1;
|
|
84
|
+
}
|
|
85
|
+
config.set('plugins', [...DEFAULT_PLUGINS, ...list]);
|
|
86
|
+
return Object.fromEntries(config);
|
|
87
|
+
};
|
|
88
|
+
const BINARY = /^(\s*)(?:npx\s+)?(?:@hey-api\/)?openapi-ts(?:\s|$)/u;
|
|
89
|
+
const fromScripts = (files) => {
|
|
90
|
+
const replaced = new Map();
|
|
91
|
+
let args;
|
|
92
|
+
for (const [name, command] of Object.entries(scripts(files))) {
|
|
93
|
+
const parts = commandParts(command);
|
|
94
|
+
const rewritten = parts.map((part) => {
|
|
95
|
+
const found = BINARY.exec(part);
|
|
96
|
+
if (found === null)
|
|
97
|
+
return part;
|
|
98
|
+
const rest = part.slice(found[0].length).trim();
|
|
99
|
+
args ??= rest === '' ? [] : rest.split(/\s+/u).filter((word) => word !== '\\');
|
|
100
|
+
return `${found[1]}contractdiff gen`;
|
|
101
|
+
});
|
|
102
|
+
if (rewritten.join('') !== command)
|
|
103
|
+
replaced.set(name, rewritten.join(''));
|
|
104
|
+
}
|
|
105
|
+
return { replaced: Object.fromEntries(replaced), args };
|
|
106
|
+
};
|
|
107
|
+
const convert = (value, findings) => {
|
|
108
|
+
if (!isDict(value)) {
|
|
109
|
+
findings.push(value === undefined ? finding('config-unreadable', POINTER, 'no `export default` or `module.exports` was found', 'write contractdiff.config.json by hand') : unreadable(POINTER, value));
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
const { input, output, plugins: listed, ...rest } = value;
|
|
113
|
+
for (const key of Object.keys(rest))
|
|
114
|
+
findings.push(dropped(`${POINTER}#`, key));
|
|
115
|
+
const path = pathOf(input, `${POINTER}#/input`, findings, 'input');
|
|
116
|
+
const out = pathOf(output, `${POINTER}#/output`, findings, 'output') ?? 'src/client';
|
|
117
|
+
if (path === undefined || path === '') {
|
|
118
|
+
findings.push(finding('nothing-to-migrate', `${POINTER}#/input`, 'the config names no input document', 'set `input` and run the migration again'));
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
if (/^https?:\/\//u.test(path))
|
|
122
|
+
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'));
|
|
123
|
+
else if (/^[\w-]+\/[\w-]+(?:[?@].*)?$/u.test(path))
|
|
124
|
+
findings.push(finding('registry-input', 'contractdiff.config.json#/input', `${path} is a Hey API Platform registry address`, 'download the document from the registry into the project and point `input` at it'));
|
|
125
|
+
const list = Array.isArray(listed) ? listed : DEFAULT_PLUGINS;
|
|
126
|
+
if (listed !== undefined && !Array.isArray(listed))
|
|
127
|
+
findings.push(unreadable(`${POINTER}#/plugins`, listed));
|
|
128
|
+
findings.push(finding('imports-change', `${POINTER}#/output`, `the files under ${out} are written with contractdiff's module names, not Hey API's \`*.gen.ts\``, `after \`contractdiff gen\`, point imports of ${out}/*.gen at the targets' files`));
|
|
129
|
+
return { input: path, targets: plugins(list, out, findings) };
|
|
130
|
+
};
|
|
131
|
+
export const migrate = (configText, files) => {
|
|
132
|
+
const findings = [];
|
|
133
|
+
const { replaced, args } = fromScripts(files);
|
|
134
|
+
const flags = args === undefined ? undefined : fromFlags(args);
|
|
135
|
+
let value = configText === undefined ? flags : readExport(configText);
|
|
136
|
+
if (Array.isArray(value)) {
|
|
137
|
+
const [first, ...rest] = value;
|
|
138
|
+
rest.forEach((_other, index) => findings.push(finding('second-input', `${POINTER}#/${String(index + 1)}`, 'a second config, and one contractdiff.config.json reads one input', 'write a second contractdiff.config.json for it in its own folder')));
|
|
139
|
+
value = first;
|
|
140
|
+
}
|
|
141
|
+
const config = convert(value, findings);
|
|
142
|
+
const { edits, findings: unwritten } = editScripts(files, replaced);
|
|
143
|
+
return { config, edits, findings: [...findings, ...unwritten], uninstall: 'npm uninstall @hey-api/openapi-ts @hey-api/client-fetch' };
|
|
144
|
+
};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
export const isUnreadable = (value) => typeof value === 'object' && value !== null && Object.keys(value).length === 1 && typeof value.unreadable === 'string';
|
|
2
|
+
const WORDS = new Map([
|
|
3
|
+
['true', true],
|
|
4
|
+
['false', false],
|
|
5
|
+
['null', null],
|
|
6
|
+
['undefined', undefined],
|
|
7
|
+
]);
|
|
8
|
+
const WORD = /-?[\w$.]+/uy;
|
|
9
|
+
const KEY = /[\w$]+/uy;
|
|
10
|
+
const ENDS = new Set(['', ',', ';', ')', ']', '}']);
|
|
11
|
+
const stickyMatch = (pattern, source, index) => {
|
|
12
|
+
pattern.lastIndex = index;
|
|
13
|
+
return pattern.exec(source)?.[0];
|
|
14
|
+
};
|
|
15
|
+
class Reader {
|
|
16
|
+
source;
|
|
17
|
+
at;
|
|
18
|
+
constructor(source, at) {
|
|
19
|
+
this.source = source;
|
|
20
|
+
this.at = at;
|
|
21
|
+
}
|
|
22
|
+
blank() {
|
|
23
|
+
for (;;) {
|
|
24
|
+
const rest = this.source.slice(this.at);
|
|
25
|
+
const skipped = /^(?:\s|\/\/[^\n]*|\/\*[\s\S]*?\*\/)/u.exec(rest)?.[0];
|
|
26
|
+
if (skipped === undefined)
|
|
27
|
+
return;
|
|
28
|
+
this.at += skipped.length;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
peek() {
|
|
32
|
+
this.blank();
|
|
33
|
+
return this.source.charAt(this.at);
|
|
34
|
+
}
|
|
35
|
+
endOfString(start) {
|
|
36
|
+
const quote = this.source.charAt(start);
|
|
37
|
+
let index = start + 1;
|
|
38
|
+
while (index < this.source.length && this.source.charAt(index) !== quote)
|
|
39
|
+
index += this.source.charAt(index) === '\\' ? 2 : 1;
|
|
40
|
+
return index + 1;
|
|
41
|
+
}
|
|
42
|
+
skip() {
|
|
43
|
+
const start = this.at;
|
|
44
|
+
let depth = 0;
|
|
45
|
+
while (this.at < this.source.length) {
|
|
46
|
+
const char = this.source.charAt(this.at);
|
|
47
|
+
if (depth === 0 && /[,;)\]}]/u.test(char))
|
|
48
|
+
break;
|
|
49
|
+
if (/["'`]/u.test(char)) {
|
|
50
|
+
this.at = this.endOfString(this.at);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (/[([{]/u.test(char))
|
|
54
|
+
depth += 1;
|
|
55
|
+
else if (/[)\]}]/u.test(char))
|
|
56
|
+
depth -= 1;
|
|
57
|
+
this.at += 1;
|
|
58
|
+
}
|
|
59
|
+
return { unreadable: this.source.slice(start, this.at).trim() };
|
|
60
|
+
}
|
|
61
|
+
string() {
|
|
62
|
+
const start = this.at;
|
|
63
|
+
const end = this.endOfString(start);
|
|
64
|
+
const body = this.source.slice(start + 1, end - 1);
|
|
65
|
+
this.at = end;
|
|
66
|
+
if (this.source.charAt(start) === '`' && body.includes('${'))
|
|
67
|
+
return { unreadable: this.source.slice(start, end) };
|
|
68
|
+
return body.replaceAll(/\\(.)/gu, '$1');
|
|
69
|
+
}
|
|
70
|
+
list() {
|
|
71
|
+
this.at += 1;
|
|
72
|
+
const items = [];
|
|
73
|
+
while (this.peek() !== ']' && this.at < this.source.length) {
|
|
74
|
+
items.push(this.value());
|
|
75
|
+
if (this.peek() === ',')
|
|
76
|
+
this.at += 1;
|
|
77
|
+
}
|
|
78
|
+
this.at += 1;
|
|
79
|
+
return items;
|
|
80
|
+
}
|
|
81
|
+
key() {
|
|
82
|
+
const char = this.peek();
|
|
83
|
+
if (/["'`]/u.test(char)) {
|
|
84
|
+
const read = this.string();
|
|
85
|
+
return typeof read === 'string' ? read : undefined;
|
|
86
|
+
}
|
|
87
|
+
const word = stickyMatch(KEY, this.source, this.at);
|
|
88
|
+
if (word === undefined)
|
|
89
|
+
return undefined;
|
|
90
|
+
this.at += word.length;
|
|
91
|
+
return word;
|
|
92
|
+
}
|
|
93
|
+
object() {
|
|
94
|
+
this.at += 1;
|
|
95
|
+
const entries = [];
|
|
96
|
+
while (this.peek() !== '}' && this.at < this.source.length) {
|
|
97
|
+
const start = this.at;
|
|
98
|
+
const key = this.key();
|
|
99
|
+
if (key !== undefined && this.peek() === ':') {
|
|
100
|
+
this.at += 1;
|
|
101
|
+
entries.push([key, this.value()]);
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
this.at = start;
|
|
105
|
+
const skipped = this.skip();
|
|
106
|
+
entries.push([skipped.unreadable, skipped]);
|
|
107
|
+
}
|
|
108
|
+
if (this.peek() === ',')
|
|
109
|
+
this.at += 1;
|
|
110
|
+
}
|
|
111
|
+
this.at += 1;
|
|
112
|
+
return Object.fromEntries(entries);
|
|
113
|
+
}
|
|
114
|
+
value() {
|
|
115
|
+
const char = this.peek();
|
|
116
|
+
if (char === '{')
|
|
117
|
+
return this.object();
|
|
118
|
+
if (char === '[')
|
|
119
|
+
return this.list();
|
|
120
|
+
if (/["'`]/u.test(char))
|
|
121
|
+
return this.string();
|
|
122
|
+
const word = stickyMatch(WORD, this.source, this.at);
|
|
123
|
+
if (word !== undefined && ENDS.has(this.source.slice(this.at + word.length).trimStart().charAt(0))) {
|
|
124
|
+
if (WORDS.has(word)) {
|
|
125
|
+
this.at += word.length;
|
|
126
|
+
return WORDS.get(word);
|
|
127
|
+
}
|
|
128
|
+
if (!Number.isNaN(Number(word))) {
|
|
129
|
+
this.at += word.length;
|
|
130
|
+
return Number(word);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return this.skip();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
export const readExport = (source) => {
|
|
137
|
+
const found = /(?:export\s+default|module\.exports\s*=)\s*(?:[$A-Z_a-z][\w$]*\s*\(\s*)?/u.exec(source);
|
|
138
|
+
return found === null ? undefined : new Reader(source, found.index + found[0].length).value();
|
|
139
|
+
};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { posix } from 'node:path';
|
|
2
|
+
import { migrate as migrateTypes } from './migrate-openapi-typescript.js';
|
|
3
|
+
import { finding } from './migrate-shared.js';
|
|
4
|
+
const SOURCE = /\.(?:[cm]?[jt]s|[jt]sx)$/u;
|
|
5
|
+
const DEFAULT_IMPORT = /import\s+([$A-Z_a-z][\w$]*)\s+from\s+(["'])openapi-fetch\2/gu;
|
|
6
|
+
const ANY_IMPORT = /from\s+["']openapi-fetch["']|import\(\s*["']openapi-fetch["']\s*\)|require\(\s*["']openapi-fetch["']\s*\)/gu;
|
|
7
|
+
const CALL = /\.(GET|PUT|POST|DELETE|OPTIONS|HEAD|PATCH|TRACE)\(/gu;
|
|
8
|
+
const lineOf = (text, index) => text.slice(0, index).split('\n').length;
|
|
9
|
+
const specifier = (file, client, text) => {
|
|
10
|
+
const relative = posix.relative(posix.dirname(file), client).replace(/\.ts$/u, /from\s+["']\.\.?\/[^"']*\.js["']/u.test(text) ? '.js' : '');
|
|
11
|
+
return relative.startsWith('.') ? relative : `./${relative}`;
|
|
12
|
+
};
|
|
13
|
+
const TYPE_ARGUMENTS = /<[^>(]*>\(/uy;
|
|
14
|
+
export const dropTypeArguments = (text, name) => {
|
|
15
|
+
let result = '';
|
|
16
|
+
let from = 0;
|
|
17
|
+
for (let at = -1;;) {
|
|
18
|
+
at = text.indexOf(`${name}<`, at + 1);
|
|
19
|
+
if (at === -1)
|
|
20
|
+
break;
|
|
21
|
+
TYPE_ARGUMENTS.lastIndex = at + name.length;
|
|
22
|
+
const match = TYPE_ARGUMENTS.exec(text);
|
|
23
|
+
if (match === null || /[\w$]/u.test(text.charAt(at - 1)))
|
|
24
|
+
continue;
|
|
25
|
+
result += `${text.slice(from, at + name.length)}(`;
|
|
26
|
+
from = at + name.length + match[0].length;
|
|
27
|
+
}
|
|
28
|
+
return result + text.slice(from);
|
|
29
|
+
};
|
|
30
|
+
const rewrite = (path, before, client) => {
|
|
31
|
+
const findings = [];
|
|
32
|
+
let after = before;
|
|
33
|
+
for (const [statement, name = '', quote = ''] of before.matchAll(DEFAULT_IMPORT)) {
|
|
34
|
+
after = after.replace(statement, `import { ${name === 'createClient' ? name : `createClient as ${name}`} } from ${quote}${specifier(path, client, before)}${quote}`);
|
|
35
|
+
after = dropTypeArguments(after, name);
|
|
36
|
+
}
|
|
37
|
+
for (const left of after.matchAll(ANY_IMPORT)) {
|
|
38
|
+
findings.push(finding('import-not-rewritten', `${path}#L${String(lineOf(after, left.index))}`, 'this import of openapi-fetch is not a default `createClient` import', 'import `createClient` from the generated client instead; it has one method per operation'));
|
|
39
|
+
}
|
|
40
|
+
for (const call of after.matchAll(CALL)) {
|
|
41
|
+
findings.push(finding('call-by-path', `${path}#L${String(lineOf(after, call.index))}`, `\`.${String(call[1])}(…)\` calls by method and path, and the generated client has one method per operation`, 'call the method named by the operation’s `operationId` instead'));
|
|
42
|
+
}
|
|
43
|
+
return after === before ? { findings } : { edit: { path, before, after }, findings };
|
|
44
|
+
};
|
|
45
|
+
export const migrate = (configText, files) => {
|
|
46
|
+
const types = migrateTypes(configText, files);
|
|
47
|
+
const uninstall = 'npm uninstall openapi-fetch openapi-typescript';
|
|
48
|
+
if (types.config === undefined)
|
|
49
|
+
return { ...types, uninstall };
|
|
50
|
+
const { out } = types.config.targets.types;
|
|
51
|
+
const client = posix.join(posix.dirname(out), 'client.ts');
|
|
52
|
+
const config = { ...types.config, targets: { ...types.config.targets, fetch: { generator: 'fetch', out: client } } };
|
|
53
|
+
const sources = Object.entries(files)
|
|
54
|
+
.filter(([path, text]) => SOURCE.test(path) && text.includes('openapi-fetch'))
|
|
55
|
+
.map(([path, text]) => rewrite(path, text, client));
|
|
56
|
+
return {
|
|
57
|
+
config,
|
|
58
|
+
edits: [...types.edits, ...sources.flatMap((one) => (one.edit === undefined ? [] : [one.edit]))],
|
|
59
|
+
findings: [...types.findings, ...sources.flatMap((one) => one.findings)],
|
|
60
|
+
uninstall,
|
|
61
|
+
};
|
|
62
|
+
};
|