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

nvidia-build-spec.ts

121 lines4.2 KB

1import { extractEndpointSchemas } from '../ingest/bundle.ts'
2import type { BundledEndpoint, SpecSource } from './types.ts'
3​
4/** Hosted OpenAPI published in NVIDIA Build's own React Flight data. */
5import {
6 nvidiaInferNamesModel,
7 nvidiaStatedModelIds,
8 nvidiaFactsFromDocument,
9} from './nvidia-openapi.ts'
10import type { NvidiaInferFacts } from './nvidia-openapi.ts'
11​
12/** Read a JSON object without evaluating any page script. */
13function jsonObject(text: string, offset: number): unknown {
14 let start = offset
15 while (/\s/.test(text[start] ?? '') && start < text.length) start++
16 if (text[start] !== '{')
17 throw new Error('nvidia Build: openAPISpec is not an object')
18 let depth = 0
19 let quoted = false
20 let escaped = false
21 for (let index = start; index < text.length; index++) {
22 const char = text[index]
23 if (quoted) {
24 if (escaped) escaped = false
25 else if (char === '\\') escaped = true
26 else if (char === '"') quoted = false
27 continue
28 }
29 if (char === '"') quoted = true
30 else if (char === '{') depth++
31 else if (char === '}' && --depth === 0)
32 return JSON.parse(text.slice(start, index + 1)) as unknown
33 }
34 throw new Error('nvidia Build: unterminated openAPISpec')
36​
37export function parseNvidiaBuildSpec(
38 html: string,
39 rawId: string,
40): NvidiaInferFacts | null {
41 if (html.includes('NEXT_HTTP_ERROR_FALLBACK;404')) return null
42 const chunks = [
43 ...html.matchAll(/self\.__next_f\.push\(\[1,("(?:[^"\\]|\\.)*")\]\)/g),
44 ].map((match) => {
45 const value: unknown = JSON.parse(match[1]!)
46 if (typeof value !== 'string')
47 throw new Error('nvidia Build: unreadable Flight string')
48 return value
49 })
50 if (!chunks.length)
51 throw new Error('nvidia Build: page contains no native Flight data')
52 const flight = chunks.join('')
53 const documents = [...flight.matchAll(/"openAPISpec"\s*:/g)].map((match) =>
54 jsonObject(flight, match.index + match[0].length),
55 )
56 if (!documents.length) {
57 if (html.includes('openAPISpec'))
58 throw new Error('nvidia Build: published schema marker is unreadable')
59 return null
60 }
61 const unique = new Set(documents.map((doc) => JSON.stringify(doc)))
62 if (unique.size !== 1)
63 throw new Error('nvidia Build: conflicting published OpenAPI documents')
64 const facts = nvidiaFactsFromDocument(documents[0])
65 if (!facts)
66 throw new Error('nvidia Build: published OpenAPI document is unreadable')
67 return validateNvidiaBuildFacts(facts, rawId)
69​
70/** Recheck exact native identity and derive facts again on cached contracts. */
71export function validateNvidiaBuildFacts(
72 facts: NvidiaInferFacts,
73 rawId: string,
74): NvidiaInferFacts {
75 const parsed = nvidiaFactsFromDocument(facts.document)
76 if (!parsed)
77 throw new Error('nvidia Build: cached published document is unreadable')
78 const stated = nvidiaStatedModelIds(parsed.document)
79 if (stated.length !== 1 || !nvidiaInferNamesModel(rawId, parsed.document))
80 throw new Error(
81 `nvidia Build: schema identity conflict: expected ${rawId}; stated ${stated.join(', ')}`,
82 )
83 return parsed
85​
86/** Keep the native wire path; rawId is only a logical per-model presentation ID. */
87export function nvidiaOwnedEndpoint(
88 rawId: string,
89 facts: NvidiaInferFacts,
90 source: SpecSource,
91): { endpoint: BundledEndpoint; warnings: string[] } | null {
92 if (!facts.activity) return null
93 const operation = Object.entries(facts.document.paths ?? {}).find(
94 ([path, item]) =>
95 item.post &&
96 (path.includes('chat/completions') ||
97 path.includes('/embeddings') ||
98 /(^|\/)completions$/.test(path)),
99 )
100 if (!operation) return null
101 const [path, item] = operation
102 const schemas = extractEndpointSchemas(facts.document, path, 'post-200')
103 return {
104 endpoint: {
105 publicId: rawId,
106 path,
107 activity: facts.activity,
108 description:
109 typeof item.post?.description === 'string'
110 ? item.post.description
111 : typeof item.post?.summary === 'string'
112 ? item.post.summary
113 : null,
114 source,
115 derivation: 'upstream-spec',
116 ...(schemas.input ? { input: schemas.input } : {}),
117 ...(schemas.output ? { output: schemas.output } : {}),
118 },
119 warnings: schemas.warnings,
120 }