@keploy/capture-sdk 3.0.1

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 ADDED
@@ -0,0 +1,482 @@
1
+ # @keploy/capture-sdk
2
+
3
+ The browser SDK for [Keploy UI Flow Capture](https://keploy.io/docs/ui-capture/overview/).
4
+ It records what a real user does in your web app — the DOM through
5
+ [rrweb](https://github.com/rrweb-io/rrweb), and every `fetch` and
6
+ `XMLHttpRequest` exchange the page makes — masks personal data before
7
+ anything leaves the browser, and posts the recording in batches to
8
+ Keploy. Keploy turns the recordings into deduplicated flows and, from
9
+ those, into Playwright tests that replay against recorded mocks.
10
+
11
+ This package runs inside your bundle, on your users' machines, which is
12
+ why it is **Apache-2.0** while the rest of the product is proprietary.
13
+ It is the only part of UI Flow Capture on npm: the tests are generated
14
+ and run by the `keploy` binary, not by another package.
15
+
16
+ ## What ships today
17
+
18
+ **The version is the git tag's** -- the committed manifest says
19
+ `0.0.0-tag` and the release lane writes the tag's version in before it
20
+ publishes (`RELEASING.md` in the repository; `sdk.version` on every
21
+ batch is that number). **The pipeline behind the SDK is mid-migration.**
22
+ The SDK
23
+ records, masks and posts as this page describes. What happens to a
24
+ recording after it arrives does not all exist yet: the ingest route and
25
+ the app-bound keys it needs are on an unmerged branch of the Keploy API
26
+ server, so no deployment has them; flow extraction writes one
27
+ placeholder flow with no steps; **Generate Test** produces no files and
28
+ **Run Test** executes nothing. The
29
+ [overview](https://keploy.io/docs/ui-capture/overview/) has the
30
+ part-by-part list under "What ships today", and the screenshots below
31
+ show what the dashboard will do with a recording, not what today's
32
+ pipeline produces from one.
33
+
34
+ Those docs pages, and the images below, publish with the docs release
35
+ that accompanies this package. If you are reading this before that
36
+ lands, they 404; [support@keploy.io](mailto:support@keploy.io) has the
37
+ current state.
38
+
39
+ ## What you get
40
+
41
+ Recorded sessions become flows in the Keploy dashboard:
42
+
43
+ ![The UI Flows list: each flow with its page path, step count, how many sessions matched it, and its verdict on the last run](https://raw.githubusercontent.com/keploy/docs/main/static/img/ui-capture/flows.png)
44
+
45
+ Each flow is the sequence of steps a user took, with every network call
46
+ those steps made recorded beside them:
47
+
48
+ ![A flow's detail page: the recorded steps down the left, the network calls captured for the flow on the right](https://raw.githubusercontent.com/keploy/docs/main/static/img/ui-capture/flow-detail-full.png)
49
+
50
+ And every run of the generated tests reports one verdict per flow —
51
+ `passed`, `failed`, `blocked`, and the rest of the
52
+ [closed verdict set](https://keploy.io/docs/ui-capture/overview/):
53
+
54
+ ![The test runs page: one row per run with its per-flow verdicts and the worst-wins rollup](https://raw.githubusercontent.com/keploy/docs/main/static/img/ui-capture/test-runs.png)
55
+
56
+ ## Install
57
+
58
+ ```
59
+ npm install @keploy/capture-sdk
60
+ ```
61
+
62
+ A runtime dependency, not a dev one: it runs in production, on the
63
+ page. Its only dependency is `rrweb`, which your bundler resolves; there
64
+ are no peer dependencies. The package ships ESM and CommonJS
65
+ (`dist/index.mjs`, `dist/index.js`) with types. The bundle is 26.2 kB
66
+ (decimal) gzipped with rrweb excluded — MEASURED on the publish build
67
+ (`tsup src/index.ts`), and a test holds both that figure and the 30 KiB
68
+ ceiling this package is budgeted at. There is no script-tag build: the
69
+ only way in is an `import`.
70
+
71
+ ## Use
72
+
73
+ One call, as early in your app's startup as you can make it:
74
+
75
+ ```ts
76
+ import { KeployCapture } from "@keploy/capture-sdk";
77
+
78
+ await KeployCapture.init({
79
+ endpoint: "https://api.keploy.io/ui/v1/ingest",
80
+ apiKey: "<your app's UI ingest key>",
81
+ });
82
+ ```
83
+
84
+ `endpoint` is the ingest route of the Keploy API server your workspace
85
+ uses. `apiKey` is sent as the `X-API-Key` header on every batch. It is
86
+ a **UI ingest key**: issued for one app, it can post recordings into
87
+ that app and do nothing else — no reads, no other API — which is what
88
+ makes it safe to ship inside a page every visitor can read. Do not put
89
+ any other kind of Keploy credential here.
90
+
91
+ Those two are the only required fields. The others, with the value the
92
+ SDK uses when you leave them out:
93
+
94
+ | option | default | what it does |
95
+ | -------------------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
96
+ | `privacyMode` | `"balanced"` | `"balanced"` masks every typed input value; `"strict"` also masks every visible text node; `"off"` masks only password and hidden fields — see [Privacy](#privacy) |
97
+ | `sampleRate` | `1` | fraction of sessions recorded, decided once when a session starts. `0.1` records one visitor in ten; the rest never start |
98
+ | `networkCapture` | `true` | record `fetch` and `XMLHttpRequest` exchanges. `false` records the DOM only |
99
+ | `maxSessionDuration` | `600000` | milliseconds after which the capture ends on its own (10 minutes): recording stops, the queue is flushed, and a later `init()` starts a new session |
100
+ | `batchSize` | `50` | events per POST, as a ceiling: clamped to 5000, the most the ingest server accepts in one batch, and a batch is also cut at the server's 10 MiB body cap, so large events make more, smaller POSTs rather than one the server would refuse |
101
+ | `batchInterval` | `5000` | milliseconds between flushes. Each flush sends ONE batch, so a backlog drains at a batch per interval |
102
+ | `maxQueueSize` | `5000` | events held in memory while waiting to send; past this the oldest are dropped |
103
+ | `maxBodySize` | `524288` | how much of a request or response body is recorded (512 KB), counted in UTF-16 code units — see [What a large body looks like](#what-a-large-body-looks-like) |
104
+ | `maskSelectors` | — | CSS selectors whose matched elements have their text masked, including every text node below them. Input values are decided by `privacyMode` alone |
105
+ | `unmaskSelectors` | — | CSS selectors whose text is left in the clear, overriding `maskSelectors` and `"strict"` for the subtree below them. It cannot unmask an input value |
106
+ | `privacy` | — | a `Partial<PrivacyConfig>`: `maskSelectors`, `unmaskSelectors`, `blockSelectors`, `maskNetworkBodies`, `sensitiveHeaders`, `piiPatterns` — see [Privacy](#privacy) |
107
+ | `sessionIdGenerator` | — | supply your own session id instead of the SDK's UUID v4, to correlate with your own systems. It must be a string of 1-200 characters of letters, digits, dot, dash and underscore with no empty dot-separated segment (`tenant-7.user_42.run-3`; encode a `user:42/session 1` first) — the SDK checks what the generator produces before sending and refuses to start on anything else, a throw included (`KUI_E_SESSION_ID_INVALID`). Two live sessions with one id are refused by the server (a terminal `409`) |
108
+ | `onError` | — | called once when a terminal condition ends the capture — see [When the server rejects a batch](#when-the-server-rejects-a-batch) |
109
+
110
+ After `init`, the static surface is:
111
+
112
+ ```ts
113
+ KeployCapture.pause(); // keep the session, stop emitting events
114
+ KeployCapture.resume();
115
+ KeployCapture.getSessionId(); // "" when no session is live
116
+ KeployCapture.getCaptureIdentity(); // the browser half of the backend join, or why there is none
117
+ KeployCapture.stop(); // stop recording and send what is queued
118
+ ```
119
+
120
+ `init` returns the same instance on a second call; `stop` clears it so
121
+ a later `init` starts a new session.
122
+
123
+ A hidden tab pauses DOM recording and nothing else — the exchanges the
124
+ page makes are still recorded, because the page still makes them and
125
+ they are what a replay needs. When the tab comes back, the SDK takes a
126
+ fresh full snapshot **only if the paused recording dropped something**:
127
+ rrweb has no pause, so it kept observing while the tab was hidden, and
128
+ the mutations that were dropped would otherwise leave the events after
129
+ them naming nodes the recording never showed. A hide that dropped
130
+ nothing has nothing to re-baseline and takes none, so a visitor who
131
+ alt-tabs thirty times on a page that is not mutating uploads no
132
+ snapshots for it. `pause()` is the stronger one and stops everything,
133
+ and `resume()` re-snapshots under the same condition.
134
+
135
+ What network capture **is** gated on is the rrweb import. `init()`
136
+ awaits `import("rrweb")` before it patches `fetch` and
137
+ `XMLHttpRequest`, and in your bundle that is normally a separate chunk
138
+ fetched over the network. Until the import resolves, `fetch` and
139
+ `XMLHttpRequest` are still the browser's own: a request the page makes
140
+ in that window is not recorded at all, in a hidden tab exactly as in a
141
+ visible one. Calling `init()` as early in startup as you can narrows
142
+ that window; nothing closes it.
143
+
144
+ ## Privacy
145
+
146
+ Masking happens in the browser, before transport. Nothing here can be
147
+ undone on the server, because the server never sees the original.
148
+
149
+ **In the DOM.** `privacyMode` sets what rrweb records.
150
+
151
+ | input type | `balanced` | `strict` | `off` |
152
+ | ------------------------------------------------------------------------------------------------------------------------------ | ---------- | -------- | ------ |
153
+ | `password` | masked | masked | masked |
154
+ | `hidden` | masked | masked | masked |
155
+ | `color`, `date`, `datetime-local`, `email`, `file`, `month`, `number`, `range`, `search`, `tel`, `text`, `time`, `url`, `week` | masked | masked | kept |
156
+ | `<textarea>`, `<select>` | masked | masked | kept |
157
+ | visible text nodes | kept | masked | kept |
158
+
159
+ `hidden` is masked in every mode, `off` included: a hidden field is
160
+ machinery the user never sees or types into — a CSRF token, a session
161
+ id, an internal record id — so `off`, which is about what the user
162
+ typed, is not asking for it.
163
+
164
+ `file` is the name of the file the person picked — rrweb records the
165
+ input's value, and that value is `C:\fakepath\Resume_John_Smith.pdf`
166
+ once a file is chosen. It follows the mode like anything else the
167
+ person entered.
168
+
169
+ Those two are the reason this SDK hands rrweb its own map: rrweb's
170
+ `maskAllInputs` covers the other sixteen rows and neither of these.
171
+
172
+ `radio`, `checkbox`, `submit`, `button`, `reset` and `image` are **not**
173
+ in that table: their `value` is recorded verbatim in every mode,
174
+ `strict` included. For the first four nothing can reach it —
175
+ rrweb serialises those four before masking is consulted, so no option
176
+ this SDK could pass would change them. `reset` and `image` could be
177
+ masked and deliberately are not: a reset button's value is the caption
178
+ it shows, and an image button's is metadata the page's author wrote,
179
+ neither being anything the person using the page entered. For the
180
+ others the value is usually a label too. When it is not — a checkbox
181
+ whose value is an email address, say — the only lever is
182
+ `privacy.blockSelectors`, and that removes the element from the
183
+ recording altogether.
184
+
185
+ `privacy.blockSelectors` names elements whose content is never
186
+ recorded — a video, a chat widget, a wall of customer names — rrweb
187
+ records an empty box of the same size in their place.
188
+
189
+ `maskSelectors` masks the text of the elements it matches and of
190
+ everything below them; `unmaskSelectors` is the exception to both it
191
+ and `strict`, for the subtree below what it matches. Both are text
192
+ only: nothing you can name a selector for will un-mask an input value.
193
+ Each has a top-level spelling and a `privacy.` one, and the two lists
194
+ are merged rather than one taking precedence.
195
+
196
+ **On the network.** For every recorded exchange:
197
+
198
+ - Headers named in `privacy.sensitiveHeaders` have their values
199
+ replaced with `[REDACTED]`. The default list is `authorization`, `cookie`,
200
+ `set-cookie`, `x-api-key`, `x-auth-token` and `proxy-authorization`;
201
+ a list you pass **extends** it and cannot shrink it: those six are
202
+ redacted whatever you configure, because no redacted header value is
203
+ ever needed for replay. Every other header value is scanned for the
204
+ PII patterns below.
205
+ - Request and response bodies are redacted structurally: JSON is
206
+ parsed and every value under a sensitive key — `password`, `token`,
207
+ `secret`, `apikey`, `session`, `cookie`, `ssn`, `cardnumber`, `cvv`
208
+ and the rest of that family, including suffix forms like
209
+ `userPassword` and `authToken` — is replaced, then the JSON is
210
+ re-serialised so the recording still parses. Other bodies are scanned
211
+ as text for JWTs, email addresses, SSNs, phone numbers, IPv4
212
+ addresses and card numbers. `privacy.maskNetworkBodies: true` replaces every body
213
+ wholesale with `[MASKED]` instead.
214
+ - URLs keep their path — it is what the replay key is computed from —
215
+ and the values of query parameters named like `token`, `password`,
216
+ `secret`, `apikey`, `signature` or `sessionid` are redacted by name.
217
+ The fragment (`#...`) is dropped entirely: it never reaches a server,
218
+ so no replay needs it, and single-page routers put user state there.
219
+
220
+ The built-in patterns match JWTs, email addresses, US phone numbers,
221
+ US social-security numbers and IPv4 addresses; card numbers are
222
+ detected structurally (issuer prefix, length and Luhn), because a
223
+ length-only pattern matched every 13-digit timestamp. The same set runs
224
+ over header values, over string values inside JSON bodies, and over
225
+ non-JSON bodies as a whole — one scanner, three places.
226
+
227
+ `privacy.piiPatterns: [{ name, pattern }]` adds your own, and they run
228
+ wherever that scanner does. Every occurrence is replaced whether or not
229
+ your pattern carries `g`, and never a JSON key or a number, so the body
230
+ still parses.
231
+
232
+ They do **not** run over URLs, and that is deliberate: the path and the
233
+ query values are what the replay key is computed from, so rewriting
234
+ them makes the recording unmatchable. Put an identifier that must be
235
+ scrubbable by pattern in a header or the body.
236
+
237
+ `PrivacyEngine` is exported if you want to run the same masking on
238
+ your own strings:
239
+
240
+ ```ts
241
+ import { PrivacyEngine } from "@keploy/capture-sdk";
242
+
243
+ new PrivacyEngine().maskText("contact user@example.com now"); // "contact [REDACTED] now"
244
+ ```
245
+
246
+ ## What a large body looks like
247
+
248
+ `maxBodySize` is a bound on what is recorded, not an exact byte
249
+ budget: it counts UTF-16 code units, which is what a JS string is
250
+ measured in — equal to bytes for ASCII and up to 2x under it for
251
+ multi-byte text. Counting bytes would mean encoding every body the page
252
+ sends just to decide whether to keep it.
253
+
254
+ Over the bound, there are three answers, not one:
255
+
256
+ - **Text the SDK read** is cut at the bound and marked
257
+ `...[truncated]`.
258
+ - **A cut body that was JSON** no longer parses. There is no safe way
259
+ to redact a fragment — the defect this replaced was a pattern
260
+ matching inside a serialised number, turning `{"ts":1699999999999}`
261
+ into `{"ts":[REDACTED]}`, which no longer parses either — so it is
262
+ refused whole and recorded as `[UNPARSEABLE_BODY_NOT_REDACTED]`.
263
+ Never partly redacted, and never left in the clear.
264
+ - **A body the SDK does not read** is recorded as a note naming what
265
+ it was, with a size where there is one to give. Not every note has
266
+ one: a streaming request body cannot be sized without consuming it,
267
+ and the notes for a response that could not be read as text and for
268
+ a body the SDK never read carry none either. Where a note does carry
269
+ a size it is the figure the SDK had, not always a measurement —
270
+ `[Response body too large: N bytes]` repeats the server's
271
+ `Content-Length` for a body it never downloaded. So a note is not a
272
+ way to size a body against `maxBodySize`. There are seven, one for
273
+ each way a body can be one the SDK does not read:
274
+ - `[Blob: N bytes, truncated]` — a `fetch` Blob over the bound.
275
+ - `[Blob: N bytes]` — any Blob sent through `XMLHttpRequest`, which
276
+ serialises its body inside `send()`, where reading a Blob (an async
277
+ call) would mean holding the request up.
278
+ - `[Binary: N bytes]` — a buffer over the bound, or one that is not
279
+ UTF-8 text. A buffer that is text and fits is recorded as that
280
+ text.
281
+ - `[Response body too large: N bytes]` — from a `Content-Length` over
282
+ the bound, so the body is never downloaded.
283
+ - `[ReadableStream]` — a streaming request body, which reading would
284
+ consume out from under your app. No size: measuring a stream means
285
+ consuming it too.
286
+ - `[<responseType> response]` — an `XMLHttpRequest` whose
287
+ `responseType` makes `responseText` throw. No size: the response
288
+ is there in a form this note does not measure.
289
+ - `[Unreadable body]` — the fail-closed answer: a body that could not
290
+ be read at all is never passed through. No size: nothing here was
291
+ read, so there was nothing to measure.
292
+
293
+ Lower `maxBodySize` to save bandwidth and you will get the second
294
+ answer for most large JSON, not a shorter body. If you need the shape
295
+ of a large response more than its contents, that is the trade.
296
+
297
+ ## What leaves the browser
298
+
299
+ Each POST carries: the session id; a batch of events — rrweb DOM events
300
+ and the masked network exchanges (method, URL, headers, bodies, status,
301
+ duration); the page metadata (URL, user agent, viewport, referrer,
302
+ language, device pixel ratio, start time); the SDK name and version;
303
+ and the capture identity that lets Keploy join this recording to a
304
+ backend recording of the same requests — the session id, the page's
305
+ origin, a start timestamp, and a nonce minted with
306
+ `crypto.getRandomValues` or not at all (without a CSPRNG the recording
307
+ is still made; it is just not joinable). Payloads are gzipped when the
308
+ browser has `CompressionStream`.
309
+
310
+ The metadata and the capture identity ride on **every** batch, not just
311
+ the first. A batch is the only thing the server is guaranteed to
312
+ receive, and either of them arriving only with the first one is lost
313
+ whenever that batch is the one that fails. They are a few hundred bytes
314
+ against a batch of up to 50 events.
315
+
316
+ Nothing is sent to anyone but the `endpoint` you configured.
317
+
318
+ An event that `JSON.stringify` refuses never leaves at all — a custom
319
+ event holding a circular reference or a `BigInt`. Every event is
320
+ measured as it is queued, so such an event is dropped there rather
321
+ than thrown back into the code that emitted it; so is an event that
322
+ alone is over the ingest server's 10 MiB body cap (an rrweb snapshot
323
+ of a very large page, a captured body under a raised `maxBodySize`),
324
+ which no batch could carry. The first of each kind in a capture logs a
325
+ `console.error`; any after it are dropped silently, because an emitter in a render loop
326
+ would otherwise write a line every few milliseconds into the page the
327
+ SDK is there to record. `onError` is not called — that is reserved
328
+ for a condition that ENDS the capture, and this session goes on
329
+ without the event. So a recording is complete only for what
330
+ serialises and fits, and that one console line is the whole of the
331
+ notice — which is why it carries a code and its evidence:
332
+
333
+ ```
334
+ [keploy] KUI_E_EVENT_OVERSIZED: dropped an event: 11059200 bytes in a body, over the ingest server's 10485760-byte cap, so no batch could carry it. The capture continues; any further such events in this capture are dropped silently. evidence={"eventId":"7","eventType":"dom","bytes":11059200,"cap":10485760}
335
+ ```
336
+
337
+ `KUI_E_EVENT_UNSERIALISABLE` (evidence `eventId`, `eventType`,
338
+ `reason`) and `KUI_E_EVENT_OVERSIZED` (evidence `eventId`,
339
+ `eventType`, `bytes`, `cap`) are warning-severity entries of the same
340
+ error corpus as the codes above, and `SDK_WARNINGS` is the SDK's copy
341
+ of their summaries and remedies; a program that only has the console
342
+ can match the token and parse the JSON after the first `evidence=`
343
+ (the line is one line, and nothing before the marker is yours: the
344
+ event's id and type are in the JSON, not in the prose). A new
345
+ `init()` starts a new count: once per capture, not once per page.
346
+
347
+ ### The last batch
348
+
349
+ When the page unloads — a navigation, a tab close — whatever is still
350
+ queued is sent in one `keepalive` request from the `pagehide` handler.
351
+ Browsers cap the sum of a document's in-flight keepalive bodies at
352
+ 64 KiB (MEASURED in Chromium 145: 65,536 bytes accepted, 65,537
353
+ refused), and a request over that is refused before it leaves, losing
354
+ everything in it. So that last request is cut at the first event that
355
+ does not fit, oldest first, and what does not fit stays behind — an
356
+ event held back is one whose node ids the events after it depend on,
357
+ so shipping past it would be worse than stopping there.
358
+
359
+ What **is** guaranteed: every event the SDK has accepted and not yet
360
+ posted is visible to that last request, including a batch the transport
361
+ had already taken off the queue and not yet sent (one being gzipped, or
362
+ waiting out a retry backoff). It is put back at the front so the cut
363
+ sees the session in order.
364
+
365
+ What is **not**: a request already on the wire when the document dies.
366
+ A keepalive request survives the document, so it usually arrives — but
367
+ if it does not, the SDK cannot know and cannot resend it. And an event
368
+ whose JSON, with the envelope that wraps it, exceeds the 64 KiB cap
369
+ cannot travel this way at all; the SDK posts such an event the moment
370
+ it is queued rather than leaving it to be cut here — but not while the
371
+ browser reports itself offline. The post is deferred then to the
372
+ `online` event, which drains the queue rather than sending the one
373
+ batch a timed flush sends. A navigation before that event still runs
374
+ the unload flush, and this event is precisely what that flush cannot
375
+ carry: it is lost, with everything queued behind it and anything ahead
376
+ of it that does not fit the single batch that flush sends — the
377
+ failure the immediate post exists to close, open for as long as the
378
+ browser says it is offline. And on a slow uplink a navigation can still cancel the
379
+ post that did go out. `maxBodySize` bounds a network event's size, and
380
+ `privacy.blockSelectors` keeps subtrees out of the DOM snapshot.
381
+
382
+ ## When the server rejects a batch
383
+
384
+ A `4xx` other than `429` is terminal: a revoked key, a key for another
385
+ app, or a second run claiming a session id that is already live. The
386
+ SDK ends the CAPTURE — recording stops, `fetch` and `XMLHttpRequest`
387
+ are unpatched, and the singleton is released — logs a `console.error`
388
+ carrying the server's own explanation, and calls `onError` once with a
389
+ `CaptureError`. It does not retry into a permanent rejection and it
390
+ does not quietly produce an empty recording; and because the singleton
391
+ is released, a later `init()` with a working key starts a new session
392
+ rather than handing back the one that failed.
393
+
394
+ The `CaptureError` is for the program, not just the person reading the
395
+ console. Branch on `code`, never on the message:
396
+
397
+ | `code` | the server answered | what to do (`remedy.manual`, in short) |
398
+ | --------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
399
+ | `KUI_E_INGEST_KEY_REJECTED` | 401 or 403 | the key is missing, unknown, expired, revoked, or not a UI ingest key (a personal access token is refused) — mint one with the api-server GraphQL mutation `createUIIngestKey(appId, name, ttlDays)` and pass it as `apiKey` |
400
+ | `KUI_E_INGEST_ENDPOINT_NOT_FOUND` | 404 or 405 | `endpoint` is wrong, not the key — the ingest route is `<api-server>/ui/v1/ingest`. Only a typo under `/ui/v1/` or a same-origin proxy produces this; a wrong endpoint on another origin fails its CORS preflight, which the SDK can only retry as a network error, so silence is not proof the endpoint is right |
401
+ | `KUI_E_SESSION_CONFLICT` | 409 | this session id is already claimed — give each run its own, usually by removing a fixed-value `sessionIdGenerator` |
402
+ | `KUI_E_INGEST_REJECTED` | any other terminal 4xx | read `serverMessage`; `ui session has reached its size limit` means stop and re-init for a new session, anything else is an SDK/server version mismatch (the SDK checks the session id, clamps `batchSize` and cuts every batch at the 10 MiB body cap before sending, so nothing you configure produces one) and `issues` names the field |
403
+ | `KUI_E_SESSION_ID_INVALID` | nothing — raised before the first byte | `sessionIdGenerator` returned a string outside the server's rule (`evidence.rule`), returned a non-string, or threw — `evidence.received` says which; make it return a string inside the rule, or remove the override |
404
+
405
+ `onError` receives one of two subclasses of `CaptureError`, and
406
+ branching on `code` narrows to it, so a TypeScript handler can read the
407
+ evidence the remedy names. An `IngestRejection` (the four
408
+ server-answered codes) carries `status`, `serverMessage` (the `error`
409
+ field of the server's JSON body, or the body's text, or `null`),
410
+ `issues` (the server's `[{ path, message }]` when its body had them — a
411
+ 400 says which field — or `null`), `remedy` (`{ command, manual }` —
412
+ `command` is `null` on all five, because no build has a verb that mints
413
+ a key, edits the endpoint or rotates a session), and `evidence`
414
+ (`{ status, serverMessage, endpoint, sessionId }` plus `issues` when
415
+ sent, exactly the fields the corpus declares). A `SessionIdRefusal`
416
+ (`KUI_E_SESSION_ID_INVALID`) is raised by the SDK itself before anything
417
+ is sent, so its `status` is `null` and its evidence is
418
+ `{ sessionId, received, rule }` — the string the generator returned or
419
+ `null`, what it produced (`number 42`, `object {}`, `threw Error: boom`),
420
+ and the rule. The five codes, their summaries, remedies and evidence
421
+ are the entries of the same name in `@keploy/contract`'s error corpus;
422
+ the SDK carries a copy because rrweb is its only runtime dependency,
423
+ and a test holds the copy to the corpus. The status-to-code mapping is
424
+ `spec/sdk-errors.v1.json`; the session-id rule is
425
+ `spec/session-id.v1.json`, the api-server's rule stated once — the
426
+ SDK and the sidecar execute the file today, and the api-server's own
427
+ executor lands with its next vendoring of the corpus. `onError` runs
428
+ after the capture has ended and the singleton is released, so a handler
429
+ may call `init()` again and get a fresh capture:
430
+
431
+ ```ts
432
+ import { KeployCapture } from "@keploy/capture-sdk";
433
+
434
+ await KeployCapture.init({
435
+ endpoint,
436
+ apiKey,
437
+ onError: (err) => {
438
+ if (err.code === "KUI_E_SESSION_ID_INVALID")
439
+ fixGenerator(err.evidence.received);
440
+ else if (err.code === "KUI_E_INGEST_KEY_REJECTED") rotateKeyAndReload();
441
+ else
442
+ report(
443
+ err.code,
444
+ err.serverMessage,
445
+ err.evidence.issues,
446
+ err.remedy.manual,
447
+ );
448
+ },
449
+ });
450
+ ```
451
+
452
+ A `429`, a `5xx` or a network failure gets three attempts:
453
+ up to 1 s between the first and the second, up to 2 s between the
454
+ second and the third, and then — if the third fails too — up to a
455
+ further 4 s before the batch goes back to the front of the queue. Two
456
+ gaps between three attempts; the last wait delays the re-queue rather
457
+ than an attempt.
458
+
459
+ ## What it deliberately does not do
460
+
461
+ - **No replay, no assertions, no selectors.** The SDK records raw and
462
+ never normalises what it saw; the server does that once at ingest, so
463
+ record time and replay time cannot disagree.
464
+ - **No `Math.random` fallback for the session nonce**, so a recording
465
+ is either joinable or says why it is not.
466
+ - **No sampling by user.** `sampleRate` is decided per session start.
467
+
468
+ ## Docs and help
469
+
470
+ - [UI Flow Capture overview](https://keploy.io/docs/ui-capture/overview/) — how recordings
471
+ become flows, generated tests and verdicts
472
+ - [Installing the SDK](https://keploy.io/docs/ui-capture/install-sdk/) — this page, in
473
+ more detail
474
+ - [Keploy documentation](https://keploy.io/docs/)
475
+ - [Keploy community Slack](https://join.slack.com/t/keploy/shared_invite/zt-3zcnuqfgl-WYK1NMhslVHsCtNcA1ULwA)
476
+ - <support@keploy.io>
477
+
478
+ ## License
479
+
480
+ Apache-2.0. The full text ships in this package: see
481
+ [LICENSE](./LICENSE). The rest of Keploy UI Flow Capture is
482
+ proprietary; this package is the part that runs in your own bundle.
package/dist/auto.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { KeployCapture } from "./index";
2
+ import type { CaptureConfig } from "./types";
3
+ declare global {
4
+ interface Window {
5
+ __KEPLOY_CONFIG__?: Partial<CaptureConfig>;
6
+ KeployCaptureSDK?: typeof KeployCapture;
7
+ }
8
+ }