Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,15 @@ updates:
patterns:
- "vitest"
- "@vitest/*"
# publint and @arethetypeswrong/cli are pre-1.0, so breaking changes ship
# as minors; either can start failing `npm run check:package` against
# publint, @arethetypeswrong/cli and esbuild are pre-1.0, so breaking changes ship
# 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:
patterns:
- "publint"
- "@arethetypeswrong/*"
- "esbuild"
npm-minor-patch:
patterns:
- "*"
Expand Down
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +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,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

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 well under 1KB on webpack, against the ~14KB the hook pulls in regardless.

## Quick Start

Expand Down
18 changes: 18 additions & 0 deletions __tests__/common/keys.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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))
})
})
36 changes: 36 additions & 0 deletions __tests__/config/defaults.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { describe, it, expect } 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'

/**
* 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.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)
})

it('copies the patterns array without copying the patterns themselves', () => {
expect(DEFAULT_CONFIG.piiFiltering.patterns[0]).toBe(DEFAULT_PII_PATTERNS[0])
})
})
1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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}\"",
Expand All @@ -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",
Expand Down
90 changes: 90 additions & 0 deletions scripts/assert-bundle-budget.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/**
* 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 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 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 no other check prunes the entry and runs the result.
*
* Usage: npm run check:package (which builds first)
*/

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, '..')

/**
* ~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

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('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)
}

// 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()
4 changes: 2 additions & 2 deletions src/common/keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@ export const CAMEL_TO_SNAKE: Record<string, string> = {
/**
* 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
Expand Down
87 changes: 51 additions & 36 deletions src/config/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,20 @@ export const DEFAULT_PII_PATTERNS: PiiPattern[] = [
},
]

/** Built in a function for the same reason as createDefaultConfig below. */
function createPiiFilterConfig(): PiiFilterConfig {
return {
enabled: false,
mode: 'reject',
patterns: [...DEFAULT_PII_PATTERNS],
}
}

/**
* 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: [...DEFAULT_PII_PATTERNS],
}
export const DEFAULT_PII_FILTER_CONFIG: PiiFilterConfig = /* @__PURE__ */ createPiiFilterConfig()

/**
* Standard UTM parameters (snake_case format for URLs)
Expand All @@ -83,53 +88,63 @@ 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. 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.
*/
export const DEFAULT_CONFIG: ResolvedUtmConfig = {
/** UTM tracking is enabled by default */
enabled: true,
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: [...STANDARD_UTM_PARAMETERS],
/** 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: { ...DEFAULT_SANITIZE_CONFIG },
/** Sanitization disabled by default */
sanitize: { ...DEFAULT_SANITIZE_CONFIG },

/** PII filtering disabled by default (deep copy to prevent shared references) */
piiFiltering: { ...DEFAULT_PII_FILTER_CONFIG, patterns: [...DEFAULT_PII_PATTERNS] },
/** 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: { ...DEFAULT_ATTRIBUTION_CONFIG },
/** Last-touch attribution by default */
attribution: { ...DEFAULT_ATTRIBUTION_CONFIG },
}
}

/**
* 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()

/**
* Get a copy of the default configuration
* Use this to avoid accidentally mutating the defaults
Expand Down
Loading