MCPcopy Index your code
hub / github.com/github/copilot-sdk / normalizeSchemaForTypeScript

Function normalizeSchemaForTypeScript

scripts/codegen/typescript.ts:254–336  ·  view source on GitHub ↗
(schema: JSONSchema7)

Source from the content-addressed store, hash-verified

252}
253
254export function normalizeSchemaForTypeScript(schema: JSONSchema7): JSONSchema7 {
255 const root = structuredClone(schema) as JSONSchema7 & {
256 definitions?: Record<string, unknown>;
257 $defs?: Record<string, unknown>;
258 };
259 const definitions = { ...(root.definitions ?? {}) };
260 const draftDefinitionAliases = new Map<string, string>();
261
262 for (const [key, value] of Object.entries(root.$defs ?? {})) {
263 if (key in definitions) {
264 // The definitions entry is authoritative (it went through the full pipeline).
265 // Drop the $defs duplicate and rewrite any $ref pointing at it to use definitions.
266 draftDefinitionAliases.set(key, key);
267 } else {
268 draftDefinitionAliases.set(key, key);
269 definitions[key] = value;
270 }
271 }
272
273 root.definitions = definitions;
274 delete root.$defs;
275
276 const rewrite = (value: unknown): unknown => {
277 if (Array.isArray(value)) {
278 return value.map(rewrite);
279 }
280 if (!value || typeof value !== "object") {
281 return value;
282 }
283
284 const rewritten = Object.fromEntries(
285 Object.entries(value as Record<string, unknown>).map(([key, child]) => [key, rewrite(child)])
286 ) as Record<string, unknown>;
287
288 // The TypeScript codegen doesn't distinguish opaque JSON from any
289 // other unconstrained value, so drop the marker before feeding the
290 // schema to json-schema-to-typescript. C# codegen reads the marker
291 // from its own (un-normalized) view of the schema and emits
292 // `JsonElement` instead.
293 stripOpaqueJsonMarker(rewritten);
294
295 const enumValueDescriptions = getEnumValueDescriptions(rewritten as JSONSchema7);
296 if (enumValueDescriptions && Array.isArray(rewritten.enum) && rewritten.enum.every((entry) => typeof entry === "string")) {
297 rewritten.tsType = (rewritten.enum as string[])
298 .map((entry) => {
299 const comment = enumValueDescriptions[entry];
300 const literal = JSON.stringify(entry);
301 return comment ? `${tsDocCommentText(comment)}\n| ${literal}` : `| ${literal}`;
302 })
303 .join("\n");
304 delete rewritten.type;
305 delete rewritten.enum;
306 delete rewritten["x-enumDescriptions"];
307 }
308
309 if (typeof rewritten.$ref === "string") {
310 const externalRef = parseExternalSchemaRef(rewritten.$ref);
311 if (externalRef && EXTERNAL_SCHEMA_TS_IMPORT[externalRef.schemaFile]) {

Callers 3

generateSessionEventsFunction · 0.85
generateRpcFunction · 0.85

Calls 2

rewriteFunction · 0.70
setMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…