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.
@@ -0,0 +1,255 @@
1
+ /**
2
+ * Describes which URLs are inside the tracking fence.
3
+ *
4
+ * - `string`: an API root such as `'/api'` or `'https://api.shop.com/v2'`.
5
+ * Relative roots resolve against the page origin. A URL matches when its
6
+ * origin is identical and its path starts with the root's path on a segment
7
+ * boundary (`/api` matches `/api/products`, not `/apiary`). A string always
8
+ * covers child paths too. `*` matches one path segment
9
+ * (`'/api/products/*\/reviews'`), and a method prefix limits it to one method
10
+ * (`'POST /api/upload'`).
11
+ * - `'same-origin'`: every URL on the page's own origin.
12
+ * - `RegExp`: tested against the absolute URL string.
13
+ * - function: receives the parsed URL and the upper-case method.
14
+ */
15
+ type UrlMatcher = string | RegExp | ((url: URL, method: string) => boolean);
16
+ interface ProxyAnalyticsOptions {
17
+ /** Required. Only responses from these API roots are tracked; everything else passes through untouched. */
18
+ apis: UrlMatcher | readonly UrlMatcher[];
19
+ /** URLs inside `apis` that should still pass through untouched (auth, uploads, ...). Same forms as `apis`. */
20
+ ignore?: UrlMatcher | readonly UrlMatcher[];
21
+ /**
22
+ * Collector URL that batches are POSTed to (as `text/plain` JSON, which avoids
23
+ * CORS preflights). Omit to only feed plugins / `onBatch`.
24
+ */
25
+ endpoint?: string;
26
+ /** Fraction of page sessions to track, decided once at install. Unsampled sessions patch nothing. Default `1`. */
27
+ sampleRate?: number;
28
+ /**
29
+ * Fraction of fenced responses to track, decided per response. Default `1`.
30
+ * On a server one process serves every user, so `sampleRate` (per process)
31
+ * is all-or-nothing there: use this instead. Unsampled responses are left
32
+ * completely untouched.
33
+ */
34
+ responseSampleRate?: number;
35
+ /** How often to flush counts, in ms. Default `10000`. */
36
+ flushInterval?: number;
37
+ /**
38
+ * Groups requests into endpoints. Default: `METHOD /path/with/:id/segments`
39
+ * (origin included only when it differs from the page origin; query string dropped).
40
+ */
41
+ endpointKey?: (info: {
42
+ method: string;
43
+ url: URL;
44
+ }) => string;
45
+ /** Track non-2xx responses too. Default `false` (error bodies have different shapes). */
46
+ trackErrors?: boolean;
47
+ /**
48
+ * Which interception points to install. All default to `true`.
49
+ * - `fetch`: wraps `fetch` and instruments `Response#json/text/clone` for fenced URLs.
50
+ * - `xhr`: instruments `XMLHttpRequest#responseText/response` for fenced URLs.
51
+ * - `jsonParse`: lets `JSON.parse` recognise bodies that came from fenced responses
52
+ * (needed for axios, ky and anything else that parses text itself).
53
+ * - `cloneSafety`: unwraps tracking proxies before structuredClone, postMessage,
54
+ * IndexedDB writes and history state, which would otherwise throw DataCloneError.
55
+ */
56
+ intercept?: {
57
+ fetch?: boolean;
58
+ xhr?: boolean;
59
+ jsonParse?: boolean;
60
+ cloneSafety?: boolean;
61
+ };
62
+ /** Field inventory (which paths exist in responses) is what lets the dashboard show never-read fields. */
63
+ inventory?: {
64
+ /** Fraction of responses to inventory. Default `1`. Set `0` to disable. */
65
+ sampleRate?: number;
66
+ /** Array elements walked per array when inventorying. Default `100`. */
67
+ maxArrayItems?: number;
68
+ };
69
+ /** Path normalisation. */
70
+ paths?: {
71
+ /** Object keys matching any of these collapse to `{*}` (records keyed by ids). Defaults cover numeric ids, UUIDs and long hex. */
72
+ dynamicKeys?: readonly RegExp[];
73
+ /** Objects with more keys than this collapse the overflow to `{*}`. Default `256`. */
74
+ maxKeysPerObject?: number;
75
+ /** Deeper reads are not recorded. Default `32`. */
76
+ maxDepth?: number;
77
+ };
78
+ /**
79
+ * Web worker used for inventory and sending. `true` (default) uses an inline
80
+ * blob worker and falls back to the main thread if it can't start (e.g. CSP).
81
+ * Pass a URL to a self-hosted copy of `dist/worker.js`, a factory, or `false`.
82
+ */
83
+ worker?: boolean | string | URL | (() => Worker);
84
+ /** Base URL used to resolve relative `apis` roots outside browsers. Defaults to `location.href`. */
85
+ baseUrl?: string;
86
+ plugins?: readonly ProxyAnalyticsPlugin[];
87
+ onError?: (error: unknown, phase: ErrorPhase) => void;
88
+ debug?: boolean;
89
+ }
90
+ type ErrorPhase = 'request' | 'response' | 'parse' | 'track' | 'flush' | 'plugin' | 'worker';
91
+ type ReadKind = 'direct' | 'bulk';
92
+ interface RequestEvent {
93
+ readonly transport: 'fetch' | 'xhr';
94
+ readonly url: URL;
95
+ readonly method: string;
96
+ readonly endpoint: string;
97
+ /** Adds a request header. Only available to plugins; the core never adds headers. */
98
+ setHeader(name: string, value: string): void;
99
+ }
100
+ interface ResponseEvent {
101
+ readonly transport: 'fetch' | 'xhr' | 'manual';
102
+ readonly url: URL | undefined;
103
+ readonly method: string;
104
+ readonly endpoint: string;
105
+ readonly status: number;
106
+ /** Response header lookup (case-insensitive). */
107
+ header(name: string): string | null;
108
+ }
109
+ interface FirstReadEvent {
110
+ readonly endpoint: string;
111
+ readonly path: string;
112
+ readonly kind: ReadKind;
113
+ }
114
+ interface PluginApi {
115
+ readonly sessionId: string;
116
+ flush(): Promise<void>;
117
+ track<T>(data: T, options: {
118
+ endpoint: string;
119
+ }): T;
120
+ unwrap<T>(value: T): T;
121
+ }
122
+ /**
123
+ * Plugins hook into the request/response lifecycle. Every hook is optional and
124
+ * isolated: a throwing hook is reported through `onError` and skipped.
125
+ *
126
+ * Order for a fenced request:
127
+ * onRequest → (network) → onResponse → transformBody → transformData → onTrack
128
+ * then, as the app reads data: onFirstRead; and on every flush: onBatch.
129
+ */
130
+ interface ProxyAnalyticsPlugin {
131
+ readonly name: string;
132
+ /** Called once at install. May return a teardown function. */
133
+ setup?(api: PluginApi): (() => void) | undefined;
134
+ /** Before a fenced request is sent. Must be synchronous (XHR#send is). */
135
+ onRequest?(event: RequestEvent): void;
136
+ /** When a fenced response arrives. Return `false` to leave it untracked. */
137
+ onResponse?(event: ResponseEvent): boolean | undefined;
138
+ /** Rewrite the raw body before parsing (e.g. decode a compressed packet into JSON text). */
139
+ transformBody?(body: string, event: ResponseEvent): string;
140
+ /** Replace parsed data before it is wrapped for tracking. */
141
+ transformData?(data: unknown, event: ResponseEvent): unknown;
142
+ /** After a response has been wrapped for tracking. */
143
+ onTrack?(event: ResponseEvent): void;
144
+ /** First read of a path within one response. Opt-in: only wired when a plugin defines it. */
145
+ onFirstRead?(event: FirstReadEvent): void;
146
+ /** Inspect or modify a batch before it is sent. Return `false` to drop it. */
147
+ onBatch?(batch: Batch): Batch | false | undefined;
148
+ }
149
+ /**
150
+ * Read counters for one path: [pathIndex, anyRead, directRead, bulkRead].
151
+ * Each counter is the number of responses (not reads) in which that kind of
152
+ * read happened, so a list of 500 products whose `price` is rendered counts
153
+ * as one response reading `items[*].price`.
154
+ */
155
+ type ReadTuple = [path: number, any: number, direct: number, bulk: number];
156
+ /** [pathIndex, responsesContainingPath] */
157
+ type PresenceTuple = [path: number, count: number];
158
+ interface EndpointBatch {
159
+ /** Endpoint key, e.g. `GET /api/products/:id`. */
160
+ key: string;
161
+ /** Responses tracked in this window. */
162
+ responses?: number;
163
+ reads?: ReadTuple[];
164
+ /** Responses inventoried in this window (the denominator for `present`). */
165
+ inventoried?: number;
166
+ present?: PresenceTuple[];
167
+ }
168
+ interface Batch {
169
+ v: 1;
170
+ /** Random per-page-session id. */
171
+ sid: string;
172
+ /** Milliseconds since epoch at send time. */
173
+ ts: number;
174
+ /** Session sample rate, so collectors can scale counts. */
175
+ rate: number;
176
+ /** Path dictionary referenced by index from `reads` / `present`. */
177
+ paths: string[];
178
+ endpoints: EndpointBatch[];
179
+ /** Free-form plugin data. */
180
+ meta?: Record<string, unknown>;
181
+ }
182
+ interface ProxyAnalytics {
183
+ /** `false` when this session was not sampled (nothing is patched). */
184
+ readonly enabled: boolean;
185
+ readonly sessionId: string;
186
+ /** Send pending counts now. */
187
+ flush(): Promise<void>;
188
+ /** Restore every patched global and stop timers. */
189
+ uninstall(): void;
190
+ /** Manually track data that didn't come through fetch/XHR (WebSocket messages, SDK results, ...). */
191
+ track<T>(data: T, options: {
192
+ endpoint: string;
193
+ }): T;
194
+ }
195
+
196
+ /**
197
+ * Sends pending counts from the installed instance, if any. Works from any
198
+ * module in the process, which matters on servers: Next.js loads
199
+ * `instrumentation.ts` and route code as separate bundles, so the handle that
200
+ * `install()` returned isn't reachable from a route. Call it where the platform
201
+ * keeps the function alive after the response (`after(flush)` in Next.js,
202
+ * `ctx.waitUntil(flush())` on edge-style hosts).
203
+ */
204
+ declare function flush(): Promise<void>;
205
+ /**
206
+ * Starts tracking. Only responses from `apis` (minus `ignore`) are touched;
207
+ * every other request passes straight through to the native implementation.
208
+ *
209
+ * ```ts
210
+ * const analytics = install({
211
+ * apis: 'https://api.shop.com/v2',
212
+ * endpoint: 'https://collector.shop.com/collect',
213
+ * })
214
+ * ```
215
+ */
216
+ declare function install(options: ProxyAnalyticsOptions): ProxyAnalytics;
217
+
218
+ /**
219
+ * Endpoint keys for PostgREST, the REST layer behind Supabase
220
+ * (`/rest/v1/<table>?select=...`).
221
+ *
222
+ * Each table + select list becomes its own endpoint, so one report row maps to
223
+ * one query in code (`supabase.from('cases').select('*')` →
224
+ * `GET cases?select=*`). Filters, ordering and paging are dropped. RPC calls
225
+ * keep their function name (`POST rpc/search_cases`). Anything outside
226
+ * `/rest/v1/` falls back to `METHOD /path`.
227
+ *
228
+ * ```ts
229
+ * install({ apis: `${SUPABASE_URL}/rest/v1`, endpointKey: postgrestEndpointKey })
230
+ * ```
231
+ */
232
+ declare function postgrestEndpointKey({ method, url }: {
233
+ method: string;
234
+ url: URL;
235
+ }): string;
236
+
237
+ /** Identity helper for authoring plugins with full type inference. */
238
+ declare function definePlugin<P extends ProxyAnalyticsPlugin>(plugin: P): P;
239
+
240
+ declare const DEFAULT_DYNAMIC_KEYS: readonly RegExp[];
241
+
242
+ /** True if `value` is a tracking proxy. */
243
+ declare function isTracked(value: unknown): boolean;
244
+ /**
245
+ * Returns `value` with every tracking proxy replaced by its raw data. Untouched
246
+ * subtrees are shared, not copied. Reading through this function is never
247
+ * recorded. Use it before handing data to APIs that structured-clone.
248
+ */
249
+ declare function unwrap<T>(value: T): T;
250
+
251
+ /** `GET /api/products/123?x=1` → `GET /api/products/:id` (origin kept only if foreign). */
252
+ declare function defaultEndpointKey(method: string, url: URL, pageOrigin: string | undefined): string;
253
+
254
+ export { DEFAULT_DYNAMIC_KEYS, defaultEndpointKey, definePlugin, flush, install, isTracked, postgrestEndpointKey, unwrap };
255
+ export type { Batch, EndpointBatch, ErrorPhase, FirstReadEvent, PluginApi, PresenceTuple, ProxyAnalytics, ProxyAnalyticsOptions, ProxyAnalyticsPlugin, ReadKind, ReadTuple, RequestEvent, ResponseEvent, UrlMatcher };