microsoft/typespec
Publicmirrored from https://github.com/microsoft/typespecAvailable
packages/html-program-viewer/src/emitter.ts
40lines · modecode
| 1 | import { EmitContext, emitFile, resolvePath } from "@typespec/compiler"; |
| 2 | import { renderProgram } from "./ui.js"; |
| 3 | |
| 4 | import { createTypeSpecLibrary, JSONSchemaType } from "@typespec/compiler"; |
| 5 | |
| 6 | export interface HtmlProgramViewerOptions { |
| 7 | /** |
| 8 | * Override compiler output-dir |
| 9 | */ |
| 10 | "output-dir"?: string; |
| 11 | } |
| 12 | |
| 13 | const EmitterOptionsSchema: JSONSchemaType<HtmlProgramViewerOptions> = { |
| 14 | type: "object", |
| 15 | additionalProperties: false, |
| 16 | properties: { |
| 17 | "output-dir": { type: "string", nullable: true }, |
| 18 | }, |
| 19 | required: [], |
| 20 | }; |
| 21 | |
| 22 | export const libDef = { |
| 23 | name: "@typespec/openapi3", |
| 24 | diagnostics: {}, |
| 25 | emitter: { |
| 26 | options: EmitterOptionsSchema as JSONSchemaType<HtmlProgramViewerOptions>, |
| 27 | }, |
| 28 | } as const; |
| 29 | |
| 30 | export const $lib = createTypeSpecLibrary(libDef); |
| 31 | |
| 32 | export async function $onEmit(context: EmitContext<HtmlProgramViewerOptions>) { |
| 33 | const html = renderProgram(context.program); |
| 34 | const outputDir = context.emitterOutputDir; |
| 35 | const htmlPath = resolvePath(outputDir, "typespec-program.html"); |
| 36 | await emitFile(context.program, { |
| 37 | path: htmlPath, |
| 38 | content: `<!DOCTYPE html><html lang="en"><link rel="stylesheet" href="style.css"><body>${html}</body></html>`, |
| 39 | }); |
| 40 | } |
| 41 | |