Open History to see the last commit
1// Consumer-build contract: public Collection/query behavior, error names, and
2// index metadata have the same observations after identifier minification.
3// The driver bundles the built packages/db/dist, which is what consumers
4// install, so it also covers the private-member renaming in the db build.
5// Authority: the corresponding source-facing tests in packages/db/tests for
6// queryOnce, live queries, collection events/indexes, and errors. The model is
7// a plain array filter/sort/projection over one initial and one updated source
8// snapshot; the driver invokes only the bundled public entry. This fixed slice
9// does not replace the generated oracles or framework adapter conformance.
10// The --calibrate modes are hostile controls for this check, not CI jobs.
11import assert from 'node:assert/strict'
12import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'
13import path from 'node:path'
14import { fileURLToPath, pathToFileURL } from 'node:url'
15import { build } from 'esbuild'
16import { assertDbDistFresh } from '../packages/db/scripts/assert-dist-fresh.mjs'
17
18const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
19const mode = process.argv[2]
20assert.ok(
21 mode === undefined ||
22 mode === '--calibrate-error-name' ||
23 mode === '--calibrate-public-member' ||
24 mode === '--calibrate-output-shape',
25 `Unknown mode: ${mode}`,
26)
27
28const dbNodeModules = path.join(root, 'packages/db/node_modules')
29const dbNodeModulesInfo = await stat(dbNodeModules).catch((error) => {
30 if (error.code !== 'ENOENT') throw error
31 return null
32})
33assert.ok(
34 dbNodeModulesInfo?.isDirectory(),
35 'Install workspace dependencies before running test:minified-db',
36)
37
38const builtEntry = await assertDbDistFresh(root)
39const bundleDirectory = await mkdtemp(path.join(dbNodeModules, '.minified-db-'))
40const bundlePath = path.join(bundleDirectory, 'index.mjs')
41
42const aliasIvm = {
43 name: 'inline-db-ivm',
44 setup(builder) {
45 builder.onResolve({ filter: /^@tanstack\/db-ivm$/ }, () => ({
46 path: path.join(root, 'packages/db-ivm/src/index.ts'),
47 }))
48 },
49}
50
51const errorNameMutant = {
52 name: 'error-name-mutant',
53 setup(builder) {
54 builder.onLoad(
55 { filter: /packages\/db\/dist\/esm\/errors\.js$/ },
56 async ({ path: file }) => {
57 const source = await readFile(file, 'utf8')
58 const original = 'this.name = `CollectionConfigurationError`'
59 assert.equal(
60 source.split(original).length,
61 2,
62 'mutant target exists once',
63 )
64 return {
65 contents: source.replace(original, 'this.name = new.target.name'),
66 loader: 'js',
67 }
68 },
69 )
70 },
71}
72
73// These are the public names currently assigned by the exported error classes.
74// Subclasses often deliberately inherit their family's name. Abort errors
75// intentionally use the platform AbortError name. Keep the export inventory
76// check below so a newly exported class must receive an explicit expectation.
77const errorGroups = {
78 TanStackDBError: `TanStackDBError`,
79 NonRetriableError: `NonRetriableError`,
80 SchemaValidationError: `SchemaValidationError`,
81 DuplicateDbInstanceError: `DuplicateDbInstanceError`,
82 CollectionConfigurationError: `CollectionConfigurationError CollectionRequiresConfigError CollectionRequiresSyncConfigError InvalidSchemaError SchemaMustBeSynchronousError`,
83 InvalidSyncPersistenceCapabilityError: `InvalidSyncPersistenceCapabilityError`,
84 CollectionStateError: `CollectionStateError CollectionInErrorStateError InvalidCollectionStatusTransitionError CollectionIsInErrorStateError NegativeActiveSubscribersError LiveQueryObserverDisposedError LiveQueryWindowControllerDisposedError`,
85 CollectionOperationError: `CollectionOperationError UndefinedKeyError InvalidKeyError DuplicateKeyError DuplicateKeySyncError MissingUpdateArgumentError NoKeysPassedToUpdateError UpdateKeyNotFoundError KeyUpdateNotAllowedError NoKeysPassedToDeleteError DeleteKeyNotFoundError`,
86 MissingHandlerError: `MissingHandlerError MissingInsertHandlerError MissingUpdateHandlerError MissingDeleteHandlerError`,
87 TransactionError: `TransactionError MissingMutationFunctionError TransactionNotPendingMutateError TransactionAlreadyCompletedRollbackError DuplicateTransactionIdError TransactionNotPendingCommitError NoPendingSyncTransactionWriteError SyncTransactionAlreadyCommittedWriteError SyncRowReusedWithoutPreviousValueError NoPendingSyncTransactionCommitError SyncTransactionAlreadyCommittedError SyncQueueInvariantError`,
88 PacedTransactionManualCommitError: `PacedTransactionManualCommitError`,
89 QueueCapacityExceededError: `QueueCapacityExceededError`,
90 QueueDisposedError: `QueueDisposedError`,
91 ThrottleCallDroppedError: `ThrottleCallDroppedError`,
92 DebounceCallDroppedError: `DebounceCallDroppedError`,
93 OnMutateMustBeSynchronousError: `OnMutateMustBeSynchronousError`,
94 QueryBuilderError: `QueryBuilderError OnlyOneSourceAllowedError SubQueryMustHaveFromClauseError InvalidSourceError InvalidSourceTypeError JoinConditionMustBeEqualityError QueryMustHaveFromClauseError InvalidWhereExpressionError`,
95 QueryCompilationError: `QueryCompilationError DistinctRequiresSelectError FnSelectWithGroupByError UnsupportedFnSelectResultError UnsupportedRootScalarSelectError HavingRequiresGroupByError LimitOffsetRequireOrderByError CollectionInputNotFoundError DuplicateAliasInSubqueryError UnsupportedFromTypeError UnknownExpressionTypeError EmptyReferencePathError UnknownFunctionError JoinCollectionNotFoundError MissingAliasInputsError SetWindowRequiresOrderByError`,
96 UnsafeAliasPathError: `UnsafeAliasPathError`,
97 JoinError: `JoinError UnsupportedJoinTypeError InvalidJoinConditionSameSourceError InvalidJoinConditionSourceMismatchError InvalidJoinConditionLeftSourceError InvalidJoinConditionRightSourceError InvalidJoinCondition UnsupportedJoinSourceTypeError`,
98 GroupByError: `GroupByError NonAggregateExpressionNotInGroupByError UnsupportedAggregateFunctionError AggregateFunctionNotInSelectError UnknownHavingExpressionTypeError`,
99 StorageError: `StorageError SerializationError`,
100 LocalStorageCollectionError: `LocalStorageCollectionError StorageKeyRequiredError InvalidStorageDataFormatError InvalidStorageObjectFormatError`,
101 DatabaseRequiredError: `DatabaseRequiredError`,
102 GetKeyRequiredError: `GetKeyRequiredError`,
103 NameRequiredError: `NameRequiredError`,
104 ObjectStoreNotFoundError: `ObjectStoreNotFoundError`,
105 SyncCleanupError: `SyncCleanupError`,
106 AbortError: `SyncTransactionAbortedError CollectionPreloadAbortedError LoadSubsetOperationAbortedError`,
107 QueryOptimizerError: `QueryOptimizerError CannotCombineEmptyExpressionListError`,
108 SetWindowReentrancyError: `SetWindowReentrancyError`,
109 UnhashableQueryIRError: `UnhashableQueryIRError`,
110}
111
112function checkErrorNames(db) {
113 const expected = new Map(
114 Object.entries(errorGroups).flatMap(([name, exports]) =>
115 exports.split(' ').map((exportName) => [exportName, name]),
116 ),
117 )
118 const actual = Object.entries(db)
119 .filter(
120 ([, value]) =>
121 typeof value === 'function' && value.prototype instanceof Error,
122 )
123 .map(([name]) => name)
124 .sort()
125 assert.deepEqual(
126 actual,
127 [...expected.keys()].sort(),
128 'every exported error has a checked name',
129 )
130
131 for (const [exportName, name] of expected) {
132 const args =
133 exportName === 'MissingAliasInputsError' ? [[]] : ['insert', [], []]
134 const error = new db[exportName](...args)
135 assert.equal(error.name, name, `${exportName}.name`)
136 assert.ok(error instanceof Error, `${exportName} is an Error`)
137 }
138 return expected.size
139}
140
141async function checkCollectionsAndQueries(db) {
142 const initial = [
143 { id: 1, name: 'Ada', age: 28 },
144 { id: 2, name: 'Bea', age: 21 },
145 { id: 3, name: 'Cal', age: 35 },
146 ]
147 let sync
148 const source = db.createCollection({
149 id: 'minified-public-source',
150 getKey: (row) => row.id,
151 defaultIndexType: db.BasicIndex,
152 sync: {
153 sync(actions) {
154 sync = actions
155 actions.begin()
156 for (const value of initial) actions.write({ type: 'insert', value })
157 actions.commit()
158 actions.markReady()
159 },
160 },
161 })
162 let live
163 try {
164 const indexEvents = []
165 source.on('index:added', (event) => indexEvents.push(event))
166 const index = source.createIndex((row) => row.age, {
167 indexType: db.BasicIndex,
168 name: 'by-age',
169 })
170 assert.equal(
171 typeof source.getIndexMetadata,
172 'function',
173 'public index metadata method',
174 )
175 const metadata = source.getIndexMetadata()
176 assert.equal(metadata.length, 1)
177 assert.equal(metadata[0].indexId, index.id)
178 assert.equal(metadata[0].name, 'by-age')
179 assert.equal(metadata[0].resolver.kind, 'constructor')
180 assert.equal(metadata[0].resolver.name, 'BasicIndex')
181 assert.equal(indexEvents.length, 1)
182 assert.equal(indexEvents[0].index.signature, metadata[0].signature)
183 assert.equal(indexEvents[0].index.name, 'by-age')
184 assert.equal(indexEvents[0].index.resolver.name, 'BasicIndex')
185
186 await source.preload()
187 assert.deepEqual(
188 [...source.values()].map((row) => row.id).sort(),
189 [1, 2, 3],
190 )
191
192 // A small conformance and oracle slice: expected rows come from a plain
193 // array filter/sort/projection, independent of the query/index machinery.
194 const expected = (rows) =>
195 rows
196 .filter((row) => row.age > 25)
197 .sort((a, b) => a.age - b.age)
198 .map(({ id, name }) => ({ id, name }))
199 const query = (q) =>
200 q
201 .from({ user: source })
202 .where(({ user }) => db.gt(user.age, 25))
203 .orderBy(({ user }) => user.age, 'asc')
204 .select(({ user }) => ({ id: user.id, name: user.name }))
205 const selectedRows = (rows) =>
206 rows.map((row) => {
207 const selected = { ...row }
208 delete selected.$hasPendingWrites
209 delete selected.$synced
210 delete selected.$origin
211 delete selected.$key
212 delete selected.$collectionId
213 return selected
214 })
215 const queryRows = [...(await db.queryOnce(query))]
216 if (mode === '--calibrate-output-shape') {
217 queryRows[0] = { ...queryRows[0], age: 28 }
218 }
219 assert.deepEqual(selectedRows(queryRows), expected(initial))
220
221 live = db.createLiveQueryCollection(query)
222 await live.preload()
223 assert.deepEqual(selectedRows([...live.values()]), expected(initial))
224
225 const changed = [
226 { id: 1, name: 'Ada', age: 28 },
227 { id: 2, name: 'Bea', age: 31 },
228 { id: 3, name: 'Cal', age: 35 },
229 ]
230 sync.begin()
231 sync.write({ type: 'update', value: changed[1] })
232 await sync.commit()
233 assert.deepEqual(selectedRows([...live.values()]), expected(changed))
234 assert.deepEqual(selectedRows(await db.queryOnce(query)), expected(changed))
235 } finally {
236 if (live) await live.cleanup()
237 await source.cleanup()
238 }
239}
240
241try {
242 const bundle = await build({
243 absWorkingDir: root,
244 entryPoints: [builtEntry],
245 outfile: bundlePath,
246 bundle: true,
247 minify: true,
248 format: 'esm',
249 target: 'es2020',
250 platform: 'node',
251 metafile: true,
252 external: ['@standard-schema/spec', '@tanstack/pacer-lite'],
253 plugins: [
254 aliasIvm,
255 ...(mode === '--calibrate-error-name' ? [errorNameMutant] : []),
256 ],
257 ...(mode === '--calibrate-public-member'
258 ? { mangleProps: /^getIndexMetadata$/ }
259 : {}),
260 logLevel: 'silent',
261 })
262 assert.ok(
263 Object.keys(bundle.metafile.inputs).some((input) =>
264 input.includes('packages/db-ivm/src/'),
265 ),
266 'db-ivm is inlined into the minified bundle',
267 )
268 const db = await import(pathToFileURL(bundlePath).href)
269 const errorCount = checkErrorNames(db)
270 await checkCollectionsAndQueries(db)
271 console.log(
272 `Minified public API: ${errorCount} error names, index metadata, query rows, live updates OK`,
273 )
274} finally {
275 await rm(bundleDirectory, { recursive: true, force: true })
276}