From 0679928c65c2c7969447548bf3a81441dc175d27 Mon Sep 17 00:00:00 2001 From: Jack Misner Date: Fri, 23 Oct 2026 14:11:43 +0100 Subject: [PATCH 1/7] perf: make the module-scope defaults provably pure A consumer importing one function from the root entry shipped 1,347 bytes, of which about 1,040 was DEFAULT_CONFIG and everything it reaches. esbuild cannot prove an array or object spread pure - spreading invokes an iterator, which could in principle be patched - so it retained the defaults even when nothing referenced them. Annotating each module-scope initialiser takes that import to 303 bytes. The win is not confined to esbuild. Measured per bundler, root entry, one static import: esbuild 1,347 to 306, Rolldown 994 to 305, webpack 469 to 307. Rollup already pruned these. webpack's CommonJS consumer drops from 1,109 to 516, which is the first thing in this sequence to help a require() consumer at all. The exported constants stay the single source of truth rather than being inlined as literals: DEFAULT_SANITIZE_CONFIG and its siblings are all public API, so duplicating their data into DEFAULT_CONFIG would create two exported things that can drift. The spreads are replaced by annotated calls, not by references, because they exist to copy - DEFAULT_CONFIG.sanitize must not alias DEFAULT_SANITIZE_CONFIG. Nothing covered that. Replacing those five copies with references left all 635 existing tests passing, so the new tests pin it: identity, and that a write through one exported default cannot reach another. Five of the eight fail on the reference form. scripts/assert-bundle-budget.js guards the saving, because annotations are comments. Removing one, or adding an un-annotated spread to DEFAULT_CONFIG, costs every consumer a kilobyte and changes nothing a test would see; dropping a single annotation takes the measured bundle to 1,211 bytes, over the 600 budget. esbuild joins the package-check Dependabot group, since it is pre-1.0 and its output size is what the budget measures. The published files grow 183 bytes to save each consumer ten times that. dist/server/index.js shrinks, and the dead top-level statement esbuild used to leave there - the residue of the same spread - is gone. --- .github/dependabot.yml | 1 + __tests__/config/defaults.test.ts | 86 +++++++++++++++++++++++++++++++ package-lock.json | 1 + package.json | 3 +- scripts/assert-bundle-budget.js | 76 +++++++++++++++++++++++++++ src/common/keys.ts | 4 +- src/config/defaults.ts | 12 +++-- 7 files changed, 175 insertions(+), 8 deletions(-) create mode 100644 __tests__/config/defaults.test.ts create mode 100644 scripts/assert-bundle-budget.js diff --git a/.github/dependabot.yml b/.github/dependabot.yml index f754ead..d819d24 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -88,6 +88,7 @@ updates: patterns: - "publint" - "@arethetypeswrong/*" + - "esbuild" npm-minor-patch: patterns: - "*" diff --git a/__tests__/config/defaults.test.ts b/__tests__/config/defaults.test.ts new file mode 100644 index 0000000..a7d596a --- /dev/null +++ b/__tests__/config/defaults.test.ts @@ -0,0 +1,86 @@ +import { describe, it, expect, afterEach } from 'vitest' +import { + DEFAULT_CONFIG, + DEFAULT_SANITIZE_CONFIG, + DEFAULT_PII_FILTER_CONFIG, + DEFAULT_PII_PATTERNS, + DEFAULT_ATTRIBUTION_CONFIG, + STANDARD_UTM_PARAMETERS, +} from '../../src/config/defaults' +import { + SNAKE_TO_CAMEL, + CAMEL_TO_SNAKE, + STANDARD_SNAKE_KEYS, + STANDARD_CAMEL_KEYS, +} from '../../src/common/keys' + +/** + * Every constant here is exported from the root entry, so one of them aliasing + * another would let a consumer mutating one default silently change a second. + */ +describe('exported defaults are independent of each other', () => { + it('DEFAULT_CONFIG holds copies of the sibling default objects', () => { + expect(DEFAULT_CONFIG.sanitize).not.toBe(DEFAULT_SANITIZE_CONFIG) + expect(DEFAULT_CONFIG.piiFiltering).not.toBe(DEFAULT_PII_FILTER_CONFIG) + expect(DEFAULT_CONFIG.attribution).not.toBe(DEFAULT_ATTRIBUTION_CONFIG) + expect(DEFAULT_CONFIG.allowedParameters).not.toBe(STANDARD_UTM_PARAMETERS) + expect(DEFAULT_CONFIG.piiFiltering.patterns).not.toBe(DEFAULT_PII_PATTERNS) + expect(DEFAULT_PII_FILTER_CONFIG.patterns).not.toBe(DEFAULT_PII_PATTERNS) + }) + + it('DEFAULT_CONFIG still equals the defaults it copies', () => { + expect(DEFAULT_CONFIG.sanitize).toEqual(DEFAULT_SANITIZE_CONFIG) + expect(DEFAULT_CONFIG.attribution).toEqual(DEFAULT_ATTRIBUTION_CONFIG) + expect(DEFAULT_CONFIG.allowedParameters).toEqual(STANDARD_UTM_PARAMETERS) + expect(DEFAULT_CONFIG.piiFiltering.patterns).toEqual(DEFAULT_PII_PATTERNS) + }) +}) + +describe('mutating one exported default does not reach another', () => { + const originalSanitizeEnabled = DEFAULT_SANITIZE_CONFIG.enabled + const originalPatternCount = DEFAULT_PII_PATTERNS.length + const originalParameterCount = DEFAULT_CONFIG.allowedParameters.length + + afterEach(() => { + DEFAULT_SANITIZE_CONFIG.enabled = originalSanitizeEnabled + DEFAULT_CONFIG.sanitize.enabled = originalSanitizeEnabled + DEFAULT_PII_PATTERNS.length = originalPatternCount + DEFAULT_CONFIG.piiFiltering.patterns.length = originalPatternCount + DEFAULT_PII_FILTER_CONFIG.patterns.length = originalPatternCount + DEFAULT_CONFIG.allowedParameters.length = originalParameterCount + }) + + it('writing through DEFAULT_CONFIG.sanitize leaves DEFAULT_SANITIZE_CONFIG alone', () => { + DEFAULT_CONFIG.sanitize.enabled = !originalSanitizeEnabled + expect(DEFAULT_SANITIZE_CONFIG.enabled).toBe(originalSanitizeEnabled) + }) + + it('pushing to DEFAULT_CONFIG.allowedParameters leaves STANDARD_UTM_PARAMETERS alone', () => { + DEFAULT_CONFIG.allowedParameters.push('utm_injected') + expect(STANDARD_UTM_PARAMETERS).not.toContain('utm_injected') + }) + + it('pushing to DEFAULT_CONFIG.piiFiltering.patterns leaves DEFAULT_PII_PATTERNS alone', () => { + DEFAULT_CONFIG.piiFiltering.patterns.push({ name: 'injected', pattern: /x/, enabled: true }) + expect(DEFAULT_PII_PATTERNS.map((p) => p.name)).not.toContain('injected') + }) + + it('pushing to DEFAULT_PII_FILTER_CONFIG.patterns leaves DEFAULT_PII_PATTERNS alone', () => { + DEFAULT_PII_FILTER_CONFIG.patterns.push({ name: 'injected', pattern: /x/, enabled: true }) + expect(DEFAULT_PII_PATTERNS.map((p) => p.name)).not.toContain('injected') + }) +}) + +/** + * These lists are derived from the maps above them. Pinning the relationship + * keeps a literal rewrite of either from drifting out of step. + */ +describe('standard key lists match the maps they come from', () => { + it('STANDARD_SNAKE_KEYS lists the keys of SNAKE_TO_CAMEL', () => { + expect(STANDARD_SNAKE_KEYS).toEqual(Object.keys(SNAKE_TO_CAMEL)) + }) + + it('STANDARD_CAMEL_KEYS lists the keys of CAMEL_TO_SNAKE', () => { + expect(STANDARD_CAMEL_KEYS).toEqual(Object.keys(CAMEL_TO_SNAKE)) + }) +}) diff --git a/package-lock.json b/package-lock.json index 4d7e339..0679a66 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,6 +13,7 @@ "@testing-library/react": "^16.0.0", "@types/react": "^18.0.0", "@vitest/coverage-v8": "^5.0.0", + "esbuild": "^0.28.2", "jsdom": "^30.0.1", "oxlint": "^1.0.0", "prettier": "^3.0.0", diff --git a/package.json b/package.json index fc95c49..6b346fc 100644 --- a/package.json +++ b/package.json @@ -51,7 +51,7 @@ "test:watch": "vitest", "coverage": "vitest run --coverage", "type-check": "tsc --noEmit", - "check:package": "npm run build && publint --strict && attw --pack . --profile node16 && node scripts/assert-no-import-side-effects.js", + "check:package": "npm run build && publint --strict && attw --pack . --profile node16 && node scripts/assert-no-import-side-effects.js && node scripts/assert-bundle-budget.js", "lint": "oxlint", "lint:fix": "oxlint --fix", "format": "prettier --write \"src/**/*.{ts,tsx}\" \"__tests__/**/*.{ts,tsx}\"", @@ -74,6 +74,7 @@ "@testing-library/react": "^16.0.0", "@types/react": "^18.0.0", "@vitest/coverage-v8": "^5.0.0", + "esbuild": "^0.28.2", "jsdom": "^30.0.1", "oxlint": "^1.0.0", "prettier": "^3.0.0", diff --git a/scripts/assert-bundle-budget.js b/scripts/assert-bundle-budget.js new file mode 100644 index 0000000..8c53830 --- /dev/null +++ b/scripts/assert-bundle-budget.js @@ -0,0 +1,76 @@ +#!/usr/bin/env node + +/** + * Fails if a consumer importing one small function from the root entry would + * ship more than BUDGET_BYTES. + * + * What this protects is a `/* @__PURE__ *\/` annotation on each module-scope + * default in src/config/defaults.ts and src/common/keys.ts. A bundler needs + * those to prove the defaults droppable; without them it retains DEFAULT_CONFIG + * and its dependencies, which measured 1,347 bytes against 306. They are + * comments, so removing one — or adding an un-annotated spread to DEFAULT_CONFIG + * — costs every consumer about a kilobyte and changes nothing any test can see. + * + * Usage: node scripts/assert-bundle-budget.js + */ + +import { build } from 'esbuild' +import { existsSync } from 'fs' +import { fileURLToPath } from 'url' +import { dirname, join, resolve } from 'path' + +const __dirname = dirname(fileURLToPath(import.meta.url)) +const root = resolve(__dirname, '..') + +/** + * Measured at 306 bytes when every module-scope default is annotated. The + * headroom absorbs ordinary growth in the one function under test while still + * catching the loss of an annotation, the cheapest of which is worth ~170 bytes. + */ +const BUDGET_BYTES = 600 + +const ENTRY = 'dist/index.js' +const SYMBOL = 'toSnakeCase' + +async function main() { + if (!existsSync(join(root, ENTRY))) { + console.error(`${ENTRY} is missing. Run \`npm run build\` first.`) + process.exit(1) + } + + // Bundled straight from dist rather than from a packed tarball: the ESM root + // entry is the same file either way, and this keeps the check to a few ms. + const result = await build({ + stdin: { + contents: `import { ${SYMBOL} } from './${ENTRY}'\nglobalThis.__out = ${SYMBOL}(globalThis.__in)\n`, + resolveDir: root, + sourcefile: 'budget-entry.js', + loader: 'js', + }, + bundle: true, + minify: true, + format: 'esm', + platform: 'browser', + target: 'es2020', + external: ['react', 'react/jsx-runtime'], + write: false, + logLevel: 'silent', + }) + + const bytes = result.outputFiles[0].contents.byteLength + + if (bytes > BUDGET_BYTES) { + console.error( + `Importing { ${SYMBOL} } from the root entry now bundles to ${bytes} bytes, over the ${BUDGET_BYTES} budget.`, + ) + console.error( + 'A module-scope value in src/config/defaults.ts or src/common/keys.ts is no longer provably pure.', + ) + console.error('Check that each one is still annotated `/* @__PURE__ */`.') + process.exit(1) + } + + console.log(`Root entry bundles to ${bytes} bytes for one import (budget ${BUDGET_BYTES}).`) +} + +await main() diff --git a/src/common/keys.ts b/src/common/keys.ts index b7d164a..ac123fe 100644 --- a/src/common/keys.ts +++ b/src/common/keys.ts @@ -34,12 +34,12 @@ export const CAMEL_TO_SNAKE: Record = { /** * All standard snake_case UTM keys */ -export const STANDARD_SNAKE_KEYS = Object.keys(SNAKE_TO_CAMEL) +export const STANDARD_SNAKE_KEYS = /* @__PURE__ */ Object.keys(SNAKE_TO_CAMEL) /** * All standard camelCase UTM keys */ -export const STANDARD_CAMEL_KEYS = Object.keys(CAMEL_TO_SNAKE) +export const STANDARD_CAMEL_KEYS = /* @__PURE__ */ Object.keys(CAMEL_TO_SNAKE) /** * Convert a single key from snake_case to camelCase diff --git a/src/config/defaults.ts b/src/config/defaults.ts index 9b379ae..3f88efb 100644 --- a/src/config/defaults.ts +++ b/src/config/defaults.ts @@ -67,7 +67,7 @@ export const DEFAULT_PII_PATTERNS: PiiPattern[] = [ export const DEFAULT_PII_FILTER_CONFIG: PiiFilterConfig = { enabled: false, mode: 'reject', - patterns: [...DEFAULT_PII_PATTERNS], + patterns: /* @__PURE__ */ DEFAULT_PII_PATTERNS.slice(), } /** @@ -106,7 +106,7 @@ export const DEFAULT_CONFIG: ResolvedUtmConfig = { appendToShares: true, /** Capture standard UTM parameters by default */ - allowedParameters: [...STANDARD_UTM_PARAMETERS], + allowedParameters: /* @__PURE__ */ STANDARD_UTM_PARAMETERS.slice(), /** Values are not folded to lowercase by default */ lowercaseValues: false, @@ -121,13 +121,15 @@ export const DEFAULT_CONFIG: ResolvedUtmConfig = { excludeFromShares: [], /** Sanitization disabled by default */ - sanitize: { ...DEFAULT_SANITIZE_CONFIG }, + sanitize: /* @__PURE__ */ Object.assign({}, DEFAULT_SANITIZE_CONFIG), /** PII filtering disabled by default (deep copy to prevent shared references) */ - piiFiltering: { ...DEFAULT_PII_FILTER_CONFIG, patterns: [...DEFAULT_PII_PATTERNS] }, + piiFiltering: /* @__PURE__ */ Object.assign({}, DEFAULT_PII_FILTER_CONFIG, { + patterns: /* @__PURE__ */ DEFAULT_PII_PATTERNS.slice(), + }), /** Last-touch attribution by default */ - attribution: { ...DEFAULT_ATTRIBUTION_CONFIG }, + attribution: /* @__PURE__ */ Object.assign({}, DEFAULT_ATTRIBUTION_CONFIG), } /** From 558f0d2c2a5cc429c5add4879077910423c726f7 Mon Sep 17 00:00:00 2001 From: Jack Misner Date: Fri, 23 Oct 2026 14:13:07 +0100 Subject: [PATCH 2/7] docs: update the bundle figures this branch changed The figures merged an hour ago describe the build before the purity fix. A static import of one function is now around 300 bytes on esbuild, Rollup, Rolldown and webpack alike, rather than 1.4KB on esbuild and under 1KB elsewhere, and webpack's require-vs-import gap is about 200 bytes rather than 640. The /react delta moves from about 2.7KB to about 3KB, since its static import shrank further than its require did. The await import() sentence is unchanged: re-measured, Rollup still prunes only a directly destructured result, 464 bytes against 27,611 read off a namespace, and esbuild and Rolldown still keep everything at about 28KB. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4e9d50b..4f90ba1 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ Three entry points: All three ship dual ESM/CJS builds with TypeScript declarations. The `/react` and `/server` subpaths need TypeScript `moduleResolution` set to `node16` or `nodenext` (TS 4.7+), or `bundler` (TS 5.0+); under the legacy `node`/`node10` setting only the root entry resolves types, though all three resolve at runtime in Node. -The root entry is a barrel, so for a browser bundle it matters how you import from it. A static `import { toSnakeCase }` prunes to roughly 1.4KB on esbuild, and to well under 1KB on Rollup and webpack. A `require()` of the same entry keeps all of it on esbuild, Rollup and Rolldown — roughly 28KB minified — because none of them tree-shake CommonJS; webpack 5 does prune CommonJS exports, so there the gap is about 640 bytes. `await import()` is not a dependable substitute: esbuild and Rolldown keep the whole namespace however you access it, and Rollup prunes it only when you destructure the result directly. Use a static `import` at the call site. The subpaths are far less exposed, because most of what they contain is used either way: `/server` differs by a few hundred bytes, and `/react` by about 2.7KB on esbuild and about 500 bytes on webpack, against the ~14KB the hook pulls in regardless. +The root entry is a barrel, so for a browser bundle it matters how you import from it. A static `import { toSnakeCase }` prunes to around 300 bytes on esbuild, Rollup, Rolldown and webpack alike. A `require()` of the same entry keeps all of it on esbuild, Rollup and Rolldown — roughly 28KB minified — because none of them tree-shake CommonJS; webpack 5 does prune CommonJS exports, so there the gap is about 200 bytes. `await import()` is not a dependable substitute: esbuild and Rolldown keep the whole namespace however you access it, and Rollup prunes it only when you destructure the result directly. Use a static `import` at the call site. The subpaths are far less exposed, because most of what they contain is used either way: `/server` differs by a few hundred bytes, and `/react` by about 3KB on esbuild and about 500 bytes on webpack, against the ~14KB the hook pulls in regardless. ## Quick Start From 8d64bc47db45a21a203972f100bb43c6b94390bd Mon Sep 17 00:00:00 2001 From: Jack Misner Date: Fri, 23 Oct 2026 14:13:55 +0100 Subject: [PATCH 3/7] docs: say why the defaults use annotated calls instead of spreads A spread reads as the cleaner form, so the next person to tidy these will reach for it and hand every consumer back the kilobyte this branch removed. The budget script catches it, but only after the fact; the reason belongs where the odd-looking code is. --- CLAUDE.md | 1 + src/config/defaults.ts | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/CLAUDE.md b/CLAUDE.md index d2d1dd4..10402f9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -18,6 +18,7 @@ - `check:package` runs attw with `--profile node16`, so the `node10` row is still printed but every cell is marked `(ignored)` and it cannot affect the exit code. It is red for `/react` and `/server` because legacy resolution cannot see `exports` subpaths; that is a declared non-target, not a bug to fix. Do not add `typesVersions`: it would green the row for types only. - publint and attw each catch what the other misses. attw exits 0 on a tarball containing no declarations at all, so publint is what catches missing or unpublished files; publint passes a correctly-wired `exports` map whose declarations import chunks the build never emitted, so attw is what catches that. Dropping either silently loses a class of failure. - `scripts/assert-no-import-side-effects.js` guards `"sideEffects": false` in `check:package`, and nothing else verifies that claim. It fails a module-scope *read* of a browser global, not only a write, and fails any entry that imports a node builtin, since it cannot see what such code does at import; no entry needs one today. Detect the environment at call time, as every site in `src/` does; the script header gives the reasoning. +- The module-scope defaults in `config/defaults.ts` and `common/keys.ts` are built with `/* @__PURE__ */` annotated calls, not spreads, so a bundler can drop them: a consumer importing one function ships ~300 bytes instead of ~1,350. Tidying them back into `{ ...x }` silently costs that; `scripts/assert-bundle-budget.js` is what notices. - The flag saves a consumer bytes only when none of an entry's exports are used. `sideEffects` is module-granularity and `splitting: false` emits each entry as a single JS module, so there is no partial drop. Do not advertise it as a tree-shaking win. ## Releases diff --git a/src/config/defaults.ts b/src/config/defaults.ts index 3f88efb..571a9ba 100644 --- a/src/config/defaults.ts +++ b/src/config/defaults.ts @@ -86,6 +86,12 @@ export const STANDARD_UTM_PARAMETERS = [ * Default configuration with all values set * This is used as the base when merging with user-provided config */ +/** + * The copies below are annotated calls rather than spreads because a bundler + * cannot prove a spread pure — it invokes an iterator — and so retains this + * object even where nothing references it, costing a consumer about a kilobyte. + * `scripts/assert-bundle-budget.js` fails if an annotation is lost. + */ export const DEFAULT_CONFIG: ResolvedUtmConfig = { /** UTM tracking is enabled by default */ enabled: true, From b0236e3ba4cbbaa15b19950f9c796fe368902c05 Mon Sep 17 00:00:00 2001 From: Jack Misner Date: Fri, 23 Oct 2026 14:20:56 +0100 Subject: [PATCH 4/7] fix: keep the maintainer note out of the published declarations The note was a second JSDoc block stacked above DEFAULT_CONFIG, so TypeScript took it as the declaration's doc comment and the real description - "Default configuration with all values set" - was orphaned above it. It shipped that way: dist/defaults-*.d.ts carried build-tooling trivia as the documentation for a public constant, pointing at a script that is not in the package. Line comments inside the object cannot be read as a doc comment, and they sit where someone would reach for the cleaner spread, which is where the warning is wanted. Also corrects the byte figures in the budget script, which quoted 1,347 and 306 from a fixture whose entry writes globalThis.__input where the script writes globalThis.__in - three characters, three bytes. The script now quotes what it measures: 1,344 and 303. --- scripts/assert-bundle-budget.js | 4 ++-- src/config/defaults.ts | 10 ++++------ 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/scripts/assert-bundle-budget.js b/scripts/assert-bundle-budget.js index 8c53830..ac28dc3 100644 --- a/scripts/assert-bundle-budget.js +++ b/scripts/assert-bundle-budget.js @@ -7,7 +7,7 @@ * What this protects is a `/* @__PURE__ *\/` annotation on each module-scope * default in src/config/defaults.ts and src/common/keys.ts. A bundler needs * those to prove the defaults droppable; without them it retains DEFAULT_CONFIG - * and its dependencies, which measured 1,347 bytes against 306. They are + * and its dependencies, which measured 1,344 bytes against 303 here. They are * comments, so removing one — or adding an un-annotated spread to DEFAULT_CONFIG * — costs every consumer about a kilobyte and changes nothing any test can see. * @@ -23,7 +23,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url)) const root = resolve(__dirname, '..') /** - * Measured at 306 bytes when every module-scope default is annotated. The + * Measured at 303 bytes when every module-scope default is annotated. The * headroom absorbs ordinary growth in the one function under test while still * catching the loss of an annotation, the cheapest of which is worth ~170 bytes. */ diff --git a/src/config/defaults.ts b/src/config/defaults.ts index 571a9ba..2cf18ea 100644 --- a/src/config/defaults.ts +++ b/src/config/defaults.ts @@ -86,13 +86,11 @@ export const STANDARD_UTM_PARAMETERS = [ * Default configuration with all values set * This is used as the base when merging with user-provided config */ -/** - * The copies below are annotated calls rather than spreads because a bundler - * cannot prove a spread pure — it invokes an iterator — and so retains this - * object even where nothing references it, costing a consumer about a kilobyte. - * `scripts/assert-bundle-budget.js` fails if an annotation is lost. - */ export const DEFAULT_CONFIG: ResolvedUtmConfig = { + // The copies here are annotated calls rather than spreads because a bundler + // cannot prove a spread pure — it invokes an iterator — and so retains this + // object even where nothing references it, costing a consumer about a + // kilobyte. scripts/assert-bundle-budget.js fails if an annotation is lost. /** UTM tracking is enabled by default */ enabled: true, From 490f8cb9131401006aa386111a7efdb084c37f0e Mon Sep 17 00:00:00 2001 From: Jack Misner Date: Fri, 23 Oct 2026 14:25:12 +0100 Subject: [PATCH 5/7] fix: stop the budget claiming coverage it does not have, and run the bundle The guard cannot see either annotation in common/keys.ts. Stripping them from the built dist and re-measuring gives 456 and 324 bytes against a 600 budget, so both pass. My "fails when a single annotation is removed" check happened to hit one of the six in defaults.ts, which are worth ~920 bytes each, and I generalised from that one sample. Three claims were false as a result: the script's "cheapest annotation is worth ~170 bytes" (it is 21), its failure message naming keys.ts, and the CLAUDE.md line saying the script notices for both files. No budget fixes this: catching a 21-byte loss needs a ceiling 17 bytes above the baseline. So the prose now says what is true - a breach always points at defaults.ts - and records that the keys.ts pair is unguarded and worth 174 bytes between them. The guard also only weighed the bundle, never ran it. An annotation on a call that is not pure would license a bundler to drop something needed, and nothing in the repo would notice: vitest runs unminified src with no tree-shaking. It now executes the pruned bundle and asserts one conversion, which costs milliseconds since esbuild already returns the code in memory. A dist tampered to answer wrongly is caught. And the annotations rest on a precondition nothing stated: the sources must stay plain data literals. Object.assign reads them with Get and writes the target with Set, so a getter, a __proto__ key or a Proxy on any of these public constants would make an annotation false, invisibly to both the tests and the byte budget. Spread syntax could not be subverted that way; the replacement can, so the condition is now written where the code is. --- CLAUDE.md | 2 +- scripts/assert-bundle-budget.js | 38 ++++++++++++++++++++++++--------- src/config/defaults.ts | 3 +++ 3 files changed, 32 insertions(+), 11 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 10402f9..9956182 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -18,7 +18,7 @@ - `check:package` runs attw with `--profile node16`, so the `node10` row is still printed but every cell is marked `(ignored)` and it cannot affect the exit code. It is red for `/react` and `/server` because legacy resolution cannot see `exports` subpaths; that is a declared non-target, not a bug to fix. Do not add `typesVersions`: it would green the row for types only. - publint and attw each catch what the other misses. attw exits 0 on a tarball containing no declarations at all, so publint is what catches missing or unpublished files; publint passes a correctly-wired `exports` map whose declarations import chunks the build never emitted, so attw is what catches that. Dropping either silently loses a class of failure. - `scripts/assert-no-import-side-effects.js` guards `"sideEffects": false` in `check:package`, and nothing else verifies that claim. It fails a module-scope *read* of a browser global, not only a write, and fails any entry that imports a node builtin, since it cannot see what such code does at import; no entry needs one today. Detect the environment at call time, as every site in `src/` does; the script header gives the reasoning. -- The module-scope defaults in `config/defaults.ts` and `common/keys.ts` are built with `/* @__PURE__ */` annotated calls, not spreads, so a bundler can drop them: a consumer importing one function ships ~300 bytes instead of ~1,350. Tidying them back into `{ ...x }` silently costs that; `scripts/assert-bundle-budget.js` is what notices. +- The module-scope defaults in `config/defaults.ts` and `common/keys.ts` are built with `/* @__PURE__ */` annotated calls, not spreads, so a bundler can drop them: a consumer importing one function ships ~300 bytes instead of ~1,350. Tidying them back into `{ ...x }` silently costs that. `scripts/assert-bundle-budget.js` notices for `defaults.ts`; the two `keys.ts` annotations are worth 153 and 21 bytes and no byte budget can cover the 21. - The flag saves a consumer bytes only when none of an entry's exports are used. `sideEffects` is module-granularity and `splitting: false` emits each entry as a single JS module, so there is no partial drop. Do not advertise it as a tree-shaking win. ## Releases diff --git a/scripts/assert-bundle-budget.js b/scripts/assert-bundle-budget.js index ac28dc3..350369d 100644 --- a/scripts/assert-bundle-budget.js +++ b/scripts/assert-bundle-budget.js @@ -5,11 +5,19 @@ * ship more than BUDGET_BYTES. * * What this protects is a `/* @__PURE__ *\/` annotation on each module-scope - * default in src/config/defaults.ts and src/common/keys.ts. A bundler needs - * those to prove the defaults droppable; without them it retains DEFAULT_CONFIG - * and its dependencies, which measured 1,344 bytes against 303 here. They are - * comments, so removing one — or adding an un-annotated spread to DEFAULT_CONFIG - * — costs every consumer about a kilobyte and changes nothing any test can see. + * initialiser in src/config/defaults.ts. A bundler needs those to prove + * DEFAULT_CONFIG droppable; without one it retains the whole object and its + * dependencies, which measures ~1,200 bytes against ~300. They are comments, so + * removing one costs every consumer about a kilobyte and changes nothing any + * test can see. + * + * It does NOT cover the two annotations in src/common/keys.ts, which are worth + * 153 and 21 bytes: catching the 21 would need a ceiling with no headroom at + * all. A breach therefore always points at defaults.ts. + * + * The bundle is executed as well as weighed, because an annotation on a call + * that is not in fact pure would license a bundler to drop something needed, + * and no test here bundles anything. * * Usage: node scripts/assert-bundle-budget.js */ @@ -23,9 +31,9 @@ const __dirname = dirname(fileURLToPath(import.meta.url)) const root = resolve(__dirname, '..') /** - * Measured at 303 bytes when every module-scope default is annotated. The - * headroom absorbs ordinary growth in the one function under test while still - * catching the loss of an annotation, the cheapest of which is worth ~170 bytes. + * ~300 bytes with every defaults.ts initialiser annotated, ~1,200 with any one + * of them lost. The headroom absorbs ordinary growth in the function under test + * and patch-level minifier drift. */ const BUDGET_BYTES = 600 @@ -64,13 +72,23 @@ async function main() { `Importing { ${SYMBOL} } from the root entry now bundles to ${bytes} bytes, over the ${BUDGET_BYTES} budget.`, ) console.error( - 'A module-scope value in src/config/defaults.ts or src/common/keys.ts is no longer provably pure.', + 'A module-scope initialiser in src/config/defaults.ts is no longer provably pure.', ) console.error('Check that each one is still annotated `/* @__PURE__ */`.') process.exit(1) } - console.log(`Root entry bundles to ${bytes} bytes for one import (budget ${BUDGET_BYTES}).`) + // Proves the pruning kept what the import actually needs. + globalThis.__in = 'utmTeamId' + const code = Buffer.from(result.outputFiles[0].contents).toString('utf-8') + await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`) + if (globalThis.__out !== 'utm_team_id') { + console.error(`The pruned bundle returned ${JSON.stringify(globalThis.__out)} for 'utmTeamId'.`) + console.error('An annotated call was not pure, so a needed value was dropped.') + process.exit(1) + } + + console.log(`Root entry bundles to ${bytes} bytes and still works (budget ${BUDGET_BYTES}).`) } await main() diff --git a/src/config/defaults.ts b/src/config/defaults.ts index 2cf18ea..bf997ee 100644 --- a/src/config/defaults.ts +++ b/src/config/defaults.ts @@ -91,6 +91,9 @@ export const DEFAULT_CONFIG: ResolvedUtmConfig = { // cannot prove a spread pure — it invokes an iterator — and so retains this // object even where nothing references it, costing a consumer about a // kilobyte. scripts/assert-bundle-budget.js fails if an annotation is lost. + // The sources must stay plain data literals: a getter, a __proto__ key or a + // Proxy on any of them makes an annotation false, and a bundler would then + // drop a call that is not pure. /** UTM tracking is enabled by default */ enabled: true, From d487d882d5a1690770d5ee97ad12eb1bff250056 Mon Sep 17 00:00:00 2001 From: Jack Misner Date: Fri, 23 Oct 2026 14:33:16 +0100 Subject: [PATCH 6/7] refactor: build the defaults in annotated factories instead of annotated copies Six annotations on individual copies become two on factory calls, and the spreads come back. Measured, this is the better shape on every axis for four bytes. The budget could only see four of the six. Each annotation inside DEFAULT_CONFIG was worth ~920 bytes and was caught, but the two in common/keys.ts cost 153 and 21, and no ceiling catches 21 against a baseline of 303. With one annotation per object, losing either costs the whole object: 671 and 1,228 bytes, both over budget. The keys.ts pair stays uncovered, which is now the only gap rather than one of three. It also removes a hazard rather than documenting it. Object.assign reads its sources with Get and writes the target with Set, so a getter, a __proto__ key or a Proxy on any of those public constants would have made an annotation false - invisible to the tests and to the byte budget alike. Spread syntax cannot be subverted that way, so the precondition that needed writing down no longer exists. And the comment no longer has to explain why a copy is written as Object.assign({}, x), which read as a lint target. What remains is the one thing a reader would otherwise undo: the factory exists so the annotation has a call to attach to. Cost: 992 bytes against 988 for a consumer who does use the defaults. The four mutation tests are gone. They were strictly implied by the identity assertions above them - with no getter or Proxy involved, a write through one object cannot reach a different one - and they were the only tests in the repo writing to exported module state, which CLAUDE.md warns against. One test replaces them, pinning the nuance identity does not cover: the patterns array is copied while its member objects stay shared. The key-list tests move to common/keys.test.ts, which covers that module and had no coverage of them. Also: the CLAUDE.md bullet was inserted between the two sideEffects bullets, so "The flag" came to sit under a bullet about annotations and lost its referent. It now goes last and points at the code rather than restating it. The dependabot group comment names esbuild, which the pattern list gained. --- .github/dependabot.yml | 2 +- CLAUDE.md | 2 +- __tests__/common/keys.test.ts | 18 +++++++ __tests__/config/defaults.test.ts | 59 ++------------------ scripts/assert-bundle-budget.js | 26 +++++---- src/config/defaults.ts | 90 ++++++++++++++++--------------- 6 files changed, 85 insertions(+), 112 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index d819d24..7e8e1e2 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -80,7 +80,7 @@ updates: patterns: - "vitest" - "@vitest/*" - # publint and @arethetypeswrong/cli are pre-1.0, so breaking changes ship + # publint, @arethetypeswrong/cli and esbuild are pre-1.0, so breaking changes ship # as minors; either can start failing `npm run check:package` against # unchanged package code. This group covers ALL update types, majors # included, so such a bump cannot block the grouped batch behind it. diff --git a/CLAUDE.md b/CLAUDE.md index 9956182..151f586 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -18,8 +18,8 @@ - `check:package` runs attw with `--profile node16`, so the `node10` row is still printed but every cell is marked `(ignored)` and it cannot affect the exit code. It is red for `/react` and `/server` because legacy resolution cannot see `exports` subpaths; that is a declared non-target, not a bug to fix. Do not add `typesVersions`: it would green the row for types only. - publint and attw each catch what the other misses. attw exits 0 on a tarball containing no declarations at all, so publint is what catches missing or unpublished files; publint passes a correctly-wired `exports` map whose declarations import chunks the build never emitted, so attw is what catches that. Dropping either silently loses a class of failure. - `scripts/assert-no-import-side-effects.js` guards `"sideEffects": false` in `check:package`, and nothing else verifies that claim. It fails a module-scope *read* of a browser global, not only a write, and fails any entry that imports a node builtin, since it cannot see what such code does at import; no entry needs one today. Detect the environment at call time, as every site in `src/` does; the script header gives the reasoning. -- The module-scope defaults in `config/defaults.ts` and `common/keys.ts` are built with `/* @__PURE__ */` annotated calls, not spreads, so a bundler can drop them: a consumer importing one function ships ~300 bytes instead of ~1,350. Tidying them back into `{ ...x }` silently costs that. `scripts/assert-bundle-budget.js` notices for `defaults.ts`; the two `keys.ts` annotations are worth 153 and 21 bytes and no byte budget can cover the 21. - The flag saves a consumer bytes only when none of an entry's exports are used. `sideEffects` is module-granularity and `splitting: false` emits each entry as a single JS module, so there is no partial drop. Do not advertise it as a tree-shaking win. +- The exported defaults in `config/defaults.ts` are built by `@__PURE__` annotated factory calls, and `common/keys.ts` derives its key lists the same way, so a bundler can drop them: one imported function costs ~300 bytes rather than ~1,200 on esbuild. Inlining a factory or losing an annotation silently gives that back; see the comment above `createDefaultConfig` and `scripts/assert-bundle-budget.js`. ## Releases diff --git a/__tests__/common/keys.test.ts b/__tests__/common/keys.test.ts index af2199d..a46c5ef 100644 --- a/__tests__/common/keys.test.ts +++ b/__tests__/common/keys.test.ts @@ -12,6 +12,10 @@ import { detectKeyFormat, normalizeKey, toUrlKey, + SNAKE_TO_CAMEL, + CAMEL_TO_SNAKE, + STANDARD_SNAKE_KEYS, + STANDARD_CAMEL_KEYS, } from '../../src/common/keys' describe('toSnakeCase', () => { @@ -245,3 +249,17 @@ describe('isValidUtmParameters', () => { expect(isValidUtmParameters({ utmSource: 'test' })).toBe(true) }) }) + +/** + * These lists are derived from the maps above them. Pinning the relationship + * keeps a literal rewrite of either from drifting out of step. + */ +describe('standard key lists match the maps they come from', () => { + it('STANDARD_SNAKE_KEYS lists the keys of SNAKE_TO_CAMEL', () => { + expect(STANDARD_SNAKE_KEYS).toEqual(Object.keys(SNAKE_TO_CAMEL)) + }) + + it('STANDARD_CAMEL_KEYS lists the keys of CAMEL_TO_SNAKE', () => { + expect(STANDARD_CAMEL_KEYS).toEqual(Object.keys(CAMEL_TO_SNAKE)) + }) +}) diff --git a/__tests__/config/defaults.test.ts b/__tests__/config/defaults.test.ts index a7d596a..6498876 100644 --- a/__tests__/config/defaults.test.ts +++ b/__tests__/config/defaults.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, afterEach } from 'vitest' +import { describe, it, expect } from 'vitest' import { DEFAULT_CONFIG, DEFAULT_SANITIZE_CONFIG, @@ -7,12 +7,6 @@ import { DEFAULT_ATTRIBUTION_CONFIG, STANDARD_UTM_PARAMETERS, } from '../../src/config/defaults' -import { - SNAKE_TO_CAMEL, - CAMEL_TO_SNAKE, - STANDARD_SNAKE_KEYS, - STANDARD_CAMEL_KEYS, -} from '../../src/common/keys' /** * Every constant here is exported from the root entry, so one of them aliasing @@ -30,57 +24,14 @@ describe('exported defaults are independent of each other', () => { it('DEFAULT_CONFIG still equals the defaults it copies', () => { expect(DEFAULT_CONFIG.sanitize).toEqual(DEFAULT_SANITIZE_CONFIG) + expect(DEFAULT_CONFIG.piiFiltering).toEqual(DEFAULT_PII_FILTER_CONFIG) expect(DEFAULT_CONFIG.attribution).toEqual(DEFAULT_ATTRIBUTION_CONFIG) expect(DEFAULT_CONFIG.allowedParameters).toEqual(STANDARD_UTM_PARAMETERS) expect(DEFAULT_CONFIG.piiFiltering.patterns).toEqual(DEFAULT_PII_PATTERNS) }) -}) - -describe('mutating one exported default does not reach another', () => { - const originalSanitizeEnabled = DEFAULT_SANITIZE_CONFIG.enabled - const originalPatternCount = DEFAULT_PII_PATTERNS.length - const originalParameterCount = DEFAULT_CONFIG.allowedParameters.length - - afterEach(() => { - DEFAULT_SANITIZE_CONFIG.enabled = originalSanitizeEnabled - DEFAULT_CONFIG.sanitize.enabled = originalSanitizeEnabled - DEFAULT_PII_PATTERNS.length = originalPatternCount - DEFAULT_CONFIG.piiFiltering.patterns.length = originalPatternCount - DEFAULT_PII_FILTER_CONFIG.patterns.length = originalPatternCount - DEFAULT_CONFIG.allowedParameters.length = originalParameterCount - }) - - it('writing through DEFAULT_CONFIG.sanitize leaves DEFAULT_SANITIZE_CONFIG alone', () => { - DEFAULT_CONFIG.sanitize.enabled = !originalSanitizeEnabled - expect(DEFAULT_SANITIZE_CONFIG.enabled).toBe(originalSanitizeEnabled) - }) - - it('pushing to DEFAULT_CONFIG.allowedParameters leaves STANDARD_UTM_PARAMETERS alone', () => { - DEFAULT_CONFIG.allowedParameters.push('utm_injected') - expect(STANDARD_UTM_PARAMETERS).not.toContain('utm_injected') - }) - - it('pushing to DEFAULT_CONFIG.piiFiltering.patterns leaves DEFAULT_PII_PATTERNS alone', () => { - DEFAULT_CONFIG.piiFiltering.patterns.push({ name: 'injected', pattern: /x/, enabled: true }) - expect(DEFAULT_PII_PATTERNS.map((p) => p.name)).not.toContain('injected') - }) - - it('pushing to DEFAULT_PII_FILTER_CONFIG.patterns leaves DEFAULT_PII_PATTERNS alone', () => { - DEFAULT_PII_FILTER_CONFIG.patterns.push({ name: 'injected', pattern: /x/, enabled: true }) - expect(DEFAULT_PII_PATTERNS.map((p) => p.name)).not.toContain('injected') - }) -}) - -/** - * These lists are derived from the maps above them. Pinning the relationship - * keeps a literal rewrite of either from drifting out of step. - */ -describe('standard key lists match the maps they come from', () => { - it('STANDARD_SNAKE_KEYS lists the keys of SNAKE_TO_CAMEL', () => { - expect(STANDARD_SNAKE_KEYS).toEqual(Object.keys(SNAKE_TO_CAMEL)) - }) - it('STANDARD_CAMEL_KEYS lists the keys of CAMEL_TO_SNAKE', () => { - expect(STANDARD_CAMEL_KEYS).toEqual(Object.keys(CAMEL_TO_SNAKE)) + /** The spread these replaced copied the array but shared its member objects. */ + it('copies the patterns array without copying the patterns themselves', () => { + expect(DEFAULT_CONFIG.piiFiltering.patterns[0]).toBe(DEFAULT_PII_PATTERNS[0]) }) }) diff --git a/scripts/assert-bundle-budget.js b/scripts/assert-bundle-budget.js index 350369d..3c35e45 100644 --- a/scripts/assert-bundle-budget.js +++ b/scripts/assert-bundle-budget.js @@ -1,25 +1,23 @@ -#!/usr/bin/env node - /** * Fails if a consumer importing one small function from the root entry would - * ship more than BUDGET_BYTES. + * ship more than BUDGET_BYTES, or if the pruned bundle does not work. * - * What this protects is a `/* @__PURE__ *\/` annotation on each module-scope - * initialiser in src/config/defaults.ts. A bundler needs those to prove - * DEFAULT_CONFIG droppable; without one it retains the whole object and its - * dependencies, which measures ~1,200 bytes against ~300. They are comments, so - * removing one costs every consumer about a kilobyte and changes nothing any - * test can see. + * What this protects is the `@__PURE__` annotation on each exported default in + * src/config/defaults.ts. A bundler needs one to prove the object droppable, + * and cannot prove a spread pure by itself, which is why those objects are + * built by a factory call. Losing an annotation retains the whole object and + * everything it reaches: ~1,200 bytes against ~300, with nothing any test can + * see. * - * It does NOT cover the two annotations in src/common/keys.ts, which are worth - * 153 and 21 bytes: catching the 21 would need a ceiling with no headroom at - * all. A breach therefore always points at defaults.ts. + * It does not cover the two annotations in src/common/keys.ts, worth 153 and 21 + * bytes to this import. Catching the 21 would need a ceiling with no headroom, + * so a breach here always points at defaults.ts. * * The bundle is executed as well as weighed, because an annotation on a call * that is not in fact pure would license a bundler to drop something needed, - * and no test here bundles anything. + * and nothing else here bundles anything. * - * Usage: node scripts/assert-bundle-budget.js + * Usage: npm run check:package (which builds first) */ import { build } from 'esbuild' diff --git a/src/config/defaults.ts b/src/config/defaults.ts index bf997ee..0649d66 100644 --- a/src/config/defaults.ts +++ b/src/config/defaults.ts @@ -64,12 +64,17 @@ export const DEFAULT_PII_PATTERNS: PiiPattern[] = [ * Default PII filtering configuration * PII filtering is disabled by default but has sensible defaults when enabled */ -export const DEFAULT_PII_FILTER_CONFIG: PiiFilterConfig = { - enabled: false, - mode: 'reject', - patterns: /* @__PURE__ */ DEFAULT_PII_PATTERNS.slice(), +/** Built in a function for the same reason as createDefaultConfig below. */ +function createPiiFilterConfig(): PiiFilterConfig { + return { + enabled: false, + mode: 'reject', + patterns: [...DEFAULT_PII_PATTERNS], + } } +export const DEFAULT_PII_FILTER_CONFIG: PiiFilterConfig = /* @__PURE__ */ createPiiFilterConfig() + /** * Standard UTM parameters (snake_case format for URLs) */ @@ -86,59 +91,60 @@ export const STANDARD_UTM_PARAMETERS = [ * Default configuration with all values set * This is used as the base when merging with user-provided config */ -export const DEFAULT_CONFIG: ResolvedUtmConfig = { - // The copies here are annotated calls rather than spreads because a bundler - // cannot prove a spread pure — it invokes an iterator — and so retains this - // object even where nothing references it, costing a consumer about a - // kilobyte. scripts/assert-bundle-budget.js fails if an annotation is lost. - // The sources must stay plain data literals: a getter, a __proto__ key or a - // Proxy on any of them makes an annotation false, and a bundler would then - // drop a call that is not pure. - /** UTM tracking is enabled by default */ - enabled: true, +/** + * Built in a function so the annotation on the export below has a call to + * attach to. A bundler cannot prove an object or array spread pure, so without + * it this object is retained for every consumer, at about a kilobyte. + * scripts/assert-bundle-budget.js fails if the annotation is lost. + */ +function createDefaultConfig(): ResolvedUtmConfig { + return { + /** UTM tracking is enabled by default */ + enabled: true, - /** Use snake_case format by default (matches URL query params) */ - keyFormat: 'snake_case', + /** Use snake_case format by default (matches URL query params) */ + keyFormat: 'snake_case', - /** Default storage key for browser storage */ - storageKey: 'utm_parameters', + /** Default storage key for browser storage */ + storageKey: 'utm_parameters', - /** Use sessionStorage by default (ephemeral, cleared on tab close) */ - storageType: 'session', + /** Use sessionStorage by default (ephemeral, cleared on tab close) */ + storageType: 'session', - /** Auto-capture UTM params when React hook mounts */ - captureOnMount: true, + /** Auto-capture UTM params when React hook mounts */ + captureOnMount: true, - /** Append UTM params to share URLs by default */ - appendToShares: true, + /** Append UTM params to share URLs by default */ + appendToShares: true, - /** Capture standard UTM parameters by default */ - allowedParameters: /* @__PURE__ */ STANDARD_UTM_PARAMETERS.slice(), + /** Capture standard UTM parameters by default */ + allowedParameters: [...STANDARD_UTM_PARAMETERS], - /** Values are not folded to lowercase by default */ - lowercaseValues: false, + /** Values are not folded to lowercase by default */ + lowercaseValues: false, - /** No default parameters set */ - defaultParams: {}, + /** No default parameters set */ + defaultParams: {}, - /** No platform-specific share context by default */ - shareContextParams: {}, + /** No platform-specific share context by default */ + shareContextParams: {}, - /** No parameters excluded from shares by default */ - excludeFromShares: [], + /** No parameters excluded from shares by default */ + excludeFromShares: [], - /** Sanitization disabled by default */ - sanitize: /* @__PURE__ */ Object.assign({}, DEFAULT_SANITIZE_CONFIG), + /** Sanitization disabled by default */ + sanitize: { ...DEFAULT_SANITIZE_CONFIG }, - /** PII filtering disabled by default (deep copy to prevent shared references) */ - piiFiltering: /* @__PURE__ */ Object.assign({}, DEFAULT_PII_FILTER_CONFIG, { - patterns: /* @__PURE__ */ DEFAULT_PII_PATTERNS.slice(), - }), + /** PII filtering disabled by default (deep copy to prevent shared references) */ + piiFiltering: { ...DEFAULT_PII_FILTER_CONFIG, patterns: [...DEFAULT_PII_PATTERNS] }, - /** Last-touch attribution by default */ - attribution: /* @__PURE__ */ Object.assign({}, DEFAULT_ATTRIBUTION_CONFIG), + /** Last-touch attribution by default */ + attribution: { ...DEFAULT_ATTRIBUTION_CONFIG }, + } } +export const DEFAULT_CONFIG: ResolvedUtmConfig = /* @__PURE__ */ createDefaultConfig() + /** * Get a copy of the default configuration * Use this to avoid accidentally mutating the defaults From ae474532ee7190266c0b7f49bc41dba9784fa0ce Mon Sep 17 00:00:00 2001 From: Jack Misner Date: Fri, 23 Oct 2026 14:47:31 +0100 Subject: [PATCH 7/7] fix: put the public docs back on the exports, and correct what the guard claims The factory refactor stranded two public doc comments. "Default configuration with all values set" and "Default PII filtering configuration" ended up above the factory functions, which are not exported, so dist/defaults-*.d.ts carried bare `declare const DEFAULT_CONFIG` and `declare const DEFAULT_PII_FILTER_CONFIG` where every sibling keeps its description. Two commits earlier I moved an internal note out of those declarations; this put the real docs out with it. They are back on the export lines, with the factory rationale left on the function where it cannot reach a consumer. "A bundler cannot prove an object or array spread pure" is false for Rollup, which drops both factories unannotated - 362 bytes either way. Having fixed the iterator half of that sentence I left the subject overgeneral. It now names esbuild and Rolldown and says Rollup can. The guard said it protects "each exported default" in defaults.ts and told a maintainer to check "each one". Six constants are exported there and two are factory calls; the other four are plain literals needing no annotation, so that wording sends someone annotating literals. It now names the two, and the error message names them too. "~1,200 with any one of them lost" was measured from the DEFAULT_CONFIG annotation only. Losing the DEFAULT_PII_FILTER_CONFIG one gives 671. Both breach the budget, so the mechanism holds, but the figure covered half the cases. Now ~670 or ~1,200. A breach "always points at defaults.ts" overclaimed: growth in toSnakeCase or in keys.ts could also cross a 297-byte headroom. Softened to most likely. "Nothing else here bundles anything" was literally false, since tsup bundles on every build; what is true is that no other check prunes the entry and runs the result. The header no longer restates the reasoning the src comment holds. The test comment "the spread these replaced" described a shape that no longer exists - the factory restored the spreads, so the spread is the live implementation and nothing replaced it. Deleted rather than reworded. README: /react on webpack is fixture-sensitive. My fixture measures 471 bytes and an independent one 224, while both agree on root (209) and /server (202), so a precise figure does not belong there. "Well under 1KB" is true of both. --- .github/dependabot.yml | 2 +- CLAUDE.md | 2 +- README.md | 2 +- __tests__/config/defaults.test.ts | 1 - scripts/assert-bundle-budget.js | 26 ++++++++++++-------------- src/config/defaults.ts | 24 ++++++++++++------------ 6 files changed, 27 insertions(+), 30 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 7e8e1e2..72b39cf 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -81,7 +81,7 @@ updates: - "vitest" - "@vitest/*" # publint, @arethetypeswrong/cli and esbuild are pre-1.0, so breaking changes ship - # as minors; either can start failing `npm run check:package` against + # as minors; any of them can start failing `npm run check:package` against # unchanged package code. This group covers ALL update types, majors # included, so such a bump cannot block the grouped batch behind it. package-check: diff --git a/CLAUDE.md b/CLAUDE.md index 151f586..e3aa605 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -19,7 +19,7 @@ - publint and attw each catch what the other misses. attw exits 0 on a tarball containing no declarations at all, so publint is what catches missing or unpublished files; publint passes a correctly-wired `exports` map whose declarations import chunks the build never emitted, so attw is what catches that. Dropping either silently loses a class of failure. - `scripts/assert-no-import-side-effects.js` guards `"sideEffects": false` in `check:package`, and nothing else verifies that claim. It fails a module-scope *read* of a browser global, not only a write, and fails any entry that imports a node builtin, since it cannot see what such code does at import; no entry needs one today. Detect the environment at call time, as every site in `src/` does; the script header gives the reasoning. - The flag saves a consumer bytes only when none of an entry's exports are used. `sideEffects` is module-granularity and `splitting: false` emits each entry as a single JS module, so there is no partial drop. Do not advertise it as a tree-shaking win. -- The exported defaults in `config/defaults.ts` are built by `@__PURE__` annotated factory calls, and `common/keys.ts` derives its key lists the same way, so a bundler can drop them: one imported function costs ~300 bytes rather than ~1,200 on esbuild. Inlining a factory or losing an annotation silently gives that back; see the comment above `createDefaultConfig` and `scripts/assert-bundle-budget.js`. +- The exported defaults in `config/defaults.ts` are built by `@__PURE__` annotated factory calls, and `common/keys.ts` derives its key lists the same way, so a bundler can drop them: one imported function costs ~300 bytes rather than ~1,400 on esbuild. Inlining a factory or losing an annotation silently gives that back; see the comment above `createDefaultConfig` and `scripts/assert-bundle-budget.js`. ## Releases diff --git a/README.md b/README.md index 4f90ba1..5d15a48 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ Three entry points: All three ship dual ESM/CJS builds with TypeScript declarations. The `/react` and `/server` subpaths need TypeScript `moduleResolution` set to `node16` or `nodenext` (TS 4.7+), or `bundler` (TS 5.0+); under the legacy `node`/`node10` setting only the root entry resolves types, though all three resolve at runtime in Node. -The root entry is a barrel, so for a browser bundle it matters how you import from it. A static `import { toSnakeCase }` prunes to around 300 bytes on esbuild, Rollup, Rolldown and webpack alike. A `require()` of the same entry keeps all of it on esbuild, Rollup and Rolldown — roughly 28KB minified — because none of them tree-shake CommonJS; webpack 5 does prune CommonJS exports, so there the gap is about 200 bytes. `await import()` is not a dependable substitute: esbuild and Rolldown keep the whole namespace however you access it, and Rollup prunes it only when you destructure the result directly. Use a static `import` at the call site. The subpaths are far less exposed, because most of what they contain is used either way: `/server` differs by a few hundred bytes, and `/react` by about 3KB on esbuild and about 500 bytes on webpack, against the ~14KB the hook pulls in regardless. +The root entry is a barrel, so for a browser bundle it matters how you import from it. A static `import { toSnakeCase }` prunes to around 300 bytes on esbuild, Rollup, Rolldown and webpack alike. A `require()` of the same entry keeps all of it on esbuild, Rollup and Rolldown — roughly 28KB minified — because none of them tree-shake CommonJS; webpack 5 does prune CommonJS exports, so there the gap is about 200 bytes. `await import()` is not a dependable substitute: esbuild and Rolldown keep the whole namespace however you access it, and Rollup prunes it only when you destructure the result directly. Use a static `import` at the call site. The subpaths are far less exposed, because most of what they contain is used either way: `/server` differs by a few hundred bytes, and `/react` by about 3KB on esbuild and well under 1KB on webpack, against the ~14KB the hook pulls in regardless. ## Quick Start diff --git a/__tests__/config/defaults.test.ts b/__tests__/config/defaults.test.ts index 6498876..953a8ac 100644 --- a/__tests__/config/defaults.test.ts +++ b/__tests__/config/defaults.test.ts @@ -30,7 +30,6 @@ describe('exported defaults are independent of each other', () => { expect(DEFAULT_CONFIG.piiFiltering.patterns).toEqual(DEFAULT_PII_PATTERNS) }) - /** The spread these replaced copied the array but shared its member objects. */ it('copies the patterns array without copying the patterns themselves', () => { expect(DEFAULT_CONFIG.piiFiltering.patterns[0]).toBe(DEFAULT_PII_PATTERNS[0]) }) diff --git a/scripts/assert-bundle-budget.js b/scripts/assert-bundle-budget.js index 3c35e45..901a8d5 100644 --- a/scripts/assert-bundle-budget.js +++ b/scripts/assert-bundle-budget.js @@ -2,20 +2,20 @@ * Fails if a consumer importing one small function from the root entry would * ship more than BUDGET_BYTES, or if the pruned bundle does not work. * - * What this protects is the `@__PURE__` annotation on each exported default in - * src/config/defaults.ts. A bundler needs one to prove the object droppable, - * and cannot prove a spread pure by itself, which is why those objects are - * built by a factory call. Losing an annotation retains the whole object and - * everything it reaches: ~1,200 bytes against ~300, with nothing any test can - * see. + * What this protects is the two `@__PURE__` annotations in + * src/config/defaults.ts, on the factory calls that build + * DEFAULT_PII_FILTER_CONFIG and DEFAULT_CONFIG. The comment above + * createDefaultConfig says why they are written that way. Losing either retains + * the object and everything it reaches - ~670 or ~1,200 bytes against ~300 - + * with nothing any test can see. * * It does not cover the two annotations in src/common/keys.ts, worth 153 and 21 * bytes to this import. Catching the 21 would need a ceiling with no headroom, - * so a breach here always points at defaults.ts. + * so a breach here is most likely one of the defaults.ts pair. * * The bundle is executed as well as weighed, because an annotation on a call * that is not in fact pure would license a bundler to drop something needed, - * and nothing else here bundles anything. + * and no other check prunes the entry and runs the result. * * Usage: npm run check:package (which builds first) */ @@ -29,8 +29,8 @@ const __dirname = dirname(fileURLToPath(import.meta.url)) const root = resolve(__dirname, '..') /** - * ~300 bytes with every defaults.ts initialiser annotated, ~1,200 with any one - * of them lost. The headroom absorbs ordinary growth in the function under test + * ~300 bytes with both defaults.ts annotations in place, ~670 or ~1,200 with + * either lost. The headroom absorbs ordinary growth in the function under test * and patch-level minifier drift. */ const BUDGET_BYTES = 600 @@ -69,10 +69,8 @@ async function main() { console.error( `Importing { ${SYMBOL} } from the root entry now bundles to ${bytes} bytes, over the ${BUDGET_BYTES} budget.`, ) - console.error( - 'A module-scope initialiser in src/config/defaults.ts is no longer provably pure.', - ) - console.error('Check that each one is still annotated `/* @__PURE__ */`.') + console.error('Most likely a factory call in src/config/defaults.ts lost its annotation.') + console.error('DEFAULT_PII_FILTER_CONFIG and DEFAULT_CONFIG each need one.') process.exit(1) } diff --git a/src/config/defaults.ts b/src/config/defaults.ts index 0649d66..b2bf198 100644 --- a/src/config/defaults.ts +++ b/src/config/defaults.ts @@ -60,10 +60,6 @@ export const DEFAULT_PII_PATTERNS: PiiPattern[] = [ }, ] -/** - * Default PII filtering configuration - * PII filtering is disabled by default but has sensible defaults when enabled - */ /** Built in a function for the same reason as createDefaultConfig below. */ function createPiiFilterConfig(): PiiFilterConfig { return { @@ -73,6 +69,10 @@ function createPiiFilterConfig(): PiiFilterConfig { } } +/** + * Default PII filtering configuration + * PII filtering is disabled by default but has sensible defaults when enabled + */ export const DEFAULT_PII_FILTER_CONFIG: PiiFilterConfig = /* @__PURE__ */ createPiiFilterConfig() /** @@ -88,14 +88,10 @@ export const STANDARD_UTM_PARAMETERS = [ ] as const /** - * Default configuration with all values set - * This is used as the base when merging with user-provided config - */ -/** - * Built in a function so the annotation on the export below has a call to - * attach to. A bundler cannot prove an object or array spread pure, so without - * it this object is retained for every consumer, at about a kilobyte. - * scripts/assert-bundle-budget.js fails if the annotation is lost. + * Built in a function so the annotation on the export below has a call to attach + * to. esbuild and Rolldown cannot prove a spread pure, Rollup can, so without it + * this object is retained for an esbuild or Rolldown consumer at about a + * kilobyte. scripts/assert-bundle-budget.js fails if the annotation is lost. */ function createDefaultConfig(): ResolvedUtmConfig { return { @@ -143,6 +139,10 @@ function createDefaultConfig(): ResolvedUtmConfig { } } +/** + * Default configuration with all values set + * This is used as the base when merging with user-provided config + */ export const DEFAULT_CONFIG: ResolvedUtmConfig = /* @__PURE__ */ createDefaultConfig() /**