Skip to content
Source
Sign inSign up
samwillis/neon-realtime-electric
Open History to see the last commit

compare-public-api.mjs

171 lines5.3 KB

1import ts from 'typescript'
2import assert from 'node:assert/strict'
3import { readFile, writeFile, mkdir } from 'node:fs/promises'
4import { existsSync } from 'node:fs'
5import { createHash } from 'node:crypto'
6import path from 'node:path'
7import { fileURLToPath } from 'node:url'
8​
9const root = fileURLToPath(new URL('../', import.meta.url))
10const referenceRoot = path.join(
11 root,
12 '.artifacts/package-compatibility/reference/node_modules/@electric-sql/client'
14const candidateRoot = path.join(root, 'packages/client')
15assert.ok(
16 existsSync(referenceRoot),
17 'Run pnpm test:package to install the isolated reference first'
19const entries = [
20 'dist/index.d.ts',
21 'dist/cjs/index.d.cts',
22 'dist/index.react-native.d.ts',
23 'dist/cjs/index.react-native.d.cts',
25const report = {}
26for (const entry of entries) {
27 const reference = inventory(path.join(referenceRoot, entry))
28 const candidate = inventory(path.join(candidateRoot, entry))
29 assert.deepEqual(
30 candidate,
31 reference,
32 `${entry}: public declarations differ from the pinned Electric client`
33 )
34 report[entry] = candidate
36const originalPackage = JSON.parse(
37 await readFile(path.join(referenceRoot, 'package.json'), 'utf8')
39const forkPackage = JSON.parse(
40 await readFile(path.join(candidateRoot, 'package.json'), 'utf8')
42for (const field of [
43 'exports',
44 'main',
45 'module',
46 'react-native',
47 'types',
48 'typesVersions',
49 'sideEffects',
50]) {
51 assert.deepEqual(
52 forkPackage[field],
53 originalPackage[field],
54 `Package ${field} differs`
55 )
57const sourcePaths = JSON.parse(
58 await readFile(path.join(root, 'upstream/electric-client.json'), 'utf8')
59).files.filter(
60 ({ path: relative }) =>
61 relative.startsWith('src/') && relative !== 'src/react-native-shim.d.ts'
63for (const { path: relative } of sourcePaths) {
64 const published = await readFile(path.join(referenceRoot, relative))
65 const candidate = await readFile(path.join(candidateRoot, relative))
66 // Source identity proves the initial baseline. Later transport edits are
67 // reviewed independently; they must still preserve the declaration report.
68 if (process.argv.includes('--pristine'))
69 assert.ok(
70 published.equals(candidate),
71 `${relative}: published source differs`
72 )
74await mkdir(path.join(root, '.artifacts'), { recursive: true })
75await writeFile(
76 path.join(root, '.artifacts/public-api.json'),
77 JSON.stringify(report, null, 2) + '\n'
79console.log(
80 `Public API matches: ${report['dist/index.d.ts'].exports.length} exports, all four declaration entry points and package resolution fields`
82​
83function inventory(entry) {
84 const program = ts.createProgram([entry], {
85 target: ts.ScriptTarget.ESNext,
86 module: ts.ModuleKind.NodeNext,
87 moduleResolution: ts.ModuleResolutionKind.NodeNext,
88 strict: true,
89 skipLibCheck: false,
90 noEmit: true,
91 types: [],
92 })
93 const checker = program.getTypeChecker()
94 const file = program.getSourceFile(entry)
95 assert.ok(file, `Missing declaration entry ${entry}`)
96 const module = checker.getSymbolAtLocation(file)
97 assert.ok(module, `Not a module: ${entry}`)
98 const exports = checker
99 .getExportsOfModule(module)
100 .map((symbol) => symbol.name)
101 .sort()
102 const printer = ts.createPrinter({
103 removeComments: true,
104 newLine: ts.NewLineKind.LineFeed,
105 })
106 // Follow exported aliases and every package-local declaration they reference.
107 // Include non-exported helper declarations, since their definitions can change
108 // public options/return types without changing an exported signature's text.
109 const reachable = new Map()
110 const pending = checker.getExportsOfModule(module)
111 const seen = new Set()
112 while (pending.length) {
113 let symbol = pending.pop()
114 if (symbol.flags & ts.SymbolFlags.Alias)
115 symbol = checker.getAliasedSymbol(symbol)
116 if (seen.has(symbol)) continue
117 seen.add(symbol)
118 for (const declaration of symbol.declarations ?? []) {
119 if (!isLocal(declaration.getSourceFile().fileName)) continue
120 const transformed = ts.transform(declaration, [stripPrivateMembers])
121 const text = printer
122 .printNode(
123 ts.EmitHint.Unspecified,
124 transformed.transformed[0],
125 declaration.getSourceFile()
126 )
127 .trim()
128 transformed.dispose()
129 const hash = createHash('sha256').update(text).digest('hex')
130 reachable.set(`${symbol.name}:${hash}`, {
131 name: symbol.name,
132 declaration: text,
133 })
134 visit(declaration)
135 }
136 }
137 return {
138 exports,
139 declarations: [...reachable.values()].sort(
140 (a, b) =>
141 a.name.localeCompare(b.name) ||
142 a.declaration.localeCompare(b.declaration)
143 ),
144 }
145​
146 function isLocal(filename) {
147 return filename.startsWith(path.dirname(entry) + path.sep)
148 }
149 function visit(node) {
150 if (ts.isIdentifier(node)) {
151 const symbol = checker.getSymbolAtLocation(node)
152 if (symbol) pending.push(symbol)
153 }
154 // Private members are implementation details, not cross-install identity.
155 if (isPrivate(node)) return
156 ts.forEachChild(node, visit)
157 }
159​
160function isPrivate(node) {
161 return (
162 (node.name && ts.isPrivateIdentifier(node.name)) ||
163 !!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Private)
164 )
166​
167function stripPrivateMembers(context) {
168 const visitor = (node) =>
169 isPrivate(node) ? undefined : ts.visitEachChild(node, visitor, context)
170 return (node) => ts.visitNode(node, visitor)