Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

go-struct-parser.ts

382 lines11.8 KB

1/**
2 * Go source → JSON Schema.
3 *
4 * BytePlus ships no fetchable OpenAPI document, but its official Go SDK
5 * (`byteplus-sdk/byteplus-go-sdk-v2`) declares the whole Ark data plane as
6 * plain structs with `json:"…"` tags. Unlike the Python SDK — whose Pydantic
7 * models need a Python runtime to introspect — Go structs are just text, so
8 * this parser runs inside the Worker on the ordinary spec-sync cron and the
9 * spec tracks upstream SDK releases with no codegen step.
10 *
11 * Deliberately narrow: it understands the subset of Go the SDK's model
12 * package actually uses (see `go-struct-parser.test.ts` for the census it was
13 * written against), not the language. Anything it cannot map becomes an
14 * unconstrained schema plus a warning rather than a hard failure — a partial
15 * spec still beats no spec, and the warnings surface in the sync outcome.
16 */
17​
18export type JsonSchema = Record<string, unknown>
19​
20export interface ParsedGoSource {
21 /** Component schemas keyed by Go type name. */
22 schemas: Record<string, JsonSchema>
23 warnings: Array<string>
25​
26export interface GoSourceFile {
27 /** Display name used in warnings (e.g. `chat_completion.go`). */
28 name: string
29 text: string
31​
32/** Go primitive → JSON Schema type. */
33const GO_PRIMITIVES: Record<string, JsonSchema> = {
34 string: { type: 'string' },
35 bool: { type: 'boolean' },
36 int: { type: 'integer' },
37 int8: { type: 'integer' },
38 int16: { type: 'integer' },
39 int32: { type: 'integer' },
40 int64: { type: 'integer' },
41 uint: { type: 'integer' },
42 uint8: { type: 'integer' },
43 uint16: { type: 'integer' },
44 uint32: { type: 'integer' },
45 uint64: { type: 'integer' },
46 float32: { type: 'number' },
47 float64: { type: 'number' },
48 // Go aliases: byte = uint8, rune = int32.
49 byte: { type: 'integer' },
50 rune: { type: 'integer' },
51 'time.Time': { type: 'string', format: 'date-time' },
52 'json.RawMessage': {},
53 any: {},
54 'interface{}': {},
56​
57interface GoField {
58 /** JSON wire name. */
59 name: string
60 goType: string
61 description?: string
62 /** Go's `omitempty` is the SDK's own optionality signal. */
63 optional: boolean
65​
66interface GoStruct {
67 name: string
68 description?: string
69 fields: Array<GoField>
71​
72/** `// comment` lines immediately above a declaration become its description. */
73function collectDocComment(lines: Array<string>, declIndex: number): string {
74 const out: Array<string> = []
75 for (let i = declIndex - 1; i >= 0; i--) {
76 const line = lines[i]?.trim() ?? ''
77 if (line.startsWith('//')) {
78 out.unshift(line.replace(/^\/\/\s?/, ''))
79 continue
80 }
81 break
82 }
83 return out.join(' ').trim()
85​
86/**
87 * Split a struct-field line into (name, type, tag).
88 *
89 * Go field syntax is `Name Type \`tag\``, with the name omitted for an
90 * embedded type. Types never contain spaces in this package
91 * (`map[string]interface{}`, `[]*ChatCompletionMessage`), so once the
92 * backtick tag is removed a whitespace split is unambiguous.
93 */
94function parseFieldLine(
95 raw: string,
96): { ident?: string; goType: string; tag?: string } | null {
97 const line = raw.trim()
98 if (!line || line.startsWith('//')) return null
99​
100 const tagMatch = /`([^`]*)`\s*$/.exec(line)
101 const tag = tagMatch?.[1]
102 const head = (tagMatch ? line.slice(0, tagMatch.index) : line).trim()
103 if (!head) return null
104​
105 const parts = head.split(/\s+/)
106 // A lone token is an embedded type (`ExtraBody`, `HttpHeader`).
107 if (parts.length === 1) return { goType: parts[0] ?? '', tag }
108 return { ident: parts[0], goType: parts.slice(1).join(' '), tag }
110​
111/** Pull the wire name and `omitempty` out of a struct tag. */
112function parseJsonTag(
113 tag: string | undefined,
114): { name: string; optional: boolean } | null {
115 if (!tag) return null
116 const raw = /json:"([^"]*)"/.exec(tag)?.[1]
117 if (raw === undefined) return null
118 const [name = '', ...opts] = raw.split(',')
119 // `json:"-"` means "never serialise".
120 if (name === '-') return null
121 return { name, optional: opts.includes('omitempty') }
123​
124interface Declarations {
125 structs: Map<string, GoStruct>
126 /** `type X string` → enum values gathered from const blocks. */
127 namedScalars: Map<string, { underlying: string; description?: string }>
128 /** `type X = Y`. */
129 aliases: Map<string, string>
130 /** `type X map[K]V` / `type X []T`. */
131 namedComposites: Map<string, string>
132 enums: Map<string, Array<string>>
134​
135function parseDeclarations(files: Array<GoSourceFile>): {
136 decls: Declarations
137 warnings: Array<string>
138} {
139 const decls: Declarations = {
140 structs: new Map(),
141 namedScalars: new Map(),
142 aliases: new Map(),
143 namedComposites: new Map(),
144 enums: new Map(),
145 }
146 const warnings: Array<string> = []
147​
148 for (const file of files) {
149 const lines = file.text.split('\n')
150 for (let i = 0; i < lines.length; i++) {
151 const line = lines[i] ?? ''
152​
153 // ---- struct ----
154 const structMatch = /^type\s+(\w+)\s+struct\s*\{/.exec(line)
155 if (structMatch) {
156 const name = structMatch[1] ?? ''
157 const fields: Array<GoField> = []
158 let j = i + 1
159 for (; j < lines.length; j++) {
160 const body = lines[j] ?? ''
161 if (/^\}/.test(body)) break
162 const parsed = parseFieldLine(body)
163 if (!parsed) continue
164 const json = parseJsonTag(parsed.tag)
165 if (!json) continue
166 // An embedded type with a wire name behaves like a normal field.
167 fields.push({
168 name: json.name,
169 goType: parsed.goType,
170 optional: json.optional,
171 description: collectDocComment(lines, j) || undefined,
172 })
173 }
174 decls.structs.set(name, {
175 name,
176 description: collectDocComment(lines, i) || undefined,
177 fields,
178 })
179 i = j
180 continue
181 }
182​
183 // ---- alias: type X = Y ----
184 const aliasMatch = /^type\s+(\w+)\s*=\s*([\w.]+)\s*$/.exec(line)
185 if (aliasMatch) {
186 decls.aliases.set(aliasMatch[1] ?? '', aliasMatch[2] ?? '')
187 continue
188 }
189​
190 // ---- named composite: type X map[...]... / []T ----
191 const compositeMatch = /^type\s+(\w+)\s+((?:map\[|\[\]).+)$/.exec(line)
192 if (compositeMatch) {
193 decls.namedComposites.set(
194 compositeMatch[1] ?? '',
195 (compositeMatch[2] ?? '').trim(),
196 )
197 continue
198 }
199​
200 // ---- named scalar: type X string ----
201 const scalarMatch = /^type\s+(\w+)\s+([\w.]+)\s*$/.exec(line)
202 const scalarUnderlying = scalarMatch?.[2]
203 if (scalarMatch && scalarUnderlying && GO_PRIMITIVES[scalarUnderlying]) {
204 decls.namedScalars.set(scalarMatch[1] ?? '', {
205 underlying: scalarUnderlying,
206 description: collectDocComment(lines, i) || undefined,
207 })
208 continue
209 }
210​
211 // ---- const block: enum values for named scalars ----
212 if (/^const\s*\(/.test(line)) {
213 for (let j = i + 1; j < lines.length; j++) {
214 const body = lines[j] ?? ''
215 if (/^\)/.test(body)) {
216 i = j
217 break
218 }
219 // `ThinkingTypeEnabled ThinkingType = "enabled"`
220 const entry = /^\s*\w+\s+(\w+)\s*=\s*"([^"]*)"/.exec(body)
221 if (!entry) continue
222 const typeName = entry[1] ?? ''
223 const value = entry[2] ?? ''
224 const existing = decls.enums.get(typeName) ?? []
225 if (!existing.includes(value)) existing.push(value)
226 decls.enums.set(typeName, existing)
227 }
228 continue
229 }
230​
231 // Single-line const: `const X Type = "v"`
232 const singleConst = /^const\s+\w+\s+(\w+)\s*=\s*"([^"]*)"/.exec(line)
233 if (singleConst) {
234 const typeName = singleConst[1] ?? ''
235 const value = singleConst[2] ?? ''
236 const existing = decls.enums.get(typeName) ?? []
237 if (!existing.includes(value)) existing.push(value)
238 decls.enums.set(typeName, existing)
239 }
240 }
241 }
242​
243 if (decls.structs.size === 0) {
244 warnings.push('go-parser: no struct declarations found')
245 }
246 return { decls, warnings }
248​
249const REF_PREFIX = '#/components/schemas/'
250​
251/** Resolve a Go type expression to a JSON Schema, recording refs it needs. */
252function typeToSchema(
253 goType: string,
254 decls: Declarations,
255 used: Set<string>,
256 warnings: Array<string>,
257 context: string,
258): JsonSchema {
259 let type = goType.trim()
260 // Pointers carry no JSON meaning — optionality comes from `omitempty`.
261 while (type.startsWith('*')) type = type.slice(1)
262​
263 if (type.startsWith('[]')) {
264 const inner = type.slice(2)
265 // []byte marshals to a base64 string, not an array.
266 if (inner === 'byte' || inner === 'uint8') return { type: 'string' }
267 return {
268 type: 'array',
269 items: typeToSchema(inner, decls, used, warnings, context),
270 }
271 }
272​
273 const mapMatch = /^map\[[^\]]+\](.+)$/.exec(type)
274 if (mapMatch) {
275 const value = typeToSchema(
276 mapMatch[1] ?? '',
277 decls,
278 used,
279 warnings,
280 context,
281 )
282 return {
283 type: 'object',
284 ...(Object.keys(value).length > 0 ? { additionalProperties: value } : {}),
285 }
286 }
287​
288 const primitive = GO_PRIMITIVES[type]
289 if (primitive) return { ...primitive }
290​
291 const alias = decls.aliases.get(type)
292 if (alias) return typeToSchema(alias, decls, used, warnings, context)
293​
294 const composite = decls.namedComposites.get(type)
295 if (composite) return typeToSchema(composite, decls, used, warnings, context)
296​
297 if (decls.structs.has(type) || decls.namedScalars.has(type)) {
298 used.add(type)
299 return { $ref: REF_PREFIX + type }
300 }
301​
302 // Qualified types from packages we did not fetch, and anything else the
303 // subset does not model: unconstrained rather than wrong.
304 warnings.push(`go-parser: ${context}: unmapped type '${goType}'`)
305 return {}
307​
308function structToSchema(
309 struct: GoStruct,
310 decls: Declarations,
311 used: Set<string>,
312 warnings: Array<string>,
313): JsonSchema {
314 const properties: Record<string, JsonSchema> = {}
315 const required: Array<string> = []
316 for (const field of struct.fields) {
317 const schema = typeToSchema(
318 field.goType,
319 decls,
320 used,
321 warnings,
322 `${struct.name}.${field.name}`,
323 )
324 properties[field.name] = field.description
325 ? { ...schema, description: field.description }
326 : schema
327 // No `omitempty` means Go always writes the field.
328 if (!field.optional) required.push(field.name)
329 }
330 return {
331 type: 'object',
332 ...(struct.description ? { description: struct.description } : {}),
333 properties,
334 ...(required.length > 0 ? { required } : {}),
335 }
337​
338function namedScalarToSchema(name: string, decls: Declarations): JsonSchema {
339 const scalar = decls.namedScalars.get(name)
340 const base = { ...(GO_PRIMITIVES[scalar?.underlying ?? 'string'] ?? {}) }
341 const values = decls.enums.get(name)
342 return {
343 ...base,
344 ...(scalar?.description ? { description: scalar.description } : {}),
345 ...(values?.length ? { enum: values } : {}),
346 }
348​
349/**
350 * Parse Go sources and emit component schemas for `roots` plus their full
351 * reference closure — nothing else, so unrelated SDK types (batch jobs,
352 * context caching, …) stay out of the document.
353 */
354export function parseGoSchemas(
355 files: Array<GoSourceFile>,
356 roots: Array<string>,
357): ParsedGoSource {
358 const { decls, warnings } = parseDeclarations(files)
359 const schemas: Record<string, JsonSchema> = {}
360​
361 const queue = [...roots]
362 const seen = new Set<string>()
363 while (queue.length > 0) {
364 const name = queue.shift()
365 if (name === undefined || seen.has(name)) continue
366 seen.add(name)
367​
368 const used = new Set<string>()
369 const struct = decls.structs.get(name)
370 if (struct) {
371 schemas[name] = structToSchema(struct, decls, used, warnings)
372 } else if (decls.namedScalars.has(name)) {
373 schemas[name] = namedScalarToSchema(name, decls)
374 } else {
375 warnings.push(`go-parser: root type '${name}' not found`)
376 continue
377 }
378 for (const ref of used) if (!seen.has(ref)) queue.push(ref)
379 }
380​
381 return { schemas, warnings }