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

assert-import-surface.ts

322 lines8.4 KB

1import { readFileSync } from 'node:fs'
2import { builtinModules } from 'node:module'
3import { dirname, extname, join, normalize, resolve } from 'node:path'
4import { fileURLToPath } from 'node:url'
5​
6const scriptDir = dirname(fileURLToPath(import.meta.url))
7const repoRoot = resolve(scriptDir, '../../..')
8const fixtureRoot = resolve(scriptDir, '..')
9​
10const packageEntries = new Map<string, string>([
11 ['@tanstack/ai-react', 'packages/ai-react/src/index.ts'],
12 ['@tanstack/ai-client', 'packages/ai-client/src/index.ts'],
13 ['@tanstack/ai-event-client', 'packages/ai-event-client/src/index.ts'],
14 ['@tanstack/ai-utils', 'packages/ai-utils/src/index.ts'],
15 ['@tanstack/ai/client', 'packages/ai/src/client.ts'],
16])
17​
18const providerSdkPackages = new Set([
19 '@anthropic-ai/sdk',
20 '@fal-ai/client',
21 '@google/genai',
22 '@google/generative-ai',
23 '@openrouter/sdk',
24 'elevenlabs',
25 'ollama',
26 'openai',
27])
28​
29const forbiddenPackages = new Set([
30 '@tanstack/ai-react-ui',
31 '@tanstack/react-ai-devtools',
32 '@tanstack/solid-ai-devtools',
33 'react-dom',
34 'solid-js',
35 'svelte',
36 'vue',
37])
38​
39const providerPackagePattern =
40 /^@tanstack\/ai-(anthropic|byteplus|elevenlabs|fal|gemini|grok|groq|ollama|openai|openrouter)(?:\/|$)/
41​
42const forbiddenPackagePrefixes = ['@vue/']
43const builtins = new Set(
44 builtinModules.flatMap((name) => [name, `node:${name}`]),
46​
47const forbiddenServerSymbols = new Set([
48 'chat',
49 'chatParamsFromRequest',
50 'chatParamsFromRequestBody',
51 'embedding',
52 'generateAudio',
53 'generateImage',
54 'generateSpeech',
55 'generateTranscription',
56 'generateVideo',
57 'getVideoJobStatus',
58 'mergeAgentTools',
59 'realtimeToken',
60 'streamToText',
61 'summarize',
62 'toHttpResponse',
63 'toHttpStream',
64 'toServerSentEventsResponse',
65 'toServerSentEventsStream',
66])
67​
68interface SpecifierUse {
69 names?: Set<string>
70 specifier: string
72​
73const visited = new Set<string>()
74const failures: Array<string> = []
75​
76function read(file: string) {
77 return readFileSync(file, 'utf8')
79​
80function normalized(file: string) {
81 return normalize(file).replaceAll('\\', '/')
83​
84function assertNoForbiddenText(file: string, source: string) {
85 if (
86 normalized(file).startsWith(normalized(fixtureRoot)) &&
87 source.includes('/api/chat')
88 ) {
89 failures.push(`${file} contains the browser default /api/chat`)
90 }
92​
93function parseNames(namedBlock: string): Set<string> {
94 const withoutComments = stripComments(namedBlock)
95 const names = withoutComments
96 .split(',')
97 .map((part) => part.trim())
98 .filter(Boolean)
99 .map((part) =>
100 part
101 .replace(/^type\s+/, '')
102 .split(/\s+as\s+/)[0]
103 ?.trim(),
104 )
105 .filter((name): name is string => Boolean(name))
106​
107 return new Set(names)
109​
110function stripComments(source: string) {
111 return source.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, '')
113​
114function mergeUse(
115 uses: Array<SpecifierUse>,
116 specifier: string,
117 names: Set<string> | undefined,
118) {
119 const existing = uses.find((use) => use.specifier === specifier)
120 if (!existing) {
121 uses.push({ specifier, ...(names ? { names } : {}) })
122 return
123 }
124 if (!names || !existing.names) {
125 delete existing.names
126 return
127 }
128 for (const name of names) existing.names.add(name)
130​
131function importUses(source: string): Array<SpecifierUse> {
132 const parseSource = stripComments(source)
133 const uses: Array<SpecifierUse> = []
134 const importPattern =
135 /import\s+(?:type\s+)?([\s\S]*?)\s+from\s+['"]([^'"]+)['"]/g
136 const sideEffectPattern = /import\s+['"]([^'"]+)['"]/g
137 const dynamicPattern = /import\(\s*['"]([^'"]+)['"]\s*\)/g
138​
139 for (const match of parseSource.matchAll(importPattern)) {
140 const clause = match[1]?.trim() ?? ''
141 const specifier = match[2]
142 if (!specifier) continue
143​
144 const named = clause.match(/\{([\s\S]*?)\}/)
145 mergeUse(uses, specifier, named ? parseNames(named[1] ?? '') : undefined)
146 }
147​
148 for (const match of parseSource.matchAll(sideEffectPattern)) {
149 if (match[1]) mergeUse(uses, match[1], undefined)
150 }
151​
152 for (const match of parseSource.matchAll(dynamicPattern)) {
153 if (match[1]) mergeUse(uses, match[1], undefined)
154 }
155​
156 return uses
158​
159function exportUsesForNames(
160 source: string,
161 requestedNames?: Set<string>,
162): Array<SpecifierUse> {
163 const parseSource = stripComments(source)
164 const uses: Array<SpecifierUse> = []
165 const exportFromPattern =
166 /export\s+(?:type\s+)?\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"]/g
167 const exportAllPattern = /export\s+(?:type\s+)?\*\s+from\s+['"]([^'"]+)['"]/g
168​
169 for (const match of parseSource.matchAll(exportFromPattern)) {
170 const exportedNames = parseNames(match[1] ?? '')
171 const specifier = match[2]
172 if (!specifier) continue
173​
174 const matchingNames =
175 requestedNames === undefined
176 ? exportedNames
177 : new Set(
178 Array.from(exportedNames).filter((name) =>
179 requestedNames.has(name),
180 ),
181 )
182​
183 if (matchingNames.size > 0) mergeUse(uses, specifier, matchingNames)
184 }
185​
186 for (const match of parseSource.matchAll(exportAllPattern)) {
187 if (match[1]) mergeUse(uses, match[1], requestedNames)
188 }
189​
190 return uses
192​
193function localExportSources(
194 source: string,
195 requestedNames: Set<string>,
196): Array<string> {
197 const parseSource = stripComments(source)
198 const sources: Array<string> = []
199 const localExportPattern =
200 /export\s+(?:async\s+)?(?:function|class|const|let|var|interface|type)\s+([A-Za-z_$][\w$]*)/g
201​
202 for (const match of parseSource.matchAll(localExportPattern)) {
203 const name = match[1]
204 if (name && requestedNames.has(name)) {
205 sources.push(name)
206 }
207 }
208​
209 return sources
211​
212function resolveRelative(fromFile: string, specifier: string) {
213 const base = resolve(dirname(fromFile), specifier)
214 const candidates = extname(base)
215 ? [base]
216 : [`${base}.ts`, `${base}.tsx`, `${base}.js`, join(base, 'index.ts')]
217​
218 return candidates.find((candidate) => {
219 try {
220 readFileSync(candidate)
221 return true
222 } catch {
223 return false
224 }
225 })
227​
228function checkForbiddenNamedImport(
229 fromFile: string,
230 specifier: string,
231 names?: Set<string>,
232) {
233 if (!names) return
234​
235 for (const name of names) {
236 if (forbiddenServerSymbols.has(name)) {
237 failures.push(
238 `${fromFile} imports or re-exports server-only helper ${name} from ${specifier}`,
239 )
240 }
241 }
243​
244function checkExternal(fromFile: string, use: SpecifierUse) {
245 const { names, specifier } = use
246​
247 if (specifier === '@tanstack/ai') {
248 failures.push(
249 `${fromFile} imports root @tanstack/ai; use @tanstack/ai/client for the React Native client graph`,
250 )
251 }
252 if (providerSdkPackages.has(specifier)) {
253 failures.push(`${fromFile} imports provider SDK ${specifier}`)
254 }
255 if (providerPackagePattern.test(specifier)) {
256 failures.push(`${fromFile} imports provider package ${specifier}`)
257 }
258 if (forbiddenPackages.has(specifier)) {
259 failures.push(`${fromFile} imports non-RN package ${specifier}`)
260 }
261 if (forbiddenPackagePrefixes.some((prefix) => specifier.startsWith(prefix))) {
262 failures.push(`${fromFile} imports non-RN package ${specifier}`)
263 }
264 if (builtins.has(specifier)) {
265 failures.push(`${fromFile} imports Node builtin ${specifier}`)
266 }
267​
268 checkForbiddenNamedImport(fromFile, specifier, names)
270​
271function walk(file: string, requestedExports?: Set<string>) {
272 const visitKey = `${normalized(file)}::${
273 requestedExports ? Array.from(requestedExports).sort().join(',') : '*'
274 }`
275 if (visited.has(visitKey)) return
276 visited.add(visitKey)
277​
278 const source = read(file)
279 assertNoForbiddenText(file, source)
280​
281 if (requestedExports) {
282 for (const localName of localExportSources(source, requestedExports)) {
283 if (forbiddenServerSymbols.has(localName)) {
284 failures.push(`${file} exports server-only helper ${localName}`)
285 }
286 }
287 }
288​
289 const uses = [
290 ...importUses(source),
291 ...(requestedExports ? exportUsesForNames(source, requestedExports) : []),
292 ]
293​
294 for (const use of uses) {
295 const packageEntry = packageEntries.get(use.specifier)
296 if (packageEntry) {
297 walk(resolve(repoRoot, packageEntry), use.names)
298 continue
299 }
300​
301 if (use.specifier.startsWith('.')) {
302 const resolved = resolveRelative(file, use.specifier)
303 if (resolved) {
304 walk(resolved, use.names)
305 }
306 continue
307 }
308​
309 checkExternal(file, use)
310 }
312​
313walk(resolve(fixtureRoot, 'src/App.tsx'))
314​
315if (failures.length > 0) {
316 console.error(failures.join('\n'))
317 process.exit(1)
319​
320console.log(
321 `React Native import surface smoke passed (${visited.size} visits).`,