Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Json schema @extension #2057

Merged
merged 5 commits into from
Jun 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"changes": [
{
"packageName": "@typespec/json-schema",
"comment": "Support @extension for adding arbitrary vendor extensions into the output.",
"type": "none"
}
],
"packageName": "@typespec/json-schema"
}
28 changes: 28 additions & 0 deletions packages/json-schema/lib/main.tsp
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,18 @@ extern dec contentMediaType(target: string | Reflection.ModelProperty, value: va
*/
extern dec contentSchema(target: string | Reflection.ModelProperty, value: unknown);

/**
* Specify a custom property to add to the emitted schema. Useful for adding custom keywords
* and other vendor-specific extensions. The value will be converted to a schema unless the parameter
* is wrapped in the `Json<T>` template. For example, `@extension("x-schema", { x: "value" })` will
* emit a JSON schema value for `x-schema`, whereas `@extension("x-schema", Json<{x: "value"}>)` will
nguerrera marked this conversation as resolved.
Show resolved Hide resolved
* emit the raw JSON code `{x: "value"}`.
*
* @param key the name of the keyword of vendor extension, e.g. `x-custom`.
* @param value the value of the keyword. Will be converted to a schema unless wrapped in Json<T>.
*/
extern dec extension(target: unknown, key: valueof string, value: unknown);

enum Format {
dateTime: "date-time",
date: "date",
Expand All @@ -129,3 +141,19 @@ enum Format {
relativeJsonPointer: "relative-json-pointer",
regex: "regex",
}

/**
* Specify that the provided template argument should be emitted as raw JSON or YAML
* as opposed to a schema. Use in combination with the @extension decorator. For example,
* `@extension("x-schema", { x: "value" })` will emit a JSON schema value for `x-schema`,
* whereas `@extension("x-schema", Json<{x: "value"}>)` will emit the raw JSON code
* `{x: "value"}`.
*/
@Private.validatesRawJson(T)
model Json<T> {
value: T;
}

namespace Private {
extern dec validatesRawJson(target: Reflection.Model, value: unknown);
}
28 changes: 28 additions & 0 deletions packages/json-schema/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
Tuple,
Type,
Union,
typespecTypeToJson,
} from "@typespec/compiler";
import { JsonSchemaEmitter } from "./json-schema-emitter.js";
import { JSONSchemaEmitterOptions, createStateSymbol } from "./lib.js";
Expand Down Expand Up @@ -220,3 +221,30 @@ export function $prefixItems(
export function getPrefixItems(program: Program, target: Type): Tuple | undefined {
return program.stateMap(prefixItemsKey).get(target);
}

export interface ExtensionRecord {
key: string;
value: Type;
}

const extensionsKey = createStateSymbol("JsonSchema.extension");
export function $extension(context: DecoratorContext, target: Type, key: string, value: Type) {
const stateMap = context.program.stateMap(extensionsKey) as Map<Type, ExtensionRecord[]>;
const extensions = stateMap.has(target)
? stateMap.get(target)!
: stateMap.set(target, []).get(target)!;

extensions.push({ key, value });
}

export function getExtensions(program: Program, target: Type): ExtensionRecord[] {
return program.stateMap(extensionsKey).get(target) ?? [];
}

export function $validatesRawJson(context: DecoratorContext, target: Model, value: Type) {
const [_, diagnostics] = typespecTypeToJson(value, target);
if (diagnostics.length > 0) {
context.program.reportDiagnostics(diagnostics);
}
}
$validatesRawJson.namespace = "Private";
57 changes: 42 additions & 15 deletions packages/json-schema/src/json-schema-emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
Scalar,
StringLiteral,
Type,
typespecTypeToJson,
Union,
UnionVariant,
} from "@typespec/compiler";
Expand All @@ -48,6 +49,7 @@ import {
getContentEncoding,
getContentMediaType,
getContentSchema,
getExtensions,
getId,
getMaxContains,
getMaxProperties,
Expand Down Expand Up @@ -175,26 +177,30 @@ export class JsonSchemaEmitter extends TypeEmitter<Record<string, any>, JSONSche

const enumTypesArray = [...enumTypes];

const withConstraints = new ObjectBuilder({
$schema: "https://json-schema.org/draft/2020-12/schema",
$id: this.#getDeclId(en),
type: enumTypesArray.length === 1 ? enumTypesArray[0] : enumTypesArray,
enum: [...enumValues],
});
this.#applyConstraints(en, withConstraints);
return this.emitter.result.declaration(
name,
new ObjectBuilder({
$schema: "https://json-schema.org/draft/2020-12/schema",
$id: this.#getDeclId(en),
type: enumTypesArray.length === 1 ? enumTypesArray[0] : enumTypesArray,
enum: [...enumValues],
})

withConstraints
);
}

unionDeclaration(union: Union, name: string): EmitterOutput<object> {
return this.emitter.result.declaration(
name,
new ObjectBuilder({
$schema: "https://json-schema.org/draft/2020-12/schema",
$id: this.#getDeclId(union),
anyOf: this.emitter.emitUnionVariants(union),
})
);
const withConstraints = new ObjectBuilder({
$schema: "https://json-schema.org/draft/2020-12/schema",
$id: this.#getDeclId(union),
anyOf: this.emitter.emitUnionVariants(union),
});

this.#applyConstraints(union, withConstraints);

return this.emitter.result.declaration(name, withConstraints);
}

unionLiteral(union: Union): EmitterOutput<object> {
Expand Down Expand Up @@ -366,7 +372,10 @@ export class JsonSchemaEmitter extends TypeEmitter<Record<string, any>, JSONSche
return this.emitter.result.declaration(name, builderSchema);
}

#applyConstraints(type: Scalar | Model | ModelProperty, schema: ObjectBuilder<unknown>) {
#applyConstraints(
type: Scalar | Model | ModelProperty | Union | Enum,
schema: ObjectBuilder<unknown>
) {
const applyConstraint = (fn: (p: Program, t: Type) => any, key: string) => {
const value = fn(this.emitter.getProgram(), type);
if (value !== undefined) {
Expand Down Expand Up @@ -426,6 +435,24 @@ export class JsonSchemaEmitter extends TypeEmitter<Record<string, any>, JSONSche
}
schema.set("prefixItems", prefixItemsSchema);
}

const extensions = getExtensions(this.emitter.getProgram(), type);
for (const extension of extensions) {
// todo: fix up when we have an authoritative way to ask "am I an instantiation of that template"
if (
extension.value.kind === "Model" &&
extension.value.name === "Json" &&
extension.value.namespace?.name === "JsonSchema"
) {
// we check in a decorator
schema.set(
extension.key,
typespecTypeToJson(extension.value.properties.get("value")!.type, null as any)[0]
);
} else {
schema.set(extension.key, this.emitter.emitTypeReference(extension.value));
}
}
}

#scalarBuiltinBaseType(scalar: Scalar): Scalar | null {
Expand Down
12 changes: 12 additions & 0 deletions packages/json-schema/test/enums.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,16 @@ describe("emitting enums", () => {
assert.deepStrictEqual(Foo.type, ["string", "number"]);
assert.deepStrictEqual(Foo.enum, ["hi", 2]);
});

it("handles extensions", async () => {
const schemas = await emitSchema(`
@extension("x-foo", Json<"foo">)
enum Foo {
a: "hi";
b: 2;
}
`);
const Foo = schemas["Foo.json"];
assert.strictEqual(Foo["x-foo"], "foo");
});
});
13 changes: 13 additions & 0 deletions packages/json-schema/test/models.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,17 @@ describe("emitting models", () => {
assert.strictEqual(Foo.properties.b.title, "b");
assert.strictEqual(Foo.properties.b.deprecated, true);
});

it("handles extensions", async () => {
const { "Foo.json": Foo } = await emitSchema(`
@extension("x-hi", "bye")
model Foo {
@extension("x-hi", Json<"hello">)
b: string;
}
`);

assert.deepStrictEqual(Foo["x-hi"], { type: "string", const: "bye" });
assert.deepStrictEqual(Foo.properties.b["x-hi"], "hello");
});
});
9 changes: 9 additions & 0 deletions packages/json-schema/test/scalars.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,13 @@ describe("emitting scalars", () => {
`);
});
});

it("handles extensions", async () => {
const schemas = await emitSchema(`
@extension("x-scalar", Json<true>)
scalar Test extends uint8;
`);

assert.strictEqual(schemas["Test.json"]["x-scalar"], true);
});
});
15 changes: 15 additions & 0 deletions packages/json-schema/test/unions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,19 @@ describe("emitting unions", () => {
{ type: "string", const: "hello" },
]);
});

it("handles extensions", async () => {
const schemas = await emitSchema(`
@extension("x-foo", Json<true>)
union Foo {
x: Bar;
y: Baz;
}

model Bar { };
model Baz { };
`);
const Foo = schemas["Foo.json"];
assert.strictEqual(Foo["x-foo"], true);
});
});