perf(schemas): eliminate generator/clone overhead in schema compaction and compact union projections (#13313)

This commit is contained in:
morluto authored and GitHub committed 2026-11-22 03:57:03 +00:00
1 parent 4485912fd8
commit 87243c0c0e
79 files changed
+1531 -477

No files matched your search

@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "492ec1ac2a1230c5",
"input compact": "b856f57616759699",
"output compact": "9bd80958780175fe"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "88ba9b1c0d33d10f",
"input compact": "9d206f6b3abdf4ec",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "699d21a37250979b",
"input compact": "790dbff706736eb5",
"output compact": "4bda7c3651bfc579"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "b16f62e36c31a0cc",
"input compact": "7a8f6b11c2fc74da",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "eff327dda5c10d9a",
"input compact": "e23c7fd3aa68a1cf",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "b91fd6378ec89ada",
"input compact": "f960ef76daeef6ed",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "a1b45d95750ca8ef",
"input compact": "4547fa615d144de1",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "57f1e31eab5d6150",
"input compact": "15a7a050f212e5de",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "f9475f6ca1476ae0",
"input compact": "c006fdc2cf6e418a",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "fdb69f3d5123e80e",
"input compact": "77e65e0e9eb01447",
"output compact": "3e22807c622e44b2"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "4425590849a07d7f",
"input compact": "00fbe6b4dfd83953",
"output compact": "4bda7c3651bfc579"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "5ecb2020ae1f8f42",
"input compact": "bc92ddcecb69050b",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "6ca4f62a458ff3d7",
"input compact": "d106ecd6b92b8dac",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "d78773a7ca2051f5",
"input compact": "ae72c77877e2eae1",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "3c840e5bbd9e9894",
"input compact": "a23336a36554f9ba",
"output compact": "9cda19dfa1310afa"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "e5d2cfec1580148e",
"input compact": "f8dfc9b3b7744976",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "f4d383779c829cc1",
"input compact": "961c1bc71b1cf86f",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "6f391991d856198a",
"input compact": "79d06f0abbf80d96",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "dec153ba3fc1960c",
"input compact": "a130f123d585a1c4",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "aabcc05db1232b21",
"input compact": "e5c144292d7105da",
"output compact": "4bda7c3651bfc579"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "72d0fff774075e7c",
"input compact": "c25da9676d1393ff",
"output compact": "4bda7c3651bfc579"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "59748ce45f667d12",
"input compact": "76a620fb6276d952",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "fdd4a3a111b4308b",
"input compact": "a994241bc7cb700d",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "a048bd94aa23c39e",
"input compact": "43545508189c0e49",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "4bfd2a08afbc54fc",
"input compact": "d62275796c282288",
"output compact": "4bda7c3651bfc579"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "c14ca0aea789c645",
"input compact": "1a0e365c7324c025",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "f8a87e80e0ca66fe",
"input compact": "1e5fbc1c470c2a23",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "f5cc9dc3caf9edf4",
"input compact": "caedaefd2eef892b",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "01c7ceeb7a6ac4d4",
"input compact": "bb4626f7525df90d",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "fe4818885a05bfb0",
"input compact": "b3d6b50f46b084c5",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "b64e74c7116cc99b",
"input compact": "26391ae9478bdad4",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "2c6c9865b3119ae2",
"input compact": "54859945355f676d",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "ab5465849952e847",
"input compact": "1f819bf93544186a",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "0a9a2b524be0ce15",
"input compact": "d8f23fd89529aeab",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "2e70facfe9d6f4f4",
"input compact": "8828739c3844ee36",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "6b084c215c2391a6",
"input compact": "70b0e7fbb4c73e61",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "7c1e0a2a80f4c87c",
"input compact": "6acc5ad4d85e761a",
"output compact": "4bda7c3651bfc579"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "8211b6c65f46d420",
"input compact": "3c8cc4cd79f2c6d0",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "5969a9c826c2c055",
"input compact": "d77cd7aa06705c28",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "3460ff3dfbfb1b2a",
"input compact": "ed896c6083b81754",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "55e64710a49b9fa2",
"input compact": "1f21147802cdb88d",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "3748645472ab43e5",
"input compact": "31f1ee648744d596",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "e85331872a5525e6",
"input compact": "26e2194d53a10150",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "7a138da90fc5e650",
"input compact": "284eab844f7b23e8",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "9a171b304737ce3d",
"input compact": "72d51d50e5a963a0",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "ae6db425047c0a8f",
"input compact": "66a45fb27e9e1150",
"output compact": "4bda7c3651bfc579"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "6d62658ca139ecb4",
"input compact": "d83d3a86dd1c0360",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "4478f0c5fb8ad186",
"input compact": "0ae5cc790aab456e",
"output compact": "f1344e6ff37d2aa3"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "b04d2099435f3cac",
"input compact": "2a8129999798f240",
"output compact": "f685f02d537b3bdf"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "4b137397fb16524d",
"input compact": "f6ad8e9a8e5d0766",
"output compact": "4bda7c3651bfc579"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "8e887061536632ee",
"input compact": "71abd7cd93c5b515",
"output compact": "9cda19dfa1310afa"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "e04053c4c8250c81",
"input compact": "0b19d55284a3a83d",
"output compact": "4bda7c3651bfc579"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "3ef1f34cab7e4387",
"input compact": "66da388cb3838500",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "79890b6c44be3b32",
"input compact": "ef74c2046f0c6373",
"output compact": "4bda7c3651bfc579"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "b68bdfd126b58c24",
"input compact": "0b5d0a4eb732f002",
"output compact": "4bda7c3651bfc579"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "827ccf60f59990d4",
"input compact": "0dff7f90efa0d080",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "914f9d8e19bfa4e5",
"input compact": "1d829a751c1960a6",
"output compact": "4bda7c3651bfc579"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "1457e8daaa15b8ce",
"input compact": "5dcd84c87e77a7fd",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "849dbbcd225a233a",
"input compact": "94ca5237a58adcb5",
"output compact": "2565468480ec3144"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "bed8f76edd347cb6",
"input compact": "888e03078dfafb8c",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "2d2afa5eefb4be64",
"input compact": "95e63e507a5480b2",
"output compact": "4bda7c3651bfc579"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "fac6a749ccacd74f",
"input compact": "62a36a8847614d47",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "ae3268db6e89a16b",
"input compact": "a0239c9f31bd11d9",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "4f5355f35275f28b",
"input compact": "3c58bca74c60f033",
"output compact": "39446aa1012006cc"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "9c58fa7f6dfaccdb",
"input compact": "5748324d2731a18e",
"output compact": "9cda19dfa1310afa"
},
"patterns": {
+187 -33
View File
@@ -205,7 +205,13 @@ describe("portable advertised dialect projection", () => {
view: {
oneOf: [
{ type: "object", properties: { kind: { const: "a" } } },
{ type: "object", properties: { kind: { const: "b" } } },
{
type: "object",
properties: {
kind: { const: "b" },
extra: { type: "string" },
},
},
],
},
limit: { type: ["integer", "null"], minimum: 1 },
@@ -220,7 +226,10 @@ describe("portable advertised dialect projection", () => {
},
{
type: "object",
properties: { kind: { type: "string", enum: ["b"] } },
properties: {
kind: { type: "string", enum: ["b"] },
extra: { type: "string" },
},
},
],
},
@@ -231,43 +240,188 @@ describe("portable advertised dialect projection", () => {
advertisedInputDialectViolations({ name: "probe", inputSchema: schema }),
).toEqual([]);
});
});
it("moves the root description and dropped cross-field constraints to tool guidance", () => {
const projection = project(
{
table: { type: "string" },
row_limit: { type: "integer" },
ids: { type: "array", items: { type: "string" }, uniqueItems: true },
name: { type: "string", not: { enum: ["reserved"] } },
it("moves the root description and dropped cross-field constraints to tool guidance", () => {
const projection = project(
{
table: { type: "string" },
row_limit: { type: "integer" },
ids: { type: "array", items: { type: "string" }, uniqueItems: true },
name: { type: "string", not: { enum: ["reserved"] } },
},
{
description: "Root guidance.",
dependentRequired: { row_limit: ["table"] },
if: { required: ["table"] },
then: { required: ["row_limit"] },
},
);
expect(projection.guidance).toEqual([
"Root guidance.",
"When row_limit is provided, also provide table.",
"`ids` entries must be distinct.",
'`name` must not be "reserved".',
]);
expect(projection.schema).not.toHaveProperty("description");
expect(
advertisedInputDialectViolations({
name: "probe",
inputSchema: projection.schema,
}),
).toEqual([]);
});
it("bounds nested descriptions without splitting a surrogate pair", () => {
const description = `${"x".repeat(1022)}😀tail`;
const { schema } = project({ value: { type: "string", description } });
const value = (schema.properties as Record<string, Record<string, string>>)
.value!;
expect(value.description!.length).toBeLessThanOrEqual(1024);
expect(value.description!.endsWith("x…")).toBe(true);
});
describe("product-union factoring and safe-integer bounds", () => {
it("factors matching object union branches that differ only on one string enum", () => {
const { schema } = project({
target: {
anyOf: [
{
type: "object",
properties: { kind: { const: "whole" } },
required: ["kind"],
additionalProperties: false,
},
{
type: "object",
properties: {
kind: { const: "volume" },
offset: { type: "integer", minimum: 0 },
},
required: ["kind", "offset"],
additionalProperties: false,
},
{
type: "object",
properties: {
kind: { const: "section" },
offset: { type: "integer", minimum: 0 },
},
required: ["kind", "offset"],
additionalProperties: false,
},
],
},
{
description: "Root guidance.",
dependentRequired: { row_limit: ["table"] },
if: { required: ["table"] },
then: { required: ["row_limit"] },
collapsed: {
oneOf: [
{
type: "object",
properties: { mode: { const: "fast" }, limit: { type: "integer" } },
required: ["mode"],
},
{
type: "object",
properties: { mode: { const: "deep" }, limit: { type: "integer" } },
required: ["mode"],
},
],
},
);
expect(projection.guidance).toEqual([
"Root guidance.",
"When row_limit is provided, also provide table.",
"`ids` entries must be distinct.",
'`name` must not be "reserved".',
]);
expect(projection.schema).not.toHaveProperty("description");
});
expect(schema.properties).toEqual({
target: {
type: "object",
anyOf: [
{
type: "object",
properties: { kind: { type: "string", enum: ["whole"] } },
required: ["kind"],
additionalProperties: false,
},
{
type: "object",
properties: {
kind: { type: "string", enum: ["volume", "section"] },
offset: { type: "integer", minimum: 0 },
},
required: ["kind", "offset"],
additionalProperties: false,
},
],
},
collapsed: {
type: "object",
properties: {
mode: { type: "string", enum: ["fast", "deep"] },
limit: { type: "integer" },
},
required: ["mode"],
},
});
expect(
advertisedInputDialectViolations({
name: "probe",
inputSchema: projection.schema,
}),
advertisedInputDialectViolations({ name: "probe", inputSchema: schema }),
).toEqual([]);
});
it("bounds nested descriptions without splitting a surrogate pair", () => {
const description = `${"x".repeat(1022)}😀tail`;
const { schema } = project({ value: { type: "string", description } });
const value = (schema.properties as Record<string, Record<string, string>>)
.value!;
expect(value.description!.length).toBeLessThanOrEqual(1024);
expect(value.description!.endsWith("x…")).toBe(true);
it("keeps branches separate when required, closure, descriptions, or multiple fields differ", () => {
const { schema } = project({
kept_separate: {
anyOf: [
{
type: "object",
properties: {
a: { const: "x", description: "First" },
b: { const: "1" },
},
required: ["a", "b"],
},
{
type: "object",
properties: {
a: { const: "y", description: "Second" },
b: { const: "1" },
},
required: ["a", "b"],
},
{
type: "object",
properties: {
a: { const: "z", description: "First" },
b: { const: "2" },
},
required: ["a", "b"],
},
],
},
});
const branches = (
(schema.properties as Record<string, Record<string, unknown>>)
.kept_separate!.anyOf as unknown[]
).length;
expect(branches).toBe(3);
});
it("omits redundant JavaScript safe-integer bounds while keeping real bounds", () => {
const { schema } = project({
unbounded_int: {
type: "integer",
minimum: Number.MIN_SAFE_INTEGER,
maximum: Number.MAX_SAFE_INTEGER,
},
non_negative: {
type: "integer",
minimum: 0,
maximum: Number.MAX_SAFE_INTEGER,
},
bounded: {
type: "integer",
minimum: 1,
maximum: 100,
},
});
expect(schema.properties).toEqual({
unbounded_int: { type: "integer" },
non_negative: { type: "integer", minimum: 0 },
bounded: { type: "integer", minimum: 1, maximum: 100 },
});
});
});
+110 -3
View File
@@ -1,6 +1,7 @@
import { isDeepStrictEqual } from "node:util";
import { isRecord } from "../kernel/isRecord.js";
import { setOwnSchemaProperty } from "./jsonSchemaKeywords.js";
import {
ADVERTISED_BOUND_LIMIT,
ADVERTISED_DESCRIPTION_MAX_CHARACTERS,
@@ -164,8 +165,10 @@ const inclusiveBounds = (source: Schema, out: Schema): void => {
: source.exclusiveMaximum;
maximum = typeof maximum === "number" ? Math.min(maximum, upper) : upper;
}
if (typeof minimum === "number") out.minimum = minimum;
if (typeof maximum === "number") out.maximum = maximum;
if (typeof minimum === "number" && minimum !== Number.MIN_SAFE_INTEGER)
out.minimum = minimum;
if (typeof maximum === "number" && maximum !== Number.MAX_SAFE_INTEGER)
out.maximum = maximum;
};
/** Length and item bounds clients can compile, and the portable pattern. */
@@ -209,6 +212,108 @@ const isStringEnum = (branch: unknown): branch is Schema =>
Array.isArray(branch.enum) &&
onlyKeys(branch, ["type", "enum", "description"]);
const isNonEmptyStringEnum = (branch: unknown): branch is Schema =>
isStringEnum(branch) && isStringList(branch.enum) && branch.enum.length > 0;
const sameNonPropertyKeywords = (left: Schema, right: Schema): boolean => {
const leftKeys = Object.keys(left);
if (leftKeys.length !== Object.keys(right).length) return false;
for (const key of leftKeys) {
if (key === "properties") continue;
if (!Object.hasOwn(right, key) || !isDeepStrictEqual(left[key], right[key]))
return false;
}
return true;
};
const singleDifferingStringEnumKey = (
left: Schema,
right: Schema,
): string | undefined => {
if (
left.type !== "object" ||
right.type !== "object" ||
!isRecord(left.properties) ||
!isRecord(right.properties) ||
!sameNonPropertyKeywords(left, right)
)
return undefined;
const leftProps = left.properties;
const rightProps = right.properties;
if (Object.keys(leftProps).length !== Object.keys(rightProps).length)
return undefined;
let diffKey: string | undefined;
for (const key in leftProps) {
if (!Object.hasOwn(leftProps, key)) continue;
if (!Object.hasOwn(rightProps, key)) return undefined;
if (isDeepStrictEqual(leftProps[key], rightProps[key])) continue;
if (diffKey !== undefined) return undefined;
diffKey = key;
}
if (diffKey === undefined) return undefined;
const leftProp = leftProps[diffKey];
const rightProp = rightProps[diffKey];
if (!isNonEmptyStringEnum(leftProp) || !isNonEmptyStringEnum(rightProp))
return undefined;
return leftProp.description === rightProp.description ? diffKey : undefined;
};
const mergeBranchOnEnumProperty = (
groupBranch: Schema,
incomingBranch: Schema,
diffKey: string,
): Schema => {
const leftProps = groupBranch.properties as Schema;
const rightProps = incomingBranch.properties as Schema;
const leftEnum = leftProps[diffKey] as Schema;
const rightEnum = rightProps[diffKey] as Schema;
const nextProps = { ...leftProps };
setOwnSchemaProperty(nextProps, diffKey, {
...leftEnum,
enum: [
...new Set([
...(leftEnum.enum as readonly string[]),
...(rightEnum.enum as readonly string[]),
]),
],
});
return { ...groupBranch, properties: nextProps };
};
/**
* Exact product-union factoring: object branches that agree on every keyword
* and property except one string-enum discriminator collapse into one branch.
*/
const factorObjectEnumUnions = (branches: readonly unknown[]): unknown[] => {
const groups: { branch: unknown; diffKey?: string }[] = [];
for (const branch of branches) {
if (
!isRecord(branch) ||
branch.type !== "object" ||
!isRecord(branch.properties)
) {
groups.push({ branch });
continue;
}
let matched = false;
for (const group of groups) {
if (!isRecord(group.branch)) continue;
const diffKey = singleDifferingStringEnumKey(group.branch, branch);
if (
diffKey !== undefined &&
(group.diffKey === undefined || group.diffKey === diffKey)
) {
group.branch = mergeBranchOnEnumProperty(group.branch, branch, diffKey);
group.diffKey = diffKey;
matched = true;
break;
}
}
if (!matched) groups.push({ branch });
}
return groups.map((group) => group.branch);
};
/** `[T, "null"]` becomes the single nullable form: a typed branch or null. */
const nullableForm = (out: Schema): Schema => {
if (
@@ -334,7 +439,9 @@ class DialectProjection {
? source.oneOf
: undefined;
if (alternatives === undefined) return;
const branches = this.unionBranches(alternatives, path, out.type);
const branches = factorObjectEnumUnions(
this.unionBranches(alternatives, path, out.type),
);
if (
branches.length > 0 &&
out.enum === undefined &&
+66 -6
View File
@@ -7,7 +7,8 @@ import {
advertisedInputDialectViolations,
} from "./advertisedDialect.js";
import { compactAdvertisedInputSchema } from "./compactInputSchema.js";
import { stripAnnotations } from "./compactJsonSchema.js";
import { inlineWithinBudget, stripAnnotations } from "./compactJsonSchema.js";
import { JsonSchemaReferences } from "./jsonSchemaReferences.js";
const serializedBytes = (value: unknown): number =>
Buffer.byteLength(JSON.stringify(value), "utf8");
@@ -322,8 +323,11 @@ describe("portable dialect unions", () => {
},
{
type: "object",
properties: { kind: { const: "type" } },
required: ["kind"],
properties: {
kind: { const: "type" },
text: { type: "string" },
},
required: ["kind", "text"],
},
],
},
@@ -349,8 +353,11 @@ describe("portable dialect unions", () => {
},
{
type: "object",
properties: { kind: { type: "string", enum: ["type"] } },
required: ["kind"],
properties: {
kind: { type: "string", enum: ["type"] },
text: { type: "string" },
},
required: ["kind", "text"],
},
],
});
@@ -359,7 +366,7 @@ describe("portable dialect unions", () => {
for (const value of [
[],
[{ kind: "click" }],
[{ kind: "type" }],
[{ kind: "type", text: "ok" }],
[{ kind: "other" }],
])
expect(advertised({ actions: value })).toBe(
@@ -1071,3 +1078,56 @@ describe("reduced array item presentation", () => {
expect(advertisedValidate(input)).toBe(true);
});
});
describe("on-the-fly annotation stripping parity", () => {
it("matches pre-stripped inlining for map keys, empty schemas, ref siblings, and stripped pointers", () => {
const cases: readonly Record<string, unknown>[] = [
{
type: "object",
description: "Root doc stays.",
default: { x: 1 },
properties: {
default: { type: "boolean", default: true, title: "Default flag" },
any: { description: "Becomes json value schema." },
forbid: { not: { description: "Empty negation." } },
aliased: { $ref: "#/$defs/leaf", description: "Sibling doc drops." },
},
$defs: {
leaf: { type: "string", description: "Def doc drops.", title: "L" },
},
},
{
$schema: "http://json-schema.org/draft-07/schema#",
type: "object",
definitions: { leaf: { type: "number", examples: [1] } },
properties: {
count: { $ref: "#/definitions/leaf", description: "Doc drops." },
},
},
{
type: "object",
$defs: {
node: { type: "string", default: "fallback" },
},
properties: {
bad: { $ref: "#/$defs/node/default" },
},
},
{
type: "object",
properties: {
bad: { $ref: "#/properties/x/description" },
x: { type: "string", description: "Stripped doc" },
},
},
];
for (const schema of cases) {
const expected = inlineWithinBudget(stripAnnotations(schema), 16_384);
const actual = inlineWithinBudget(schema, 16_384, {
stripAnnotations: true,
references: new JsonSchemaReferences(schema),
});
expect(actual).toEqual(expected);
}
});
});
+13 -7
View File
@@ -7,8 +7,8 @@ import {
reduceToShallowProperties,
schemaDepth,
serializedBytes,
stripAnnotations,
} from "./compactJsonSchema.js";
import { JsonSchemaReferences } from "./jsonSchemaReferences.js";
// The compact input presentation: every advertised input schema is
// self-contained (the dialect admits no `$ref` or `$defs`), inside the
@@ -46,18 +46,20 @@ const retainRootPropertyGuidance = (
!isSchemaObject(stripped.properties)
)
return stripped;
const properties = { ...stripped.properties };
let properties: Record<string, unknown> | undefined;
for (const name of retainedRootPropertyDescriptions) {
const source = schema.properties[name];
const kept = properties[name];
const kept = (properties ?? stripped.properties)[name];
if (
isSchemaObject(source) &&
isSchemaObject(kept) &&
typeof source.description === "string"
)
) {
properties ??= { ...stripped.properties };
properties[name] = { ...kept, description: source.description };
}
}
return { ...stripped, properties };
return properties === undefined ? stripped : { ...stripped, properties };
};
const withinDialect = (schema: Record<string, unknown>): boolean =>
@@ -76,7 +78,11 @@ export const compactAdvertisedInputSchema = (
schema: Record<string, unknown>,
budgetBytes: number,
): CompactedInputSchema => {
const expanded = inlineWithinBudget(stripAnnotations(schema), budgetBytes);
const references = new JsonSchemaReferences(schema);
const expanded = inlineWithinBudget(schema, budgetBytes, {
stripAnnotations: true,
references,
});
const inline =
expanded === undefined
? undefined
@@ -91,7 +97,7 @@ export const compactAdvertisedInputSchema = (
)
return { ...inline, presentation: "inline" };
const reduced = projectToAdvertisedDialect(
reduceToShallowProperties(schema, INPUT_REDUCED_ANNOTATION),
reduceToShallowProperties(schema, INPUT_REDUCED_ANNOTATION, references),
);
if (serializedBytes(reduced.schema) <= budgetBytes)
return { ...reduced, presentation: "reduced" };
+343 -179
View File
@@ -1,13 +1,15 @@
import { Budget } from "../domain/budget.js";
import { isRecord } from "../kernel/isRecord.js";
import {
JsonSchemaReferences,
type JsonSchemaScope,
} from "./jsonSchemaReferences.js";
import {
mapSchemaChildren,
schemaArrays,
schemaChildren,
schemaMaps,
schemaLiteralValues,
schemaPointerSteps,
} from "./jsonSchemaKeywords.js";
// Shared compact JSON Schema projection primitives; canonical validation stays separate.
@@ -30,6 +32,15 @@ const jsonValueTypes = [
// portable advertised dialect has no any-value form, so a compact input that
// needs this presentation is reduced instead.
export const jsonValueSchema = () => ({ type: [...jsonValueTypes], items: {} });
const EMPTY_SCHEMA_JSON = JSON.stringify(jsonValueSchema());
const utf8ByteLength = (text: string): number => {
const len = text.length;
for (let i = 0; i < len; i++) {
if (text.charCodeAt(i) >= 0x80) return Buffer.byteLength(text, "utf8");
}
return len;
};
const enumValueTypes = (values: readonly unknown[]): readonly string[] => [
...new Set(
@@ -45,19 +56,25 @@ const enumValueTypes = (values: readonly unknown[]): readonly string[] => [
export const isSchemaObject = isRecord;
export const serializedBytes = (value: unknown): number =>
Buffer.byteLength(JSON.stringify(value), "utf8");
utf8ByteLength(JSON.stringify(value));
export const schemaDepth = (value: unknown, depth = 0): number => {
if (Array.isArray(value))
return Math.max(
depth,
...value.map((child) => schemaDepth(child, depth + 1)),
);
if (Array.isArray(value)) {
let max = depth;
for (let i = 0; i < value.length; i++) {
const childDepth = schemaDepth(value[i], depth + 1);
if (childDepth > max) max = childDepth;
}
return max;
}
if (!isSchemaObject(value)) return depth;
return Math.max(
depth,
...Object.values(value).map((child) => schemaDepth(child, depth + 1)),
);
let max = depth;
for (const key in value) {
if (!Object.hasOwn(value, key)) continue;
const childDepth = schemaDepth(value[key], depth + 1);
if (childDepth > max) max = childDepth;
}
return max;
};
/** Strict clients commonly reject advertised schemas deeper than ten nodes. */
@@ -68,33 +85,20 @@ const rebuildSchemaPositions = (
node: unknown,
rebuild: (child: unknown) => unknown,
): unknown => {
if (Array.isArray(node)) return node.map((child) => rebuild(child));
if (!isSchemaObject(node)) return node;
const out: Record<string, unknown> = {};
for (const [key, value] of Object.entries(node)) {
if (schemaLiteralValues.has(key)) {
out[key] = value;
continue;
if (Array.isArray(node)) {
let out: unknown[] | undefined;
for (let i = 0; i < node.length; i++) {
const child = node[i];
const mapped = rebuild(child);
if (mapped !== child) {
if (out === undefined) out = node.slice();
out[i] = mapped;
}
}
if (schemaMaps.has(key) && isSchemaObject(value)) {
out[key] = Object.fromEntries(
Object.entries(value).map(([name, child]) => [name, rebuild(child)]),
);
continue;
}
if (schemaArrays.has(key) && Array.isArray(value)) {
out[key] = value.map((child) => rebuild(child));
continue;
}
if (schemaChildren.has(key)) {
out[key] = Array.isArray(value)
? value.map((child) => rebuild(child))
: rebuild(value);
continue;
}
out[key] = value;
return out ?? node;
}
return out;
if (!isSchemaObject(node)) return node;
return mapSchemaChildren(node, rebuild);
};
/**
@@ -111,9 +115,10 @@ export const stripAnnotations = (
stripChildAnnotations,
) as Record<string, unknown>;
const out: Record<string, unknown> = {};
for (const [key, value] of Object.entries(rebuilt)) {
for (const key in rebuilt) {
if (!Object.hasOwn(rebuilt, key)) continue;
if (annotationKeys.has(key) && key !== "description") continue;
out[key] = value;
out[key] = rebuilt[key];
}
return out;
};
@@ -121,158 +126,317 @@ export const stripAnnotations = (
const stripChildAnnotations = (child: unknown): unknown => {
const rebuilt = rebuildSchemaPositions(child, stripChildAnnotations);
if (!isSchemaObject(rebuilt)) return rebuilt;
const kept: Record<string, unknown> = {};
for (const [key, value] of Object.entries(rebuilt))
if (!annotationKeys.has(key)) kept[key] = value;
return kept;
let kept: Record<string, unknown> | undefined;
for (const key in rebuilt) {
if (!Object.hasOwn(rebuilt, key) || !annotationKeys.has(key)) continue;
if (kept === undefined) {
kept = {};
for (const copyKey in rebuilt) {
if (Object.hasOwn(rebuilt, copyKey) && !annotationKeys.has(copyKey))
kept[copyKey] = rebuilt[copyKey];
}
}
break;
}
return kept ?? rebuilt;
};
type SchemaPosition = "schema" | "map" | "data";
type ObjectEmitMode = "normal" | "root" | "siblings" | "root-siblings";
export interface InlineWithinBudgetOptions {
readonly stripAnnotations?: boolean;
readonly references?: JsonSchemaReferences;
}
const childSchemaPosition = (
key: string,
position: SchemaPosition,
): SchemaPosition => {
if (position === "map") return "schema";
if (position !== "schema") return "data";
if (schemaMaps.has(key)) return "map";
return schemaArrays.has(key) || schemaChildren.has(key) ? "schema" : "data";
};
class BudgetedSchemaSerializer {
readonly chunks: string[] = [];
resolved = true;
private readonly active = new Map<JsonSchemaScope, Set<string>>();
constructor(
private readonly budget: Budget,
private readonly references: JsonSchemaReferences,
private readonly strip: boolean,
) {}
private emitAscii(text: string): boolean {
if (!this.budget.tryCharge(text.length)) return false;
this.chunks.push(text);
return true;
}
private emitText(text: string): boolean {
if (!this.budget.tryCharge(utf8ByteLength(text))) return false;
this.chunks.push(text);
return true;
}
private isSkippedKey(
key: string,
position: SchemaPosition,
mode: ObjectEmitMode,
): boolean {
if (position !== "schema") return false;
if ((mode === "siblings" || mode === "root-siblings") && key === "$ref")
return true;
if (
definitionKeys.has(key) ||
key === "$id" ||
key === "$anchor" ||
key === "$schema"
)
return true;
const isRoot = mode === "root" || mode === "root-siblings";
return (
this.strip &&
annotationKeys.has(key) &&
!(isRoot && key === "description")
);
}
private isEffectivelyEmpty(
value: Record<string, unknown>,
isRoot: boolean,
): boolean {
for (const key in value) {
if (!Object.hasOwn(value, key) || value[key] === undefined) continue;
if (
this.strip &&
annotationKeys.has(key) &&
!(isRoot && key === "description")
)
continue;
return false;
}
return true;
}
private hasSiblings(
value: Record<string, unknown>,
isRoot: boolean,
): boolean {
for (const key in value) {
if (!Object.hasOwn(value, key) || value[key] === undefined) continue;
if (
key === "$ref" ||
key === "$id" ||
key === "$anchor" ||
key === "$schema"
)
continue;
if (
this.strip &&
annotationKeys.has(key) &&
!(isRoot && key === "description")
)
continue;
return true;
}
return false;
}
private isStrippedTarget(
scope: JsonSchemaScope,
path: readonly string[],
): boolean {
const steps = schemaPointerSteps(path);
const last = steps[steps.length - 1];
return (
last?.kind === "value" &&
annotationKeys.has(last.keyword) &&
!(
last.keyword === "description" &&
steps.length === 1 &&
scope === this.references.rootScope
)
);
}
visit(
value: unknown,
position: SchemaPosition,
scope: JsonSchemaScope | undefined,
isRoot: boolean,
): boolean {
if (Array.isArray(value)) {
if (!this.emitAscii("[")) return false;
for (let i = 0; i < value.length; i++) {
if (i > 0 && !this.emitAscii(",")) return false;
if (!this.visit(value[i], position, scope, false)) return false;
}
return this.emitAscii("]");
}
if (isSchemaObject(value)) {
return position === "schema"
? this.visitSchemaObject(value, scope, isRoot)
: this.visitObject(value, position, scope, "normal");
}
const serialized = JSON.stringify(value);
return this.emitText(serialized === undefined ? "null" : serialized);
}
private visitSchemaObject(
value: Record<string, unknown>,
scope: JsonSchemaScope | undefined,
isRoot: boolean,
): boolean {
const currentScope = this.references.enter(value, scope);
if (
currentScope === undefined ||
currentScope.dialect !== this.references.rootScope.dialect ||
Object.hasOwn(value, "$dynamicRef") ||
Object.hasOwn(value, "$recursiveRef") ||
Object.hasOwn(value, "$dynamicAnchor") ||
Object.hasOwn(value, "$recursiveAnchor")
) {
this.resolved = false;
return false;
}
if (this.isEffectivelyEmpty(value, isRoot))
return this.emitAscii(EMPTY_SCHEMA_JSON);
if (Object.hasOwn(value, "$ref") && typeof value.$ref === "string")
return this.visitReference(value, value.$ref, currentScope, isRoot);
return this.visitObject(
value,
"schema",
currentScope,
isRoot ? "root" : "normal",
);
}
private visitReference(
value: Record<string, unknown>,
ref: string,
currentScope: JsonSchemaScope,
isRoot: boolean,
): boolean {
let scopeRefs = this.active.get(currentScope);
if (scopeRefs?.has(ref)) {
this.resolved = false;
return false;
}
const target = this.references.resolve(currentScope, ref);
if (
target.kind !== "target" ||
(this.strip && this.isStrippedTarget(currentScope, target.path))
) {
this.resolved = false;
return false;
}
const siblings = this.hasSiblings(value, isRoot);
// Draft 7 ignores siblings, while clients such as Ajv also apply them.
// Do not label either interpretation an equivalent inline advertisement.
if (currentScope.dialect === "draft-07" && siblings) {
this.resolved = false;
return false;
}
if (scopeRefs === undefined) {
scopeRefs = new Set();
this.active.set(currentScope, scopeRefs);
}
scopeRefs.add(ref);
const ok = !siblings
? this.visit(target.value, "schema", currentScope, false)
: this.emitAscii('{"allOf":[') &&
this.visit(target.value, "schema", currentScope, false) &&
this.emitAscii(",") &&
this.visitObject(
value,
"schema",
currentScope,
isRoot ? "root-siblings" : "siblings",
) &&
this.emitAscii("]}");
scopeRefs.delete(ref);
return ok;
}
private visitObject(
value: Record<string, unknown>,
position: SchemaPosition,
scope: JsonSchemaScope | undefined,
mode: ObjectEmitMode,
): boolean {
if (!this.emitAscii("{")) return false;
let first = true;
for (const key in value) {
if (!Object.hasOwn(value, key)) continue;
const child = value[key];
if (child === undefined) continue;
if (this.isSkippedKey(key, position, mode)) continue;
if (!first && !this.emitAscii(",")) return false;
first = false;
if (!this.emitText(JSON.stringify(key)) || !this.emitAscii(":"))
return false;
// `not: {}` forbids a value; no client infers a type for a value it
// must omit, and the any-value list would place `items` beside a
// non-array type, which Gemini function declarations reject.
if (
position === "schema" &&
key === "not" &&
isSchemaObject(child) &&
this.isEffectivelyEmpty(child, false)
) {
if (!this.emitAscii("{}")) return false;
continue;
}
const childPosition = childSchemaPosition(key, position);
if (!this.visit(child, childPosition, scope, false)) return false;
}
return this.emitAscii("}");
}
}
/** Stop serialization at the budget before allocating an expanded schema. */
export const inlineWithinBudget = (
root: Record<string, unknown>,
budgetBytes: number,
options?: InlineWithinBudgetOptions,
): Record<string, unknown> | undefined => {
const references = new JsonSchemaReferences(root);
const identity = Object.fromEntries(
["$id", "$anchor", "$schema"].flatMap((key) =>
Object.hasOwn(root, key) ? [[key, root[key]]] : [],
),
);
const identityBytes =
Object.keys(identity).length === 0 ? 0 : serializedBytes(identity) - 2;
if (identityBytes > budgetBytes) return undefined;
let resolved = true;
function* serialize(
value: unknown,
position: "schema" | "map" | "data",
scope: JsonSchemaScope | undefined,
active: ReadonlyMap<JsonSchemaScope, ReadonlySet<string>>,
): Generator<string> {
if (Array.isArray(value)) {
yield "[";
for (const [index, child] of value.entries()) {
if (index > 0) yield ",";
yield* serialize(child, position, scope, active);
}
yield "]";
} else if (isSchemaObject(value)) {
const currentScope =
position === "schema" ? references.enter(value, scope) : scope;
if (
position === "schema" &&
(currentScope === undefined ||
currentScope.dialect !== references.rootScope.dialect ||
[
"$dynamicRef",
"$recursiveRef",
"$dynamicAnchor",
"$recursiveAnchor",
].some((key) => Object.hasOwn(value, key)))
) {
resolved = false;
return;
}
if (position === "schema" && Object.keys(value).length === 0) {
yield JSON.stringify(jsonValueSchema());
return;
}
if (position === "schema" && typeof value.$ref === "string") {
const target = references.resolve(currentScope, value.$ref);
if (
target.kind !== "target" ||
currentScope === undefined ||
active.get(currentScope)?.has(value.$ref)
) {
resolved = false;
return;
}
const {
$ref,
$id: _id,
$anchor: _anchor,
$schema: _schema,
...siblings
} = value;
const nextActive = new Map(active);
nextActive.set(
currentScope,
new Set([...(active.get(currentScope) ?? []), $ref]),
);
// Draft 7 ignores siblings, while clients such as Ajv also apply them.
// Do not label either interpretation an equivalent inline advertisement.
if (
currentScope.dialect === "draft-07" &&
Object.keys(siblings).length > 0
) {
resolved = false;
return;
}
const expanded =
Object.keys(siblings).length === 0
? target.value
: { allOf: [target.value, siblings] };
yield* serialize(expanded, "schema", currentScope, nextActive);
return;
}
yield "{";
let first = true;
for (const [key, child] of Object.entries(value)) {
if (
position === "schema" &&
(definitionKeys.has(key) ||
key === "$id" ||
key === "$anchor" ||
key === "$schema")
)
continue;
if (!first) yield ",";
first = false;
yield JSON.stringify(key) + ":";
// `not: {}` forbids a value; no client infers a type for a value it
// must omit, and the any-value list would place `items` beside a
// non-array type, which Gemini function declarations reject.
if (
position === "schema" &&
key === "not" &&
isSchemaObject(child) &&
Object.keys(child).length === 0
) {
yield "{}";
continue;
}
const childPosition =
position === "map"
? "schema"
: position === "schema" && schemaMaps.has(key)
? "map"
: position === "schema" &&
(schemaArrays.has(key) || schemaChildren.has(key))
? "schema"
: "data";
yield* serialize(child, childPosition, currentScope, active);
}
yield "}";
} else {
yield JSON.stringify(value);
const limit = Number.isSafeInteger(budgetBytes)
? budgetBytes
: budgetBytes > 0
? Number.MAX_SAFE_INTEGER
: -1;
if (limit < 0) return undefined;
const references = options?.references ?? new JsonSchemaReferences(root);
const identity: Record<string, unknown> = {};
let hasIdentity = false;
for (const key of ["$id", "$anchor", "$schema"] as const) {
if (Object.hasOwn(root, key) && root[key] !== undefined) {
identity[key] = root[key];
hasIdentity = true;
}
}
const chunks: string[] = [];
let bytes = identityBytes;
for (const chunk of serialize(
root,
"schema",
references.rootScope,
new Map(),
)) {
bytes += Buffer.byteLength(chunk, "utf8");
if (bytes > budgetBytes || !resolved) return undefined;
chunks.push(chunk);
}
if (!resolved) return undefined;
const expanded: unknown = JSON.parse(chunks.join(""));
const identityBytes = hasIdentity ? serializedBytes(identity) - 2 : 0;
const budget = new Budget(limit);
if (!budget.tryCharge(identityBytes)) return undefined;
const serializer = new BudgetedSchemaSerializer(
budget,
references,
options?.stripAnnotations === true,
);
if (
!serializer.visit(root, "schema", references.rootScope, true) ||
!serializer.resolved
)
return undefined;
const expanded: unknown = JSON.parse(serializer.chunks.join(""));
if (!isSchemaObject(expanded)) return undefined;
// Every emitted dependency is now static and reference-free. Nested resource
// identifiers/anchors can leave without duplicating identities at call sites.
if (!hasIdentity) return expanded;
const schema = { ...identity, ...expanded };
return serializedBytes(schema) <= budgetBytes ? schema : undefined;
};
@@ -470,6 +634,7 @@ const reducedPropertyTypes = (
export const reduceToShallowProperties = (
schema: Record<string, unknown>,
reducedAnnotation: string,
references: JsonSchemaReferences = new JsonSchemaReferences(schema),
): Record<string, unknown> => {
const properties = isSchemaObject(schema.properties) ? schema.properties : {};
const description = [
@@ -478,7 +643,6 @@ export const reduceToShallowProperties = (
]
.filter((text) => text !== undefined)
.join(" ");
const references = new JsonSchemaReferences(schema);
const shallow = Object.fromEntries(
Object.entries(properties).map(([name, value]) => {
const description =
+7 -3
View File
@@ -6,8 +6,8 @@ import {
reduceToShallowProperties,
schemaDepth,
serializedBytes,
stripAnnotations,
} from "./compactJsonSchema.js";
import { JsonSchemaReferences } from "./jsonSchemaReferences.js";
// Output schemas dominate a complete `tools/list` frame. The compact profile
// bounds each advertised output contract so frame-capped hosts can finish the
@@ -53,7 +53,11 @@ export const compactAdvertisedOutputSchema = (
schema: Record<string, unknown>,
budgetBytes: number,
): CompactedOutputSchema => {
const inline = inlineWithinBudget(stripAnnotations(schema), budgetBytes);
const references = new JsonSchemaReferences(schema);
const inline = inlineWithinBudget(schema, budgetBytes, {
stripAnnotations: true,
references,
});
if (inline !== undefined && schemaDepth(inline) <= COMPACT_SCHEMA_MAX_DEPTH)
return {
schema: withoutContentBoundIdentity(inline),
@@ -64,7 +68,7 @@ export const compactAdvertisedOutputSchema = (
// valid canonical output.
const reduced =
schema.type === "object" || isSchemaObject(schema.properties)
? reduceToShallowProperties(schema, OUTPUT_REDUCED_ANNOTATION)
? reduceToShallowProperties(schema, OUTPUT_REDUCED_ANNOTATION, references)
: jsonValueSchema();
if (serializedBytes(reduced) <= budgetBytes)
return {
+84
View File
@@ -39,6 +39,90 @@ export const schemaSubschemas = (
return [];
});
/** Assign an own data property without triggering `__proto__` prototype mutation. */
export const setOwnSchemaProperty = (
target: Record<string, unknown>,
key: string,
value: unknown,
): void => {
if (key === "__proto__") {
Object.defineProperty(target, key, {
value,
enumerable: true,
configurable: true,
writable: true,
});
} else {
target[key] = value;
}
};
const mapSchemaMap = (
mapValue: Record<string, unknown>,
keyword: string,
map: (child: unknown, keyword: string) => unknown,
): Record<string, unknown> => {
let out: Record<string, unknown> | undefined;
for (const name in mapValue) {
if (!Object.hasOwn(mapValue, name)) continue;
const child = mapValue[name];
const mapped = map(child, keyword);
if (mapped !== child) {
if (out === undefined) out = { ...mapValue };
setOwnSchemaProperty(out, name, mapped);
}
}
return out ?? mapValue;
};
const mapSchemaArray = (
items: readonly unknown[],
keyword: string,
map: (child: unknown, keyword: string) => unknown,
): readonly unknown[] => {
let out: unknown[] | undefined;
for (let i = 0; i < items.length; i++) {
const child = items[i];
const mapped = map(child, keyword);
if (mapped !== child) {
if (out === undefined) out = items.slice();
out[i] = mapped;
}
}
return out ?? items;
};
/**
* Copy-on-write map over every direct subschema position of `schema`.
* Returns `schema` itself when no child changes; skips `skipKeyword` when given.
*/
export const mapSchemaChildren = (
schema: Record<string, unknown>,
map: (child: unknown, keyword: string) => unknown,
skipKeyword?: string,
): Record<string, unknown> => {
let out: Record<string, unknown> | undefined;
for (const keyword in schema) {
if (!Object.hasOwn(schema, keyword) || keyword === skipKeyword) continue;
const value = schema[keyword];
let nextValue = value;
if (schemaMaps.has(keyword)) {
if (isRecord(value)) nextValue = mapSchemaMap(value, keyword, map);
} else if (schemaArrays.has(keyword)) {
if (Array.isArray(value)) nextValue = mapSchemaArray(value, keyword, map);
} else if (schemaChildren.has(keyword)) {
nextValue = Array.isArray(value)
? mapSchemaArray(value, keyword, map)
: map(value, keyword);
}
if (nextValue !== value) {
if (out === undefined) out = { ...schema };
setOwnSchemaProperty(out, keyword, nextValue);
}
}
return out ?? schema;
};
/** Instance values, unless explicitly reached by a schema reference. */
export const schemaLiteralValues = new Set([
"const",
+123 -50
View File
@@ -71,6 +71,41 @@ const sameResourceFragment = (
return hash === -1 ? "" : reference.slice(hash + 1);
};
const pushObjectChildren = (
items: readonly unknown[],
scope: JsonSchemaScope,
pending: { value: unknown; scope: JsonSchemaScope }[],
): void => {
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (isObject(item)) pending.push({ value: item, scope });
}
};
const enqueueSchemaChildren = (
value: SchemaObject,
scope: JsonSchemaScope,
pending: { value: unknown; scope: JsonSchemaScope }[],
): void => {
for (const key in value) {
if (!Object.hasOwn(value, key)) continue;
const child = value[key];
if (schemaMaps.has(key)) {
if (!isObject(child)) continue;
for (const name in child) {
if (!Object.hasOwn(child, name)) continue;
const item = child[name];
if (isObject(item)) pending.push({ value: item, scope });
}
} else if (schemaArrays.has(key)) {
if (Array.isArray(child)) pushObjectChildren(child, scope, pending);
} else if (schemaChildren.has(key)) {
if (Array.isArray(child)) pushObjectChildren(child, scope, pending);
else if (isObject(child)) pending.push({ value: child, scope });
}
}
};
/** Per-projection scope ownership; no external resource loading or dynamic-reference evaluation. */
export class JsonSchemaReferences {
readonly rootScope: JsonSchemaScope;
@@ -89,6 +124,10 @@ export class JsonSchemaReferences {
Map<string, JsonSchemaScope>
>();
readonly #ambiguous = new WeakSet<JsonSchemaScope>();
readonly #resolved = new WeakMap<
JsonSchemaScope,
Map<string, LocalReference>
>();
constructor(root: SchemaObject) {
let baseUri: string | undefined;
@@ -105,7 +144,9 @@ export class JsonSchemaReferences {
if (baseUri !== undefined) this.#identities.set(baseUri, this.rootScope);
// Index resources before consumers resolve anything, so later duplicate IDs
// cannot invalidate facts that have already escaped from the owner.
const pending = [{ value: root as unknown, scope: this.rootScope }];
const pending: { value: unknown; scope: JsonSchemaScope }[] = [
{ value: root as unknown, scope: this.rootScope },
];
const visited = new WeakMap<JsonSchemaScope, WeakSet<object>>();
while (pending.length > 0) {
const { value, scope: parent } = pending.pop()!;
@@ -119,30 +160,43 @@ export class JsonSchemaReferences {
}
if (seen.has(value)) continue;
seen.add(value);
for (const keyword of ["$ref", "$dynamicRef", "$recursiveRef"]) {
const reference = value[keyword];
if (typeof reference !== "string") continue;
this.#referenceSites.push({ scope, reference, keyword });
if (keyword !== "$ref") continue;
const target = this.resolve(scope, reference);
if (target.kind === "target")
pending.push({ value: target.value, scope });
}
for (const [key, child] of Object.entries(value)) {
if (schemaMaps.has(key) && isObject(child)) {
for (const item of Object.values(child))
pending.push({ value: item, scope });
} else if (
(schemaArrays.has(key) || schemaChildren.has(key)) &&
Array.isArray(child)
) {
for (const item of child) pending.push({ value: item, scope });
} else if (schemaChildren.has(key))
pending.push({ value: child, scope });
}
this.#recordReferenceSites(value, scope, pending);
enqueueSchemaChildren(value, scope, pending);
}
}
#recordReferenceSites(
value: SchemaObject,
scope: JsonSchemaScope,
pending: { value: unknown; scope: JsonSchemaScope }[],
): void {
if (Object.hasOwn(value, "$ref") && typeof value.$ref === "string") {
const reference = value.$ref;
this.#referenceSites.push({ scope, reference, keyword: "$ref" });
const target = this.resolve(scope, reference);
if (target.kind === "target" && isObject(target.value))
pending.push({ value: target.value, scope });
}
if (
Object.hasOwn(value, "$dynamicRef") &&
typeof value.$dynamicRef === "string"
)
this.#referenceSites.push({
scope,
reference: value.$dynamicRef,
keyword: "$dynamicRef",
});
if (
Object.hasOwn(value, "$recursiveRef") &&
typeof value.$recursiveRef === "string"
)
this.#referenceSites.push({
scope,
reference: value.$recursiveRef,
keyword: "$recursiveRef",
});
}
enter(
schema: SchemaObject,
parent: JsonSchemaScope | undefined,
@@ -236,36 +290,55 @@ export class JsonSchemaReferences {
scope: JsonSchemaScope | undefined,
reference: string,
): LocalReference {
// Re-check ambiguity before reading #resolved: a scope resolved during
// construction may later be marked ambiguous when a sibling ID collides.
if (scope === undefined || this.enter(scope.root, scope) === undefined)
return { kind: "unresolved", reason: "scope" };
const local = sameResourceFragment(reference, scope.baseUri);
if (local === undefined) return { kind: "unresolved", reason: "external" };
let fragment: string;
try {
fragment = decodeURIComponent(local);
} catch {
return { kind: "unresolved", reason: "fragment" };
let cachedByRef = this.#resolved.get(scope);
if (cachedByRef !== undefined) {
const cached = cachedByRef.get(reference);
if (cached !== undefined) return cached;
} else {
cachedByRef = new Map();
this.#resolved.set(scope, cachedByRef);
}
if (fragment === "") return { kind: "target", value: scope.root, path: [] };
if (!fragment.startsWith("/")) return { kind: "anchor" };
let value: unknown = scope.root;
const path: string[] = [];
for (const token of fragment.slice(1).split("/")) {
if (/~(?:[^01]|$)/u.test(token))
return { kind: "unresolved", reason: "pointer" };
const key = unescapeJsonPointerToken(token);
if (
value === null ||
typeof value !== "object" ||
!Object.hasOwn(value, key) ||
(Array.isArray(value) && !/^(?:0|[1-9][0-9]*)$/u.test(key))
)
return { kind: "unresolved", reason: "pointer" };
if (value !== scope.root && isObject(value) && "$id" in value)
return { kind: "unresolved", reason: "resource-boundary" };
path.push(key);
value = Reflect.get(value, key);
}
return { kind: "target", value, path };
const resolved = resolveLocalReference(scope, reference);
cachedByRef.set(reference, resolved);
return resolved;
}
}
const resolveLocalReference = (
scope: JsonSchemaScope,
reference: string,
): LocalReference => {
const local = sameResourceFragment(reference, scope.baseUri);
if (local === undefined) return { kind: "unresolved", reason: "external" };
let fragment: string;
try {
fragment = decodeURIComponent(local);
} catch {
return { kind: "unresolved", reason: "fragment" };
}
if (fragment === "") return { kind: "target", value: scope.root, path: [] };
if (!fragment.startsWith("/")) return { kind: "anchor" };
let value: unknown = scope.root;
const path: string[] = [];
for (const token of fragment.slice(1).split("/")) {
if (/~(?:[^01]|$)/u.test(token))
return { kind: "unresolved", reason: "pointer" };
const key = unescapeJsonPointerToken(token);
if (
value === null ||
typeof value !== "object" ||
!Object.hasOwn(value, key) ||
(Array.isArray(value) && !/^(?:0|[1-9][0-9]*)$/u.test(key))
)
return { kind: "unresolved", reason: "pointer" };
if (value !== scope.root && isObject(value) && "$id" in value)
return { kind: "unresolved", reason: "resource-boundary" };
path.push(key);
value = Reflect.get(value, key);
}
return { kind: "target", value, path };
};
@@ -223,3 +223,75 @@ it("advertises the analysis view output without large inline alternatives", () =
INLINE_ALTERNATIVE_BYTES,
);
});
describe("shareOutputDefinitions incremental merge & length bounds", () => {
it("preserves earliest definition order when an earlier dirty entry matches a later entry", () => {
const shared = shareOutputDefinitions({
type: "object",
properties: {
first: { $ref: "#/$defs/outerEarly" },
second: { $ref: "#/$defs/outerLate" },
},
$defs: {
leafA: { type: "integer", minimum: 1 },
outerEarly: { type: "array", items: { $ref: "#/$defs/leafB" } },
outerLate: { type: "array", items: { $ref: "#/$defs/leafA" } },
leafB: { type: "integer", minimum: 1 },
},
});
expect(shared).toEqual({
type: "object",
properties: {
first: { $ref: "#/$defs/outerEarly" },
second: { $ref: "#/$defs/outerEarly" },
},
$defs: {
leafA: { type: "integer", minimum: 1 },
outerEarly: { type: "array", items: { $ref: "#/$defs/leafA" } },
},
});
});
it("hoists alternatives strictly past INLINE_ALTERNATIVE_BYTES including escapes", () => {
const exactBase = {
type: "object",
properties: { p: { type: "string", description: "" } },
};
const overhead = JSON.stringify(exactBase).length;
const exactFit = {
...exactBase,
properties: {
p: {
type: "string",
description: "x".repeat(INLINE_ALTERNATIVE_BYTES - overhead),
},
},
};
const oneOver = {
...exactBase,
properties: {
p: {
type: "string",
description: `${"x".repeat(INLINE_ALTERNATIVE_BYTES - overhead)}\n`,
},
},
};
expect(JSON.stringify(exactFit).length).toBe(INLINE_ALTERNATIVE_BYTES);
expect(JSON.stringify(oneOver).length).toBe(INLINE_ALTERNATIVE_BYTES + 2);
const shared = shareOutputDefinitions({
type: "object",
properties: {
u: { anyOf: [exactFit, oneOver] },
},
$defs: { unused: { type: "boolean" } },
});
const branches = (
(shared.properties as Record<string, Record<string, unknown>>).u!
.anyOf as unknown[]
).map((b) => JSON.stringify(b));
expect(branches).toEqual([
JSON.stringify(exactFit),
'{"$ref":"#/$defs/__branch0"}',
]);
});
});
+379 -81
View File
@@ -1,22 +1,23 @@
import {
mapSchemaChildren,
schemaArrays,
schemaChildren,
schemaMaps,
schemaSubschemas,
setOwnSchemaProperty,
} from "./jsonSchemaKeywords.js";
import { isRecord } from "../kernel/isRecord.js";
type Schema = Record<string, unknown>;
/** Keywords that change how a reference resolves inside the subschema that holds them. */
const RESOLUTION_KEYWORDS = [
const RESOLUTION_KEYWORDS = new Set([
"$id",
"$anchor",
"$dynamicAnchor",
"$dynamicRef",
"$recursiveAnchor",
"$recursiveRef",
];
]);
const DEFINITION_KEYWORDS = ["$defs", "definitions"] as const;
type DefinitionKeyword = (typeof DEFINITION_KEYWORDS)[number];
const ALTERNATIVE_KEYWORDS = new Set(["anyOf", "oneOf"]);
@@ -61,44 +62,169 @@ export const shareOutputDefinitions = (root: Schema): Schema => {
};
const definitionKeyword = (root: Schema): DefinitionKeyword | undefined => {
const present = DEFINITION_KEYWORDS.filter((keyword) =>
Object.hasOwn(root, keyword),
);
return present.length === 1 ? present[0] : undefined;
let found: DefinitionKeyword | undefined;
for (const keyword of DEFINITION_KEYWORDS) {
if (!Object.hasOwn(root, keyword)) continue;
if (found !== undefined) return undefined;
found = keyword;
}
return found;
};
/**
* Rebuild one schema level, mapping each direct subschema. Instance values
* and unknown keywords are kept as they are. `definitions` names the root's
* own definition map, which callers handle separately.
*/
const mapSubschemas = (
schema: Schema,
map: (child: unknown, keyword: string) => unknown,
definitions?: DefinitionKeyword,
): Schema =>
Object.fromEntries(
Object.entries(schema).map(([keyword, value]) => {
if (keyword === definitions) return [keyword, value];
if (schemaMaps.has(keyword) && isRecord(value))
return [
keyword,
Object.fromEntries(
Object.entries(value).map(([name, child]) => [
name,
map(child, keyword),
]),
),
];
const jsonStringLength = (text: string): number => {
let len = 2;
for (let i = 0; i < text.length; i++) {
const code = text.charCodeAt(i);
if (
code === 0x22 ||
code === 0x5c ||
code < 0x20 ||
(code >= 0xd800 && code <= 0xdfff)
)
return JSON.stringify(text).length;
len += 1;
}
return len;
};
const exceedsJsonArrayLength = (
items: readonly unknown[],
limit: number,
used: { total: number },
): boolean => {
used.total += 2;
if (used.total > limit) return true;
for (let i = 0; i < items.length; i++) {
if (i > 0) {
used.total += 1;
if (used.total > limit) return true;
}
const item = items[i];
if (
item === undefined ||
typeof item === "function" ||
typeof item === "symbol"
) {
used.total += 4;
if (used.total > limit) return true;
continue;
}
if (exceedsJsonLengthStep(item, limit, used)) return true;
}
return false;
};
const exceedsJsonObjectLength = (
object: Record<string, unknown>,
limit: number,
used: { total: number },
): boolean => {
if (typeof (object as { toJSON?: unknown }).toJSON === "function") {
const text = JSON.stringify(object);
used.total += text === undefined ? 0 : text.length;
return used.total > limit;
}
used.total += 2;
if (used.total > limit) return true;
let first = true;
for (const key in object) {
if (!Object.hasOwn(object, key)) continue;
const child = object[key];
if (
child === undefined ||
typeof child === "function" ||
typeof child === "symbol"
)
continue;
if (!first) {
used.total += 1;
if (used.total > limit) return true;
}
first = false;
used.total += jsonStringLength(key) + 1;
if (used.total > limit || exceedsJsonLengthStep(child, limit, used))
return true;
}
return false;
};
const exceedsJsonLengthStep = (
value: unknown,
limit: number,
used: { total: number },
): boolean => {
if (typeof value === "string") {
used.total += jsonStringLength(value);
return used.total > limit;
}
if (value === null || typeof value !== "object") {
const serialized = JSON.stringify(value);
used.total += serialized === undefined ? 4 : serialized.length;
return used.total > limit;
}
if (Array.isArray(value)) return exceedsJsonArrayLength(value, limit, used);
return exceedsJsonObjectLength(value as Record<string, unknown>, limit, used);
};
/** Short-circuiting check equivalent to `JSON.stringify(value).length > limit`. */
const exceedsJsonLength = (value: unknown, limit: number): boolean =>
exceedsJsonLengthStep(value, limit, { total: 0 });
const mapResolvesWithinDefinitions = (
value: Record<string, unknown>,
prefix: string,
names: ReadonlySet<string>,
): boolean => {
for (const name in value) {
if (
Object.hasOwn(value, name) &&
!resolvesWithinDefinitions(value[name], prefix, names)
)
return false;
}
return true;
};
const arrayResolvesWithinDefinitions = (
items: readonly unknown[],
prefix: string,
names: ReadonlySet<string>,
): boolean => {
for (let i = 0; i < items.length; i++) {
if (!resolvesWithinDefinitions(items[i], prefix, names)) return false;
}
return true;
};
const childrenResolveWithinDefinitions = (
schema: Record<string, unknown>,
prefix: string,
names: ReadonlySet<string>,
): boolean => {
for (const key in schema) {
if (!Object.hasOwn(schema, key)) continue;
const value = schema[key];
if (schemaMaps.has(key)) {
if (
(schemaArrays.has(keyword) || schemaChildren.has(keyword)) &&
Array.isArray(value)
isRecord(value) &&
!mapResolvesWithinDefinitions(value, prefix, names)
)
return [keyword, value.map((child) => map(child, keyword))];
if (schemaChildren.has(keyword)) return [keyword, map(value, keyword)];
return [keyword, value];
}),
);
return false;
} else if (schemaArrays.has(key)) {
if (
Array.isArray(value) &&
!arrayResolvesWithinDefinitions(value, prefix, names)
)
return false;
} else if (schemaChildren.has(key)) {
const ok = Array.isArray(value)
? arrayResolvesWithinDefinitions(value, prefix, names)
: resolvesWithinDefinitions(value, prefix, names);
if (!ok) return false;
}
}
return true;
};
const resolvesWithinDefinitions = (
schema: unknown,
@@ -106,8 +232,10 @@ const resolvesWithinDefinitions = (
names: ReadonlySet<string>,
): boolean => {
if (!isRecord(schema)) return true;
if (RESOLUTION_KEYWORDS.some((keyword) => Object.hasOwn(schema, keyword)))
return false;
for (const keyword in schema) {
if (!Object.hasOwn(schema, keyword)) continue;
if (RESOLUTION_KEYWORDS.has(keyword)) return false;
}
if (Object.hasOwn(schema, "$ref")) {
const reference = schema.$ref;
if (typeof reference !== "string" || !reference.startsWith(prefix))
@@ -115,9 +243,7 @@ const resolvesWithinDefinitions = (
const name = reference.slice(prefix.length);
if (!PLAIN_DEFINITION_NAME.test(name) || !names.has(name)) return false;
}
return schemaSubschemas(schema, { includeDefinitions: true }).every((child) =>
resolvesWithinDefinitions(child, prefix, names),
);
return childrenResolveWithinDefinitions(schema, prefix, names);
};
const hoistLargeAlternatives = (
@@ -127,6 +253,7 @@ const hoistLargeAlternatives = (
prefix: string,
): Schema => {
const hoisted: Schema = {};
let hasHoisted = false;
const names = new Set(Object.keys(definitions));
let next = 0;
const freshName = (): string => {
@@ -138,7 +265,7 @@ const hoistLargeAlternatives = (
};
const visit = (schema: unknown, own?: DefinitionKeyword): unknown => {
if (!isRecord(schema)) return schema;
return mapSubschemas(
return mapSchemaChildren(
schema,
(child, parent) => {
const rebuilt = visit(child);
@@ -146,26 +273,211 @@ const hoistLargeAlternatives = (
!ALTERNATIVE_KEYWORDS.has(parent) ||
!isRecord(rebuilt) ||
Object.hasOwn(rebuilt, "$ref") ||
JSON.stringify(rebuilt).length <= INLINE_ALTERNATIVE_BYTES
!exceedsJsonLength(rebuilt, INLINE_ALTERNATIVE_BYTES)
)
return rebuilt;
const name = freshName();
hoisted[name] = rebuilt;
setOwnSchemaProperty(hoisted, name, rebuilt);
hasHoisted = true;
return { $ref: `${prefix}${name}` };
},
own,
);
};
const rebuiltDefinitions = Object.fromEntries(
Object.entries(definitions).map(([name, body]) => [name, visit(body)]),
);
let rebuiltDefinitions: Schema | undefined;
for (const name in definitions) {
if (!Object.hasOwn(definitions, name)) continue;
const body = definitions[name];
const rebuilt = visit(body);
if (rebuilt !== body) {
if (rebuiltDefinitions === undefined)
rebuiltDefinitions = { ...definitions };
setOwnSchemaProperty(rebuiltDefinitions, name, rebuilt);
}
}
const rebuiltRoot = visit(root, keyword) as Schema;
if (!hasHoisted && rebuiltDefinitions === undefined && rebuiltRoot === root)
return root;
return {
...rebuiltRoot,
[keyword]: { ...rebuiltDefinitions, ...hoisted },
[keyword]: hasHoisted
? { ...(rebuiltDefinitions ?? definitions), ...hoisted }
: (rebuiltDefinitions ?? definitions),
};
};
const addReferrer = (
referrers: Map<string, Set<string>>,
target: string,
caller: string,
): void => {
let set = referrers.get(target);
if (set === undefined) {
set = new Set();
referrers.set(target, set);
}
set.add(caller);
};
const collectDefinitionReferrers = (
caller: string,
node: unknown,
prefix: string,
referrers: Map<string, Set<string>>,
): void => {
if (!isRecord(node)) return;
if (Object.hasOwn(node, "$ref")) {
const reference = node.$ref;
if (typeof reference === "string" && reference.startsWith(prefix))
addReferrer(referrers, reference.slice(prefix.length), caller);
}
for (const key in node) {
if (!Object.hasOwn(node, key)) continue;
const value = node[key];
if (schemaMaps.has(key)) {
if (!isRecord(value)) continue;
for (const name in value) {
if (Object.hasOwn(value, name))
collectDefinitionReferrers(caller, value[name], prefix, referrers);
}
} else if (schemaArrays.has(key)) {
if (!Array.isArray(value)) continue;
for (let i = 0; i < value.length; i++)
collectDefinitionReferrers(caller, value[i], prefix, referrers);
} else if (schemaChildren.has(key)) {
if (Array.isArray(value)) {
for (let i = 0; i < value.length; i++)
collectDefinitionReferrers(caller, value[i], prefix, referrers);
} else {
collectDefinitionReferrers(caller, value, prefix, referrers);
}
}
}
};
const redirectWithAliases = (
node: unknown,
aliases: ReadonlyMap<string, string>,
prefix: string,
options?: {
readonly ownKeyword?: DefinitionKeyword;
readonly onTarget?: (target: string) => void;
},
): unknown => {
if (!isRecord(node)) return node;
const onTarget = options?.onTarget;
const rebuilt = mapSchemaChildren(
node,
(child) =>
redirectWithAliases(
child,
aliases,
prefix,
onTarget === undefined ? undefined : { onTarget },
),
options?.ownKeyword,
);
if (!Object.hasOwn(rebuilt, "$ref")) return rebuilt;
const reference = rebuilt.$ref;
if (typeof reference !== "string" || !reference.startsWith(prefix))
return rebuilt;
const target = aliases.get(reference.slice(prefix.length));
if (target === undefined) return rebuilt;
onTarget?.(target);
return { ...rebuilt, $ref: `${prefix}${target}` };
};
interface MergeState {
readonly order: Map<string, number>;
readonly live: Map<string, unknown>;
readonly bodyText: Map<string, string>;
readonly firstByBody: Map<string, string>;
readonly referrers: Map<string, Set<string>>;
readonly finalAlias: Map<string, string>;
}
const seedMergeState = (definitions: Schema, prefix: string): MergeState => {
const order = new Map<string, number>();
const live = new Map<string, unknown>();
const bodyText = new Map<string, string>();
const firstByBody = new Map<string, string>();
const referrers = new Map<string, Set<string>>();
const finalAlias = new Map<string, string>();
let index = 0;
for (const name in definitions) {
if (!Object.hasOwn(definitions, name)) continue;
order.set(name, index++);
const body = definitions[name];
// Zod emits equal schemas with the same key order. A body that differs
// only in key order stays separate, which costs bytes, not meaning.
const text = JSON.stringify(body);
const first = firstByBody.get(text);
if (first === undefined) {
firstByBody.set(text, name);
bodyText.set(name, text);
live.set(name, body);
} else {
finalAlias.set(name, first);
}
}
if (finalAlias.size > 0) {
for (const [name, body] of live)
collectDefinitionReferrers(name, body, prefix, referrers);
}
return { order, live, bodyText, firstByBody, referrers, finalAlias };
};
const runMergeRound = (
state: MergeState,
roundMerged: ReadonlyMap<string, string>,
prefix: string,
): Map<string, string> => {
const dirtySet = new Set<string>();
for (const loser of roundMerged.keys()) {
const callers = state.referrers.get(loser);
if (callers === undefined) continue;
for (const caller of callers) {
if (state.live.has(caller)) dirtySet.add(caller);
}
}
const nextMerged = new Map<string, string>();
if (dirtySet.size === 0) return nextMerged;
const dirty = [...dirtySet].sort(
(left, right) => state.order.get(left)! - state.order.get(right)!,
);
for (const name of dirty) {
state.firstByBody.delete(state.bodyText.get(name)!);
const nextBody = redirectWithAliases(
state.live.get(name),
roundMerged,
prefix,
{ onTarget: (target) => addReferrer(state.referrers, target, name) },
);
state.live.set(name, nextBody);
}
for (const name of dirty) {
const text = JSON.stringify(state.live.get(name));
const existing = state.firstByBody.get(text);
if (existing === undefined) {
state.firstByBody.set(text, name);
state.bodyText.set(name, text);
} else if (state.order.get(name)! < state.order.get(existing)!) {
state.firstByBody.set(text, name);
state.bodyText.set(name, text);
state.bodyText.delete(existing);
state.live.delete(existing);
nextMerged.set(existing, name);
state.finalAlias.set(existing, name);
} else {
state.bodyText.delete(name);
state.live.delete(name);
nextMerged.set(name, existing);
state.finalAlias.set(name, existing);
}
}
return nextMerged;
};
/**
* Merge definitions with identical bodies into the first of them, repeating
* until no two remain identical, because a merge can make the definitions
@@ -176,37 +488,23 @@ const mergeIdenticalDefinitions = (
keyword: DefinitionKeyword,
prefix: string,
): Schema => {
let current = root;
for (;;) {
const definitions = current[keyword] as Schema;
const firstByBody = new Map<string, string>();
const merged = new Map<string, string>();
for (const [name, body] of Object.entries(definitions)) {
// Zod emits equal schemas with the same key order. A body that differs
// only in key order stays separate, which costs bytes, not meaning.
const text = JSON.stringify(body);
const first = firstByBody.get(text);
if (first === undefined) firstByBody.set(text, name);
else merged.set(name, first);
}
if (merged.size === 0) return current;
const redirect = (schema: unknown, own?: DefinitionKeyword): unknown => {
if (!isRecord(schema)) return schema;
const rebuilt = mapSubschemas(schema, (child) => redirect(child), own);
const reference = rebuilt.$ref;
if (typeof reference !== "string") return rebuilt;
const target = merged.get(reference.slice(prefix.length));
return target === undefined
? rebuilt
: { ...rebuilt, $ref: `${prefix}${target}` };
};
current = {
...(redirect(current, keyword) as Schema),
[keyword]: Object.fromEntries(
Object.entries(definitions)
.filter(([name]) => !merged.has(name))
.map(([name, body]) => [name, redirect(body)]),
),
};
const definitions = root[keyword] as Schema;
const state = seedMergeState(definitions, prefix);
let roundMerged: Map<string, string> = new Map(state.finalAlias);
while (roundMerged.size > 0)
roundMerged = runMergeRound(state, roundMerged, prefix);
if (state.finalAlias.size === 0) return root;
const resolvedAlias = new Map<string, string>();
for (const [loser, initial] of state.finalAlias) {
let target = initial;
while (state.finalAlias.has(target)) target = state.finalAlias.get(target)!;
resolvedAlias.set(loser, target);
}
const mergedDefinitions: Schema = {};
for (const [name, body] of state.live)
setOwnSchemaProperty(mergedDefinitions, name, body);
const redirectedRoot = redirectWithAliases(root, resolvedAlias, prefix, {
ownKeyword: keyword,
}) as Schema;
return { ...redirectedRoot, [keyword]: mergedDefinitions };
};
+9 -24
View File
@@ -6,6 +6,7 @@ import { isRecord as isObject } from "../kernel/isRecord.js";
import { advertisedSchemaPatterns } from "./advertisedDialect.js";
import { projectPortablePattern } from "./portablePattern.js";
import {
mapSchemaChildren,
schemaArrays,
schemaChildren,
schemaMaps,
@@ -487,29 +488,13 @@ const hasLiteralReference = (root: Record<string, unknown>): boolean => {
/** Copy schema positions, replacing each pattern with its exact portable form. */
const replaceExactPatterns = (schema: unknown): unknown => {
if (!isObject(schema)) return schema;
return Object.fromEntries(
Object.entries(schema).map(([key, value]) => {
if (key === "pattern" && typeof value === "string") {
const projection = projectPortablePattern(value);
return [key, projection.kind === "exact" ? projection.pattern : value];
}
if (schemaMaps.has(key) && isObject(value))
return [
key,
Object.fromEntries(
Object.entries(value).map(([name, child]) => [
name,
replaceExactPatterns(child),
]),
),
];
if (
(schemaArrays.has(key) || schemaChildren.has(key)) &&
Array.isArray(value)
)
return [key, value.map(replaceExactPatterns)];
if (schemaChildren.has(key)) return [key, replaceExactPatterns(value)];
return [key, value];
}),
const rebuilt = mapSchemaChildren(
schema as Record<string, unknown>,
replaceExactPatterns,
);
if (typeof rebuilt.pattern !== "string") return rebuilt;
const projection = projectPortablePattern(rebuilt.pattern);
if (projection.kind !== "exact" || projection.pattern === rebuilt.pattern)
return rebuilt;
return { ...rebuilt, pattern: projection.pattern };
};
+21
View File
@@ -242,3 +242,24 @@ it("rejects every malformed discovery without changing visibility", async () =>
expect(f.changed).not.toHaveBeenCalled();
}
});
it("ranks name matches ahead of description-only matches and caches projected input schemas", async () => {
const f = await connect({ bulk: true });
const first = await f.discover({ query: "sqlite", limit: 3 });
const firstPage = DISCOVER_TOOLS.outputSchema.parse(first.structuredContent);
expect(firstPage.tools.map(({ name }) => name)).toEqual([
"alpha_sqlite",
"beta_sqlite",
"binary_session",
]);
const repeat = await f.discover({
names: ["alpha_sqlite", "bulk_00"],
});
const repeatPage = DISCOVER_TOOLS.outputSchema.parse(
repeat.structuredContent,
);
expect(repeatPage.tools[0]?.input_schema).toEqual(
firstPage.tools[0]?.input_schema,
);
expect(repeatPage.loaded_count).toBe(5);
});
+51 -25
View File
@@ -30,6 +30,10 @@ export class ProgressiveToolCatalog {
>;
/** Exact names and counts also cover the always-advertised adapter. */
private readonly inventory: ReadonlyMap<string, CatalogListing>;
private readonly inputSchemas = new WeakMap<
RegisteredTool,
Record<string, unknown>
>();
constructor(
registrations: ReadonlyMap<string, RegisteredTool>,
@@ -70,6 +74,43 @@ export class ProgressiveToolCatalog {
});
}
private inputSchemaFor(registered: RegisteredTool): Record<string, unknown> {
let schema = this.inputSchemas.get(registered);
if (schema === undefined) {
schema = (registered.inputSchema?.["~standard"].jsonSchema.input({
target: "draft-2020-12",
}) as Record<string, unknown> | undefined) ?? { type: "object" };
this.inputSchemas.set(registered, schema);
}
return schema;
}
private rankMatches(query: string | undefined): readonly string[] {
const words = (query ?? "").toLowerCase().split(/\s+/u).filter(Boolean);
const ranked: { readonly name: string; readonly score: number }[] = [];
for (const [name, tool] of this.tools) {
let matchesAll = true;
for (let i = 0; i < words.length; i++) {
if (!tool.search.includes(words[i]!)) {
matchesAll = false;
break;
}
}
if (!matchesAll) continue;
let score = 0;
for (let i = 0; i < words.length; i++) {
if (name.includes(words[i]!)) score += 1;
}
ranked.push({ name, score });
}
ranked.sort(
(left, right) =>
right.score - left.score ||
(left.name < right.name ? -1 : left.name > right.name ? 1 : 0),
);
return ranked.map((entry) => entry.name);
}
discover(input: z.infer<typeof DISCOVER_TOOLS.inputSchema>) {
const names =
input.names === undefined ? undefined : [...new Set(input.names)];
@@ -93,37 +134,24 @@ export class ProgressiveToolCatalog {
),
false,
);
const words = (input.query ?? "")
.toLowerCase()
.split(/\s+/u)
.filter(Boolean);
const matches =
names ??
[...this.tools]
.filter(([, tool]) => words.every((word) => tool.search.includes(word)))
.map(([name]) => name)
.sort((left, right) => {
const score = (name: string) =>
words.filter((word) => name.includes(word)).length;
return (
score(right) - score(left) ||
(left < right ? -1 : left > right ? 1 : 0)
);
});
const matches = names ?? this.rankMatches(input.query);
const page =
names ?? matches.slice(input.offset, input.offset + input.limit);
const selected = page.map((name) => ({
name,
...this.inventory.get(name)!,
}));
let loadedCount = 0;
for (const { registered } of this.inventory.values()) {
if (registered.enabled) loadedCount += 1;
}
for (let i = 0; i < selected.length; i++) {
if (!selected[i]!.registered.enabled) loadedCount += 1;
}
const result: z.infer<typeof DISCOVER_TOOLS.outputSchema> = {
profile: "hot-cold",
inventory_count: this.inventory.size,
loaded_count:
[...this.inventory.values()].filter(
({ registered }) => registered.enabled,
).length +
selected.filter(({ registered }) => !registered.enabled).length,
loaded_count: loadedCount,
total_matches: matches.length,
next_offset:
names === undefined && input.offset + page.length < matches.length
@@ -132,9 +160,7 @@ export class ProgressiveToolCatalog {
tools: selected.map(({ name, description, registered }) => ({
name,
description,
input_schema: registered.inputSchema?.["~standard"].jsonSchema.input({
target: "draft-2020-12",
}) ?? { type: "object" },
input_schema: this.inputSchemaFor(registered),
})),
next_step:
selected.length === 0
+1 -1
View File
@@ -157,7 +157,7 @@ it.each([
minItems: 1,
maxItems: 20,
},
offset: { type: "integer", minimum: 0, maximum: 9007199254740991 },
offset: { type: "integer", minimum: 0 },
limit: { type: "integer", minimum: 1, maximum: 20 },
});
expect(JSON.stringify(discovery.inputSchema)).not.toContain('"default"');