@astro-spec/diff 0.0.0-stage → 1.0.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 otoneko.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,75 @@
1
- # Temporary Holding Version
1
+ # @astro-spec/diff
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Detect breaking changes between two OpenAPI documents, such as those astro-spec writes
4
+
5
+ Compares the OpenAPI document of your actions and endpoints before and after a change, and fails when the change can break a client written against the old one. Run it in CI next to the document that [`@astro-spec/openapi`](../openapi#readme) writes with `outputFile`.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install --save-dev @astro-spec/diff
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```sh
16
+ npx astro-spec-diff old.json openapi.json
17
+ ```
18
+
19
+ ```text
20
+ BREAKING POST /_actions/user.get request body (application/json).tenant: Is now required.
21
+ BREAKING POST /_actions/user.get response 200 (application/json+devalue).createdAt: Is no longer always present.
22
+ info GET /api/users/{id}: The operation was added.
23
+
24
+ 2 breaking changes.
25
+ ```
26
+
27
+ Each document can be a file or a URL. Add `--json` to print the changes as JSON.
28
+
29
+ The command exits with status 0 when nothing breaks, 1 when something does, and 2 when the arguments are wrong or a document cannot be read.
30
+
31
+ ## What counts as breaking
32
+
33
+ A change is breaking when a client written against the old document can fail against the new one. Requests and responses are checked in opposite directions: a request must still accept everything it accepted, and a successful response must not hold anything it never held.
34
+
35
+ | Where | Breaking | Not breaking |
36
+ | --- | --- | --- |
37
+ | Operations | An operation is removed. | An operation is added or deprecated. |
38
+ | Request body and parameters | A property or parameter becomes required, a type or enum value is no longer accepted, a media type is removed, or a property is removed from an object that allows no other properties. | An optional property or parameter is added, or a type is widened. |
39
+ | Successful responses | A required property is removed or becomes optional, a type is widened (for example, it can now be `null`), or an enum value is added. | A property is added, or a type is narrowed. |
40
+
41
+ The comparison covers types, enum and `const` values, object properties and their `required` lists, and array items, with local `$ref`s followed. Error responses and keywords such as string lengths are not compared.
42
+
43
+ ## In GitHub Actions
44
+
45
+ Commit the document with `outputFile`, then compare it with the one on the base branch in pull requests:
46
+
47
+ ```yaml
48
+ name: API
49
+ on: pull_request
50
+
51
+ jobs:
52
+ breaking-changes:
53
+ runs-on: ubuntu-latest
54
+ steps:
55
+ - uses: actions/checkout@v7
56
+ with:
57
+ fetch-depth: 0
58
+ - uses: actions/setup-node@v7
59
+ with:
60
+ node-version: 24
61
+ - run: npm ci
62
+ - run: npm run build
63
+ - run: git show origin/${{ github.base_ref }}:openapi.json > base-openapi.json
64
+ - run: npx astro-spec-diff base-openapi.json openapi.json
65
+ ```
66
+
67
+ `npm run build` writes `openapi.json` from the code in the pull request, so the comparison holds even if the committed file was not regenerated.
68
+
69
+ ## API
70
+
71
+ `diffDocuments(before, after)` returns the changes as `{ operation, location, message, breaking }` objects, breaking ones first. `runDiffCli(args)` runs the command and resolves to `true` when something breaks. Both are exported from `@astro-spec/diff`.
72
+
73
+ ## License
74
+
75
+ [MIT](https://github.com/betterlib/astro-spec/blob/main/LICENSE)
package/dist/bin.d.mts ADDED
@@ -0,0 +1 @@
1
+ export {}
package/dist/bin.mjs ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { t as runDiffCli } from "./run-diff-cli-CvHPymms.mjs";
3
+ // src/bin.ts
4
+ try {
5
+ if (await runDiffCli(process.argv.slice(2))) process.exitCode = 1;
6
+ } catch (error) {
7
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
8
+ process.exitCode = 2;
9
+ }
10
+ export {};
@@ -0,0 +1,38 @@
1
+ type Change = {
2
+ breaking: boolean;
3
+ location: string;
4
+ message: string;
5
+ };
6
+ /** An OpenAPI 3.1 document, as far as the comparison reads it. */
7
+ type OpenApiDocument = {
8
+ paths?: Record<string, Record<string, unknown>>;
9
+ };
10
+ /** One difference between two documents, for the operation named by `operation`. */
11
+ type DocumentChange = Change & {
12
+ operation: string;
13
+ };
14
+ /**
15
+ * Compares two OpenAPI documents and lists what changed for clients, breaking changes first.
16
+ * A change is breaking when a client written against `before` can fail against `after`: an
17
+ * operation or success response was removed, a request now needs or rejects something, or a
18
+ * successful response can now hold something it never held before.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * const changes = diffDocuments(oldDocument, newDocument)
23
+ * if (changes.some(({ breaking }) => breaking)) process.exitCode = 1
24
+ * ```
25
+ */
26
+ export declare const diffDocuments: (before: OpenApiDocument, after: OpenApiDocument) => DocumentChange[];
27
+ /**
28
+ * Runs the `astro-spec-diff` command with the given arguments, without the node and script
29
+ * paths. Resolves to `true` when it found a breaking change, so the caller can set the exit
30
+ * code. Throws when the arguments are wrong or a document cannot be read.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * if (await runDiffCli(['old.json', 'openapi.json'])) process.exitCode = 1
35
+ * ```
36
+ */
37
+ export declare const runDiffCli: (args: string[]) => Promise<boolean>;
38
+ export type { DocumentChange, OpenApiDocument };
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ export { n as diffDocuments, t as runDiffCli } from "./run-diff-cli-CvHPymms.mjs";
@@ -0,0 +1,284 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ // src/diff-schemas.ts
5
+ const jsonType = (value) => value === null ? "null" : Array.isArray(value) ? "array" : Number.isInteger(value) ? "integer" : typeof value;
6
+ const typesOf = (schema) => {
7
+ if (schema.type !== void 0) return new Set(Array.isArray(schema.type) ? schema.type : [schema.type]);
8
+ if (schema.const !== void 0) return /* @__PURE__ */ new Set([jsonType(schema.const)]);
9
+ if (schema.enum) return new Set(schema.enum.map(jsonType));
10
+ const members = schema.anyOf ?? schema.oneOf;
11
+ if (!members) return void 0;
12
+ const memberTypes = members.map(typesOf);
13
+ if (memberTypes.some((types) => types === void 0)) return void 0;
14
+ return new Set(memberTypes.flatMap((types) => [...types ?? []]));
15
+ };
16
+ const allows = (allowed, type) => allowed.has(type) || type === "integer" && allowed.has("number");
17
+ const valuesOf = (schema) => schema.const !== void 0 ? [schema.const] : schema.enum;
18
+ const sameValue = (a, b) => JSON.stringify(a) === JSON.stringify(b);
19
+ const at = (location, key) => location ? `${location}.${key}` : key;
20
+ /**
21
+ * Lists the differences between two versions of a schema that matter to a client. In a request,
22
+ * a change is breaking when the new schema rejects something the old one accepted; in a
23
+ * response, when the new schema allows something the old one never produced.
24
+ *
25
+ * Both schemas must have their `$ref`s inlined. It compares types, enum values, object
26
+ * properties and their `required` lists, and array items. Other keywords, such as string
27
+ * lengths, are not compared.
28
+ */
29
+ const diffSchemas = (old, next, direction, location = "") => {
30
+ const [narrow, wide] = direction === "request" ? [old, next] : [next, old];
31
+ const breaking = (message) => ({
32
+ breaking: true,
33
+ location,
34
+ message
35
+ });
36
+ const changes = [];
37
+ const narrowTypes = typesOf(narrow);
38
+ const wideTypes = typesOf(wide);
39
+ if (wideTypes) {
40
+ const lost = narrowTypes ? [...narrowTypes].filter((type) => !allows(wideTypes, type)) : ["any"];
41
+ if (lost.length > 0) changes.push(breaking(direction === "request" ? `No longer accepts ${lost.join(", ")}.` : `Can now be ${lost.join(", ")}.`));
42
+ }
43
+ const narrowValues = valuesOf(narrow);
44
+ const wideValues = valuesOf(wide);
45
+ if (wideValues) {
46
+ const list = (values) => values.map((value) => JSON.stringify(value)).join(", ");
47
+ if (!narrowValues) changes.push(breaking(direction === "request" ? `Only accepts ${list(wideValues)}.` : "Is no longer limited to fixed values."));
48
+ else {
49
+ const lost = narrowValues.filter((value) => !wideValues.some((other) => sameValue(value, other)));
50
+ if (lost.length > 0) changes.push(breaking(direction === "request" ? `No longer accepts ${list(lost)}.` : `Can now be ${list(lost)}.`));
51
+ }
52
+ }
53
+ const oldProperties = old.properties ?? {};
54
+ const nextProperties = next.properties ?? {};
55
+ const oldRequired = new Set(old.required ?? []);
56
+ const nextRequired = new Set(next.required ?? []);
57
+ for (const name of /* @__PURE__ */ new Set([...Object.keys(oldProperties), ...Object.keys(nextProperties)])) {
58
+ const property = at(location, name);
59
+ const oldProperty = oldProperties[name];
60
+ const nextProperty = nextProperties[name];
61
+ if (direction === "request") {
62
+ if (nextRequired.has(name) && !oldRequired.has(name)) changes.push({
63
+ breaking: true,
64
+ location: property,
65
+ message: "Is now required."
66
+ });
67
+ else if (oldProperty && !nextProperty) changes.push({
68
+ breaking: next.additionalProperties === false,
69
+ location: property,
70
+ message: "Was removed."
71
+ });
72
+ else if (!oldProperty && nextProperty) changes.push({
73
+ breaking: false,
74
+ location: property,
75
+ message: "Was added."
76
+ });
77
+ } else if (oldRequired.has(name) && !nextRequired.has(name)) changes.push({
78
+ breaking: true,
79
+ location: property,
80
+ message: nextProperty ? "Is no longer always present." : "Was removed."
81
+ });
82
+ else if (!oldProperty && nextProperty) changes.push({
83
+ breaking: false,
84
+ location: property,
85
+ message: "Was added."
86
+ });
87
+ if (oldProperty && nextProperty) changes.push(...diffSchemas(oldProperty, nextProperty, direction, property));
88
+ }
89
+ if (old.items && next.items) changes.push(...diffSchemas(old.items, next.items, direction, at(location, "[]")));
90
+ return changes;
91
+ };
92
+ // src/diff-documents.ts
93
+ const METHODS = [
94
+ "get",
95
+ "put",
96
+ "post",
97
+ "delete",
98
+ "options",
99
+ "head",
100
+ "patch",
101
+ "trace"
102
+ ];
103
+ const operationsOf = (document) => new Map(Object.entries(document.paths ?? {}).flatMap(([path, item]) => METHODS.filter((method) => item[method]).map((method) => [`${method.toUpperCase()} ${path}`, item[method]])));
104
+ const lookUp = (document, ref) => ref.slice(2).split("/").map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~")).reduce((node, key) => node?.[key], document);
105
+ const createInline = (document) => {
106
+ const inline = (value, seen) => {
107
+ if (Array.isArray(value)) return value.map((item) => inline(item, seen));
108
+ if (typeof value !== "object" || value === null) return value;
109
+ const { $ref, ...rest } = value;
110
+ if (typeof $ref === "string" && $ref.startsWith("#/")) {
111
+ if (seen.has($ref)) return {};
112
+ return inline(lookUp(document, $ref) ?? {}, /* @__PURE__ */ new Set([...seen, $ref]));
113
+ }
114
+ return Object.fromEntries(Object.entries(rest).map(([key, item]) => [key, inline(item, seen)]));
115
+ };
116
+ return (schema) => inline(schema ?? {}, /* @__PURE__ */ new Set());
117
+ };
118
+ const parameterKey = ({ name, in: location }) => `${location} ${name}`;
119
+ const diffParameters = (before, after, inline) => {
120
+ const old = new Map((before.parameters ?? []).map((parameter) => [parameterKey(parameter), parameter]));
121
+ const next = new Map((after.parameters ?? []).map((parameter) => [parameterKey(parameter), parameter]));
122
+ return [.../* @__PURE__ */ new Set([...old.keys(), ...next.keys()])].flatMap((key) => {
123
+ const oldParameter = old.get(key);
124
+ const nextParameter = next.get(key);
125
+ const location = `parameter ${key}`;
126
+ if (!oldParameter) return [nextParameter?.required ? {
127
+ breaking: true,
128
+ location,
129
+ message: "Was added as required."
130
+ } : {
131
+ breaking: false,
132
+ location,
133
+ message: "Was added."
134
+ }];
135
+ if (!nextParameter) return [{
136
+ breaking: false,
137
+ location,
138
+ message: "Was removed."
139
+ }];
140
+ return [...nextParameter.required && !oldParameter.required ? [{
141
+ breaking: true,
142
+ location,
143
+ message: "Is now required."
144
+ }] : [], ...diffSchemas(inline.before(oldParameter.schema), inline.after(nextParameter.schema), "request", location)];
145
+ });
146
+ };
147
+ const diffContent = (before, after, direction, location, inline) => Object.entries(before ?? {}).flatMap(([mediaType, media]) => {
148
+ const nextMedia = after?.[mediaType];
149
+ const mediaLocation = `${location} (${mediaType})`;
150
+ if (!nextMedia) return [{
151
+ breaking: true,
152
+ location: mediaLocation,
153
+ message: "This media type was removed."
154
+ }];
155
+ return diffSchemas(inline.before(media.schema), inline.after(nextMedia.schema), direction, mediaLocation);
156
+ });
157
+ const isSuccess = (status) => /^2\d\d$/.test(status);
158
+ const diffOperation = (before, after, inline) => {
159
+ const changes = [];
160
+ if (after.deprecated && !before.deprecated) changes.push({
161
+ breaking: false,
162
+ location: "",
163
+ message: "Is now deprecated."
164
+ });
165
+ changes.push(...diffParameters(before, after, inline));
166
+ if (after.requestBody?.required && !before.requestBody?.required) changes.push({
167
+ breaking: true,
168
+ location: "request body",
169
+ message: "Is now required."
170
+ });
171
+ changes.push(...diffContent(before.requestBody?.content, after.requestBody?.content, "request", "request body", inline));
172
+ for (const [status, response] of Object.entries(before.responses ?? {})) {
173
+ if (!isSuccess(status)) continue;
174
+ const nextResponse = after.responses?.[status];
175
+ if (!nextResponse) {
176
+ changes.push({
177
+ breaking: true,
178
+ location: `response ${status}`,
179
+ message: "Was removed."
180
+ });
181
+ continue;
182
+ }
183
+ changes.push(...diffContent(response.content, nextResponse.content, "response", `response ${status}`, inline));
184
+ }
185
+ return changes;
186
+ };
187
+ /**
188
+ * Compares two OpenAPI documents and lists what changed for clients, breaking changes first.
189
+ * A change is breaking when a client written against `before` can fail against `after`: an
190
+ * operation or success response was removed, a request now needs or rejects something, or a
191
+ * successful response can now hold something it never held before.
192
+ *
193
+ * @example
194
+ * ```ts
195
+ * const changes = diffDocuments(oldDocument, newDocument)
196
+ * if (changes.some(({ breaking }) => breaking)) process.exitCode = 1
197
+ * ```
198
+ */
199
+ const diffDocuments = (before, after) => {
200
+ const oldOperations = operationsOf(before);
201
+ const nextOperations = operationsOf(after);
202
+ const inline = {
203
+ before: createInline(before),
204
+ after: createInline(after)
205
+ };
206
+ const changes = [];
207
+ for (const [operation, oldOperation] of oldOperations) {
208
+ const nextOperation = nextOperations.get(operation);
209
+ if (!nextOperation) {
210
+ changes.push({
211
+ operation,
212
+ breaking: true,
213
+ location: "",
214
+ message: "The operation was removed."
215
+ });
216
+ continue;
217
+ }
218
+ for (const change of diffOperation(oldOperation, nextOperation, inline)) changes.push({
219
+ operation,
220
+ ...change
221
+ });
222
+ }
223
+ for (const operation of nextOperations.keys()) if (!oldOperations.has(operation)) changes.push({
224
+ operation,
225
+ breaking: false,
226
+ location: "",
227
+ message: "The operation was added."
228
+ });
229
+ return changes.toSorted((a, b) => Number(b.breaking) - Number(a.breaking));
230
+ };
231
+ // src/run-diff-cli.ts
232
+ const HELP = `Usage: astro-spec-diff OLD NEW [--json]
233
+
234
+ Compare two OpenAPI documents and exit with status 1 when NEW breaks clients of OLD.
235
+
236
+ OLD, NEW Path or URL of each document
237
+ --json Print the changes as JSON
238
+ -h, --help Show this help
239
+ `;
240
+ const readDocument = async (input) => JSON.parse(/^https?:\/\//.test(input) ? await (await fetch(input)).text() : await readFile(resolve(input), "utf8"));
241
+ const formatChange = ({ breaking, operation, location, message }) => `${breaking ? "BREAKING" : "info "} ${operation}${location ? ` ${location}` : ""}: ${message}`;
242
+ /**
243
+ * Runs the `astro-spec-diff` command with the given arguments, without the node and script
244
+ * paths. Resolves to `true` when it found a breaking change, so the caller can set the exit
245
+ * code. Throws when the arguments are wrong or a document cannot be read.
246
+ *
247
+ * @example
248
+ * ```ts
249
+ * if (await runDiffCli(['old.json', 'openapi.json'])) process.exitCode = 1
250
+ * ```
251
+ */
252
+ const runDiffCli = async (args) => {
253
+ const { values, positionals } = parseArgs({
254
+ args,
255
+ allowPositionals: true,
256
+ options: {
257
+ json: { type: "boolean" },
258
+ help: {
259
+ type: "boolean",
260
+ short: "h"
261
+ }
262
+ }
263
+ });
264
+ if (values.help) {
265
+ process.stdout.write(HELP);
266
+ return false;
267
+ }
268
+ const [oldInput, newInput] = positionals;
269
+ if (!oldInput || !newInput || positionals.length > 2) throw new Error(`Expected two documents, got ${positionals.length}.\n\n${HELP}`);
270
+ const changes = diffDocuments(await readDocument(oldInput), await readDocument(newInput));
271
+ const breakingCount = changes.filter(({ breaking }) => breaking).length;
272
+ if (values.json) process.stdout.write(`${JSON.stringify(changes, null, 2)}\n`);
273
+ else {
274
+ const lines = changes.map(formatChange);
275
+ const summary = breakingCount > 0 ? `${breakingCount} breaking change${breakingCount === 1 ? "" : "s"}.` : "No breaking changes.";
276
+ process.stdout.write(`${[
277
+ ...lines,
278
+ ...lines.length > 0 ? [""] : [],
279
+ summary
280
+ ].join("\n")}\n`);
281
+ }
282
+ return breakingCount > 0;
283
+ };
284
+ export { diffDocuments as n, runDiffCli as t };
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@astro-spec/diff",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "Detect breaking changes between two OpenAPI documents, such as those astro-spec writes",
5
+ "keywords": [
6
+ "astro",
7
+ "openapi",
8
+ "astro-actions",
9
+ "breaking-changes",
10
+ "ci"
11
+ ],
12
+ "homepage": "https://github.com/betterlib/astro-spec/tree/main/packages/diff#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/betterlib/astro-spec/issues"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/betterlib/astro-spec.git",
19
+ "directory": "packages/diff"
20
+ },
21
+ "license": "MIT",
22
+ "author": "otoneko.",
23
+ "type": "module",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.mts",
27
+ "default": "./dist/index.mjs"
28
+ },
29
+ "./package.json": "./package.json"
30
+ },
31
+ "bin": {
32
+ "astro-spec-diff": "./dist/bin.mjs"
33
+ },
34
+ "files": [
35
+ "dist"
36
+ ],
37
+ "engines": {
38
+ "node": ">=22.12.0"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public",
42
+ "provenance": true
43
+ },
44
+ "scripts": {
45
+ "build": "tsdown",
46
+ "typecheck": "tsc --noEmit"
47
+ }
6
48
  }