test: consolidate redundant assertions into boundary workflows
Remove getter, enum, cloned-projection, cache-identity, and obsolete profile assertions along with the shadow JSON Schema engine and dead test-only APIs. Retain producer, filesystem, SDK, lifecycle, integrity, and malformed-format coverage. Document the priority of real end-to-end workflows, boundary integration, and producer goldens.
This commit is contained in:
@@ -254,17 +254,8 @@ it("distinguishes an unreported Java version from an unsupported old version", a
|
||||
it("cancels an in-flight Java readiness probe", async () => {
|
||||
const root = await createTestTempDirectory("rea-jadx-cancel-");
|
||||
const jar = join(root, "jadx-headless-mcp.jar");
|
||||
const javaHome = join(root, "fake-jdk");
|
||||
const bin = join(javaHome, "bin");
|
||||
const java = join(bin, "java");
|
||||
const marker = join(root, "java-probe-started");
|
||||
await mkdir(bin, { recursive: true });
|
||||
const { javaHome, marker } = await createHangingJdk(root);
|
||||
await writeJadxJarInventory(jar);
|
||||
await writeFile(
|
||||
java,
|
||||
`#!/bin/sh\nexec ${process.execPath} -e 'require("node:fs").writeFileSync(process.argv[1], "ready"); setTimeout(() => {}, 30_000)' '${marker}'\n`,
|
||||
);
|
||||
await chmod(java, 0o700);
|
||||
const controller = new AbortController();
|
||||
const pending = inspectJadxAvailability(
|
||||
{ REA_JADX_MCP_JAR: jar, JAVA_HOME: javaHome },
|
||||
@@ -272,11 +263,13 @@ it("cancels an in-flight Java readiness probe", async () => {
|
||||
);
|
||||
try {
|
||||
await expect
|
||||
.poll(() =>
|
||||
readFile(marker, "utf8").then(
|
||||
() => true,
|
||||
() => false,
|
||||
),
|
||||
.poll(
|
||||
() =>
|
||||
readFile(marker, "utf8").then(
|
||||
() => true,
|
||||
() => false,
|
||||
),
|
||||
{ timeout: 10_000 },
|
||||
)
|
||||
.toBe(true);
|
||||
controller.abort();
|
||||
@@ -290,17 +283,8 @@ it("cancels an in-flight Java readiness probe", async () => {
|
||||
it("reports a killed Java probe as unresolved instead of missing runtime", async () => {
|
||||
const root = await createTestTempDirectory("rea-jadx-timeout-");
|
||||
const jar = join(root, "jadx-headless-mcp.jar");
|
||||
const javaHome = join(root, "fake-jdk");
|
||||
const bin = join(javaHome, "bin");
|
||||
const java = join(bin, "java");
|
||||
const marker = join(root, "java-probe-started");
|
||||
await mkdir(bin, { recursive: true });
|
||||
const { javaHome, java } = await createHangingJdk(root);
|
||||
await writeJadxJarInventory(jar);
|
||||
await writeFile(
|
||||
java,
|
||||
`#!/bin/sh\nexec ${process.execPath} -e 'require("node:fs").writeFileSync(process.argv[1], "ready"); setTimeout(() => {}, 30_000)' '${marker}'\n`,
|
||||
);
|
||||
await chmod(java, 0o700);
|
||||
|
||||
const availability = await inspectJadxAvailability({
|
||||
REA_JADX_MCP_JAR: jar,
|
||||
@@ -320,6 +304,20 @@ it("reports a killed Java probe as unresolved instead of missing runtime", async
|
||||
expect(availability.reason).not.toContain("Select a full JDK");
|
||||
});
|
||||
|
||||
const createHangingJdk = async (root: string) => {
|
||||
const javaHome = join(root, "fake-jdk");
|
||||
const bin = join(javaHome, "bin");
|
||||
const java = join(bin, "java");
|
||||
const marker = join(root, "java-probe-started");
|
||||
await mkdir(bin, { recursive: true });
|
||||
await writeFile(
|
||||
java,
|
||||
`#!/bin/sh\nexec ${process.execPath} -e 'require("node:fs").writeFileSync(process.argv[1], "ready"); setTimeout(() => {}, 30_000)' '${marker}'\n`,
|
||||
);
|
||||
await chmod(java, 0o700);
|
||||
return { javaHome, java, marker };
|
||||
};
|
||||
|
||||
const createFakeJdk = async (
|
||||
root: string,
|
||||
compiler = true,
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
|
||||
const runCli = async (arguments_: readonly string[]) => {
|
||||
try {
|
||||
const result = await execute(
|
||||
process.execPath,
|
||||
["scripts/rea.mjs", ...arguments_],
|
||||
{
|
||||
cwd: process.cwd(),
|
||||
env: { ...process.env, REA_LOG_LEVEL: "silent" },
|
||||
timeout: 15_000,
|
||||
},
|
||||
);
|
||||
return { exitCode: 0, ...result };
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"code" in cause &&
|
||||
typeof cause.code === "number" &&
|
||||
"stdout" in cause &&
|
||||
typeof cause.stdout === "string" &&
|
||||
"stderr" in cause &&
|
||||
typeof cause.stderr === "string"
|
||||
)
|
||||
return {
|
||||
exitCode: cause.code,
|
||||
stdout: cause.stdout,
|
||||
stderr: cause.stderr,
|
||||
};
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
it("shows MCP doctor help without starting a server and keeps option errors actionable", async () => {
|
||||
const parentHelp = await runCli(["mcp", "--help"]);
|
||||
expect(parentHelp.exitCode).toBe(0);
|
||||
expect(parentHelp.stdout).toContain("doctor");
|
||||
|
||||
const help = await runCli(["mcp", "doctor", "--help"]);
|
||||
expect(help.exitCode).toBe(0);
|
||||
expect(help.stdout).toContain("Usage: rea mcp doctor [options]");
|
||||
expect(help.stdout).toContain("--format <toon|json|yaml|md|jsonl>");
|
||||
expect(help.stdout).toContain("--full-output");
|
||||
|
||||
const invalid = await runCli(["mcp", "doctor", "--not-an-option"]);
|
||||
expect(invalid.exitCode).toBe(1);
|
||||
expect(invalid.stdout).toContain(
|
||||
"Unknown mcp doctor option: --not-an-option",
|
||||
);
|
||||
});
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
import { nativeUiResultSchema } from "../../../src/domain/native/nativeUiObservation.js";
|
||||
import { processCaptureSchema } from "../../../src/domain/process/processCapture.js";
|
||||
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
|
||||
import { inlineLocalJsonSchemaReferences } from "../../fixtures/localJsonSchemaReferences.js";
|
||||
|
||||
const record = (value: unknown): Record<string, unknown> => {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
@@ -25,6 +24,25 @@ const record = (value: unknown): Record<string, unknown> => {
|
||||
return value as Record<string, unknown>;
|
||||
};
|
||||
|
||||
const schemaNode = (
|
||||
root: Record<string, unknown>,
|
||||
value: unknown,
|
||||
): Record<string, unknown> => {
|
||||
const schema = record(value);
|
||||
if (typeof schema.$ref !== "string") return schema;
|
||||
if (!schema.$ref.startsWith("#/"))
|
||||
throw new Error("Expected a local advertised schema reference");
|
||||
const referenced = schema.$ref
|
||||
.slice(2)
|
||||
.split("/")
|
||||
.reduce<unknown>(
|
||||
(parent, key) =>
|
||||
record(parent)[key.replaceAll("~1", "/").replaceAll("~0", "~")],
|
||||
root,
|
||||
);
|
||||
return { ...record(referenced), ...schema };
|
||||
};
|
||||
|
||||
it("advertises semantic output invariants and keeps producers aligned with Zod", async () => {
|
||||
const contracts = [
|
||||
toolContract("capture_native_ui_scenario"),
|
||||
@@ -56,7 +74,7 @@ it("advertises semantic output invariants and keeps producers aligned with Zod",
|
||||
if (tool?.outputSchema === undefined)
|
||||
throw new Error(`${name} output schema missing`);
|
||||
const outputSchema = record(tool.outputSchema);
|
||||
const result = record(record(outputSchema.properties).result);
|
||||
const result = record(record(outputSchema.properties).normalized_result);
|
||||
const standaloneResultSchema = z.record(z.string(), z.unknown()).parse({
|
||||
...result,
|
||||
...(typeof outputSchema.$schema === "string"
|
||||
@@ -66,8 +84,11 @@ it("advertises semantic output invariants and keeps producers aligned with Zod",
|
||||
? {}
|
||||
: { $defs: outputSchema.$defs }),
|
||||
});
|
||||
const node = (value: unknown) =>
|
||||
schemaNode(standaloneResultSchema, value);
|
||||
return {
|
||||
result: record(inlineLocalJsonSchemaReferences(standaloneResultSchema)),
|
||||
result: node(result),
|
||||
node,
|
||||
validate: new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
@@ -76,18 +97,18 @@ it("advertises semantic output invariants and keeps producers aligned with Zod",
|
||||
};
|
||||
|
||||
const native = outputResultSchema("capture_native_ui_scenario");
|
||||
const initial = record(record(native.result.properties).initial);
|
||||
const screenshotUnion = record(record(initial.properties).screenshot);
|
||||
const initial = native.node(record(native.result.properties).initial);
|
||||
const screenshotUnion = native.node(record(initial.properties).screenshot);
|
||||
const screenshotVariants = screenshotUnion.anyOf;
|
||||
if (!Array.isArray(screenshotVariants))
|
||||
throw new Error("Expected nullable screenshot schema");
|
||||
const screenshotProperties = record(
|
||||
record(screenshotVariants[0]).properties,
|
||||
native.node(screenshotVariants[0]).properties,
|
||||
);
|
||||
expect(record(screenshotProperties.base64).description).toContain(
|
||||
expect(native.node(screenshotProperties.base64).description).toContain(
|
||||
"PNG signature",
|
||||
);
|
||||
expect(record(screenshotProperties.sha256).description).toContain(
|
||||
expect(native.node(screenshotProperties.sha256).description).toContain(
|
||||
"decoded PNG bytes",
|
||||
);
|
||||
const pngBytes = Buffer.from("not a PNG");
|
||||
@@ -124,7 +145,7 @@ it("advertises semantic output invariants and keeps producers aligned with Zod",
|
||||
const process = outputResultSchema("capture_process_scenario");
|
||||
expect(process.result.description).toContain("canonical scenario");
|
||||
expect(process.result.description).toContain(
|
||||
"older input without an event journal",
|
||||
"The event journal is required",
|
||||
);
|
||||
const validCapture = processCaptureSchema.parse(
|
||||
EMPTY_PROCESS_CAPTURE_EXAMPLE,
|
||||
|
||||
@@ -1,32 +1,13 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
firstProcedureAddress,
|
||||
requireDistinctTargetHashes,
|
||||
requireAddressArray,
|
||||
requireFunctionDossierOracle,
|
||||
requireFunctionDossier,
|
||||
requirePseudocode,
|
||||
} from "../../../../src/application/RealHopperAssertions.js";
|
||||
|
||||
describe("real Hopper semantic assertions", () => {
|
||||
it("rejects two target paths containing the same binary", () => {
|
||||
expect(() => requireDistinctTargetHashes("same", "same")).toThrow(
|
||||
/distinct binaries/u,
|
||||
);
|
||||
expect(() => requireDistinctTargetHashes("", "other")).toThrow();
|
||||
expect(() => requireDistinctTargetHashes("first", "second")).not.toThrow();
|
||||
});
|
||||
it("extracts a real procedure address from the complete inventory", () => {
|
||||
expect(firstProcedureAddress([{ address: "0x1000", name: "main" }])).toBe(
|
||||
"0x1000",
|
||||
);
|
||||
expect(() => firstProcedureAddress({ address: "0x1000" })).toThrow();
|
||||
expect(() =>
|
||||
firstProcedureAddress({ items: [{ address: "items" }] }),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
describe("Hopper verifier semantic rejection", () => {
|
||||
it("rejects empty and embedded per-item decompilation failures", () => {
|
||||
expect(requirePseudocode("return 0;", "batch_decompile")).toBe("return 0;");
|
||||
for (const invalid of ["", " ", "No output", "Error: invalid address"])
|
||||
@@ -52,7 +33,7 @@ describe("real Hopper semantic assertions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("real Hopper fixture assertions", () => {
|
||||
describe("Hopper verifier fixture assertions", () => {
|
||||
it("requires fixture-specific positive dossier evidence", () => {
|
||||
const entry = fixtureDossier({
|
||||
address: "0x1000",
|
||||
|
||||
@@ -2,36 +2,27 @@ import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { SUPPORTED_CLIENT_DEFINITIONS } from "../../src/application/SupportedClients.js";
|
||||
import { PRODUCT_IDENTITY } from "../../src/identity.js";
|
||||
|
||||
const readmeLanguages = [
|
||||
{ path: "README.md", label: "English" },
|
||||
{ path: "README_zh.md", label: "简体中文" },
|
||||
{ path: "README_zh-TW.md", label: "繁體中文" },
|
||||
{ path: "README_ja.md", label: "日本語" },
|
||||
{ path: "README_ko.md", label: "한국어" },
|
||||
{ path: "README_tr.md", label: "Türkçe" },
|
||||
{ path: "README_ru.md", label: "Русский" },
|
||||
{ path: "README_vi.md", label: "Tiếng Việt" },
|
||||
{ path: "README_th.md", label: "ไทย" },
|
||||
{ path: "README_de.md", label: "Deutsch" },
|
||||
{ path: "README_es.md", label: "Español" },
|
||||
{ path: "README_fr.md", label: "Français" },
|
||||
{ path: "README_uk.md", label: "Українська" },
|
||||
{ path: "README_pl.md", label: "Polski" },
|
||||
{ path: "README_pt-BR.md", label: "Português (Brasil)" },
|
||||
{ path: "README_ar.md", label: "العربية" },
|
||||
{ path: "README_fa.md", label: "فارسی" },
|
||||
const translatedReadmes = [
|
||||
"README_zh.md",
|
||||
"README_zh-TW.md",
|
||||
"README_ja.md",
|
||||
"README_ko.md",
|
||||
"README_tr.md",
|
||||
"README_ru.md",
|
||||
"README_vi.md",
|
||||
"README_th.md",
|
||||
"README_de.md",
|
||||
"README_es.md",
|
||||
"README_fr.md",
|
||||
"README_uk.md",
|
||||
"README_pl.md",
|
||||
"README_pt-BR.md",
|
||||
"README_ar.md",
|
||||
"README_fa.md",
|
||||
] as const;
|
||||
|
||||
const translatedReadmes = readmeLanguages
|
||||
.map((language) => language.path)
|
||||
.filter((path) => path !== "README.md");
|
||||
|
||||
const normalizedProse = (content: string): string =>
|
||||
content.replace(/\s+/gu, " ").trim();
|
||||
|
||||
const jsonExamples = (content: string): unknown[] =>
|
||||
[...content.matchAll(/```json\s*([\s\S]*?)```/gu)].map((match): unknown =>
|
||||
JSON.parse(match[1] ?? ""),
|
||||
@@ -42,31 +33,8 @@ const shellExamples = (content: string): string[] =>
|
||||
(match[1] ?? "").trim(),
|
||||
);
|
||||
|
||||
const linkedTargets = (content: string): string[] =>
|
||||
[...content.matchAll(/\]\(([^)\s]+)\)/gu)]
|
||||
.map((match) => match[1] ?? "")
|
||||
.filter(
|
||||
(target) =>
|
||||
!target.startsWith("#") &&
|
||||
!/^README(?:_[A-Za-z0-9-]+)?\.md$/u.test(target),
|
||||
)
|
||||
.sort();
|
||||
|
||||
describe("onboarding documentation product facts", () => {
|
||||
it.each(readmeLanguages)(
|
||||
"links every available language from $path",
|
||||
async ({ path, label }) => {
|
||||
const content = await readFile(resolve(path), "utf8");
|
||||
const selector = content.split("\n\n")[1] ?? "";
|
||||
expect(selector).toContain(`**${label}**`);
|
||||
for (const language of readmeLanguages) {
|
||||
if (language.path !== path)
|
||||
expect(selector).toContain(`[${language.label}](${language.path})`);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps detailed requirements and versioned MCP configuration aligned in the installation guide", async () => {
|
||||
it("keeps the installation MCP example aligned with the package registration command", async () => {
|
||||
const content = await readFile(resolve("docs/installation.md"), "utf8");
|
||||
expect(jsonExamples(content)).toContainEqual(
|
||||
expect.objectContaining({
|
||||
@@ -78,90 +46,14 @@ describe("onboarding documentation product facts", () => {
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(content).toContain("Node.js 22");
|
||||
expect(content).toContain("macOS 12");
|
||||
expect(content).toContain("Ubuntu 24.04");
|
||||
expect(content).toContain("Fedora 41");
|
||||
expect(content).toContain("Arch Linux");
|
||||
expect(content).toContain("CachyOS");
|
||||
for (const client of SUPPORTED_CLIENT_DEFINITIONS)
|
||||
expect(content).toContain(client.displayName);
|
||||
});
|
||||
|
||||
it.each(translatedReadmes)(
|
||||
"keeps onboarding commands, linked guidance and structure aligned with English in %s",
|
||||
async (path) => {
|
||||
const [english, translated] = await Promise.all([
|
||||
readFile(resolve("README.md"), "utf8"),
|
||||
readFile(resolve(path), "utf8"),
|
||||
]);
|
||||
expect(shellExamples(translated)).toEqual(shellExamples(english));
|
||||
expect(linkedTargets(translated)).toEqual(linkedTargets(english));
|
||||
const headingLevels = (content: string): number[] =>
|
||||
[...content.matchAll(/^(#{1,6})\s/gmu)].map(
|
||||
(match) => match[1]?.length ?? 0,
|
||||
);
|
||||
expect(headingLevels(translated)).toEqual(headingLevels(english));
|
||||
expect(translated.match(/<summary>/gu)?.length).toBe(
|
||||
english.match(/<summary>/gu)?.length,
|
||||
);
|
||||
expect(translated).toContain("Node.js 22.x");
|
||||
expect(translated).toContain(">=22.19");
|
||||
expect(translated).toContain("24.x");
|
||||
expect(translated).toContain(">=24.11");
|
||||
expect(translated).toContain("26+");
|
||||
expect(translated).toContain("MCP-tool_catalog");
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps both English CLI onboarding paths discoverable", async () => {
|
||||
const content = await readFile(resolve("README.md"), "utf8");
|
||||
expect(content).toMatch(
|
||||
/\bnpx(?:\s+(?:--yes|-y))?\s+rea-agents(?:@[^\s]+)?\s+setup\b/u,
|
||||
);
|
||||
expect(content).toMatch(
|
||||
/\bnpm\s+install\s+(?:--global|-g)\s+rea-agents\b/u,
|
||||
);
|
||||
expect(content).toContain("rea setup");
|
||||
});
|
||||
|
||||
it("links to optional installer and unattended setup instructions", async () => {
|
||||
const [readme, installation] = await Promise.all([
|
||||
readFile(resolve("README.md"), "utf8"),
|
||||
readFile(resolve("docs/installation.md"), "utf8"),
|
||||
]);
|
||||
expect(readme).toMatch(/\]\(docs\/installation\.md(?:#[^)]+)?\)/u);
|
||||
const prose = normalizedProse(installation);
|
||||
expect(prose).toContain(
|
||||
"curl -fsSL https://raw.githubusercontent.com/morluto/rea/main/install.sh | bash",
|
||||
);
|
||||
expect(prose).toMatch(/\brea setup\b[^\n`]*--install-hopper\b/u);
|
||||
});
|
||||
|
||||
it("documents explicit setup freshness and rollback", async () => {
|
||||
const content = await readFile(resolve("docs/installation.md"), "utf8");
|
||||
const prose = normalizedProse(content);
|
||||
expect(prose).toMatch(
|
||||
/\bnpx(?:\s+(?:--yes|-y))?\s+rea-agents@latest\s+setup\b/u,
|
||||
);
|
||||
expect(prose).toMatch(
|
||||
/\bnpm exec (?:--yes|-y) --package=rea-agents@\d+\.\d+\.\d+ -- rea setup\b/u,
|
||||
);
|
||||
});
|
||||
|
||||
it("documents the published MCP Registry installation path", async () => {
|
||||
const content = await readFile(resolve("docs/installation.md"), "utf8");
|
||||
expect(content).toContain("MCP Registry");
|
||||
expect(content).toContain("io.github.morluto/rea");
|
||||
expect(jsonExamples(content)).toContainEqual(
|
||||
expect.objectContaining({
|
||||
mcpServers: expect.objectContaining({
|
||||
rea: expect.objectContaining({
|
||||
command: "npx",
|
||||
args: ["-y", PRODUCT_IDENTITY.registrationPackageSpecifier, "mcp"],
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
it("keeps translated onboarding commands aligned with the English examples", async () => {
|
||||
const english = shellExamples(await readFile(resolve("README.md"), "utf8"));
|
||||
for (const path of translatedReadmes)
|
||||
expect(
|
||||
shellExamples(await readFile(resolve(path), "utf8")),
|
||||
path,
|
||||
).toEqual(english);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -119,14 +119,4 @@ describe("release configuration", () => {
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps generated API HTML out of the tracked tree", async () => {
|
||||
await expect(readFile("typedoc.json", "utf8")).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
const packageJson = (await readJson("package.json")) as {
|
||||
scripts?: Record<string, string>;
|
||||
};
|
||||
expect(packageJson.scripts?.["docs:api"]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
-247
@@ -1,247 +0,0 @@
|
||||
const schemaMaps = new Set([
|
||||
"properties",
|
||||
"patternProperties",
|
||||
"dependentSchemas",
|
||||
]);
|
||||
const schemaArrays = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
|
||||
const schemaChildren = new Set([
|
||||
"items",
|
||||
"additionalItems",
|
||||
"contains",
|
||||
"additionalProperties",
|
||||
"unevaluatedProperties",
|
||||
"unevaluatedItems",
|
||||
"propertyNames",
|
||||
"not",
|
||||
"if",
|
||||
"then",
|
||||
"else",
|
||||
]);
|
||||
const lowerBounds = new Set(["minimum", "exclusiveMinimum"]);
|
||||
const upperBounds = new Set(["maximum", "exclusiveMaximum"]);
|
||||
const annotations = new Set([
|
||||
"title",
|
||||
"description",
|
||||
"$comment",
|
||||
"default",
|
||||
"examples",
|
||||
"deprecated",
|
||||
"readOnly",
|
||||
"writeOnly",
|
||||
]);
|
||||
const scopedKeywords = new Set([
|
||||
"properties",
|
||||
"patternProperties",
|
||||
"additionalProperties",
|
||||
"items",
|
||||
"additionalItems",
|
||||
"prefixItems",
|
||||
"contains",
|
||||
"unevaluatedProperties",
|
||||
"unevaluatedItems",
|
||||
]);
|
||||
|
||||
const record = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
const compatibleSibling = (
|
||||
key: string,
|
||||
previous: unknown,
|
||||
value: unknown,
|
||||
): boolean =>
|
||||
previous === undefined ||
|
||||
JSON.stringify(previous) === JSON.stringify(value) ||
|
||||
annotations.has(key) ||
|
||||
(typeof previous === "number" &&
|
||||
typeof value === "number" &&
|
||||
(lowerBounds.has(key) || upperBounds.has(key)));
|
||||
|
||||
const mergeSiblings = (
|
||||
schema: Record<string, unknown>,
|
||||
siblings: Record<string, unknown>,
|
||||
): Record<string, unknown> => {
|
||||
const merged = { ...schema, ...siblings };
|
||||
for (const [key, value] of Object.entries(siblings)) {
|
||||
const previous = schema[key];
|
||||
if (!compatibleSibling(key, previous, value))
|
||||
throw new Error(`Conflicting schema reference sibling: ${key}`);
|
||||
if (typeof previous !== "number" || typeof value !== "number") continue;
|
||||
if (lowerBounds.has(key)) merged[key] = Math.max(previous, value);
|
||||
else if (upperBounds.has(key)) merged[key] = Math.min(previous, value);
|
||||
}
|
||||
return merged;
|
||||
};
|
||||
|
||||
const normalizeStringIntersection = (
|
||||
schema: Record<string, unknown>,
|
||||
): Record<string, unknown> => {
|
||||
if (
|
||||
(schema.type !== undefined && schema.type !== "string") ||
|
||||
!Array.isArray(schema.allOf)
|
||||
)
|
||||
return schema;
|
||||
let requiresString = schema.type === "string";
|
||||
const validBounds = (value: Record<string, unknown>): boolean =>
|
||||
["minLength", "maxLength"].every(
|
||||
(key) =>
|
||||
!Object.hasOwn(value, key) ||
|
||||
(typeof value[key] === "number" &&
|
||||
Number.isInteger(value[key]) &&
|
||||
value[key] >= 0),
|
||||
) &&
|
||||
(!Object.hasOwn(value, "pattern") || typeof value.pattern === "string");
|
||||
if (!validBounds(schema)) return schema;
|
||||
const patterns = new Set<string>();
|
||||
let minimum = typeof schema.minLength === "number" ? schema.minLength : 0;
|
||||
let maximum =
|
||||
typeof schema.maxLength === "number" ? schema.maxLength : Infinity;
|
||||
if (typeof schema.pattern === "string") patterns.add(schema.pattern);
|
||||
const collect = (child: unknown): boolean => {
|
||||
if (!record(child) || (child.type !== undefined && child.type !== "string"))
|
||||
return false;
|
||||
if (
|
||||
!validBounds(child) ||
|
||||
(Object.hasOwn(child, "allOf") && !Array.isArray(child.allOf))
|
||||
)
|
||||
return false;
|
||||
if (child.type === "string") requiresString = true;
|
||||
if (
|
||||
Object.keys(child).some(
|
||||
(key) =>
|
||||
!["type", "pattern", "minLength", "maxLength", "allOf"].includes(key),
|
||||
)
|
||||
)
|
||||
return false;
|
||||
if (typeof child.pattern === "string") patterns.add(child.pattern);
|
||||
if (typeof child.minLength === "number")
|
||||
minimum = Math.max(minimum, child.minLength);
|
||||
if (typeof child.maxLength === "number")
|
||||
maximum = Math.min(maximum, child.maxLength);
|
||||
return !Array.isArray(child.allOf) || child.allOf.every(collect);
|
||||
};
|
||||
if (!schema.allOf.every(collect) || !requiresString) return schema;
|
||||
const {
|
||||
allOf: _allOf,
|
||||
pattern: _pattern,
|
||||
minLength: _min,
|
||||
maxLength: _max,
|
||||
...root
|
||||
} = schema;
|
||||
const unique = [...patterns];
|
||||
return {
|
||||
...root,
|
||||
type: "string",
|
||||
...(minimum > 0 ? { minLength: minimum } : {}),
|
||||
...(maximum < Infinity ? { maxLength: maximum } : {}),
|
||||
...(unique.length === 1 ? { pattern: unique[0] } : {}),
|
||||
...(unique.length > 1
|
||||
? { allOf: unique.map((pattern) => ({ type: "string", pattern })) }
|
||||
: {}),
|
||||
};
|
||||
};
|
||||
|
||||
/** Inline finite local references for representation-independent schema assertions. */
|
||||
export const inlineLocalJsonSchemaReferences = (
|
||||
root: Readonly<Record<string, unknown>>,
|
||||
): unknown => {
|
||||
const resolve = (reference: string): Record<string, unknown> => {
|
||||
if (!reference.startsWith("#/"))
|
||||
throw new Error(`Expected a local schema reference: ${reference}`);
|
||||
let current: unknown = root;
|
||||
for (const encoded of reference.slice(2).split("/")) {
|
||||
const key = encoded.replaceAll("~1", "/").replaceAll("~0", "~");
|
||||
if (!record(current) || !Object.hasOwn(current, key))
|
||||
throw new Error(`Missing schema reference: ${reference}`);
|
||||
current = current[key];
|
||||
}
|
||||
if (!record(current))
|
||||
throw new Error(`Expected a referenced schema object: ${reference}`);
|
||||
return current;
|
||||
};
|
||||
|
||||
const visit = (value: unknown, active: ReadonlySet<string>): unknown => {
|
||||
if (!record(value)) return value;
|
||||
if (typeof value.$ref === "string") {
|
||||
const { $ref: reference, ...siblings } = value;
|
||||
if (active.has(reference))
|
||||
throw new Error(`Recursive schema reference: ${reference}`);
|
||||
const referenced = resolve(reference);
|
||||
// Keep declarations in their original evaluation scope.
|
||||
if (Object.keys(siblings).some((key) => scopedKeywords.has(key)))
|
||||
return {
|
||||
allOf: [
|
||||
visit(referenced, new Set([...active, reference])),
|
||||
visit(siblings, active),
|
||||
],
|
||||
};
|
||||
return visit(
|
||||
mergeSiblings(referenced, siblings),
|
||||
new Set([...active, reference]),
|
||||
);
|
||||
}
|
||||
if (Array.isArray(value.allOf) && value.allOf.length === 1) {
|
||||
const child = visit(value.allOf[0], active);
|
||||
const { allOf: _allOf, ...siblings } = value;
|
||||
if (
|
||||
record(child) &&
|
||||
!Object.keys(siblings).some((key) => scopedKeywords.has(key)) &&
|
||||
Object.entries(siblings).every(([key, entry]) =>
|
||||
compatibleSibling(key, child[key], entry),
|
||||
)
|
||||
) {
|
||||
return visit(mergeSiblings(child, siblings), active);
|
||||
}
|
||||
}
|
||||
const normalized = { ...value };
|
||||
if (
|
||||
typeof normalized.pattern === "string" &&
|
||||
Array.isArray(normalized.allOf) &&
|
||||
normalized.allOf.some(
|
||||
(child: unknown) =>
|
||||
record(child) && child.pattern === normalized.pattern,
|
||||
)
|
||||
)
|
||||
delete normalized.pattern;
|
||||
if (
|
||||
typeof normalized.minimum === "number" &&
|
||||
typeof normalized.exclusiveMinimum === "number" &&
|
||||
normalized.exclusiveMinimum >= normalized.minimum
|
||||
)
|
||||
delete normalized.minimum;
|
||||
if (
|
||||
typeof normalized.maximum === "number" &&
|
||||
typeof normalized.exclusiveMaximum === "number" &&
|
||||
normalized.exclusiveMaximum <= normalized.maximum
|
||||
)
|
||||
delete normalized.maximum;
|
||||
return normalizeStringIntersection(
|
||||
Object.fromEntries(
|
||||
Object.entries(normalized)
|
||||
.filter(([key]) => key !== "$defs" && key !== "definitions")
|
||||
.map(([key, child]) => {
|
||||
if (schemaMaps.has(key) && record(child))
|
||||
return [
|
||||
key,
|
||||
Object.fromEntries(
|
||||
Object.entries(child).map(([name, schema]) => [
|
||||
name,
|
||||
visit(schema, active),
|
||||
]),
|
||||
),
|
||||
];
|
||||
if (schemaArrays.has(key) && Array.isArray(child))
|
||||
return [key, child.map((schema) => visit(schema, active))];
|
||||
if (schemaChildren.has(key))
|
||||
return [
|
||||
key,
|
||||
Array.isArray(child)
|
||||
? child.map((schema) => visit(schema, active))
|
||||
: visit(child, active),
|
||||
];
|
||||
return [key, child];
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
return visit(root, new Set());
|
||||
};
|
||||
Reference in New Issue
Block a user