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.
- 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 +409 -0
- package/dist/props-judge.js +61 -0
- package/dist/props-mutate.js +144 -0
- package/dist/props-random.js +25 -0
- package/dist/props-run.js +176 -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,129 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
import { UsageError } from './run-config.js';
|
|
5
|
+
import { handlersOf, MAP_FILE, parseMap } from './run-map.js';
|
|
6
|
+
export const typescriptIn = (root) => {
|
|
7
|
+
try {
|
|
8
|
+
return createRequire(join(root, 'package.json'))('typescript');
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
throw new UsageError('a rule on code reads handlers with the project\'s own `typescript`, and it is not installed here. fix: `npm install --save-dev typescript`, or turn the rule off');
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
const nameOf = (tsc, name) => (name !== undefined && (tsc.isIdentifier(name) || tsc.isStringLiteral(name)) ? name.text : undefined);
|
|
15
|
+
const isFunctionLike = (tsc, node) => tsc.isMethodDeclaration(node) || tsc.isFunctionExpression(node) || tsc.isArrowFunction(node);
|
|
16
|
+
export const findHandler = (tsc, file, symbol) => {
|
|
17
|
+
const [owner, member] = symbol.split('.');
|
|
18
|
+
let found;
|
|
19
|
+
const memberOf = (members) => {
|
|
20
|
+
for (const each of members) {
|
|
21
|
+
const name = nameOf(tsc, each.name);
|
|
22
|
+
if (name !== member)
|
|
23
|
+
continue;
|
|
24
|
+
if (tsc.isMethodDeclaration(each))
|
|
25
|
+
return each;
|
|
26
|
+
if (tsc.isPropertyAssignment(each) && isFunctionLike(tsc, each.initializer))
|
|
27
|
+
return each.initializer;
|
|
28
|
+
}
|
|
29
|
+
return undefined;
|
|
30
|
+
};
|
|
31
|
+
const visit = (node) => {
|
|
32
|
+
if (found !== undefined)
|
|
33
|
+
return;
|
|
34
|
+
if (tsc.isClassDeclaration(node) && node.name?.text === owner)
|
|
35
|
+
found = memberOf(node.members);
|
|
36
|
+
else if (tsc.isVariableDeclaration(node) && nameOf(tsc, node.name) === owner && node.initializer !== undefined && tsc.isObjectLiteralExpression(node.initializer))
|
|
37
|
+
found = memberOf(node.initializer.properties);
|
|
38
|
+
else
|
|
39
|
+
tsc.forEachChild(node, visit);
|
|
40
|
+
};
|
|
41
|
+
visit(file);
|
|
42
|
+
return found;
|
|
43
|
+
};
|
|
44
|
+
const rootOf = (tsc, node) => {
|
|
45
|
+
if (tsc.isIdentifier(node))
|
|
46
|
+
return node.text;
|
|
47
|
+
return tsc.isPropertyAccessExpression(node) || tsc.isElementAccessExpression(node) ? rootOf(tsc, node.expression) : undefined;
|
|
48
|
+
};
|
|
49
|
+
const calleeOf = (tsc, call) => {
|
|
50
|
+
const callee = call.expression;
|
|
51
|
+
if (tsc.isIdentifier(callee))
|
|
52
|
+
return callee.text;
|
|
53
|
+
return tsc.isPropertyAccessExpression(callee) ? callee.name.text : undefined;
|
|
54
|
+
};
|
|
55
|
+
const returnedOf = (tsc, object) => {
|
|
56
|
+
const members = new Map(object.properties.map((property) => [nameOf(tsc, property.name), property]));
|
|
57
|
+
const status = members.get('status');
|
|
58
|
+
const body = members.get('body');
|
|
59
|
+
const value = (property) => (property !== undefined && tsc.isPropertyAssignment(property) ? property.initializer : undefined);
|
|
60
|
+
const statusValue = value(status);
|
|
61
|
+
const bodyValue = value(body);
|
|
62
|
+
return {
|
|
63
|
+
...(statusValue !== undefined && tsc.isNumericLiteral(statusValue) ? { status: Number(statusValue.text) } : {}),
|
|
64
|
+
hasBody: body !== undefined,
|
|
65
|
+
...(bodyValue !== undefined && tsc.isObjectLiteralExpression(bodyValue)
|
|
66
|
+
? { bodyKeys: bodyValue.properties.flatMap((property) => [nameOf(tsc, property.name)].filter((name) => name !== undefined)) }
|
|
67
|
+
: {}),
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
export const summarize = (tsc, handler) => {
|
|
71
|
+
const first = handler.parameters[0];
|
|
72
|
+
const input = first !== undefined && tsc.isIdentifier(first.name) ? first.name.text : undefined;
|
|
73
|
+
const calls = [];
|
|
74
|
+
const inputCalls = [];
|
|
75
|
+
const returns = [];
|
|
76
|
+
const visit = (node, own) => {
|
|
77
|
+
if (tsc.isCallExpression(node)) {
|
|
78
|
+
const name = calleeOf(tsc, node);
|
|
79
|
+
if (name !== undefined) {
|
|
80
|
+
calls.push(name);
|
|
81
|
+
if (own && input !== undefined && node.arguments.some((argument) => rootOf(tsc, argument) === input))
|
|
82
|
+
inputCalls.push(name);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (own && tsc.isReturnStatement(node) && node.expression !== undefined && tsc.isObjectLiteralExpression(node.expression))
|
|
86
|
+
returns.push(returnedOf(tsc, node.expression));
|
|
87
|
+
tsc.forEachChild(node, (child) => visit(child, own && !isFunctionLike(tsc, child) && !tsc.isFunctionDeclaration(child)));
|
|
88
|
+
};
|
|
89
|
+
if (handler.body !== undefined)
|
|
90
|
+
visit(handler.body, true);
|
|
91
|
+
return { calls: [...new Set(calls)], inputCalls: [...new Set(inputCalls)], returns };
|
|
92
|
+
};
|
|
93
|
+
export const codeIndexOf = (mapOf, root, load) => {
|
|
94
|
+
let map;
|
|
95
|
+
let tsc;
|
|
96
|
+
const files = new Map();
|
|
97
|
+
const sourceOf = (file) => {
|
|
98
|
+
if (!files.has(file)) {
|
|
99
|
+
const path = resolve(root, file);
|
|
100
|
+
tsc ??= load();
|
|
101
|
+
files.set(file, existsSync(path) ? tsc.createSourceFile(file, readFileSync(path, 'utf8'), tsc.ScriptTarget.Latest) : undefined);
|
|
102
|
+
}
|
|
103
|
+
return files.get(file);
|
|
104
|
+
};
|
|
105
|
+
const read = (entry) => {
|
|
106
|
+
const where = { file: entry.file, symbol: entry.symbol, target: entry.target };
|
|
107
|
+
const source = sourceOf(entry.file);
|
|
108
|
+
if (source === undefined)
|
|
109
|
+
return { ...where, missing: `${entry.file} is not there` };
|
|
110
|
+
const found = findHandler(tsc, source, entry.symbol);
|
|
111
|
+
if (found === undefined)
|
|
112
|
+
return { ...where, missing: `${entry.symbol} is not in ${entry.file}` };
|
|
113
|
+
return { ...where, line: source.getLineAndCharacterOfPosition(found.getStart(source)).line + 1, summary: summarize(tsc, found) };
|
|
114
|
+
};
|
|
115
|
+
const cache = new Map();
|
|
116
|
+
return {
|
|
117
|
+
handlersOf: (operation) => {
|
|
118
|
+
if (!cache.has(operation)) {
|
|
119
|
+
map ??= mapOf();
|
|
120
|
+
cache.set(operation, handlersOf(map, operation).map(read));
|
|
121
|
+
}
|
|
122
|
+
return cache.get(operation);
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
};
|
|
126
|
+
export const mapIn = (root) => {
|
|
127
|
+
const path = join(root, MAP_FILE);
|
|
128
|
+
return parseMap(existsSync(path) ? readFileSync(path, 'utf8') : undefined);
|
|
129
|
+
};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `lint`'s rules on code (apicontract-lint spec.md R14, R15, kind 3): a rule whose `given` says
|
|
3
|
+
* `implementation: true` reads, for each operation it selects, the handler the user owns, found
|
|
4
|
+
* through `contractdiff.map.json`. The handler is read once, statically, into a `HandlerSummary`
|
|
5
|
+
* (`lint-code-read.ts`); the functions here judge that summary, pure and total, as the value
|
|
6
|
+
* functions judge a document.
|
|
7
|
+
*/
|
|
8
|
+
import { type Contract } from './core/model.js';
|
|
9
|
+
import { type CodeFunctionName } from './lint-names.js';
|
|
10
|
+
/** One `return { … }` in a handler: its literal status, and its literal body's keys. */
|
|
11
|
+
export interface Returned {
|
|
12
|
+
readonly status?: number;
|
|
13
|
+
/** The property names of a literal `body`; absent when the body is not an object literal or there is none. */
|
|
14
|
+
readonly bodyKeys?: readonly string[];
|
|
15
|
+
/** Whether the object has a `body` member at all. */
|
|
16
|
+
readonly hasBody: boolean;
|
|
17
|
+
}
|
|
18
|
+
/** What a rule on code reads of one handler. */
|
|
19
|
+
export interface HandlerSummary {
|
|
20
|
+
/** The name of every function the handler calls, the last name of a member call. */
|
|
21
|
+
readonly calls: readonly string[];
|
|
22
|
+
/** The functions the handler itself passes its input, or a member of it, to; a nested function's calls are not counted. */
|
|
23
|
+
readonly inputCalls: readonly string[];
|
|
24
|
+
readonly returns: readonly Returned[];
|
|
25
|
+
}
|
|
26
|
+
/** One handler of an operation, as the map names it and the source holds it. */
|
|
27
|
+
export interface Handler {
|
|
28
|
+
readonly file: string;
|
|
29
|
+
readonly symbol: string;
|
|
30
|
+
/** The target that wrote it. */
|
|
31
|
+
readonly target: string;
|
|
32
|
+
/** Where it starts, 1-based; absent when it was not found. */
|
|
33
|
+
readonly line?: number;
|
|
34
|
+
readonly summary?: HandlerSummary;
|
|
35
|
+
/** Why it could not be read, when it could not. */
|
|
36
|
+
readonly missing?: string;
|
|
37
|
+
}
|
|
38
|
+
/** A handler that was found and read: its line and its summary are there. */
|
|
39
|
+
export type ReadHandler = Handler & {
|
|
40
|
+
readonly line: number;
|
|
41
|
+
readonly summary: HandlerSummary;
|
|
42
|
+
};
|
|
43
|
+
/** Whether a handler was found and read, rather than missing. */
|
|
44
|
+
export declare const isRead: (handler: Handler) => handler is ReadHandler;
|
|
45
|
+
/** The handlers of each operation, as `lint` reads them for a run. */
|
|
46
|
+
export interface CodeIndex {
|
|
47
|
+
readonly handlersOf: (operation: string) => readonly Handler[];
|
|
48
|
+
}
|
|
49
|
+
/** The targets whose generated layer validates every request before the handler sees it. */
|
|
50
|
+
export declare const VALIDATING: Set<string>;
|
|
51
|
+
/** One code function on one handler: `undefined` when it holds, else what is wrong. */
|
|
52
|
+
export declare const applyCode: (name: CodeFunctionName, handler: ReadHandler, contract: Contract, options?: Readonly<Record<string, unknown>>) => string | undefined;
|
|
53
|
+
/** The fix for an operation the map has no handler for (R15). */
|
|
54
|
+
export declare const NO_HANDLER_FIX = "generate a server for it with `contractdiff gen` (targets nest, hono, fastify or express record the handler you own in contractdiff.map.json), or drop `implementation` from the rule";
|
|
55
|
+
/** The fix for a handler the map names and the source does not hold. */
|
|
56
|
+
export declare const NOT_FOUND_FIX = "keep the name contractdiff generated for it (the generated code requires it), or run `contractdiff gen` to write the map again";
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { pointerGet } from './core/resolve.js';
|
|
2
|
+
export const isRead = (handler) => handler.summary !== undefined;
|
|
3
|
+
export const VALIDATING = new Set(['nest', 'hono', 'fastify', 'express']);
|
|
4
|
+
const VALIDATORS = ['parse', 'safeParse', 'validate', 'assert'];
|
|
5
|
+
const ERROR = 400;
|
|
6
|
+
const strings = (value) => (Array.isArray(value) && value.every((each) => typeof each === 'string') ? value : undefined);
|
|
7
|
+
const callsOf = (summary, options) => {
|
|
8
|
+
const { name } = options;
|
|
9
|
+
if (typeof name !== 'string' || name === '')
|
|
10
|
+
return '`calls` needs `functionOptions.name`, the function to call';
|
|
11
|
+
return summary.calls.includes(name) ? undefined : `does not call \`${name}\``;
|
|
12
|
+
};
|
|
13
|
+
const validatesOf = (handler, summary, options) => {
|
|
14
|
+
if (VALIDATING.has(handler.target))
|
|
15
|
+
return undefined;
|
|
16
|
+
const names = strings(options.with) ?? VALIDATORS;
|
|
17
|
+
return summary.inputCalls.some((name) => names.includes(name)) ? undefined : `does not pass its input to ${names.map((name) => `\`${name}\``).join(', ')}`;
|
|
18
|
+
};
|
|
19
|
+
const schemaAt = (contract, ref) => {
|
|
20
|
+
try {
|
|
21
|
+
return pointerGet(contract.document, ref);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
const requiredAt = (contract, ref) => {
|
|
28
|
+
if (typeof ref !== 'string' || ref === '')
|
|
29
|
+
return '`returns-error-shape` needs `functionOptions.ref`, a pointer to the error schema';
|
|
30
|
+
const schema = schemaAt(contract, ref);
|
|
31
|
+
if (typeof schema !== 'object' || schema === null)
|
|
32
|
+
return `\`${ref}\` names no schema in the document`;
|
|
33
|
+
return strings(schema.required) ?? [];
|
|
34
|
+
};
|
|
35
|
+
const errorShapeOf = (contract, summary, options) => {
|
|
36
|
+
const required = requiredAt(contract, options.ref);
|
|
37
|
+
if (typeof required === 'string')
|
|
38
|
+
return required;
|
|
39
|
+
const problems = summary.returns.flatMap((returned) => {
|
|
40
|
+
if (returned.status === undefined || returned.status < ERROR)
|
|
41
|
+
return [];
|
|
42
|
+
if (!returned.hasBody)
|
|
43
|
+
return [`returns ${String(returned.status)} with no body`];
|
|
44
|
+
const missing = required.filter((key) => returned.bodyKeys !== undefined && !returned.bodyKeys.includes(key));
|
|
45
|
+
return missing.length === 0 ? [] : [`returns ${String(returned.status)} without ${missing.map((key) => `\`${key}\``).join(', ')} (${options.ref})`];
|
|
46
|
+
});
|
|
47
|
+
return problems.length === 0 ? undefined : problems.join('; ');
|
|
48
|
+
};
|
|
49
|
+
export const applyCode = (name, handler, contract, options = {}) => {
|
|
50
|
+
const { summary } = handler;
|
|
51
|
+
switch (name) {
|
|
52
|
+
case 'calls': {
|
|
53
|
+
return callsOf(summary, options);
|
|
54
|
+
}
|
|
55
|
+
case 'validates-input': {
|
|
56
|
+
return validatesOf(handler, summary, options);
|
|
57
|
+
}
|
|
58
|
+
case 'returns-error-shape': {
|
|
59
|
+
return errorShapeOf(contract, summary, options);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
export const NO_HANDLER_FIX = 'generate a server for it with `contractdiff gen` (targets nest, hono, fastify or express record the handler you own in contractdiff.map.json), or drop `implementation` from the rule';
|
|
64
|
+
export const NOT_FOUND_FIX = 'keep the name contractdiff generated for it (the generated code requires it), or run `contractdiff gen` to write the map again';
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `contractdiff lint`'s engine (apicontract-lint spec.md R1–R4, R8): rules are data, a ruleset maps
|
|
3
|
+
* rule ids to levels, and a run applies every rule that is not `off` to every input, in rule-id
|
|
4
|
+
* order. No rule sees another rule's output. Every finding names its rule, its level, a pointer and
|
|
5
|
+
* a `fix:` line; every run also says how many nodes each rule checked, so a clean run is a count
|
|
6
|
+
* and not only "0 problems" (R3).
|
|
7
|
+
*/
|
|
8
|
+
import { type Contract } from './core/model.js';
|
|
9
|
+
import { type CodeIndex } from './lint-code.js';
|
|
10
|
+
import { type ThenName } from './lint-names.js';
|
|
11
|
+
import { type Given, type LintNode } from './lint-select.js';
|
|
12
|
+
export declare const LEVELS: readonly ["error", "warn", "off"];
|
|
13
|
+
export type Level = (typeof LEVELS)[number];
|
|
14
|
+
export interface Then {
|
|
15
|
+
/** A member of the node, dotted for a nested one (`info.description`); the node itself when absent. */
|
|
16
|
+
readonly field?: string;
|
|
17
|
+
readonly function: ThenName;
|
|
18
|
+
readonly functionOptions?: Readonly<Record<string, unknown>>;
|
|
19
|
+
}
|
|
20
|
+
export interface LintContext {
|
|
21
|
+
readonly contract: Contract;
|
|
22
|
+
}
|
|
23
|
+
export interface Rule {
|
|
24
|
+
readonly description: string;
|
|
25
|
+
readonly given: Given;
|
|
26
|
+
/** What must hold, by the built-in functions; every entry must. */
|
|
27
|
+
readonly then?: Then | readonly Then[];
|
|
28
|
+
/** What must hold, when no built-in function says it: the problems on one node, each a message. Pure. */
|
|
29
|
+
readonly check?: (node: LintNode, context: LintContext) => readonly string[];
|
|
30
|
+
readonly fix: string;
|
|
31
|
+
/**
|
|
32
|
+
* A document and exactly what the rule finds on it (R4): the rule's own test, which the
|
|
33
|
+
* conformance suite runs. Required of a rule a plugin contributes.
|
|
34
|
+
*/
|
|
35
|
+
readonly sample?: RuleSample;
|
|
36
|
+
}
|
|
37
|
+
/** Where a rule finds a problem on its sample, and what it says. */
|
|
38
|
+
export interface SampleFinding {
|
|
39
|
+
readonly pointer: string;
|
|
40
|
+
readonly message: string;
|
|
41
|
+
}
|
|
42
|
+
export interface RuleSample {
|
|
43
|
+
readonly document: unknown;
|
|
44
|
+
readonly findings: readonly SampleFinding[];
|
|
45
|
+
}
|
|
46
|
+
export interface LintFinding {
|
|
47
|
+
readonly rule: string;
|
|
48
|
+
readonly level: Exclude<Level, 'off'>;
|
|
49
|
+
readonly file: string;
|
|
50
|
+
readonly pointer: string;
|
|
51
|
+
readonly message: string;
|
|
52
|
+
readonly fix: string;
|
|
53
|
+
/** For a rule on code (R14): the handler's line, the finding's location; `file` and `pointer` are the spec's, related. */
|
|
54
|
+
readonly code?: {
|
|
55
|
+
readonly file: string;
|
|
56
|
+
readonly line: number;
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/** How a rule did on one run: the nodes it looked at and how many failed. */
|
|
60
|
+
export interface RuleCount {
|
|
61
|
+
readonly checked: number;
|
|
62
|
+
readonly failed: number;
|
|
63
|
+
}
|
|
64
|
+
/** The operations a run lints in full: their ids, and their pointers for a node that names no operation. */
|
|
65
|
+
export interface Touched {
|
|
66
|
+
readonly ids: ReadonlySet<string>;
|
|
67
|
+
readonly sources: readonly string[];
|
|
68
|
+
}
|
|
69
|
+
/** Whether a node belongs to a touched operation: by its operation, else by where it is. */
|
|
70
|
+
export declare const touches: (touched: Touched, node: LintNode) => boolean;
|
|
71
|
+
export interface LintInput {
|
|
72
|
+
readonly file: string;
|
|
73
|
+
readonly contract: Contract;
|
|
74
|
+
/** With `--since` (R12): the operations linted in full; a node of any other runs only `lint.legacy`. */
|
|
75
|
+
readonly touched?: Touched;
|
|
76
|
+
/** The handlers the user owns, for the rules on code (R14); none when absent. */
|
|
77
|
+
readonly code?: CodeIndex;
|
|
78
|
+
}
|
|
79
|
+
export interface LintResult {
|
|
80
|
+
/** Sorted by level (error first), then file, pointer and rule. */
|
|
81
|
+
readonly findings: readonly LintFinding[];
|
|
82
|
+
readonly counts: Readonly<Record<string, RuleCount>>;
|
|
83
|
+
readonly inputs: readonly string[];
|
|
84
|
+
}
|
|
85
|
+
/** What is wrong with one node under one rule, each a message. */
|
|
86
|
+
export declare const problemsOf: (rule: Rule, node: LintNode, context: LintContext) => string[];
|
|
87
|
+
/**
|
|
88
|
+
* Run `rules` at `levels` over every input. A rule at `off`, or absent from `levels`, is not run.
|
|
89
|
+
* On an input with `touched`, only the rules in `legacy` see the untouched operations (R12).
|
|
90
|
+
*/
|
|
91
|
+
export declare const lint: (inputs: readonly LintInput[], rules: Readonly<Record<string, Rule>>, levels: Readonly<Record<string, Level>>, legacy?: ReadonlySet<string>) => LintResult;
|
|
92
|
+
/** What one rule finds on one contract, as a sample states it: pointer and message, in pointer order. */
|
|
93
|
+
export declare const findingsOn: (rule: Rule, contract: Contract) => SampleFinding[];
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { applyCode, isRead, NO_HANDLER_FIX, NOT_FOUND_FIX } from './lint-code.js';
|
|
2
|
+
import { apply } from './lint-functions.js';
|
|
3
|
+
import { CODE_FUNCTIONS } from './lint-names.js';
|
|
4
|
+
import { select } from './lint-select.js';
|
|
5
|
+
export const LEVELS = ['error', 'warn', 'off'];
|
|
6
|
+
const under = (pointer, source) => pointer === source || pointer.startsWith(`${source}/`);
|
|
7
|
+
export const touches = (touched, node) => node.operation === undefined ? touched.sources.some((source) => under(node.pointer, source)) : touched.ids.has(node.operation.id);
|
|
8
|
+
const fieldOf = (value, field) => field === undefined ? value : field.split('.').reduce((at, key) => (typeof at === 'object' && at !== null ? at[key] : undefined), value);
|
|
9
|
+
const thensOf = (rule) => {
|
|
10
|
+
if (rule.then === undefined)
|
|
11
|
+
return [];
|
|
12
|
+
return Array.isArray(rule.then) ? rule.then : [rule.then];
|
|
13
|
+
};
|
|
14
|
+
const named = (then, problem) => {
|
|
15
|
+
if (problem === undefined)
|
|
16
|
+
return [];
|
|
17
|
+
return [then.field === undefined ? problem : `\`${then.field}\` ${problem}`];
|
|
18
|
+
};
|
|
19
|
+
const isCode = (name) => CODE_FUNCTIONS.includes(name);
|
|
20
|
+
const problemOf = (then, node) => {
|
|
21
|
+
if (isCode(then.function))
|
|
22
|
+
return [];
|
|
23
|
+
return named(then, apply(then.function, fieldOf('matched' in node ? node.matched : node.value, then.field), then.functionOptions));
|
|
24
|
+
};
|
|
25
|
+
export const problemsOf = (rule, node, context) => [
|
|
26
|
+
...thensOf(rule).flatMap((then) => problemOf(then, node)),
|
|
27
|
+
...(rule.check?.(node, context) ?? []),
|
|
28
|
+
];
|
|
29
|
+
const RANK = { error: 0, warn: 1 };
|
|
30
|
+
const nodesOf = (input, run) => {
|
|
31
|
+
const nodes = select(input.contract, run.rule.given);
|
|
32
|
+
const { touched } = input;
|
|
33
|
+
return run.legacy || touched === undefined ? nodes : nodes.filter((node) => touches(touched, node));
|
|
34
|
+
};
|
|
35
|
+
const handlerProblems = (rule, handler, contract) => thensOf(rule).flatMap((then) => {
|
|
36
|
+
const options = (then.functionOptions ?? {});
|
|
37
|
+
const problem = isCode(then.function) ? applyCode(then.function, handler, contract, options) : apply(then.function, fieldOf(handler.summary, then.field), options);
|
|
38
|
+
return named(then, problem);
|
|
39
|
+
});
|
|
40
|
+
const codeChecks = (rule, node, input) => {
|
|
41
|
+
const operation = node.operation;
|
|
42
|
+
const handlers = input.code?.handlersOf(operation.id) ?? [];
|
|
43
|
+
if (handlers.length === 0) {
|
|
44
|
+
return [{ pointer: node.pointer, problems: [`map-has-no-handler: \`${operation.id}\` has no handler you own in contractdiff.map.json`], fix: NO_HANDLER_FIX }];
|
|
45
|
+
}
|
|
46
|
+
return handlers.map((handler) => {
|
|
47
|
+
const where = { pointer: node.pointer, name: handler.symbol };
|
|
48
|
+
if (!isRead(handler))
|
|
49
|
+
return { ...where, problems: [`handler-not-found: ${handler.missing}`], fix: NOT_FOUND_FIX };
|
|
50
|
+
return { ...where, problems: handlerProblems(rule, handler, input.contract), code: { file: handler.file, line: handler.line } };
|
|
51
|
+
});
|
|
52
|
+
};
|
|
53
|
+
const checksOf = (input, run) => nodesOf(input, run).flatMap((node) => run.rule.given.implementation === true ? codeChecks(run.rule, node, input) : [{ pointer: node.pointer, name: node.name, problems: problemsOf(run.rule, node, { contract: input.contract }) }]);
|
|
54
|
+
const findingsOf = (check, of) => check.problems.map((message) => ({
|
|
55
|
+
...of,
|
|
56
|
+
pointer: check.pointer,
|
|
57
|
+
message: check.name === undefined ? message : `${check.name}: ${message}`,
|
|
58
|
+
fix: check.fix ?? of.fix,
|
|
59
|
+
...(check.code === undefined ? {} : { code: check.code }),
|
|
60
|
+
}));
|
|
61
|
+
const runRule = (run, inputs) => {
|
|
62
|
+
const { id, rule, level } = run;
|
|
63
|
+
const findings = [];
|
|
64
|
+
let checked = 0;
|
|
65
|
+
let failed = 0;
|
|
66
|
+
for (const input of inputs) {
|
|
67
|
+
for (const check of checksOf(input, run)) {
|
|
68
|
+
checked += 1;
|
|
69
|
+
if (check.problems.length > 0)
|
|
70
|
+
failed += 1;
|
|
71
|
+
findings.push(...findingsOf(check, { rule: id, level, file: input.file, fix: rule.fix }));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return { findings, count: { checked, failed } };
|
|
75
|
+
};
|
|
76
|
+
export const lint = (inputs, rules, levels, legacy = new Set()) => {
|
|
77
|
+
const runs = Object.entries(levels)
|
|
78
|
+
.flatMap(([id, level]) => {
|
|
79
|
+
const rule = new Map(Object.entries(rules)).get(id);
|
|
80
|
+
return level === 'off' || rule === undefined ? [] : [{ id, ...runRule({ id, rule, level, legacy: legacy.has(id) }, inputs) }];
|
|
81
|
+
})
|
|
82
|
+
.sort((a, b) => a.id.localeCompare(b.id, 'en'));
|
|
83
|
+
const findings = runs.flatMap((run) => run.findings);
|
|
84
|
+
findings.sort((a, b) => RANK[a.level] - RANK[b.level] || a.file.localeCompare(b.file, 'en') || a.pointer.localeCompare(b.pointer, 'en') || a.rule.localeCompare(b.rule, 'en'));
|
|
85
|
+
return { findings, counts: Object.fromEntries(runs.map((run) => [run.id, run.count])), inputs: inputs.map((input) => input.file) };
|
|
86
|
+
};
|
|
87
|
+
export const findingsOn = (rule, contract) => lint([{ file: 'sample', contract }], { rule }, { rule: 'warn' }).findings.map(({ pointer, message }) => ({ pointer, message }));
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { check } from 'truefit';
|
|
2
|
+
import { fromJsonSchema } from 'truefit/json-schema';
|
|
3
|
+
export const CASINGS = ['camel', 'pascal', 'kebab', 'snake', 'macro', 'flat'];
|
|
4
|
+
const CASE = {
|
|
5
|
+
camel: /^[a-z][a-zA-Z\d]*$/u,
|
|
6
|
+
pascal: /^[A-Z][a-zA-Z\d]*$/u,
|
|
7
|
+
kebab: /^[a-z][a-z\d]*(?:-[a-z\d]+)*$/u,
|
|
8
|
+
snake: /^[a-z][a-z\d]*(?:_[a-z\d]+)*$/u,
|
|
9
|
+
macro: /^[A-Z][A-Z\d]*(?:_[A-Z\d]+)*$/u,
|
|
10
|
+
flat: /^[a-z][a-z\d]*$/u,
|
|
11
|
+
};
|
|
12
|
+
const membersOf = (value) => Object(value);
|
|
13
|
+
const shown = (value) => (value === undefined ? 'missing' : JSON.stringify(value));
|
|
14
|
+
const sizeOf = (value) => {
|
|
15
|
+
if (typeof value === 'string' || Array.isArray(value))
|
|
16
|
+
return value.length;
|
|
17
|
+
return typeof value === 'object' && value !== null ? Object.keys(value).length : undefined;
|
|
18
|
+
};
|
|
19
|
+
const lengthOf = (value, options) => {
|
|
20
|
+
if (value === undefined)
|
|
21
|
+
return 'is missing';
|
|
22
|
+
const size = sizeOf(value);
|
|
23
|
+
if (size === undefined)
|
|
24
|
+
return `${shown(value)} has no length`;
|
|
25
|
+
const { min, max } = options;
|
|
26
|
+
if (typeof min === 'number' && size < min)
|
|
27
|
+
return `has ${String(size)}, fewer than ${String(min)}`;
|
|
28
|
+
if (typeof max === 'number' && size > max)
|
|
29
|
+
return `has ${String(size)}, more than ${String(max)}`;
|
|
30
|
+
return undefined;
|
|
31
|
+
};
|
|
32
|
+
const patternOf = (value, options) => {
|
|
33
|
+
if (typeof value !== 'string')
|
|
34
|
+
return `${shown(value)} is not a string`;
|
|
35
|
+
const { match, notMatch } = options;
|
|
36
|
+
if (typeof match === 'string' && !new RegExp(match, 'u').test(value))
|
|
37
|
+
return `${shown(value)} does not match ${match}`;
|
|
38
|
+
if (typeof notMatch === 'string' && new RegExp(notMatch, 'u').test(value))
|
|
39
|
+
return `${shown(value)} matches ${notMatch}`;
|
|
40
|
+
return undefined;
|
|
41
|
+
};
|
|
42
|
+
const casingOf = (value, options) => {
|
|
43
|
+
const type = options.type;
|
|
44
|
+
if (typeof value !== 'string')
|
|
45
|
+
return `${shown(value)} is not a string`;
|
|
46
|
+
return CASE[type].test(value) ? undefined : `${shown(value)} is not ${type} case`;
|
|
47
|
+
};
|
|
48
|
+
const xorOf = (value, options) => {
|
|
49
|
+
const names = (options.properties ?? []);
|
|
50
|
+
const present = names.filter((name) => membersOf(value)[name] !== undefined);
|
|
51
|
+
if (present.length === 1)
|
|
52
|
+
return undefined;
|
|
53
|
+
const has = present.length === 0 ? 'none' : present.join(' and ');
|
|
54
|
+
return `has ${has} of ${names.join(', ')}; exactly one is wanted`;
|
|
55
|
+
};
|
|
56
|
+
export const validAgainst = (schema, value, draft = '2020-12') => {
|
|
57
|
+
const imported = fromJsonSchema(schema, { draft });
|
|
58
|
+
return check(imported.schema, value) ? undefined : `${shown(value)} is not valid against its schema`;
|
|
59
|
+
};
|
|
60
|
+
export const apply = (name, value, options = {}) => {
|
|
61
|
+
switch (name) {
|
|
62
|
+
case 'truthy': {
|
|
63
|
+
return value === undefined || value === null || value === false || value === '' || value === 0 ? `is ${shown(value)}` : undefined;
|
|
64
|
+
}
|
|
65
|
+
case 'falsy': {
|
|
66
|
+
return value === undefined || value === null || value === false || value === '' || value === 0 ? undefined : `is ${shown(value)}`;
|
|
67
|
+
}
|
|
68
|
+
case 'defined': {
|
|
69
|
+
return value === undefined ? 'is missing' : undefined;
|
|
70
|
+
}
|
|
71
|
+
case 'undefined': {
|
|
72
|
+
return value === undefined ? undefined : `is ${shown(value)}`;
|
|
73
|
+
}
|
|
74
|
+
case 'pattern': {
|
|
75
|
+
return patternOf(value, options);
|
|
76
|
+
}
|
|
77
|
+
case 'casing': {
|
|
78
|
+
return casingOf(value, options);
|
|
79
|
+
}
|
|
80
|
+
case 'enumeration': {
|
|
81
|
+
const values = (options.values ?? []);
|
|
82
|
+
return values.includes(value) ? undefined : `${shown(value)} is not one of ${values.map((item) => JSON.stringify(item)).join(', ')}`;
|
|
83
|
+
}
|
|
84
|
+
case 'length': {
|
|
85
|
+
return lengthOf(value, options);
|
|
86
|
+
}
|
|
87
|
+
case 'xor': {
|
|
88
|
+
return xorOf(value, options);
|
|
89
|
+
}
|
|
90
|
+
case 'schema': {
|
|
91
|
+
return validAgainst(options.schema, value);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
export { FUNCTIONS } from './lint-names.js';
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { ambientRuntime, run } from 'bellpull';
|
|
2
|
+
import { parse as parseYaml } from 'seniority/yaml';
|
|
3
|
+
import { readRedocly } from './lint-redocly.js';
|
|
4
|
+
import { rules } from './lint-rules.js';
|
|
5
|
+
import { readSpectral } from './lint-spectral.js';
|
|
6
|
+
import { ConfigError, UsageError, validateConfig } from './run-config.js';
|
|
7
|
+
const git = async (cwd, runtime, args) => {
|
|
8
|
+
const result = await run('git', args, { cwd, runtime }).catch(() => undefined);
|
|
9
|
+
return result?.ok === true ? result.stdout : undefined;
|
|
10
|
+
};
|
|
11
|
+
const lineOf = (text) => {
|
|
12
|
+
const line = text?.trim();
|
|
13
|
+
return line === '' ? undefined : line;
|
|
14
|
+
};
|
|
15
|
+
export const gitIn = (cwd, ambient = ambientRuntime()) => {
|
|
16
|
+
const runtime = { ...ambient, env: Object.fromEntries(Object.entries(ambient.env).filter(([key]) => !key.startsWith('GIT_'))) };
|
|
17
|
+
return {
|
|
18
|
+
commit: async (ref) => lineOf(await git(cwd, runtime, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`])),
|
|
19
|
+
mergeBase: async () => lineOf(await git(cwd, runtime, ['merge-base', 'HEAD', 'origin/main'])),
|
|
20
|
+
before: async (date) => lineOf(await git(cwd, runtime, ['rev-list', '-1', `--before=${date.toISOString()}`, 'HEAD'])),
|
|
21
|
+
show: (commit, path) => git(cwd, runtime, ['show', `${commit}:./${path}`]),
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
export const changesOf = (base, working) => {
|
|
25
|
+
const levels = { base: new Map(Object.entries(base.levels)), working: new Map(Object.entries(working.levels)) };
|
|
26
|
+
const all = { base: new Map(Object.entries(base.all)), working: new Map(Object.entries(working.all)) };
|
|
27
|
+
const ids = [...new Set([...levels.base.keys(), ...levels.working.keys()])].sort();
|
|
28
|
+
return ids.flatMap((id) => {
|
|
29
|
+
const from = levels.base.get(id);
|
|
30
|
+
const to = levels.working.get(id);
|
|
31
|
+
const definition = all.base.has(id) && all.working.has(id) && JSON.stringify(all.base.get(id)) !== JSON.stringify(all.working.get(id));
|
|
32
|
+
return from === to && !definition ? [] : [{ id, from, to, definition }];
|
|
33
|
+
});
|
|
34
|
+
};
|
|
35
|
+
export const WARN_FOR = /^(\d+)d$/u;
|
|
36
|
+
const DAY = 86_400_000;
|
|
37
|
+
export const cutoffOf = (warnFor, now) => new Date(now.getTime() - Number(WARN_FOR.exec(warnFor)?.[1]) * DAY);
|
|
38
|
+
export const newRulesOf = (levels, then) => {
|
|
39
|
+
const before = new Map(Object.entries(then));
|
|
40
|
+
return Object.entries(levels).flatMap(([id, level]) => (level === 'error' && (before.get(id) ?? 'off') === 'off' ? [id] : []));
|
|
41
|
+
};
|
|
42
|
+
export const DEFAULT_RULESETS = ['recommended'];
|
|
43
|
+
export const DEFAULT_WARN_FOR = '14d';
|
|
44
|
+
export const RULESET_FILE = /\.(?:json|ya?ml)$/u;
|
|
45
|
+
const KNOWN = new Set(Object.keys(rules));
|
|
46
|
+
export const SHORT = 7;
|
|
47
|
+
export const rulesetOfText = (name, read, configFile) => {
|
|
48
|
+
let document;
|
|
49
|
+
try {
|
|
50
|
+
document = parseYaml(read());
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
throw new ConfigError(configFile, [`\`lint.extends\` names ${name}, which cannot be read (${error.message}). fix: correct its path; it is read from the config's folder`]);
|
|
54
|
+
}
|
|
55
|
+
return (/redocly/iu.test(name.split('/').at(-1)) ? readRedocly : readSpectral)(document, name, KNOWN);
|
|
56
|
+
};
|
|
57
|
+
export const sourcesOf = (lint, flagged, read) => {
|
|
58
|
+
const names = flagged ?? lint?.extends ?? DEFAULT_RULESETS;
|
|
59
|
+
return { names, overrides: lint?.rules, files: Object.fromEntries(names.filter((name) => RULESET_FILE.test(name)).map((name) => [name, read(name)])), warnFor: lint?.warnFor ?? DEFAULT_WARN_FOR };
|
|
60
|
+
};
|
|
61
|
+
const sourcesAt = async (git, commit, config, flagged) => {
|
|
62
|
+
const where = `${config.name} at ${commit.slice(0, SHORT)}`;
|
|
63
|
+
const text = await git.show(commit, config.name);
|
|
64
|
+
let lint;
|
|
65
|
+
if (text !== undefined) {
|
|
66
|
+
let value;
|
|
67
|
+
try {
|
|
68
|
+
value = JSON.parse(text);
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
throw new ConfigError(where, [`it is not JSON (${error.message}). fix: correct it in a commit, or pass a later ref`]);
|
|
72
|
+
}
|
|
73
|
+
lint = validateConfig(value, where).lint;
|
|
74
|
+
}
|
|
75
|
+
const names = (flagged ?? lint?.extends ?? DEFAULT_RULESETS).filter((name) => RULESET_FILE.test(name));
|
|
76
|
+
const texts = new Map(await Promise.all(names.map(async (name) => [name, await git.show(commit, name)])));
|
|
77
|
+
return sourcesOf(lint, flagged, (name) => rulesetOfText(name, () => texts.get(name) ?? uncommitted(name, commit), where));
|
|
78
|
+
};
|
|
79
|
+
const uncommitted = (name, commit) => {
|
|
80
|
+
throw new Error(`it is not in commit ${commit.slice(0, SHORT)}`);
|
|
81
|
+
};
|
|
82
|
+
export const commitOf = async (git, flag, ref) => {
|
|
83
|
+
const commit = ref === 'merge-base' ? await git.mergeBase() : await git.commit(ref);
|
|
84
|
+
return commit ?? missing(flag, ref, await git.commit('HEAD'));
|
|
85
|
+
};
|
|
86
|
+
const missing = (flag, ref, head) => {
|
|
87
|
+
if (head === undefined)
|
|
88
|
+
return undefined;
|
|
89
|
+
throw new UsageError(`\`${flag} ${ref}\` names no commit here. fix: fetch it first (in CI, \`git fetch origin main\`), or pass a ref this checkout has`);
|
|
90
|
+
};
|
|
91
|
+
const appliedOf = async (run) => {
|
|
92
|
+
const ref = run.rulesFrom;
|
|
93
|
+
if (ref === undefined)
|
|
94
|
+
return { sources: run.working, changed: [] };
|
|
95
|
+
if (run.config === undefined)
|
|
96
|
+
return { sources: run.working, from: 'the working tree: there is no config to read at a ref', changed: [] };
|
|
97
|
+
if (!run.config.name.endsWith('.json'))
|
|
98
|
+
throw new UsageError(`\`--rules-from\` reads contractdiff.config.json at the ref, and the config is ${run.config.name}. fix: move the config to contractdiff.config.json, or drop --rules-from`);
|
|
99
|
+
const commit = await commitOf(run.git, '--rules-from', ref);
|
|
100
|
+
if (commit === undefined)
|
|
101
|
+
return { sources: run.working, from: 'the working tree: not a git repository', changed: [] };
|
|
102
|
+
const sources = await sourcesAt(run.git, commit, run.config, run.flagged);
|
|
103
|
+
return { sources, from: `${ref} (${commit.slice(0, SHORT)})`, changed: changesOf(run.resolve(sources), run.resolve(run.working)) };
|
|
104
|
+
};
|
|
105
|
+
const thenOf = async (run, warnFor) => {
|
|
106
|
+
const config = run.config;
|
|
107
|
+
if (!config.name.endsWith('.json'))
|
|
108
|
+
return 'the config is not JSON, so its history is not read';
|
|
109
|
+
if ((await run.git.commit('HEAD')) === undefined)
|
|
110
|
+
return 'not a git repository';
|
|
111
|
+
const commit = await run.git.before(cutoffOf(warnFor, run.now));
|
|
112
|
+
if (commit === undefined)
|
|
113
|
+
return {};
|
|
114
|
+
try {
|
|
115
|
+
return run.resolve(await sourcesAt(run.git, commit, config, run.flagged)).levels;
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
return `the rules at ${commit.slice(0, SHORT)} cannot be read (${error.message.split('\n')[0]})`;
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
export const historyOf = async (run) => {
|
|
122
|
+
const applied = await appliedOf(run);
|
|
123
|
+
const resolved = run.resolve(applied.sources);
|
|
124
|
+
const atError = Object.values(resolved.levels).includes('error');
|
|
125
|
+
if (!atError || run.config === undefined || cutoffOf(applied.sources.warnFor, run.now).getTime() === run.now.getTime())
|
|
126
|
+
return { ...applied, resolved, warnFirst: [] };
|
|
127
|
+
const then = await thenOf(run, applied.sources.warnFor);
|
|
128
|
+
if (typeof then === 'string')
|
|
129
|
+
return { ...applied, resolved, warnFirst: [], unchecked: then };
|
|
130
|
+
const warnFirst = newRulesOf(resolved.levels, then);
|
|
131
|
+
const levels = { ...resolved.levels, ...Object.fromEntries(warnFirst.map((id) => [id, 'warn'])) };
|
|
132
|
+
return { ...applied, resolved: { all: resolved.all, levels }, warnFirst };
|
|
133
|
+
};
|