forked from microsoft/typespec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
77 lines (70 loc) · 2.6 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { Diagnostic } from "@typespec/compiler";
import { createAssetEmitter } from "@typespec/compiler/emitter-framework";
import { createTestHost, expectDiagnosticEmpty } from "@typespec/compiler/testing";
import { parse } from "yaml";
import { JsonSchemaEmitter } from "../src/json-schema-emitter.js";
import { JSONSchemaEmitterOptions } from "../src/lib.js";
import { JsonSchemaTestLibrary } from "../src/testing/index.js";
export async function getHostForCadlFile(contents: string, decorators?: Record<string, any>) {
const host = await createTestHost({
libraries: [JsonSchemaTestLibrary],
});
if (decorators) {
host.addJsFile("dec.js", decorators);
contents = `import "./dec.js";\n` + contents;
}
host.addTypeSpecFile("main.cadl", contents);
await host.compile("main.cadl", {
outputDir: "cadl-output",
});
return host;
}
export async function emitSchemaWithDiagnostics(
code: string,
options: JSONSchemaEmitterOptions = {},
testOptions: { emitNamespace?: boolean; emitTypes?: string[] } = { emitNamespace: true }
): Promise<[Record<string, any>, readonly Diagnostic[]]> {
if (!options["file-type"]) {
options["file-type"] = "json";
}
code = testOptions.emitNamespace
? `import "@typespec/json-schema"; using TypeSpec.JsonSchema; @jsonSchema namespace test; ${code}`
: `import "@typespec/json-schema"; using TypeSpec.JsonSchema; ${code}`;
const host = await getHostForCadlFile(code);
const emitter = createAssetEmitter(
host.program,
JsonSchemaEmitter as any,
{
emitterOutputDir: "cadl-output",
options,
} as any
);
if (testOptions.emitTypes === undefined) {
emitter.emitType(host.program.resolveTypeReference("test")[0]!);
} else {
for (const name of testOptions.emitTypes) {
emitter.emitType(host.program.resolveTypeReference(name)[0]!);
}
}
await emitter.writeOutput();
const schemas: Record<string, any> = {};
const files = await emitter.getProgram().host.readDir("./cadl-output");
for (const file of files) {
const sf = await emitter.getProgram().host.readFile(`./cadl-output/${file}`);
if (options?.["file-type"] === "yaml") {
schemas[file] = parse(sf.text);
} else {
schemas[file] = JSON.parse(sf.text);
}
}
return [schemas, host.program.diagnostics];
}
export async function emitSchema(
code: string,
options: JSONSchemaEmitterOptions = {},
testOptions: { emitNamespace?: boolean; emitTypes?: string[] } = { emitNamespace: true }
) {
const [schemas, diagnostics] = await emitSchemaWithDiagnostics(code, options, testOptions);
expectDiagnosticEmpty(diagnostics);
return schemas;
}