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

test-production-errors.mjs

202 lines7.3 KB

1// Consumer-build contract for production error codes: a production build of
2// the public API carries no full error message text, and a development build
3// keeps it. Authority: packages/db/tests/production-error-messages-oracle.test.ts,
4// which owns the message format. This check owns erasure: it bundles the
5// built packages/db/dist the way a consumer's bundler would, with
6// `process.env.NODE_ENV` defined, and searches the output for one distinctive
7// literal from each coded class's frozen development message.
8import assert from 'node:assert/strict'
9import { readFile, readdir } from 'node:fs/promises'
10import path from 'node:path'
11import { fileURLToPath } from 'node:url'
12import { build } from 'esbuild'
13import { assertDbDistFresh } from '../packages/db/scripts/assert-dist-fresh.mjs'
14​
15const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
16const tests = path.join(root, 'packages/db/tests')
17const builtEntry = await assertDbDistFresh(root)
18const codes = JSON.parse(
19 await readFile(path.join(tests, 'fixtures/error-codes.json'), 'utf8'),
21const messages = JSON.parse(
22 await readFile(path.join(tests, 'fixtures/error-messages.json'), 'utf8'),
24​
25const sites = JSON.parse(
26 await readFile(path.join(tests, 'fixtures/error-site-messages.json'), 'utf8'),
28const readSource = (file) =>
29 readFile(path.join(root, 'packages/db/src', file), 'utf8')
30// Error classes live in errors.ts and in a few feature modules.
31const classSource = (
32 await Promise.all(
33 (await readdir(path.join(root, 'packages/db/src'), { recursive: true }))
34 .filter((file) => file.endsWith('.ts'))
35 .map(readSource),
36 )
37).join('\n')
38​
39/**
40 * The longest stretch of a message that the source holds verbatim, so it is
41 * template text rather than a sample input's value.
42 */
43function distinctiveLiteral(message, source, avoid = ``) {
44 let best = ``
45 for (const piece of message.split(/"[^"]*"|`[^`]*`|\$\{[^}?]*\??|\}|\n/)) {
46 for (let start = 0; start + best.length < piece.length; start++) {
47 let end = start + best.length + 1
48 while (end <= piece.length && source.includes(piece.slice(start, end))) {
49 if (
50 end - start > best.length &&
51 !avoid.includes(piece.slice(start, end))
52 )
53 best = piece.slice(start, end)
54 if (best.length === 40) return best.trim()
55 end++
56 }
57 }
58 }
59 return best.trim()
61​
62// Each entry: name, the text its literal comes from, and the source file that
63// must hold the literal verbatim.
64const entries = [
65 ...Object.keys(codes).map((name) => [name, messages[name][0], classSource]),
66 ...(await Promise.all(
67 Object.entries(sites).map(async ([code, { file, literals }]) => [
68 `error ${code} (${file})`,
69 literals.join('\n'),
70 await readSource(file),
71 ]),
72 )),
74// These errors share all of their text with text that every build keeps, so no
75// literal distinguishes them. The oracle still checks their guard.
76const sharedWithWarnings = new Set([
77 // the IndexedDB request-failure fallback in indexed-db-wrapper.ts
78 'error 170 (utils/error.ts)',
79])
80const coded = entries.filter(([name]) => !sharedWithWarnings.has(name))
81assert.equal(
82 entries.length - coded.length,
83 sharedWithWarnings.size,
84 'stale sharedWithWarnings entry',
86​
87// collection/config-errors.ts is development-only: ESM production bundles
88// erase validateCollectionConfig and every diagnostic it throws. A CommonJS
89// bundle cannot drop the module, so it keeps that text, as main does.
90const developmentOnly = [
91 'collection/config-errors.ts',
92 'Collection requires a "getKey" function in the config.',
94​
95// Developer hints, one literal per guarded region: production bundles drop
96// every region, in both formats, because the guard folds inside each function.
97const regions = JSON.parse(
98 await readFile(
99 path.join(tests, 'fixtures/development-only-messages.json'),
100 'utf8',
101 ),
103const hints = await Promise.all(
104 regions.map(async ({ file, literals }, region) => [
105 `development-only region ${region} (${file})`,
106 literals.join('\n'),
107 await readSource(file),
108 ]),
110​
111/**
112 * One literal per entry, unique across entries, so one entry's copy cannot
113 * keep another entry's check green. Entries whose first choice collides pick
114 * again, avoiding each other's text. An entry with no text of its own, such as
115 * one message thrown at several sites, keeps its first choice and is shared.
116 */
117const shared = new Set()
118// A development-only region may hold only a short value, such as `slow-query`;
119// it still has to be absent from production.
120function minimumLength(name) {
121 return name.startsWith('development-only') ? 8 : 12
123function chooseLiterals(list) {
124 const first = list.map(([, text, source]) => distinctiveLiteral(text, source))
125 const chosen = [...first]
126 for (let round = 0; round < 3; round++) {
127 const owners = new Map()
128 chosen.forEach((literal, index) =>
129 owners.set(literal, [...(owners.get(literal) ?? []), index]),
130 )
131 const collisions = [...owners.values()].filter((group) => group.length > 1)
132 if (!collisions.length) break
133 for (const group of collisions)
134 for (const index of group) {
135 const [, text, source] = list[index]
136 const avoid = group
137 .filter((other) => other !== index)
138 .map((other) => list[other][1])
139 .join('\n')
140 const own = distinctiveLiteral(text, source, avoid)
141 if (own.length >= minimumLength(list[index][0])) chosen[index] = own
142 else shared.add(list[index][0])
143 }
144 }
145 return list.map(([name], index) => [name, chosen[index]])
147​
148const checked = chooseLiterals([...coded, ...hints])
149const seen = new Map()
150for (const [name, literal] of checked) {
151 assert.ok(
152 shared.has(name) || !seen.has(literal),
153 `${name} and ${seen.get(literal)} share the literal ${JSON.stringify(literal)}`,
154 )
155 seen.set(literal, name)
157const short = checked.filter(
158 ([name, literal]) => literal.length < minimumLength(name),
160assert.deepEqual(short, [], 'coded errors without a distinctive literal')
161​
162// `require` consumers get the CommonJS build, so check it too.
163const cjsEntry = path.join(path.dirname(builtEntry), '../cjs/index.cjs')
164​
165async function bundle(nodeEnv, entry = builtEntry) {
166 const result = await build({
167 stdin: {
168 contents: `export * from ${JSON.stringify(entry)}`,
169 resolveDir: root,
170 },
171 bundle: true,
172 minify: true,
173 format: 'esm',
174 platform: 'neutral',
175 write: false,
176 logLevel: 'error',
177 define: { 'process.env.NODE_ENV': JSON.stringify(nodeEnv) },
178 nodePaths: [path.join(root, 'packages/db/node_modules')],
179 })
180 return result.outputFiles[0].text
182​
183for (const [format, entry, expected] of [
184 ['ESM', builtEntry, [...checked, developmentOnly]],
185 ['CommonJS', cjsEntry, checked],
186]) {
187 const production = await bundle('production', entry)
188 const development = await bundle('development', entry)
189 const kept = expected.filter(([, literal]) => production.includes(literal))
190 const missing = expected.filter(
191 ([, literal]) => !development.includes(literal),
192 )
193 assert.deepEqual(kept, [], `${format} production build kept full error text`)
194 assert.deepEqual(
195 missing,
196 [],
197 `${format} development build lost full error text`,
198 )
200console.log(
201 `production error text: ${checked.length} literals (${shared.size} shared) erased in production and kept in development, in ESM and CommonJS builds`,