proxy-analytics 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,366 @@
1
- # Temporary Holding Version
1
+ # proxy-analytics
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Property-level usage analytics for JSON REST APIs. Find out which fields of each
4
+ response your frontend actually reads, with no backend changes.
5
+
6
+ Most REST endpoints return far more than the UI uses. `proxy-analytics` wraps
7
+ the JSON your app receives in lightweight tracking proxies, records which
8
+ properties are read, and batches anonymous counts (paths, never values) to a
9
+ collector. The result is a per-endpoint, per-field report:
10
+
11
+ ```
12
+ GET /api/products 6 responses
13
+ items[*].name read in 6 / 6 (100%)
14
+ items[*].price.amount read in 6 / 6 (100%)
15
+ items[*].vendor.internalCode never read
16
+ items[*].seo.keywords never read
17
+ ...49 of 59 fields never read
18
+ ```
19
+
20
+ It's framework-agnostic: it intercepts `fetch`, `XMLHttpRequest` and
21
+ `JSON.parse`, so it works with React, Vue, Svelte, vanilla JS and any HTTP
22
+ client built on those (axios, ky, TanStack Query, SWR, RTK Query, ...).
23
+
24
+ - ~9.4 KB min+gzip, no runtime dependencies
25
+ - Only touches responses from the API roots you list; everything else passes through untouched
26
+ - Never adds request headers, never changes request bodies
27
+ - Parses and inventories responses in a web worker when available
28
+
29
+ ## Quick start
30
+
31
+ ```ts
32
+ // Run this before your HTTP clients load (first import in your entry file).
33
+ import { install } from 'proxy-analytics'
34
+
35
+ install({
36
+ apis: 'https://api.myshop.com/v2', // required: what to track
37
+ endpoint: 'https://collector.myshop.com/collect', // where batches go
38
+ })
39
+ ```
40
+
41
+ That's it. Use your app normally; counts are flushed every 10 seconds and when
42
+ the page is hidden.
43
+
44
+ For local testing, this repo ships a reference collector with a dashboard; see
45
+ the [workspace README](../../README.md).
46
+
47
+ ## Choosing what to track: `apis` and `ignore`
48
+
49
+ `apis` is required, so tracking is always opt-in per API. Anything not matched
50
+ (analytics beacons, CDNs, third-party SDKs, your collector) is forwarded to
51
+ the native implementation with the exact same arguments and returned untouched.
52
+
53
+ ```ts
54
+ install({
55
+ apis: ['/api', 'https://search.myshop.com'],
56
+ ignore: [
57
+ '/api/auth', // this path and everything under it
58
+ '/api/products/*/reviews', // * matches one path segment
59
+ 'POST /api/upload', // only this method
60
+ /\/internal\//, // RegExp, tested against the full URL
61
+ (url, method) => url.searchParams.has('nocache'),
62
+ ],
63
+ })
64
+ ```
65
+
66
+ | Pattern | Matches |
67
+ | --------------------------------------- | ------------------------------------------------------ |
68
+ | `'/api'` | same origin, path `/api` or `/api/...` (not `/apiary`) |
69
+ | `'https://api.x.com/v2'` | that origin, path under `/v2` |
70
+ | `'/api/users/*/orders'` | `*` = exactly one segment; children included |
71
+ | `'GET /api/search'` | method-qualified |
72
+ | `'same-origin'` | everything on the page's origin |
73
+ | `RegExp` | tested against the absolute URL |
74
+ | `(url: URL, method: string) => boolean` | anything else |
75
+
76
+ ## What gets recorded
77
+
78
+ **Endpoints.** Requests are grouped as `METHOD /path`, with id-like segments
79
+ (numbers, UUIDs, long hex) collapsed to `:id` and the query string dropped:
80
+ `GET /api/products/123?ref=x` becomes `GET /api/products/:id`. Foreign origins
81
+ are kept in the key. Override with `endpointKey`.
82
+
83
+ **Paths.** Reads are normalised so arrays and id-keyed records aggregate:
84
+
85
+ | Read | Path |
86
+ | ---------------------------- | ----------------------- |
87
+ | `data.items[3].price.amount` | `items[*].price.amount` |
88
+ | `data.byId['8f3a…'].name` | `byId.{*}.name` |
89
+ | `data['content-type']` | `content-type` |
90
+ | `data['a.b']` | `["a.b"]` |
91
+
92
+ **Counts are per response, not per read.** Rendering 500 products' prices
93
+ counts once for `items[*].price.amount` in that response. Each counter answers
94
+ "in how many responses was this field read?"
95
+
96
+ **Direct vs bulk reads.** A targeted read (`product.price`, `'price' in product`)
97
+ is _direct_. Reads that happen while something walks every key of an object
98
+ (spread, `Object.assign`, `Object.entries`, `JSON.stringify`, deep-equal checks,
99
+ structural sharing in query caches, store copies) are _bulk_. Bulk usually means
100
+ the data was passed along rather than displayed, but it still matters: an
101
+ object that's sent back in a PUT is "used" even if nothing renders it. The
102
+ dashboard lets you count bulk reads as used or not.
103
+
104
+ **Inventory.** To show fields that are _never_ read, each response's shape is
105
+ inventoried (which paths exist), in a web worker when possible. The report
106
+ includes how many responses contained each field, so read rates are relative
107
+ to responses where the field was actually present.
108
+
109
+ Only path strings and integer counts leave the browser. Values are never sent.
110
+
111
+ ## Getting the most useful data
112
+
113
+ The tracker sees reads through the objects your API returned. It doesn't need
114
+ to be perfect to be useful, but these practices make the numbers sharper:
115
+
116
+ 1. **Install first.** Import the module that calls `install()` before anything
117
+ else in your entry point, so it's in place before the first request.
118
+ 2. **Prefer passing response objects around over copying primitives out of
119
+ them.** If you do `const name = product.name` and store `name`, that read is
120
+ recorded (good) but later reads of `name` aren't (they're just strings). If
121
+ you store `product` and read `product.name` where it's used, every use is
122
+ attributed. Nested objects stay tracked even when their parent is spread:
123
+ `{ ...product }.price.amount` is still a tracked read of `price.amount`.
124
+ 3. **Normalisation and store copies show up as bulk.** Redux/RTK, Immer,
125
+ Valtio, Zustand and TanStack Query all work (see the compatibility table
126
+ below). Their internal walks are classified as bulk, and reads through the
127
+ stored data afterwards are still direct.
128
+ 4. **Use sampling in production.** `sampleRate: 0.05` tracks 5% of page
129
+ sessions. Unsampled sessions patch nothing at all, so they pay zero overhead.
130
+ 5. **Treat "never read" as a lead, not a verdict.** A field can be unread in
131
+ the web app but used by your mobile app, a partner, or a rarely visited
132
+ screen. Watch the report over enough sessions, versions and screens before
133
+ acting on it. The response and session counts tell you how much evidence
134
+ you have.
135
+
136
+ ## Compatibility
137
+
138
+ Verified by the integration tests in this repo:
139
+
140
+ | Library / API | Tracked | Notes |
141
+ | ---------------------------------------------------------------- | ------- | ----------------------------------------------------------------------------- |
142
+ | `fetch` + `Response#json()` | yes | |
143
+ | `fetch` + `Response#text()` + `JSON.parse` | yes | via the scoped `JSON.parse` hook |
144
+ | `Response#clone()` | yes | each clone counts as a response |
145
+ | `XMLHttpRequest` (`responseText`, `responseType: 'json'`) | yes | independent of listener order |
146
+ | axios (XHR and fetch adapters) | yes | |
147
+ | ky | yes | |
148
+ | TanStack Query (`@tanstack/query-core`) | yes | refetch structural sharing → bulk |
149
+ | SWR (React) | yes | exact rendered fields reported |
150
+ | Redux Toolkit (auto-freeze, dev checks) | yes | middleware walks → bulk; selectors → direct |
151
+ | Immer `produce` | yes | frozen results stay tracked |
152
+ | Zustand | yes | stores references; reads tracked |
153
+ | Valtio | yes | initial copy → bulk; later reads → direct |
154
+ | `structuredClone`, `postMessage`, IndexedDB, `history.pushState` | safe | unwrapped automatically and recorded as bulk (they'd otherwise throw `DataCloneError`) |
155
+ | Responses re-wrapped by frameworks (Next.js fetch dedupe) | yes | matched by URL through a `Response.prototype` hook |
156
+ | `supabase-js` / `postgrest-js`, server or browser | yes | use `postgrestEndpointKey` |
157
+ | Next.js server components, server actions, route handlers | yes | see [Server-side](#server-side-nodejs-nextjs-supabase) |
158
+
159
+ Pass `baseUrl` when using relative `apis` outside a browser.
160
+
161
+ ## Server-side (Node.js, Next.js, Supabase)
162
+
163
+ The same tracker runs on the server, where it sees what server code fetches
164
+ and reads. That's where the waste is in apps built on React Server Components
165
+ and server actions: `select('*')` from the database, a handful of columns
166
+ used.
167
+
168
+ ```ts
169
+ // instrumentation.ts (Next.js)
170
+ export async function register() {
171
+ if (process.env.NEXT_RUNTIME === 'nodejs') {
172
+ const { install, postgrestEndpointKey } = await import('proxy-analytics')
173
+ install({
174
+ apis: `${process.env.NEXT_PUBLIC_SUPABASE_URL}/rest/v1`,
175
+ endpoint: process.env.PROXY_ANALYTICS_ENDPOINT,
176
+ endpointKey: postgrestEndpointKey, // GET cases?select=*, one report per query
177
+ responseSampleRate: 0.1, // per response; sampleRate is per process on a server
178
+ })
179
+ }
180
+ }
181
+ ```
182
+
183
+ On serverless hosts the process can be frozen right after the response, so
184
+ flush where the platform keeps the function alive. `flush()` works from any
185
+ module (instrumentation and route code are separate bundles):
186
+
187
+ ```ts
188
+ import { after } from 'next/server'
189
+ import { flush } from 'proxy-analytics'
190
+
191
+ export default async function Page() {
192
+ after(flush)
193
+ // ...
194
+ }
195
+ ```
196
+
197
+ Long-running servers can rely on the regular `flushInterval`.
198
+
199
+ What the report means on a server:
200
+
201
+ - Columns your server code reads are **direct**.
202
+ - Objects passed to client components are serialized by React, so every
203
+ field in them is **bulk only**. That's a finding in itself: those fields
204
+ are shipped to the browser. Pass narrower objects to see exactly what the
205
+ server uses.
206
+ - A field that is **never read** can be dropped from the `select(...)` for
207
+ that query.
208
+
209
+ Edge runtime routes aren't covered (instrumentation runs per runtime; the
210
+ example only installs in Node).
211
+
212
+ ## Options
213
+
214
+ ```ts
215
+ install({
216
+ apis, // required: UrlMatcher | UrlMatcher[]
217
+ ignore, // UrlMatcher | UrlMatcher[]
218
+ endpoint, // collector URL; omit to only feed plugins
219
+ sampleRate: 1, // fraction of page sessions (processes, on a server) tracked
220
+ responseSampleRate: 1, // fraction of fenced responses tracked, decided per response
221
+ flushInterval: 10000, // ms
222
+ endpointKey, // ({ method, url }) => string
223
+ trackErrors: false, // also track non-2xx JSON responses
224
+ intercept: { fetch: true, xhr: true, jsonParse: true, cloneSafety: true },
225
+ inventory: { sampleRate: 1, maxArrayItems: 100 },
226
+ paths: { dynamicKeys: DEFAULT_DYNAMIC_KEYS, maxKeysPerObject: 256, maxDepth: 32 },
227
+ worker: true, // true | false | URL of self-hosted dist/worker.js | () => Worker
228
+ baseUrl, // resolve relative apis outside browsers
229
+ plugins: [],
230
+ onError: (error, phase) => {},
231
+ debug: false,
232
+ })
233
+ ```
234
+
235
+ `install()` returns a handle:
236
+
237
+ ```ts
238
+ const analytics = install({ ... })
239
+ analytics.enabled // false if this session wasn't sampled
240
+ analytics.sessionId
241
+ await analytics.flush() // send now
242
+ analytics.track(data, { endpoint: 'WS prices' }) // manual tracking
243
+ analytics.uninstall() // restore every patched global
244
+ ```
245
+
246
+ Other exports: `flush()` sends pending counts from whichever instance is
247
+ installed (for server code that can't reach the handle); `unwrap(value)`
248
+ returns raw data with no proxies and no recorded reads; `isTracked(value)`;
249
+ `definePlugin(plugin)`; `defaultEndpointKey`; `postgrestEndpointKey`;
250
+ `DEFAULT_DYNAMIC_KEYS`.
251
+
252
+ ### Strict Content-Security-Policy
253
+
254
+ The default worker is created from a blob URL. If your CSP blocks that
255
+ (`worker-src` without `blob:`), the library falls back to the main thread
256
+ automatically. To keep the work off the main thread, self-host the worker:
257
+
258
+ ```ts
259
+ install({ apis: '/api', worker: '/static/proxy-analytics-worker.js' }) // copy of dist/worker.js
260
+ ```
261
+
262
+ ## Plugins
263
+
264
+ Plugins hook into the lifecycle so future features (for example cooperating
265
+ with a reverse proxy) can be added without changing the core. Every hook is
266
+ optional and isolated: a throwing hook is reported via `onError` and skipped.
267
+
268
+ ```
269
+ onRequest → (network) → onResponse → transformBody → transformData → onTrack
270
+ … app reads data … onFirstRead
271
+ … every flush … onBatch
272
+ ```
273
+
274
+ | Hook | Use it to |
275
+ | ------------------------ | ------------------------------------------------------------------------------ |
276
+ | `setup(api)` | start timers, keep `api.flush` / `api.track` / `api.unwrap`; return a teardown |
277
+ | `onRequest(e)` | add headers with `e.setHeader()` (the core never does) |
278
+ | `onResponse(e)` | inspect status/headers; return `false` to leave a response untracked |
279
+ | `transformBody(text, e)` | rewrite the raw body before parsing (e.g. decode a compressed format) |
280
+ | `transformData(data, e)` | replace parsed data before it's wrapped |
281
+ | `onTrack(e)` | observe tracked responses |
282
+ | `onFirstRead(e)` | first read of each path per response (opt-in; only wired if defined) |
283
+ | `onBatch(batch)` | add `meta`, filter, or send elsewhere; return `false` to drop |
284
+
285
+ ```ts
286
+ import { definePlugin, install } from 'proxy-analytics'
287
+
288
+ const release = definePlugin({
289
+ name: 'release',
290
+ onBatch: (batch) => ({ ...batch, meta: { release: import.meta.env.VITE_RELEASE } }),
291
+ })
292
+
293
+ install({ apis: '/api', endpoint: '/collect', plugins: [release] })
294
+ ```
295
+
296
+ ### Manual tracking
297
+
298
+ Data that doesn't arrive through `fetch`/XHR (WebSockets, SDK results) can be
299
+ tracked explicitly:
300
+
301
+ ```ts
302
+ socket.addEventListener('message', (e) => {
303
+ const update = analytics.track(JSON.parse(e.data), { endpoint: 'WS /prices' })
304
+ render(update)
305
+ })
306
+ ```
307
+
308
+ ## Wire format (v1)
309
+
310
+ Batches are POSTed as `text/plain` JSON (a CORS "simple request", so there's no
311
+ preflight), via `sendBeacon` on page hide:
312
+
313
+ ```jsonc
314
+ {
315
+ "v": 1,
316
+ "sid": "random-session-id",
317
+ "ts": 1764360000000,
318
+ "rate": 1, // session sample rate
319
+ "paths": ["items", "items[*]", "items[*].name"],
320
+ "endpoints": [
321
+ {
322
+ "key": "GET /api/products",
323
+ "responses": 3, // responses tracked in this window
324
+ "reads": [[0, 3, 3, 0], [2, 3, 3, 0]], // [pathIndex, any, direct, bulk]
325
+ "inventoried": 3,
326
+ "present": [[0, 3], [1, 3], [2, 3]] // [pathIndex, responsesContaining]
327
+ }
328
+ ]
329
+ }
330
+ ```
331
+
332
+ ## Performance
333
+
334
+ Measured with `pnpm bench` (Node 22, numbers vary by machine):
335
+
336
+ | Scenario | Raw | Tracked |
337
+ | ------------------------------------- | ------- | --------------------------------- |
338
+ | Typical page: parse + render 20 items | 18 µs | 31 µs (+13 µs) |
339
+ | Parse + first render, 1,000 items | 0.49 ms | 1.06 ms |
340
+ | `JSON.stringify` 1,000 items | 0.42 ms | 0.44 ms |
341
+ | Spread-copy every item of 1,000 | 0.52 ms | 3.9 ms |
342
+ | Re-read 1,000 already-tracked items | 23 µs | 380 µs (~50 ns per property read) |
343
+
344
+ How it stays cheap:
345
+
346
+ - Proxies are created lazily as objects are reached.
347
+ - Each path is interned once.
348
+ - Repeat reads hit a one-entry cache (a pointer compare).
349
+ - `JSON.stringify` bypasses the traps entirely.
350
+ - Field inventory happens in a worker.
351
+
352
+ `sampleRate` is the main lever in production.
353
+
354
+ ## Known limitations
355
+
356
+ - **Copied primitives aren't followed.** Reads after a value is copied out of the response aren't attributed. Copying usually implies use, and the copy itself is recorded.
357
+ - **Same-task ambiguity.** A targeted read in the same synchronous task as a full walk of the same object (e.g. inside an Immer recipe that copies that object) can be folded into the bulk walk.
358
+ - **Untracked body paths.** `Response#body` streams, `arrayBuffer()` and `blob()` aren't tracked. Neither are WebSocket messages, unless you use `track()`.
359
+ - **Descriptor-based copies.** Code that copies via raw property descriptors (`Object.getOwnPropertyDescriptors` + `defineProperties`) gets untracked children and records nothing, so a field read only through such a copy can show as never read. Structured clones (`structuredClone`, `postMessage`, IndexedDB writes, history state) are recorded as bulk reads of everything cloned.
360
+ - **Inventory caps.** Inventory walks at most `maxArrayItems` elements per array, and objects with more than `maxKeysPerObject` keys collapse the overflow to `{*}`.
361
+ - **Early-captured `fetch`.** Clients that captured `fetch` before `install()` ran bypass it. Install first.
362
+ - **No other consumers.** Only this frontend's reads are visible. Other consumers of the same API aren't.
363
+
364
+ ## License
365
+
366
+ MIT