Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
changeKind: fix
packages:
- "@azure-tools/typespec-breaking-change"
---

Detect record value and indexed model shape changes, preserve approval targets, and normalize operation paths in linear time.
61 changes: 53 additions & 8 deletions packages/typespec-breaking-change/src/diff/diff-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import {
} from "@typespec/compiler";
import type { HttpCanonicalization } from "@typespec/http-canonicalization";
import type { DiffKind } from "../diff-kind.js";
import { resolveOrigin } from "./origin.js";
import type { ApiDiff, DiffComponent, OperationDiffIdentity, OperationIdentity } from "../types.js";
import { resolveOrigin } from "./origin.js";

export interface DiffContext {
operation: OperationIdentity;
Expand Down Expand Up @@ -76,6 +76,21 @@ export function compareTypes(baseType: Type, headType: Type, ctx: DiffContext):
}

function compareModels(base: Model, head: Model, ctx: DiffContext): ApiDiff[] {
if (
Boolean(base.indexer) !== Boolean(head.indexer) ||
isArrayModelType(base) !== isArrayModelType(head)
) {
return [
makeDiff(
typeKindChangedKind(ctx),
ctx,
ctx.elementPath,
base,
head,
`${componentLabel(ctx.component)} indexed model shape changed at ${ctx.elementPath}.`,
),
];
}
if (isArrayModelType(base) && isArrayModelType(head)) {
// Array item type changes — the violation is about the array model, not the inner item type
const diffs = compareTypes(base.indexer.value, head.indexer.value, ctx);
Expand All @@ -92,6 +107,21 @@ function compareModels(base: Model, head: Model, ctx: DiffContext): ApiDiff[] {

const diffs: ApiDiff[] = [];

if (base.indexer && head.indexer) {
diffs.push(...compareTypes(base.indexer.key, head.indexer.key, ctx));
const valueDiffs = compareTypes(base.indexer.value, head.indexer.value, ctx);
for (const diff of valueDiffs) {
if (diff.headType === head.indexer.value || diff.baseType === base.indexer.value) {
diff.baseType = base;
diff.headType = head;
diff.baseSourceLocation = getTypeSourceLocation(base);
diff.headSourceLocation = getTypeSourceLocation(head);
diff.origin = resolveOrigin(head);
}
}
diffs.push(...valueDiffs);
}

for (const [name, baseProp] of base.properties) {
const headProp = head.properties.get(name);
const elementPath = propertyElementPath(ctx.elementPath, name);
Expand Down Expand Up @@ -405,6 +435,8 @@ function getTypeKey(type: Type): string {
}

function getNamedTypeKey(type: Type): string | undefined {
// Different instantiations of Record<T> and Array<T> share their declared name.
if (type.kind === "Model" && type.indexer) return undefined;
switch (type.kind) {
case "Model":
case "Scalar":
Expand All @@ -415,7 +447,9 @@ function getNamedTypeKey(type: Type): string | undefined {
? `${getTypeKey(type.model)}.properties.${type.name}`
: `${type.kind}:${type.name}`;
case "Union":
return type.name ? qualifiedName(type.namespace, type.name) ?? `${type.kind}:${type.name}` : undefined;
return type.name
? (qualifiedName(type.namespace, type.name) ?? `${type.kind}:${type.name}`)
: undefined;
case "UnionVariant":
return typeof type.name === "string"
? `${getTypeKey(type.union)}.variants.${type.name}`
Expand Down Expand Up @@ -449,31 +483,39 @@ function propertyMadeOptionalKind(component: DiffComponent): DiffKind {

function typeChangedKind(ctx: DiffContext): DiffKind {
if (isPropertyElement(ctx.elementPath)) {
return ctx.component === "request" ? "RequestPropertyTypeChanged" : "ResponsePropertyTypeChanged";
return ctx.component === "request"
? "RequestPropertyTypeChanged"
: "ResponsePropertyTypeChanged";
}

return ctx.component === "request" ? "RequestTypeChanged" : "ResponseTypeChanged";
}

function typeNarrowedKind(ctx: DiffContext): DiffKind {
if (isPropertyElement(ctx.elementPath)) {
return ctx.component === "request" ? "RequestPropertyTypeNarrowed" : "ResponsePropertyTypeNarrowed";
return ctx.component === "request"
? "RequestPropertyTypeNarrowed"
: "ResponsePropertyTypeNarrowed";
}

return ctx.component === "request" ? "RequestTypeNarrowed" : "ResponseTypeNarrowed";
}

function typeWidenedKind(ctx: DiffContext): DiffKind {
if (isPropertyElement(ctx.elementPath)) {
return ctx.component === "request" ? "RequestPropertyTypeWidened" : "ResponsePropertyTypeWidened";
return ctx.component === "request"
? "RequestPropertyTypeWidened"
: "ResponsePropertyTypeWidened";
}

return ctx.component === "request" ? "RequestTypeWidened" : "ResponseTypeWidened";
}

function typeKindChangedKind(ctx: DiffContext): DiffKind {
if (isPropertyElement(ctx.elementPath)) {
return ctx.component === "request" ? "RequestPropertyTypeChanged" : "ResponsePropertyTypeChanged";
return ctx.component === "request"
? "RequestPropertyTypeChanged"
: "ResponsePropertyTypeChanged";
}

return ctx.component === "request" ? "RequestTypeKindChanged" : "ResponseTypeKindChanged";
Expand Down Expand Up @@ -526,7 +568,8 @@ function qualifiedName(
if (current.name) {
namespaceParts.unshift(current.name);
}
current = current.namespace as { name: string; namespace?: { name: string; namespace?: unknown } } | undefined;
current = current.namespace as
{ name: string; namespace?: { name: string; namespace?: unknown } } | undefined;
}

namespaceParts.push(name);
Expand All @@ -553,7 +596,9 @@ function describeType(type: Type): string {
case "Enum":
return qualifiedName(type.namespace, type.name) ?? type.name;
case "Union":
return type.name ? qualifiedName(type.namespace, type.name) ?? type.name : "anonymous-union";
return type.name
? (qualifiedName(type.namespace, type.name) ?? type.name)
: "anonymous-union";
case "String":
return JSON.stringify(type.value);
case "Number":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,18 @@ export interface ResolvedOperation {
* "/subscriptions/{subscriptionId}/providers/{rpName}" → "/subscriptions/{}/providers/{}"
*/
export function normalizePath(path: string): string {
return path.replace(/\{[^}]+\}/g, "{}");
const parts: string[] = [];
let position = 0;
while (position < path.length) {
const open = path.indexOf("{", position);
if (open === -1) break;
const close = path.indexOf("}", open + 1);
if (close === -1) break;
parts.push(path.slice(position, open), "{}");
position = close + 1;
}
parts.push(path.slice(position));
return parts.join("");
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { describe, expect, it } from "vitest";
import {
resolveOperationIdentities,
normalizePath,
getOperationIdentity,
identityKey,
} from "../src/diff/operation-identity.js";
import { normalizePath, resolveOperationIdentities } from "../src/diff/operation-identity.js";
import { createVersionedView, enumerateVersions } from "../src/pipeline/versions.js";
import { matchOperations } from "../src/suppression/match.js";
import { enumerateVersions, createVersionedView } from "../src/pipeline/versions.js";
import { Tester } from "./test-host.js";

describe("normalizePath", () => {
it("preserves embedded parameters and malformed paths without backtracking", () => {
expect(normalizePath("/widgets/prefix-{id}.{format}/{}")).toBe("/widgets/prefix-{}.{}/{}");
expect(normalizePath("/widgets/{{id}")).toBe("/widgets/{}");
const unmatched = "/widgets/" + "{".repeat(100_000);
expect(normalizePath(unmatched)).toBe(unmatched);
});
it("replaces parameter names with {}", () => {
expect(normalizePath("/widgets/{widgetId}")).toBe("/widgets/{}");
});
Expand Down
50 changes: 50 additions & 0 deletions packages/typespec-breaking-change/test/record-diffs.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { describe, expect, it } from "vitest";
import { analyzeProgram } from "../src/pipeline/orchestrator.js";
import { TesterWithSuppressions } from "./test-host.js";

describe("record comparisons", () => {
it.each([
["Record<string>", "Record<int32>", "ResourcePropertyTypeChanged"],

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we do the same for Record<string>, Array<string>? Also, do we have a similar test for Array<string>, Array<string> and Array<string>, string[]?

["Record<string>", "Record<string>", undefined],
["Record<string>", "string[]", "ResourcePropertyTypeChanged"],
["Record<string>", "{}", "ResourcePropertyTypeChanged"],
])("compares %s to %s", async (base, head, expectedKind) => {
const { program } = await TesterWithSuppressions.compile(`
@service @versioned(Versions) namespace Test;
enum Versions { v1: "2024-01-01", v2: "2025-01-01" }
model Widget {
@typeChangedFrom(Versions.v2, ${base})
tags: ${head};
}
@route("/widgets") @post op create(@body widget: Widget): Widget;
`);
const result = analyzeProgram(program);
expect(result.findings.map((finding) => finding.diff.kind)).toEqual(
expectedKind ? [expectedKind] : [],
);
if (expectedKind) {
expect(result.findings[0].diff.identity.element).toBe("body.properties.tags");
expect(result.findings[0].diff.origin?.declarationPath).toBe("Test.Widget.tags");
}
});

it("compares nested record values and supports approval on the owning property", async () => {
const { program } = await TesterWithSuppressions.compile(`
@service @versioned(Versions) namespace Test;
enum Versions { v1: "2024-01-01", v2: "2025-01-01" }
model Widget {
@approvedBreakingChange("Reviewed.", #{ kind: "ResourcePropertyTypeChanged" })
@typeChangedFrom(Versions.v2, Record<Record<string>>)
tags: Record<Record<int32>>;
}
@route("/widgets") @post op create(@body widget: Widget): Widget;
`);
const result = analyzeProgram(program);
expect(result.findings).toHaveLength(1);
expect(result.findings[0]).toMatchObject({
suppressed: true,
suppressionReason: "Reviewed.",
diff: { kind: "ResourcePropertyTypeChanged", identity: { element: "body.properties.tags" } },
});
});
});