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

deepseek-native-spec.ts

178 lines6.3 KB

1/** Extract the native operation JSON embedded in DeepSeek's own API docs. */
2import { PROVENANCE_MARKER, sha256Text } from './types.ts'
3import type { OpenApiDocument, SpecFetchResult } from './types.ts'
4​
5export const DEEPSEEK_CHAT_DOCS =
6 'https://api-docs.deepseek.com/api/create-chat-completion/'
7const DOCS_ORIGIN = 'https://api-docs.deepseek.com'
8​
9function record(value: unknown): value is Record<string, unknown> {
10 return typeof value === 'object' && value !== null && !Array.isArray(value)
12​
13export function ownedDeepseekAsset(value: string): string {
14 const url = new URL(value, DOCS_ORIGIN)
15 if (
16 url.origin !== DOCS_ORIGIN ||
17 !/^\/assets\/js\/[\w.~+-]+\.js$/.test(url.pathname) ||
18 url.search ||
19 url.hash
20 )
21 throw new Error(`deepseek: docs asset is not owned: ${url.href}`)
22 return url.href
24​
25/** Only parse asset names and numeric webpack mappings; never evaluate JavaScript. */
26export function discoverDeepseekChunk(main: string, runtime: string): string {
27 const key = main.match(
28 /([a-f0-9]+):\[\(\)=>Promise\.all\(\[[^\]]+\]\)\.then\([A-Za-z_$][\w$]*\.bind\([A-Za-z_$][\w$]*,\d+\)\),"@site\/docs\/api\/create-chat-completion\.api\.mdx"/,
29 )?.[1]
30 if (!key) throw new Error('deepseek: native API page module not found')
31 const pairs = [...runtime.matchAll(/\b(\d+(?:e\d+)?):"([\w-]+)"/g)]
32 const id = pairs.find((pair) => pair[2] === key)?.[1]
33 if (!id) throw new Error('deepseek: native API chunk mapping not found')
34 const values = pairs.filter((pair) => pair[1] === id).map((pair) => pair[2])
35 if (
36 values.length !== 2 ||
37 values[0] !== key ||
38 !/^[a-f0-9]+$/.test(values[1] ?? '')
39 )
40 throw new Error('deepseek: native API chunk hash mapping unreadable')
41 return ownedDeepseekAsset(`/assets/js/${key}.${values[1]}.js`)
43​
44export async function decodeDeepseekOperation(
45 chunk: string,
46): Promise<Record<string, unknown>> {
47 const entries = [
48 ...new Set(
49 [...chunk.matchAll(/\bapi:"([A-Za-z0-9+/=]+)"/g)].map(
50 (match) => match[1],
51 ),
52 ),
53 ]
54 if (entries.length !== 1 || !entries[0])
55 throw new Error('deepseek: native operation payload not found uniquely')
56 const binary = atob(entries[0])
57 const bytes = new Uint8Array(binary.length)
58 for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
59 const stream = new Blob([bytes])
60 .stream()
61 .pipeThrough(new DecompressionStream('deflate'))
62 const payload: unknown = await new Response(stream).json()
63 if (!record(payload))
64 throw new Error('deepseek: native operation is not an object')
65 return payload
67​
68export function nativeDeepseekDocument(
69 payload: Record<string, unknown>,
70): OpenApiDocument {
71 if (
72 payload.method !== 'post' ||
73 payload.path !== '/chat/completions' ||
74 !record(payload.requestBody) ||
75 !record(payload.responses)
76 )
77 throw new Error('deepseek: native chat operation contract changed')
78 if (
79 !Array.isArray(payload.servers) ||
80 payload.servers.length === 0 ||
81 !payload.servers.every(
82 (server) => record(server) && server.url === 'https://api.deepseek.com',
83 )
84 )
85 throw new Error('deepseek: native API server is not owned')
86 const content = payload.requestBody.content
87 const media = record(content) ? content['application/json'] : null
88 if (
89 !record(media) ||
90 !record(media.schema) ||
91 Object.keys(media.schema).length === 0
92 )
93 throw new Error('deepseek: native JSON request schema unpublished')
94 const responses: Record<string, unknown> = {}
95 const streaming: Record<string, unknown> = {}
96 for (const [label, response] of Object.entries(payload.responses)) {
97 const code = label.match(/^(\d{3})(?: \(No streaming\))?$/)?.[1]
98 if (code) {
99 if (code in responses)
100 throw new Error('deepseek: ambiguous native response status')
101 responses[code] = response
102 } else if (/^\d{3} \(Streaming\)$/.test(label)) {
103 streaming[label] = response
104 } else
105 throw new Error(`deepseek: unreadable native response status ${label}`)
106 }
107 if (!('200' in responses))
108 throw new Error(
109 'deepseek: native non-streaming success response unpublished',
110 )
111 const metadata = new Set([
112 'method',
113 'path',
114 'servers',
115 'securitySchemes',
116 'info',
117 'postman',
118 'jsonRequestBodyExample',
119 ])
120 const operation = Object.fromEntries(
121 Object.entries(payload).filter(([key]) => !metadata.has(key)),
122 )
123 return {
124 ...(record(payload.info) ? { info: payload.info } : {}),
125 servers: payload.servers as Array<Record<string, unknown>>,
126 ...(record(payload.securitySchemes)
127 ? { components: { securitySchemes: payload.securitySchemes } }
128 : {}),
129 paths: {
130 '/chat/completions': {
131 post: {
132 ...operation,
133 responses,
134 ...(Object.keys(streaming).length > 0
135 ? { 'x-modelschemas-streaming-responses': streaming }
136 : {}),
137 [PROVENANCE_MARKER]: { derivation: 'generated' },
138 'x-modelschemas-deepseek-native': true,
139 },
140 },
141 },
142 }
144​
145async function textAt(url: string): Promise<string> {
146 const response = await fetch(url, { signal: AbortSignal.timeout(30_000) })
147 if (!response.ok)
148 throw new Error(`deepseek: native docs ${response.status} at ${url}`)
149 if (response.url && new URL(response.url).origin !== DOCS_ORIGIN)
150 throw new Error('deepseek: native docs redirected to an unowned host')
151 return response.text()
153​
154export async function fetchNativeDeepseekSpec(): Promise<SpecFetchResult> {
155 const page = await textAt(DEEPSEEK_CHAT_DOCS)
156 const scripts = [...page.matchAll(/<script\b[^>]*\bsrc="([^"]+)"/g)].map(
157 (match) => ownedDeepseekAsset(match[1] ?? ''),
158 )
159 const main = scripts.find((url) => /\/main\.[\w-]+\.js$/.test(url))
160 const runtime = scripts.find((url) => /\/runtime~main\.[\w-]+\.js$/.test(url))
161 if (!main || !runtime)
162 throw new Error('deepseek: native docs script assets not found')
163 const [mainText, runtimeText] = await Promise.all([
164 textAt(main),
165 textAt(runtime),
166 ])
167 const url = discoverDeepseekChunk(mainText, runtimeText)
168 const chunk = await textAt(url)
169 const payload = await decodeDeepseekOperation(chunk)
170 const spec = nativeDeepseekDocument(payload)
171 const hash = await sha256Text(chunk)
172 return {
173 specs: [spec],
174 sources: [{ url, hash }],
175 outputStrategy: 'post-200',
176 specRevision: hash,
177 }