-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathutils.ts
More file actions
1517 lines (1335 loc) · 60.5 KB
/
utils.ts
File metadata and controls
1517 lines (1335 loc) · 60.5 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
/**
* Shared utilities for code generation - schema loading, file I/O, schema processing.
*/
import { execFile } from "child_process";
import fs from "fs/promises";
import type { JSONSchema7, JSONSchema7Definition } from "json-schema";
import path from "path";
import { fileURLToPath } from "url";
import { promisify } from "util";
export const execFileAsync = promisify(execFile);
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
/** Root of the copilot-sdk repo */
export const REPO_ROOT = path.resolve(__dirname, "../..");
/** Event types to exclude from generation (internal/legacy types) */
export const EXCLUDED_EVENT_TYPES = new Set(["session.import_legacy"]);
export interface DefinitionCollections {
definitions?: Record<string, JSONSchema7Definition>;
$defs?: Record<string, JSONSchema7Definition>;
}
export type EnumValueDescriptions = Record<string, string>;
export interface SessionEventEnvelopeProperty {
name: string;
schema: JSONSchema7;
required: boolean;
}
export interface JSONSchema7WithDefs extends JSONSchema7, DefinitionCollections {}
export type SchemaWithSharedDefinitions<T extends JSONSchema7 = JSONSchema7> = T & {
definitions: Record<string, JSONSchema7Definition>;
$defs: Record<string, JSONSchema7Definition>;
};
// ── Schema paths ────────────────────────────────────────────────────────────
export async function getSessionEventsSchemaPath(): Promise<string> {
const schemaPath = path.join(
REPO_ROOT,
"nodejs/node_modules/@github/copilot/schemas/session-events.schema.json"
);
await fs.access(schemaPath);
return schemaPath;
}
export async function getApiSchemaPath(cliArg?: string): Promise<string> {
if (cliArg) return cliArg;
const schemaPath = path.join(
REPO_ROOT,
"nodejs/node_modules/@github/copilot/schemas/api.schema.json"
);
await fs.access(schemaPath);
return schemaPath;
}
// ── Schema processing ───────────────────────────────────────────────────────
/**
* Post-process JSON Schema for code generators that expect enum-style literals.
* Converts boolean const values to enum.
*/
export function postProcessSchema(schema: JSONSchema7): JSONSchema7 {
if (typeof schema !== "object" || schema === null) return schema;
const processed = { ...schema } as JSONSchema7WithDefs;
if ("const" in processed && typeof processed.const === "boolean") {
processed.enum = [processed.const];
delete processed.const;
}
if (processed.properties) {
const newProps: Record<string, JSONSchema7Definition> = {};
for (const [key, value] of Object.entries(processed.properties).sort(([a], [b]) => a.localeCompare(b))) {
newProps[key] = typeof value === "object" ? postProcessSchema(value as JSONSchema7) : value;
}
processed.properties = newProps;
}
if (processed.items) {
if (typeof processed.items === "object" && !Array.isArray(processed.items)) {
processed.items = postProcessSchema(processed.items as JSONSchema7);
} else if (Array.isArray(processed.items)) {
processed.items = processed.items.map((item) =>
typeof item === "object" ? postProcessSchema(item as JSONSchema7) : item
) as JSONSchema7Definition[];
}
}
for (const combiner of ["anyOf", "allOf", "oneOf"] as const) {
if (processed[combiner]) {
processed[combiner] = processed[combiner]!.map((item) =>
typeof item === "object" ? postProcessSchema(item as JSONSchema7) : item
) as JSONSchema7Definition[];
}
}
const { definitions, $defs } = collectDefinitionCollections(processed as Record<string, unknown>);
let newDefs: Record<string, JSONSchema7Definition> | undefined;
if (Object.keys(definitions).length > 0) {
newDefs = {};
for (const [key, value] of Object.entries(definitions)) {
newDefs[key] = typeof value === "object" ? postProcessSchema(value as JSONSchema7) : value;
}
processed.definitions = newDefs;
}
let newDraftDefs: Record<string, JSONSchema7Definition> | undefined;
if (Object.keys($defs).length > 0) {
newDraftDefs = {};
for (const [key, value] of Object.entries($defs)) {
newDraftDefs[key] = typeof value === "object" ? postProcessSchema(value as JSONSchema7) : value;
}
processed.$defs = newDraftDefs;
}
if (processed.definitions && !processed.$defs) {
processed.$defs = { ...(newDefs ?? processed.definitions) };
} else if (processed.$defs && !processed.definitions) {
processed.definitions = { ...processed.$defs };
}
if (typeof processed.additionalProperties === "object") {
processed.additionalProperties = postProcessSchema(processed.additionalProperties as JSONSchema7);
}
return processed;
}
/**
* Strip boolean literal constraints (`const: true/false`, `enum: [true]`, `enum: [false]`)
* from a schema, recursively. quicktype's Python renderer attempts to derive
* identifier names from enum values; deriving a name from a boolean throws inside
* `snakeNameStyle` (TypeError: s.codePointAt is not a function).
*
* The literal narrowing isn't expressible in Python anyway, so we drop it and
* keep just `type: "boolean"`. Other codegen runs on the original schema.
*/
export function stripBooleanLiterals<T>(schema: T): T {
if (typeof schema !== "object" || schema === null) return schema;
if (Array.isArray(schema)) {
return schema.map((item) => stripBooleanLiterals(item)) as unknown as T;
}
const result: Record<string, unknown> = {};
const src = schema as unknown as Record<string, unknown>;
const isBooleanType = src.type === "boolean";
for (const [key, value] of Object.entries(src)) {
if (isBooleanType && key === "const" && typeof value === "boolean") continue;
if (
isBooleanType &&
key === "enum" &&
Array.isArray(value) &&
value.every((v) => typeof v === "boolean")
) {
continue;
}
result[key] = stripBooleanLiterals(value);
}
return result as T;
}
/**
* Normalize schema defects where a required property with a `$ref` to an object type
* has a description explicitly mentioning "null" as a valid value.
*
* In JSON Schema, `required` only means the key must be present — it doesn't prevent
* the value from being null. Some schemas mark properties as required but describe them
* as nullable (e.g., "Currently selected agent, or null if using the default").
*
* This function converts such properties from:
* `{ "$ref": "#/definitions/Foo", "description": "...null..." }`
* to:
* `{ "anyOf": [{ "$ref": "#/definitions/Foo" }, { "type": "null" }], "description": "...null..." }`
*
* This makes all downstream codegen (Go, C#, Python/quicktype, TypeScript) correctly
* emit nullable/optional types without per-language heuristics.
*/
export function normalizeNullableRequiredRefs(schema: JSONSchema7): JSONSchema7 {
if (typeof schema !== "object" || schema === null) return schema;
const processed = { ...schema };
if (processed.properties && processed.required) {
const requiredSet = new Set(processed.required);
const newProps: Record<string, JSONSchema7Definition> = {};
const newRequired = [...processed.required];
for (const [key, value] of Object.entries(processed.properties)) {
if (typeof value !== "object" || value === null) {
newProps[key] = value;
continue;
}
const prop = value as JSONSchema7;
if (
requiredSet.has(key) &&
prop.$ref &&
typeof prop.description === "string" &&
/\bnull\b/i.test(prop.description)
) {
// Convert to anyOf: [$ref, null] and remove from required
const { $ref, ...rest } = prop;
newProps[key] = {
...rest,
anyOf: [{ $ref }, { type: "null" as const }],
};
const idx = newRequired.indexOf(key);
if (idx !== -1) newRequired.splice(idx, 1);
} else {
newProps[key] = normalizeNullableRequiredRefs(prop);
}
}
processed.properties = newProps;
processed.required = newRequired;
}
// Recurse into nested schemas
if (processed.items) {
if (typeof processed.items === "object" && !Array.isArray(processed.items)) {
processed.items = normalizeNullableRequiredRefs(processed.items as JSONSchema7);
}
}
for (const combiner of ["anyOf", "allOf", "oneOf"] as const) {
if (processed[combiner]) {
processed[combiner] = processed[combiner]!.map((item) =>
typeof item === "object" ? normalizeNullableRequiredRefs(item as JSONSchema7) : item
) as JSONSchema7Definition[];
}
}
return processed;
}
// ── File output ─────────────────────────────────────────────────────────────
export async function writeGeneratedFile(relativePath: string, content: string): Promise<string> {
const fullPath = path.join(REPO_ROOT, relativePath);
await fs.mkdir(path.dirname(fullPath), { recursive: true });
await fs.writeFile(fullPath, content, "utf-8");
return fullPath;
}
// ── RPC schema types ────────────────────────────────────────────────────────
export interface RpcMethod {
rpcMethod: string;
description?: string;
params: JSONSchema7 | null;
result: JSONSchema7 | null;
stability?: string;
visibility?: string;
deprecated?: boolean;
}
export function getRpcSchemaTypeName(schema: JSONSchema7 | null | undefined, fallback: string): string {
if (typeof schema?.title === "string") return schema.title;
return fallback;
}
/**
* Returns true if the schema represents an object with properties (i.e., a type that should
* be generated as a class/struct/dataclass). Returns false for enums, primitives, arrays,
* and other non-object schemas.
*/
export function isObjectSchema(schema: JSONSchema7 | null | undefined): boolean {
if (!schema) return false;
if (schema.type === "object" && schema.properties) return true;
return false;
}
/**
* Returns true if the schema represents a void/null result (type: "null").
* These carry a title for languages that need a named empty type (e.g., Go)
* but should be treated as void in other languages.
*/
export function isVoidSchema(schema: JSONSchema7 | null | undefined): boolean {
if (!schema) return true;
return schema.type === "null";
}
/**
* If the schema is a nullable anyOf (anyOf: [nullLike, T] or [T, nullLike]),
* returns the non-null inner schema. Recognizes both `{ type: "null" }` and
* `{ not: {} }` (zod-to-json-schema 2019-09 format for undefined).
* Returns undefined if the schema is not a nullable wrapper.
*/
export function getNullableInner(schema: JSONSchema7): JSONSchema7 | undefined {
if (!schema.anyOf || !Array.isArray(schema.anyOf) || schema.anyOf.length !== 2) return undefined;
const [a, b] = schema.anyOf;
if (isNullLike(a) && !isNullLike(b)) return b as JSONSchema7;
if (isNullLike(b) && !isNullLike(a)) return a as JSONSchema7;
return undefined;
}
function isNullLike(s: unknown): boolean {
if (!s || typeof s !== "object") return false;
const obj = s as Record<string, unknown>;
if (obj.type === "null") return true;
if ("not" in obj && typeof obj.not === "object" && obj.not !== null && Object.keys(obj.not).length === 0) return true;
return false;
}
export function cloneSchemaForCodegen<T>(value: T): T {
if (Array.isArray(value)) {
return value.map((item) => cloneSchemaForCodegen(item)) as T;
}
if (value && typeof value === "object") {
const source = value as Record<string, unknown>;
const result: Record<string, unknown> = {};
for (const [key, child] of Object.entries(source)) {
result[key] = cloneSchemaForCodegen(child);
}
return result as T;
}
return value;
}
export function getEnumValueDescriptions(schema: JSONSchema7 | null | undefined): EnumValueDescriptions | undefined {
if (!schema || typeof schema !== "object") return undefined;
const rawDescriptions = (schema as Record<string, unknown>)["x-enumDescriptions"];
if (!rawDescriptions || typeof rawDescriptions !== "object" || Array.isArray(rawDescriptions)) return undefined;
const descriptions: EnumValueDescriptions = {};
for (const [value, description] of Object.entries(rawDescriptions)) {
if (typeof description !== "string") continue;
const trimmedDescription = description.trim();
if (trimmedDescription.length > 0) {
descriptions[value] = trimmedDescription;
}
}
return Object.keys(descriptions).length > 0 ? descriptions : undefined;
}
const INT32_MIN = -(2 ** 31);
const INT32_MAX = 2 ** 31 - 1;
function isIntegerValue(value: unknown): value is number {
return Number.isInteger(value);
}
export function isIntegerSchemaBoundedToInt32(schema: JSONSchema7): boolean {
return (
isIntegerValue(schema.minimum) &&
isIntegerValue(schema.maximum) &&
schema.minimum >= INT32_MIN &&
schema.maximum <= INT32_MAX
);
}
export function stableStringify(value: unknown): string {
if (Array.isArray(value)) {
return `[${value.map((item) => stableStringify(item)).join(",")}]`;
}
if (value && typeof value === "object") {
const entries = Object.entries(value as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b));
return `{${entries.map(([key, entryValue]) => `${JSON.stringify(key)}:${stableStringify(entryValue)}`).join(",")}}`;
}
return JSON.stringify(value) ?? "undefined";
}
export interface ApiSchema {
definitions?: Record<string, JSONSchema7Definition>;
$defs?: Record<string, JSONSchema7Definition>;
server?: Record<string, unknown>;
session?: Record<string, unknown>;
clientSession?: Record<string, unknown>;
}
export function isRpcMethod(node: unknown): node is RpcMethod {
return typeof node === "object" && node !== null && "rpcMethod" in node;
}
/**
* Apply `normalizeNullableRequiredRefs` to every JSON Schema reachable from the API schema
* (method params, results, and shared definitions). Call after `cloneSchemaForCodegen` to
* fix schema defects before any per-language codegen runs.
*/
export function fixNullableRequiredRefsInApiSchema(schema: ApiSchema): ApiSchema {
function walkApiNode(node: Record<string, unknown> | undefined): Record<string, unknown> | undefined {
if (!node) return undefined;
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(node)) {
if (isRpcMethod(value)) {
const method = value as RpcMethod;
result[key] = {
...method,
params: method.params ? normalizeNullableRequiredRefs(method.params) : method.params,
result: method.result ? normalizeNullableRequiredRefs(method.result) : method.result,
};
} else if (typeof value === "object" && value !== null) {
result[key] = walkApiNode(value as Record<string, unknown>);
} else {
result[key] = value;
}
}
return result;
}
function normalizeDefs(defs: Record<string, JSONSchema7Definition> | undefined): Record<string, JSONSchema7Definition> | undefined {
if (!defs) return undefined;
return Object.fromEntries(
Object.entries(defs).map(([key, value]) => [
key,
typeof value === "object" && value !== null ? normalizeNullableRequiredRefs(value as JSONSchema7) : value,
])
);
}
return {
...schema,
definitions: normalizeDefs(schema.definitions),
$defs: normalizeDefs(schema.$defs),
server: walkApiNode(schema.server),
session: walkApiNode(schema.session),
clientSession: walkApiNode(schema.clientSession),
};
}
/** Returns true when every leaf RPC method inside `node` is marked experimental. */
export function isNodeFullyExperimental(node: Record<string, unknown>): boolean {
const methods: RpcMethod[] = [];
(function collect(n: Record<string, unknown>) {
for (const value of Object.values(n)) {
if (isRpcMethod(value)) {
methods.push(value);
} else if (typeof value === "object" && value !== null) {
collect(value as Record<string, unknown>);
}
}
})(node);
return methods.length > 0 && methods.every(m => m.stability === "experimental");
}
/** Returns true when every leaf RPC method inside `node` is marked deprecated. */
export function isNodeFullyDeprecated(node: Record<string, unknown>): boolean {
const methods: RpcMethod[] = [];
(function collect(n: Record<string, unknown>) {
for (const value of Object.values(n)) {
if (isRpcMethod(value)) {
methods.push(value);
} else if (typeof value === "object" && value !== null) {
collect(value as Record<string, unknown>);
}
}
})(node);
return methods.length > 0 && methods.every(m => m.deprecated === true);
}
/**
* Returns a filtered copy of an API tree containing only methods whose visibility
* matches `keep`. Sub-groups that end up empty are pruned. Returns null if nothing
* survives the filter.
*
* `"public"` keeps methods without `visibility === "internal"`.
* `"internal"` keeps methods with `visibility === "internal"`.
*/
export function filterNodeByVisibility(
node: Record<string, unknown>,
keep: "public" | "internal",
): Record<string, unknown> | null {
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(node)) {
if (isRpcMethod(value)) {
const isInternal = (value as RpcMethod).visibility === "internal";
if (keep === "public" && isInternal) continue;
if (keep === "internal" && !isInternal) continue;
result[key] = value;
} else if (typeof value === "object" && value !== null) {
const sub = filterNodeByVisibility(value as Record<string, unknown>, keep);
if (sub) result[key] = sub;
}
}
return Object.keys(result).length === 0 ? null : result;
}
/** Returns true when a JSON Schema node is marked as deprecated. */
export function isSchemaDeprecated(schema: JSONSchema7 | null | undefined): boolean {
return typeof schema === "object" && schema !== null && (schema as Record<string, unknown>).deprecated === true;
}
/** Returns true when a JSON Schema node is marked as experimental. */
export function isSchemaExperimental(schema: JSONSchema7 | null | undefined): boolean {
return typeof schema === "object" && schema !== null && (schema as Record<string, unknown>).stability === "experimental";
}
/** Returns true when a JSON Schema node is marked as visibility:"internal" (set via `.asInternal()` on the Zod source). */
export function isSchemaInternal(schema: JSONSchema7 | null | undefined): boolean {
return typeof schema === "object" && schema !== null && (schema as Record<string, unknown>).visibility === "internal";
}
/**
* Collects the set of definition names marked `visibility: "internal"` and a
* per-definition set of internal property names. Used by code generators that
* need to apply `_`-prefix or similar renames consistently across both type
* declarations and references.
*
* Call after `propagateInternalVisibility` so transitively-internal fields are
* also picked up.
*/
export function collectInternalSymbols(schema: JSONSchema7): {
typeNames: Set<string>;
fieldsByType: Map<string, Set<string>>;
} {
const typeNames = new Set<string>();
const fieldsByType = new Map<string, Set<string>>();
const { definitions, $defs } = collectDefinitionCollections(schema as Record<string, unknown>);
const allDefs: Record<string, JSONSchema7Definition> = { ...definitions, ...$defs };
for (const [name, def] of Object.entries(allDefs)) {
if (!def || typeof def !== "object") continue;
const d = def as Record<string, unknown>;
if (d.visibility === "internal") typeNames.add(name);
const props = d.properties;
if (props && typeof props === "object" && !Array.isArray(props)) {
for (const [propName, propSchema] of Object.entries(props as Record<string, unknown>)) {
if (propSchema && typeof propSchema === "object" && (propSchema as Record<string, unknown>).visibility === "internal") {
if (!fieldsByType.has(name)) fieldsByType.set(name, new Set());
fieldsByType.get(name)!.add(propName);
}
}
}
}
return { typeNames, fieldsByType };
}
/**
* Post-process a Python module so that types marked `visibility: "internal"`
* carry an underscore prefix on their class identifier.
*
* Why: Python has no compiler-enforced visibility, but the leading-underscore
* convention is universally recognized as "no stability guarantee". Combined
* with `__all__` exclusion at the module level (handled separately), this is
* the strongest "internal" signal Python idioms provide and matches the
* cross-language bar of "we can do breaking changes on these without
* having to apologize".
*
* Field-level visibility is expected to be handled at emission time by each
* Python emitter (because field names depend on the emitter's PEP 8 normalization
* and the emitter's class-name conventions may diverge from the schema's
* definition names, breaking any single-class regex). Type-level renaming is
* safe to do globally because schema definition names match the emitted class
* identifiers for the types that carry `visibility: "internal"`.
*/
export function renameInternalPythonSymbols(
code: string,
typeNames: Iterable<string>
): string {
const escapeRegex = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
let result = code;
const sortedTypes = [...typeNames].sort((a, b) => b.length - a.length);
// Phase 1: rename each identifier globally at word boundaries.
for (const t of sortedTypes) {
result = result.replace(
new RegExp(`(?<![A-Za-z0-9_])${escapeRegex(t)}(?![A-Za-z0-9_])`, "g"),
`_${t}`
);
}
// Phase 2: restore JSON-key strings that match the rename target. Those
// strings carry the wire-protocol definition name and must remain untouched
// regardless of the Python-side rename. Patterns: `obj.get("Foo")` and
// `result["Foo"] = ...` in quicktype's serialization helpers.
for (const t of sortedTypes) {
const escaped = escapeRegex(t);
result = result.replace(
new RegExp(`(obj\\.get\\(")_${escaped}("\\))`, "g"),
`$1${t}$2`
);
result = result.replace(
new RegExp(`(result\\[")_${escaped}("\\])`, "g"),
`$1${t}$2`
);
}
return result;
}
/**
* Collects the set of (publicTypeName, internalFieldName[]) pairs from a
* processed schema. Used by code generators that need to annotate or rename
* properties whose type carries `visibility: "internal"` but whose containing
* definition is itself public — e.g. so IDEs/code completion can hint that a
* field is internal even when the type isn't renamed.
*
* Only definitions that are NOT themselves `visibility: "internal"` are included
* (those are already covered by type-level rename/visibility). The returned map
* is keyed by JSON Schema definition name; field names are the JSON property
* names (un-cased).
*/
export function collectInternalFieldsOnPublicTypes(
schema: JSONSchema7
): Map<string, Set<string>> {
const out = new Map<string, Set<string>>();
const { definitions, $defs } = collectDefinitionCollections(schema as Record<string, unknown>);
const allDefs: Record<string, JSONSchema7Definition> = { ...definitions, ...$defs };
for (const [name, def] of Object.entries(allDefs)) {
if (!def || typeof def !== "object") continue;
const d = def as Record<string, unknown>;
if (d.visibility === "internal") continue;
const props = d.properties;
if (!props || typeof props !== "object" || Array.isArray(props)) continue;
for (const [propName, propSchema] of Object.entries(props as Record<string, unknown>)) {
if (propSchema && typeof propSchema === "object" && (propSchema as Record<string, unknown>).visibility === "internal") {
if (!out.has(name)) out.set(name, new Set());
out.get(name)!.add(propName);
}
}
}
return out;
}
/**
* Annotate quicktype-generated Python field declarations whose schema is marked
* `visibility: "internal"` with a `# Internal:` comment immediately above the
* declaration. The comment is visible in IDE hovers/code completion, so
* consumers see the marker even though the identifier itself is unchanged.
*
* This is the field-level fallback for code paths that can't rename the field
* identifier (quicktype's generated `from_dict`/`to_dict` reference field names
* in patterns brittle to regex rewriting). For session-events and other
* hand-rolled emitters, prefer renaming.
*
* The `toFieldName` callback maps a JSON property name to its Python attribute
* name (typically snake_case).
*/
export function annotateInternalPythonFields(
code: string,
fieldsByType: Map<string, Set<string>>,
toFieldName: (jsonName: string) => string
): string {
const escapeRegex = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
let result = code;
for (const [typeName, fields] of fieldsByType) {
// Match the class body up to the next top-level statement. quicktype's
// generated classes are separated by blank-line boundaries.
const classRe = new RegExp(
`(@dataclass\\nclass ${escapeRegex(typeName)}[:(][^]*?)(?=\\n(?:@dataclass\\n)?class \\w|\\n\\nclass |\\n[A-Za-z_]\\w* =|$)`,
"g"
);
result = result.replace(classRe, (block) => {
for (const jsonField of fields) {
const pyField = toFieldName(jsonField);
const escaped = escapeRegex(pyField);
// Match ` fieldName: type` style declarations (PEP 526). Avoid
// double-annotating if the comment is already present immediately above.
block = block.replace(
new RegExp(`(^(?! # Internal:.*$)(?:.*\\n)?)( )${escaped}(?=\\s*:)`, "gm"),
(_match, prefix, indent) => {
// Avoid duplicate annotation if the previous line is already an Internal: marker.
if (/ # Internal:/.test(prefix)) return `${prefix}${indent}${pyField}`;
return `${prefix}${indent}# Internal: this field is an internal SDK API and is not part of the public surface.\n${indent}${pyField}`;
}
);
}
return block;
});
}
return result;
}
/**
* Walks a top-level JSON Schema and marks any property whose referenced type
* resolves to an internal definition as `visibility: "internal"` itself.
*
* Schemas can be authored with an internal-typed reference on a property that
* isn't itself explicitly marked internal (e.g. `copilotUsage` referencing
* `AssistantUsageCopilotUsage`). Code generators that map `visibility:
* "internal"` to hard language-level visibility (C# `internal`, Rust
* `pub(crate)`) would otherwise produce inconsistent-accessibility errors
* (CS0053 in C#, E0446 in Rust). This pass closes that gap by promoting
* referencing properties to internal — matching the language compilers'
* own transitivity rule.
*
* Only references that resolve directly, through arrays, or through dictionary
* `additionalProperties` are considered. References that flow only through a
* `oneOf`/`anyOf` of public+internal variants are left alone (the union itself
* is the carrier of visibility there).
*
* Mutates `schema` in place and returns it. Idempotent.
*/
export function propagateInternalVisibility(schema: JSONSchema7): JSONSchema7 {
if (typeof schema !== "object" || schema === null) return schema;
const { definitions, $defs } = collectDefinitionCollections(schema as Record<string, unknown>);
const allDefs: Record<string, JSONSchema7Definition> = { ...definitions, ...$defs };
const internalTypeNames = new Set<string>();
for (const [name, def] of Object.entries(allDefs)) {
if (def && typeof def === "object" && isSchemaInternal(def as JSONSchema7)) {
internalTypeNames.add(name);
}
}
if (internalTypeNames.size === 0) return schema;
const refToName = (ref: unknown): string | undefined => {
if (typeof ref !== "string") return undefined;
const m = ref.match(/^#\/(?:definitions|\$defs)\/([^/]+)$/);
return m ? m[1] : undefined;
};
/** Returns true when a property's *direct* type carrier is an internal definition. */
const propertyReferencesInternal = (propSchema: JSONSchema7): boolean => {
const direct = refToName((propSchema as Record<string, unknown>).$ref);
if (direct && internalTypeNames.has(direct)) return true;
const items = (propSchema as Record<string, unknown>).items;
if (items && typeof items === "object" && !Array.isArray(items)) {
const itemsRef = refToName((items as Record<string, unknown>).$ref);
if (itemsRef && internalTypeNames.has(itemsRef)) return true;
}
const addl = (propSchema as Record<string, unknown>).additionalProperties;
if (addl && typeof addl === "object") {
const addlRef = refToName((addl as Record<string, unknown>).$ref);
if (addlRef && internalTypeNames.has(addlRef)) return true;
}
return false;
};
const visit = (node: unknown): void => {
if (!node || typeof node !== "object") return;
if (Array.isArray(node)) {
for (const item of node) visit(item);
return;
}
const record = node as Record<string, unknown>;
const props = record.properties;
if (props && typeof props === "object" && !Array.isArray(props)) {
for (const propSchema of Object.values(props as Record<string, unknown>)) {
if (!propSchema || typeof propSchema !== "object") continue;
if (!isSchemaInternal(propSchema as JSONSchema7) && propertyReferencesInternal(propSchema as JSONSchema7)) {
(propSchema as Record<string, unknown>).visibility = "internal";
}
visit(propSchema);
}
}
for (const key of ["items", "additionalProperties", "anyOf", "allOf", "oneOf"]) {
if (record[key]) visit(record[key]);
}
for (const collectionKey of ["definitions", "$defs"]) {
const collection = record[collectionKey];
if (collection && typeof collection === "object" && !Array.isArray(collection)) {
for (const def of Object.values(collection as Record<string, unknown>)) {
if (def && typeof def === "object") visit(def);
}
}
}
};
visit(schema);
return schema;
}
/**
* Returns true when a JSON Schema node is marked `x-opaque-json: true` (set via
* `.asOpaqueJson()` on the Zod source). These are the only shapes that legitimately
* surface as opaque JSON in the SDK; everything else with an underspecified type
* is rejected by the runtime's schema lint pass.
*/
export function isOpaqueJson(schema: JSONSchema7 | null | undefined): boolean {
return typeof schema === "object" && schema !== null && (schema as Record<string, unknown>)["x-opaque-json"] === true;
}
/**
* Removes the `x-opaque-json` marker from a schema node in place. Useful for
* codegens (e.g. TypeScript) that don't distinguish opaque JSON from any other
* unconstrained value and would otherwise have the marker confuse downstream
* tooling. Codegens that *do* care (e.g. C#, which maps opaque JSON to
* `JsonElement`) should call `isOpaqueJson` *before* this point.
*/
export function stripOpaqueJsonMarker(schema: Record<string, unknown>): void {
delete schema["x-opaque-json"];
}
/**
* Append `@internal` and/or `@experimental` JSDoc-style tags to the `description`
* of every property that carries `visibility: "internal"` or `stability: "experimental"`
* inline. Used by codegens whose output mechanism (e.g. `json-schema-to-typescript`)
* renders `description` verbatim as JSDoc; downstream tooling then picks the tags
* up automatically.
*
* Mutates `schema` in place and returns it. Callers that don't want their input
* mutated should clone first.
*/
export function appendPropertyMarkerTagsToDescriptions(schema: JSONSchema7): JSONSchema7 {
const seen = new WeakSet<object>();
const visit = (node: unknown): void => {
if (!node || typeof node !== "object") return;
if (seen.has(node)) return;
seen.add(node);
if (Array.isArray(node)) {
for (const item of node) visit(item);
return;
}
const record = node as Record<string, unknown>;
const props = record.properties;
if (props && typeof props === "object" && !Array.isArray(props)) {
for (const propSchema of Object.values(props as Record<string, unknown>)) {
if (!propSchema || typeof propSchema !== "object") continue;
const tags: string[] = [];
if (isSchemaInternal(propSchema as JSONSchema7)) tags.push("@internal");
if (isSchemaExperimental(propSchema as JSONSchema7)) tags.push("@experimental");
if (tags.length === 0) continue;
const propRecord = propSchema as Record<string, unknown>;
const existing = typeof propRecord.description === "string" ? propRecord.description : "";
const suffix = tags.join("\n");
propRecord.description = existing.length > 0 ? `${existing}\n\n${suffix}` : suffix;
// json-schema-to-typescript drops the description on properties whose
// schema is a bare `$ref`. Rewriting to `allOf: [{$ref}]` keeps the
// referenced type while preserving the description (and our appended
// JSDoc tags) on the property declaration. Other generators don't see
// this wrapper because they consume the schema before this pass.
if (typeof propRecord.$ref === "string" && !propRecord.allOf) {
const refValue = propRecord.$ref;
delete propRecord.$ref;
propRecord.allOf = [{ $ref: refValue } as JSONSchema7Definition];
}
}
}
for (const value of Object.values(record)) {
if (value && typeof value === "object") visit(value);
}
};
visit(schema);
return schema;
}
// ── $ref resolution ─────────────────────────────────────────────────────────
/** Extract the generated type name from a `$ref` path (e.g. "#/definitions/Model" → "Model"). */
export function refTypeName(ref: string, definitions?: DefinitionCollections): string {
const baseName = ref.split("/").pop()!;
const match = ref.match(/^#\/(definitions|\$defs)\/(.+)$/);
if (!match || match[1] !== "$defs" || !definitions) return baseName;
const key = match[2];
const legacyDefinition = definitions.definitions?.[key];
const draftDefinition = definitions.$defs?.[key];
if (
legacyDefinition !== undefined &&
draftDefinition !== undefined &&
stableStringify(legacyDefinition) !== stableStringify(draftDefinition)
) {
return `Draft${baseName}`;
}
return baseName;
}
export function parseExternalSchemaRef(ref: string): { schemaFile: string; definitionName: string } | undefined {
const match = ref.match(/^([^#]+)#\/(?:definitions|\$defs)\/(.+)$/);
return match ? { schemaFile: match[1], definitionName: match[2] } : undefined;
}
export function collectExternalSchemaRefNames(schema: unknown): Map<string, Set<string>> {
const refs = new Map<string, Set<string>>();
const visit = (value: unknown): void => {
if (Array.isArray(value)) {
for (const item of value) visit(item);
return;
}
if (!value || typeof value !== "object") return;
const node = value as Record<string, unknown>;
if (typeof node.$ref === "string") {
const externalRef = parseExternalSchemaRef(node.$ref);
if (externalRef) {
let bucket = refs.get(externalRef.schemaFile);
if (!bucket) {
bucket = new Set<string>();
refs.set(externalRef.schemaFile, bucket);
}
bucket.add(externalRef.definitionName);
}
}
for (const child of Object.values(node)) visit(child);
};
visit(schema);
return refs;
}
/** Resolve a `$ref` path against a definitions map, returning the referenced schema. */
export function resolveRef(
ref: string,
definitions: DefinitionCollections | undefined
): JSONSchema7 | undefined {
const match = ref.match(/^#\/(definitions|\$defs)\/(.+)$/);
if (!match || !definitions) return undefined;
const [, namespace, key] = match;
const primary = namespace === "$defs" ? definitions.$defs : definitions.definitions;
const fallback = namespace === "$defs" ? definitions.definitions : definitions.$defs;
const def = primary?.[key] ?? fallback?.[key];
return typeof def === "object" ? (def as JSONSchema7) : undefined;
}
export function resolveSchema(
schema: JSONSchema7 | null | undefined,
definitions: DefinitionCollections | undefined
): JSONSchema7 | undefined {
let current = schema ?? undefined;
const seenRefs = new Set<string>();
while (current?.$ref) {
if (seenRefs.has(current.$ref)) break;
seenRefs.add(current.$ref);
const resolved = resolveRef(current.$ref, definitions);
if (!resolved) break;
current = resolved;
}
return current;
}
function hasObjectShape(schema: JSONSchema7): boolean {
return !!(schema.properties || schema.additionalProperties || schema.type === "object");
}
function isEmptyNotSchema(schema: JSONSchema7): boolean {
return !!schema.not && typeof schema.not === "object" && Object.keys(schema.not).length === 0;
}
function mergeObjectSchemas(schemas: JSONSchema7[]): JSONSchema7 | undefined {
const mergedProperties: Record<string, JSONSchema7Definition> = {};
const mergedRequired = new Set<string>();
const merged: JSONSchema7 = {
type: "object",
};
let hasShape = false;
for (const objectSchema of schemas) {
if (!merged.title && objectSchema.title) {
merged.title = objectSchema.title;
}
if (!merged.description && objectSchema.description) {
merged.description = objectSchema.description;
}
if (objectSchema.properties) {
Object.assign(mergedProperties, objectSchema.properties);
hasShape = true;
}
if (objectSchema.required) {
for (const name of objectSchema.required) {
mergedRequired.add(name);
}
}
if (objectSchema.additionalProperties !== undefined) {
merged.additionalProperties = objectSchema.additionalProperties;
hasShape = true;
}
}
if (!hasShape) return undefined;
if (Object.keys(mergedProperties).length > 0) {
merged.properties = mergedProperties;
}
if (mergedRequired.size > 0) {
merged.required = [...mergedRequired];
}
return merged;
}
export function resolveObjectSchema(
schema: JSONSchema7 | null | undefined,
definitions: DefinitionCollections | undefined
): JSONSchema7 | undefined {
const resolved = resolveSchema(schema, definitions) ?? schema ?? undefined;
if (!resolved) return undefined;
const resolvedHasObjectShape = hasObjectShape(resolved);
if (resolved.allOf) {
const objectSchemas: JSONSchema7[] = [];
if (resolvedHasObjectShape) {
objectSchemas.push(resolved);
}
for (const item of resolved.allOf) {
if (typeof item !== "object") continue;
const objectSchema = resolveObjectSchema(item as JSONSchema7, definitions);
if (!objectSchema) continue;
objectSchemas.push(objectSchema);
}