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

verify-react-resolution.mjs

75 lines2.3 KB

1import assert from 'node:assert/strict'
2import { realpathSync } from 'node:fs'
3import { createRequire } from 'node:module'
4import path from 'node:path'
5import { fileURLToPath } from 'node:url'
6​
7const require = createRequire(import.meta.url)
8const exampleRoot = path.resolve(fileURLToPath(new URL('..', import.meta.url)))
9const repoRoot = path.resolve(exampleRoot, '../..')
10const config = require('../metro.config.cjs')
11​
12const origins = [
13 path.resolve(exampleRoot, 'src/App.tsx'),
14 path.resolve(repoRoot, 'packages/ai-react/src/use-chat.ts'),
16const singletonModules = ['react', 'react/jsx-runtime', 'react-native']
17​
18function packageRoot(filePath, packageName) {
19 const marker = `${path.sep}node_modules${path.sep}${packageName}${path.sep}`
20 const index = filePath.lastIndexOf(marker)
21 assert.notEqual(index, -1, `${filePath} is not inside ${packageName}`)
22 return filePath.slice(0, index + marker.length - 1)
24​
25function packageVersion(filePath, packageName) {
26 const packageJson = path.join(
27 packageRoot(filePath, packageName),
28 'package.json',
29 )
30 return require(packageJson).version
32​
33function resolveWithMetroConfig(originModulePath, moduleName) {
34 return config.resolver.resolveRequest(
35 {
36 originModulePath,
37 resolveRequest() {
38 throw new Error(`Metro singleton resolver did not handle ${moduleName}`)
39 },
40 },
41 moduleName,
42 'ios',
43 ).filePath
45​
46const appReact = realpathSync(
47 require.resolve('react', { paths: [exampleRoot] }),
49const appReactNative = realpathSync(
50 require.resolve('react-native', { paths: [exampleRoot] }),
52​
53for (const origin of origins) {
54 for (const moduleName of singletonModules) {
55 const filePath = realpathSync(resolveWithMetroConfig(origin, moduleName))
56 const packageName = moduleName.startsWith('react-native')
57 ? 'react-native'
58 : 'react'
59 const expected = packageName === 'react' ? appReact : appReactNative
60 const expectedRoot = packageRoot(expected, packageName)
61​
62 assert.equal(
63 packageRoot(filePath, packageName),
64 expectedRoot,
65 `${moduleName} from ${origin} resolved to ${filePath}`,
66 )
67​
68 console.log(
69 `${path.relative(repoRoot, origin)} -> ${moduleName} -> ${packageName}@${packageVersion(
70 filePath,
71 packageName,
72 )}`,
73 )
74 }