@keploy/capture-sdk 3.0.1 → 3.1.0-rc.2

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.
Files changed (55) hide show
  1. package/README.md +1617 -130
  2. package/body-redact/package.json +6 -0
  3. package/body-worker-start/package.json +6 -0
  4. package/dist/body-jobs.d.ts +134 -0
  5. package/dist/body-redact.d.ts +23 -0
  6. package/dist/body-redact.js +1 -0
  7. package/dist/body-redact.js.map +1 -0
  8. package/dist/body-redact.mjs +1 -0
  9. package/dist/body-redact.mjs.map +1 -0
  10. package/dist/body-worker-none.d.ts +3 -0
  11. package/dist/body-worker-none.js +1 -0
  12. package/dist/body-worker-none.js.map +1 -0
  13. package/dist/body-worker-none.mjs +1 -0
  14. package/dist/body-worker-none.mjs.map +1 -0
  15. package/dist/body-worker-start.d.ts +3 -0
  16. package/dist/body-worker-start.js +1 -0
  17. package/dist/body-worker-start.js.map +1 -0
  18. package/dist/body-worker-start.mjs +1 -0
  19. package/dist/body-worker-start.mjs.map +1 -0
  20. package/dist/body-worker-unbundled.d.ts +1 -0
  21. package/dist/body-worker-unbundled.mjs +1 -0
  22. package/dist/body-worker-unbundled.mjs.map +1 -0
  23. package/dist/body-worker.d.ts +1 -0
  24. package/dist/body-worker.js +1 -0
  25. package/dist/body-worker.js.map +1 -0
  26. package/dist/errors.d.ts +224 -28
  27. package/dist/index.bundler.mjs +1 -0
  28. package/dist/index.bundler.mjs.map +1 -0
  29. package/dist/index.d.ts +23 -28
  30. package/dist/index.js +1 -2354
  31. package/dist/index.js.map +1 -0
  32. package/dist/index.mjs +1 -2297
  33. package/dist/index.mjs.map +1 -0
  34. package/dist/leave.d.ts +67 -0
  35. package/dist/module-of.d.ts +58 -0
  36. package/dist/network.d.ts +163 -4
  37. package/dist/privacy.d.ts +387 -12
  38. package/dist/recorder.d.ts +304 -64
  39. package/dist/redact.d.ts +48 -6
  40. package/dist/request-term.d.ts +23 -0
  41. package/dist/request-term.js +1 -0
  42. package/dist/request-term.js.map +1 -0
  43. package/dist/request-term.mjs +1 -0
  44. package/dist/request-term.mjs.map +1 -0
  45. package/dist/strict-attributes.d.ts +9 -0
  46. package/dist/strict-attributes.js +1 -0
  47. package/dist/strict-attributes.js.map +1 -0
  48. package/dist/strict-attributes.mjs +1 -0
  49. package/dist/strict-attributes.mjs.map +1 -0
  50. package/dist/term-candidate.d.ts +16 -0
  51. package/dist/transport.d.ts +269 -130
  52. package/dist/types.d.ts +152 -9
  53. package/package.json +37 -4
  54. package/request-term/package.json +6 -0
  55. package/strict-attributes/package.json +6 -0
@@ -1,4 +1,39 @@
1
1
  import type { CaptureConfig, SessionEvent, SessionMetadata } from "./types";
2
+ import { DomRecorderRefusal, StrictAttributesRefusal } from "./errors";
3
+ /** Exposed for tests: reactions on rrweb's held import, and the recorders they tell. */
4
+ export declare const __landing: {
5
+ reactions: () => number;
6
+ landers: () => number;
7
+ };
8
+ /**
9
+ * What moved the page to a new URL: the `cause` of the route Meta event the
10
+ * recorder writes (rrweb's own Meta, on a load or a returning tab, has none).
11
+ * "push" and "replace": a navigation that added or replaced a history entry
12
+ * -- history.pushState or replaceState (a replace that changes the URL is a
13
+ * redirect), or, where the Navigation API reports it, one the page made
14
+ * another way. "traverse": a move through the session history -- the
15
+ * browser's Back or Forward, or the page's own history.back() or go().
16
+ * "hash": a fragment navigation the History API did not make -- a link to
17
+ * `#/orders`, `location.hash = ...` -- told only where the browser has the
18
+ * Navigation API; without it such a navigation reads as "traverse".
19
+ */
20
+ export type NavigationCause = "push" | "replace" | "traverse" | "hash";
21
+ /**
22
+ * Who asked for a traversal, where the SDK saw it asked: "script" when the
23
+ * page's own script called history.back(), forward() or go(), or the
24
+ * Navigation API's navigation.back(), forward() or traverseTo(), for it. The
25
+ * route Meta carries it as `initiator`; it is absent when that is not
26
+ * known, never guessed.
27
+ */
28
+ export type NavigationInitiator = "script";
29
+ /**
30
+ * Keep collecting the page's URL credentials while no recorder is open --
31
+ * between a continuous capture's sessions -- and return the release. A
32
+ * visitor going back to `/reset/<token>` in that gap started no session,
33
+ * the token was never collected, and the next session's snapshot carried
34
+ * it once the page had hidden it (found in review).
35
+ */
36
+ export declare function collectPageSecrets(): () => void;
2
37
  export type RecorderState = "idle" | "recording" | "paused" | "stopped";
3
38
  /**
4
39
  * Callback invoked every time a new {@link SessionEvent} is produced
@@ -8,33 +43,127 @@ export type OnEventCallback = (event: SessionEvent) => void;
8
43
  /**
9
44
  * Called when the recorder ends the session ON ITS OWN — today, when
10
45
  * `maxSessionDuration` elapses. Not called for an explicit stop(): the
11
- * caller of stop() already knows.
46
+ * caller of stop() already knows. Once it returns (or throws), the
47
+ * recorder stops itself, unless the callback began stopping it with
48
+ * stopDom(): then the callback's owner finishes with stop(), as
49
+ * KeployCapture does once the exchanges answered inside the session have
50
+ * recorded.
12
51
  */
13
52
  export type OnSessionEndCallback = () => void;
53
+ /**
54
+ * Called when an event is dropped because scrubbing it passed the ingest
55
+ * server's body cap (privacy.ts ScrubOverCap): its type, how many
56
+ * characters the scrubbed event was certain to reach, and the cap.
57
+ */
58
+ export type OnScrubOversizedCallback = (eventType: SessionEvent["type"], atLeast: number, cap: number) => void;
14
59
  export declare class KeployCaptureRecorder {
15
60
  private phase;
16
61
  private userPaused;
17
62
  private hidden;
63
+ private droppedWhileShut;
18
64
  /**
19
- * A dom event has been dropped since the DOM gate last shut — i.e.
20
- * the recording has a hole that only a new baseline can close.
65
+ * A DOM event was dropped while the gate was OPEN -- its scrub failed or
66
+ * passed the body cap -- so the recording has no baseline rrweb's later
67
+ * events can be read against: each names its nodes by the ids of the
68
+ * last FullSnapshot and the mutations after it. Until a FullSnapshot is
69
+ * sent again, rrweb's incremental events are held back: posted, a click
70
+ * on a button the dropped snapshot held was resolved by the flow engine
71
+ * to `body`, and a generated test clicked the page body (found in
72
+ * review #22). Not cleared by retaking one at once: a snapshot dropped
73
+ * for its size would be dropped again. The next opening of the gate
74
+ * takes it: a hold is a hole to openDomGate() whatever the gate itself
75
+ * dropped, so nothing that sets this sets droppedWhileShut beside it.
76
+ * Set beside it, that flag outlived the snapshot that ended the hold
77
+ * wherever the drop was said from INSIDE takeFullSnapshot -- the Meta
78
+ * rrweb emits first evicting an event from a full queue, or failing its
79
+ * scrub -- since the snapshot behind it clears the hold alone: the next
80
+ * reopening of the gate serialised the whole page again for nothing
81
+ * (measured refuting review #30, real rrweb and transport: two
82
+ * takeFullSnapshot calls where one is owed).
83
+ */
84
+ private baselineLost;
85
+ /** The pending retake of a FullSnapshot after a dropped DOM event; see rebaseline(). */
86
+ private retakeTimer;
87
+ /** The pending retake is the one taken AT ONCE, after a dropped incremental; see rebaseline(). */
88
+ private retakeAtOnce;
89
+ /** How long the next retake after a dropped SNAPSHOT waits; see rebaseline(). */
90
+ private retakeDelay;
91
+ /** Uploads are failing (TransportConfig.onFailing): no snapshot is taken; see failing(). */
92
+ private outage;
93
+ /**
94
+ * UPLOADS FAIL, SO NOTHING IS RE-SERIALISED UNTIL ONE IS ACCEPTED AGAIN.
95
+ * Each DOM event the transport drops in an outage is a hole, and each
96
+ * hole asked for a FullSnapshot -- at once after an incremental -- into
97
+ * a queue nothing drains, where the snapshot evicted more DOM events
98
+ * and asked for the next. MEASURED (MEASURE.md "Outage", 22.5k nodes,
99
+ * ingest down): in the 90 s after the cap, 19 long tasks over 200 ms
100
+ * (up to 373 ms) and the heap 29 -> 211 MB. Now a hole in an outage only starts the hold (baselineLost:
101
+ * rrweb's incrementals are not queued), a retake already pending is
102
+ * cancelled, and the ONE snapshot is taken when the outage ends -- an upload accepted, or
103
+ * on a page that makes only DOM events, a queue run empty, which comes
104
+ * again only once the cap has refilled: it
105
+ * is queued after everything the outage left, so the server, sorting by
106
+ * seq, has it before every incremental that follows.
107
+ */
108
+ failing(on: boolean): void;
109
+ /**
110
+ * Events the transport dropped unsent (TransportConfig.onDropped). A
111
+ * DOM event among them is a hole exactly as one the recorder drops: no
112
+ * baseline until a FullSnapshot is sent, so rrweb's incrementals are
113
+ * held, and one is retaken (rebaseline()). Unless a snapshot queued
114
+ * after it still stands (`rebaselined`): that is the baseline already. Unsaid, clicks
115
+ * after a snapshot too big to send were posted and resolved to `body`
116
+ * (found in review #23).
117
+ */
118
+ lost(events: readonly SessionEvent[], rebaselined: boolean): void;
119
+ /**
120
+ * A dropped DOM event left the recording with no baseline: take one when
121
+ * it could fit, rather than only at the next opening of the gate -- a
122
+ * visitor who never switched tab had every later click held for the rest
123
+ * of the session (found in review #23). After an incremental, at once: a
124
+ * snapshot of the page may well fit where the event did not reach the
125
+ * server (a full queue). After a SNAPSHOT, on a backoff -- RETAKE_FIRST_MS,
126
+ * doubling to RETAKE_MAX_MS -- because the page must shrink before one
127
+ * fits and each attempt serialises the whole document. Only while the
128
+ * gate is open: a shut gate's reopening takes its own (droppedWhileShut).
129
+ * The delay starts over once a snapshot is sent.
21
130
  *
22
- * Set in emitEvent, which is the single place a dom event is
23
- * dropped, and cleared by the baseline that closes it. Without it
24
- * openDomGate() re-serialised the document on EVERY transition: a
25
- * visitor who alt-tabs thirty times on a page that mutates nothing
26
- * while hidden paid thirty FullSnapshots of a document that had not
27
- * changed. A snapshot of a real page is large — transport.ts's own
28
- * measurement is 236 KB for one — and any event over
29
- * KEEPALIVE_QUOTA_BYTES (64 KiB) is sent the moment it is queued as
30
- * a full drain, so each one is also an upload of its own.
131
+ * ONE RETAKE IS PENDING AT A TIME, and a dropped SNAPSHOT puts its
132
+ * backoff in the place of one pending at once. rrweb emits a Meta and
133
+ * then the snapshot: with the transport's queue full, the retake's own
134
+ * Meta evicted a DOM event, which asked for a retake at once from inside
135
+ * takeFullSnapshot; the snapshot behind it was then refused by the
136
+ * scrub, found that retake pending and left it -- so the page was
137
+ * serialised again on the next turn, and the next: 3,212 times in 4 s
138
+ * where the backoff allows none (found refuting review #30). A backoff
139
+ * already pending is left as it is: put off again by every drop, it
140
+ * would never fire.
31
141
  */
32
- private droppedWhileShut;
142
+ private rebaseline;
143
+ /**
144
+ * Events the transport delivered (TransportConfig.onDelivered). A
145
+ * FullSnapshot among them is the baseline on the server: the retake's
146
+ * backoff starts over.
147
+ */
148
+ delivered(events: readonly SessionEvent[]): void;
149
+ /** Which of rrweb's text nodes are a <style>'s, so their text is scrubbed as CSS (StyleTexts). */
150
+ private readonly styles;
151
+ /** The node of each id the styles' observer follows, kept from when it started (NodePresence). */
152
+ private readonly styleNodes;
33
153
  private sessionId;
34
154
  private metadata;
35
155
  private config;
36
156
  private onEvent;
37
157
  private onSessionEnd;
158
+ private onScrubOversized;
159
+ /** Told how rrweb's import went once the network is back -- null when it landed; see startRRWeb(). */
160
+ private onRRWeb;
161
+ /** Whether rrweb's import, held by the page's leave, is still to land; see startRRWeb(). */
162
+ private landing;
163
+ /** The `online` listener that retries rrweb's import; see startRRWeb(). */
164
+ private onlineRetry;
165
+ /** The timer that reads the browser's state while onlineRetry waits; see retryWhenOnline(). */
166
+ private onlinePoll;
38
167
  private rrwebStopFn;
39
168
  /** rrweb's record(), once its import has landed. Held for takeFullSnapshot. */
40
169
  private rrwebRecord;
@@ -50,9 +179,50 @@ export declare class KeployCaptureRecorder {
50
179
  private generation;
51
180
  private sessionTimer;
52
181
  private visibilityHandler;
182
+ private stopNavigation;
183
+ private lastHref;
184
+ /** location.href as the recorder last read it; see noticeUnheardMove(). */
185
+ private seenHref;
53
186
  constructor(config: CaptureConfig);
54
- start(onEvent: OnEventCallback, onSessionEnd?: OnSessionEndCallback | null): Promise<string>;
187
+ /**
188
+ * Start recording. Resolves to the session id, or "" when sampleRate
189
+ * left this visitor out. `onSessionEnd` is called when the session ends
190
+ * on its own, and the recorder then stops itself unless the callback
191
+ * called stopDom() (see OnSessionEndCallback); `startPaused` opens it paused, as pause() would;
192
+ * `onScrubOversized` when an event is dropped because scrubbing it passed
193
+ * the ingest server's body cap; `onNavigationUnwrapped` when the page made
194
+ * a History or Navigation API method the SDK wraps impossible to replace,
195
+ * with that method's name (wrapHistory).
196
+ */
197
+ start(onEvent: OnEventCallback, onSessionEnd?: OnSessionEndCallback | null, startPaused?: boolean, onScrubOversized?: OnScrubOversizedCallback | null, onRRWeb?: ((err: DomRecorderRefusal | StrictAttributesRefusal | null) => void) | null, onNavigationUnwrapped?: ((method: string) => void) | null): Promise<string>;
198
+ /**
199
+ * Stop DOM recording now, and leave the session open for what is
200
+ * already in flight (the network exchanges stop() settles): the phase
201
+ * moves to "stopping", which every gate reads as ended -- rrweb is
202
+ * not started, an import still in flight resumes into nothing, a
203
+ * hidden tab shown starts nothing, a retake due takes no snapshot, a
204
+ * same-document navigation is not recorded -- while an exchange
205
+ * already admitted still reports. Review round 3 measured the
206
+ * alternative: a tab hidden at init() and shown during stop()'s
207
+ * settle started rrweb and posted a FullSnapshot after stop(). rrweb
208
+ * is stopped here too. The visibility handler, which the phase now
209
+ * keeps from starting anything, and the navigation subscription stay
210
+ * until stop(): the URLs the page moves to are still read for their
211
+ * credentials, which the exchanges recorded in the window are
212
+ * scrubbed of. And maxSessionDuration is disarmed: the session is
213
+ * ending, and a timer that ended it inside the window dropped the
214
+ * very exchanges the window is for. stop() must follow
215
+ * (KeployCapture.stop() calls it once the settle ends); start()
216
+ * finishes a stopping session first.
217
+ */
218
+ stopDom(): void;
55
219
  stop(): void;
220
+ /** A same-document navigation, recorded as rrweb records a load: a Meta event. */
221
+ private navigated;
222
+ /** rrweb's events on their way to emitEvent, a Meta event's href recorded as the page URL. */
223
+ private recordedRRWebEvent;
224
+ /** Whether pause() closed the gate; a hidden tab does not count. */
225
+ isUserPaused(): boolean;
56
226
  /** Close the gate until resume(). A visibility change cannot reopen it. */
57
227
  pause(): void;
58
228
  /**
@@ -67,32 +237,6 @@ export declare class KeployCaptureRecorder {
67
237
  * again, the session stayed snapshotless for good.
68
238
  */
69
239
  resume(): void;
70
- /**
71
- * The DOM gate has just reopened: give the recording a baseline.
72
- *
73
- * rrweb HAS NO PAUSE, so while the gate was shut it went on observing
74
- * and emitEvent dropped what it emitted. Every incremental event
75
- * rrweb produces names its nodes by the ids of the last FullSnapshot
76
- * — an `add` introduces an id and the `attributes`, `texts` and
77
- * `removes` after it refer to it — so the events from here on refer
78
- * to nodes the recording never showed. The flow engine resolves those
79
- * ids against the node map it builds from the snapshot
80
- * (flow-engine/src/extractor.ts) and selectorFromNode answers `body`
81
- * for an id it cannot find: a click on a button added while the tab
82
- * was hidden becomes a click on `body` in the generated test, and it
83
- * passes. Nothing anywhere said the recording had a hole.
84
- *
85
- * So a reopened gate re-serialises the document and re-numbers
86
- * rrweb's mirror. Two ways in, and exactly one of them fires:
87
- *
88
- * - rrweb has not started (hidden or paused since init, where
89
- * starting it would have emitted Meta and FullSnapshot into the
90
- * shut gate). Start it now; the snapshot record() takes inside
91
- * that call IS the baseline.
92
- * - rrweb is running. takeFullSnapshot(), which also throws before
93
- * record() has run — inside a visibilitychange handler that would
94
- * be an exception in the integrator's document.
95
- */
96
240
  private openDomGate;
97
241
  /**
98
242
  * The id of the session that is LIVE, or null when none is.
@@ -124,33 +268,119 @@ export declare class KeployCaptureRecorder {
124
268
  */
125
269
  getState(): RecorderState;
126
270
  getMetadata(): SessionMetadata | null;
271
+ /** Starts rrweb when the gate allows; answers why rrweb (or strict's allow-list) could not be imported, else null. */
127
272
  private startRRWeb;
128
273
  /**
129
- * Everything the SDK's privacy configuration means to rrweb.
130
- *
131
- * NO `maskAllInputs`. MEASURED in rrweb 2.0.0-alpha.20's record()
132
- * (rrweb.js:13778-13795): `maskAllInputs: true` DISCARDS the
133
- * maskInputOptions object it was handed and substitutes a fixed map
134
- * of 16 input types, and neither `hidden` nor `file` is among them —
135
- * so the SDK's own map was dead in balanced and strict, and a CSRF
136
- * token, a session id or an internal record id in `<input
137
- * type="hidden">` was serialised in the clear in every mode.
138
- * Leaving `maskAllInputs` unset makes rrweb use the map below
139
- * verbatim (the `_maskInputOptions !== void 0` branch of the same
140
- * expression), which is the only way to name a type rrweb's fixed
141
- * map omits.
274
+ * Asks for rrweb again when the browser is back online, for this session
275
+ * only.
142
276
  *
143
- * The map is the ONLY statement of what each mode masks. Three
144
- * things are held to it and none of them keeps a second copy:
145
- * dom-masking.test.ts drives one case per entry through real rrweb
146
- * and asserts the serialised `value`, readme.test.ts holds the npm
147
- * page's privacy table to it, and readme.test.ts also requires every
148
- * input type the HTML spec has to be either in it or named in the
149
- * page's carve-out. Before that, thirteen of its rows were untested:
150
- * MEASURED, flipping `email`, `select`, `month`, `tel` and `number`
151
- * to `false` left the whole SDK suite green.
277
+ * THE BROWSER'S STATE IS READ WHILE THIS WAITS, AS WELL AS HEARD. The
278
+ * `online` event is on window, and a page's own listener, registered
279
+ * first, can stop it before it reaches this one
280
+ * (stopImmediatePropagation). Waiting for the event alone, such a page's
281
+ * capture sat for good once started offline: rrweb never asked for, its
282
+ * transport held, nothing sent and nothing said until the visitor
283
+ * switched tab (found refuting review #30, with the real stack). So a
284
+ * timer asks navigator.onLine, which is what the event reports, and
285
+ * whichever comes first runs the retry, once, and ends the other. (The
286
+ * timer asks before it runs the retry only so that a look at a browser
287
+ * still offline changes nothing: the retry would find the same, and
288
+ * start this wait over.)
289
+ */
290
+ private retryWhenOnline;
291
+ /**
292
+ * The ONE reaction on rrweb's held import (by mode): each recorder still
293
+ * landing as it lands is told. Static, so it holds none of them: a
294
+ * recorder stopped meanwhile has left the set.
295
+ */
296
+ private static whenLanded;
297
+ /** rrweb lands later, its owner told then (awaitingRRWeb): the request is free again. */
298
+ private land;
299
+ /** How the import went after start() (back online, or a leave's hold ended): refused, or recorded now or when the DOM gate next opens, its owner told. */
300
+ private loadedLate;
301
+ /** Ends the timer retryWhenOnline() started, if it is still running. */
302
+ private stopOnlinePoll;
303
+ /**
304
+ * rrweb could not be imported after start(): the capture is refused as it
305
+ * is at start, once, unless it has ended or been superseded meanwhile.
306
+ */
307
+ private refuseLate;
308
+ /**
309
+ * rrweb landed while the retry at `online` was still waiting -- the page
310
+ * resumed the capture, or showed its tab, once the browser was online,
311
+ * and the DOM gate imported rrweb itself. The capture's owner is told as
312
+ * the retry would have told it, and the retry is dropped: left waiting,
313
+ * the capture was live and recording and its transport stayed held until
314
+ * an `online` event came to ask again (found in review #28).
152
315
  */
316
+ private landedBeforeTheRetry;
317
+ /** Whether what the recorder loads -- rrweb, and under strict its allow-list -- has loaded in this document. */
318
+ private loaded;
319
+ /** Whether rrweb's import waits for the network, or for a leave's hold to end: onRRWeb says how it went. */
320
+ awaitingRRWeb(): boolean;
153
321
  private rrwebOptions;
322
+ /**
323
+ * rrweb's node `id` is still in the page: the node kept for it when the
324
+ * styles' observer started following it (rrweb's mirror forgets the id
325
+ * of a node moved out of a frame into the page; NodePresence), else the
326
+ * one rrweb's mirror has, connected, and -- in a frame -- in a frame
327
+ * that is itself still in the page, up to the top. A removed shadow
328
+ * host's insides stay in the mirror and a removed frame's nodes stay
329
+ * connected to that frame's document, so the mirror alone could not
330
+ * say. Asked by the styles' observer after a mutation that removes
331
+ * nodes; with no rrweb, nothing is pruned.
332
+ */
333
+ private inPage;
334
+ /**
335
+ * A MOVE NO LISTENER HEARD, found when the next event is recorded. A
336
+ * router that calls a pushState it saved before the SDK wrapped history
337
+ * moves the page past the wrapper; where the browser has the Navigation
338
+ * API its entry change still reports the move, and where it has none the
339
+ * move is found here, before the event that follows it is recorded, so
340
+ * that event and every one after it belong to the new page. Recorded
341
+ * while popstate itself is being dispatched (by a listener of the page's
342
+ * own that ran before the SDK's) it was the traversal; anywhere else it is
343
+ * read as a push -- a replace cannot be told apart from one any more, and
344
+ * nor can a traversal whose popstate listener caused another event first
345
+ * (earlierMove reads the innermost event).
346
+ * No timer looks
347
+ * for it: one string comparison per event, and the page URL is read
348
+ * again only when it has changed. rrweb's own Meta (the snapshot that
349
+ * reopens a shut gate) names the page itself: a move made while the
350
+ * gate was shut is that snapshot's, as a heard one is, and no step's.
351
+ */
352
+ private noticeUnheardMove;
353
+ /**
354
+ * A page URL as this capture records it: the page URL's rule
355
+ * (recordedPageUrl), then scrubPageUrl over what that keeps -- every
356
+ * query value under strict, and otherwise a value shaped like a token
357
+ * or holding a PII pattern, a JWT path segment and a URL nested in a
358
+ * value; never a value that rule kept by its own judgement of names and
359
+ * ids. Used for the session's URL and referrer and for every Meta
360
+ * event's href, rrweb's and this recorder's.
361
+ */
362
+ private scrubUrl;
363
+ /**
364
+ * The URLs in an rrweb event's DOM, scrubbed: every URL-valued
365
+ * attribute in a full snapshot (type 2), and in a mutation (type 3,
366
+ * source 0) every added subtree's, every changed attribute and every
367
+ * changed text's CSS; the CSS of a rule, a replaced sheet, a declaration
368
+ * or an adopted sheet a script put through the CSSOM (sources 8, 13,
369
+ * 15). See scrubDomAttributes and scrubDomCss. A Meta event's href is the page URL, scrubbed by
370
+ * scrubUrl in recordedRRWebEvent. It runs before the credential scrub
371
+ * (scrubSecrets), knowing the page URL's credentials by value
372
+ * (`matcher`), on rrweb's own objects, in place: copying a 50,000-node
373
+ * tree to change three attributes would cost more than the scrub. A
374
+ * throw is emitEvent's to handle, as the credential scrub's is: the
375
+ * event is not sent.
376
+ */
377
+ private scrubDomUrls;
378
+ /**
379
+ * True while an event decided now would pass the session gate: what the
380
+ * network interceptor asks at an exchange's own moment (see
381
+ * NetworkInterceptor's `admit`).
382
+ */
383
+ acceptsNetwork(): boolean;
154
384
  /**
155
385
  * Emit an event to the registered callback. This is also called
156
386
  * externally by the main KeployCapture orchestrator for network
@@ -158,7 +388,17 @@ export declare class KeployCaptureRecorder {
158
388
  *
159
389
  * THE GATES ARE HERE, so every emitter faces the same two. They used
160
390
  * to sit only in rrweb's emit callback, which meant "paused" and
161
- * "stopped" applied to DOM events and to nothing else.
391
+ * "stopped" applied to DOM events and to nothing else. `prepare`
392
+ * rewrites `data` only once the gates let the event through: rewriting
393
+ * one that is then dropped is work for nothing.
394
+ *
395
+ * `admitted`: the caller asked {@link acceptsNetwork} at the event's own
396
+ * moment and the gate was open, so a pause() since then does not drop
397
+ * it -- the exchange happened before the pause. The session must still
398
+ * be live. `at`: the event's timestamp when it is not now -- a fetch's,
399
+ * stamped when it was answered (see NetworkEventCallback). `seq`: its
400
+ * place in the session when one was taken for it before (see
401
+ * Transport.place), else the transport stamps it as it is queued.
162
402
  */
163
- emitEvent(type: SessionEvent["type"], data: unknown): void;
403
+ emitEvent(type: SessionEvent["type"], data: unknown, prepare?: (data: unknown) => unknown, admitted?: boolean, at?: number, seq?: number): void;
164
404
  }
package/dist/redact.d.ts CHANGED
@@ -2,7 +2,18 @@
2
2
  export declare const TRUNCATED_UNPARSEABLE = "[UNPARSEABLE_BODY_NOT_REDACTED]";
3
3
  /** True for a body that IS one of the SDK's own not-recorded notes. */
4
4
  export declare function isNotRecordedNote(body: string): boolean;
5
- declare function isSensitiveKey(key: string): boolean;
5
+ /**
6
+ * Whether a state is an app's word rather than OAuth's generated value:
7
+ * letters, or words joined by `-` or `_`, of at most 16 characters --
8
+ * `delivered`, `California`, `in-progress` -- or longer camelCase or
9
+ * joined words. A random run of letters past 16 is not one (review).
10
+ */
11
+ export declare function isPlainState(state: string): boolean;
12
+ /**
13
+ * A JSON key's, a HAR-style pair's or a header's name, read by the one
14
+ * rule (@keploy/contract's privacy.ts isCredentialName) as a `key`.
15
+ */
16
+ export declare function isSensitiveKey(key: string): boolean;
6
17
  /** Luhn check — the standard checksum every real card number satisfies. */
7
18
  declare function passesLuhn(digits: string): boolean;
8
19
  /**
@@ -17,26 +28,57 @@ declare function passesLuhn(digits: string): boolean;
17
28
  declare function isLikelyCardNumber(digits: string): boolean;
18
29
  /** Redact card-shaped runs inside a string, preserving everything else. */
19
30
  declare function redactCards(s: string): string;
31
+ /** A half-open span of a text to redact: [start, end). */
32
+ type Range = [number, number] | [number, number, string];
20
33
  /**
21
34
  * Apply every value-level detector to one string, then every
22
- * caller-supplied pattern.
35
+ * caller-supplied pattern, all over the string as it came.
23
36
  *
24
37
  * `extra` is the integrator's `privacy.piiPatterns`, already compiled
25
38
  * global (see PrivacyEngine). It rides through every scan the engine
26
- * makes — this function is the ONLY string scanner — so a pattern
39
+ * makes -- this function is the ONLY string scanner -- so a pattern
27
40
  * applies to a JSON string value, a text body and a header value alike.
28
41
  * It used to reach header values only, while its documentation said
29
42
  * "matched text is replaced".
30
43
  */
31
44
  export declare function redactStringValue(value: string, extra?: readonly RegExp[]): string;
45
+ /**
46
+ * The token detectors alone -- a JWT, a provider-prefixed key -- over one
47
+ * string: what the page's own text is read for (privacy.ts scrubDomText).
48
+ * A credential on screen is one whatever text is around it; an email or a
49
+ * phone number in the page's text is the page's content, which balanced
50
+ * records.
51
+ */
52
+ export declare function redactTokens(value: string): string;
53
+ /** Where `value`'s JWTs and provider-prefixed keys lie. */
54
+ export declare function tokenRanges(value: string): Range[];
55
+ /**
56
+ * Every URL a header's value holds, scrubbed as a text body's URLs are
57
+ * (TEXT_URL_RULES: a credential's own value replaced, ended at its first
58
+ * stop, every other byte kept),
59
+ * and every pair a header's leads start (EMBEDDED_NAME_IN_HEADER), as a
60
+ * relative URL's, which the URL scan does not find, is: a `Referer`, an
61
+ * `X-Redirect-To`, a `Content-Security-Policy`'s `report-uri` absolute or
62
+ * relative (`/csp-report?token=...`). A header is no replay key, so no
63
+ * pair is replaced whole for a name inside it. Only Location,
64
+ * Content-Location, Link and Refresh were read, and a URL any other header
65
+ * carried was recorded as it came (found in review).
66
+ */
67
+ export declare function scrubHeaderUrls(value: string): string;
32
68
  /**
33
69
  * Redact a captured body.
34
70
  *
35
- * JSON in, valid JSON out — always. A body that is not JSON is treated as
36
- * opaque text and only value-level detectors are applied, so it can never
37
- * be turned into something that fails to parse downstream.
71
+ * JSON in, valid JSON out — always. A body that is not JSON keeps every
72
+ * byte except what is redacted: a form's credential values and the
73
+ * pattern matches in its other values, or, in any other text, the value
74
+ * of an embedded credential pair and the pattern matches.
38
75
  */
39
76
  export declare function redactBody(body: string | null | undefined, contentType?: string, extra?: readonly RegExp[]): string | null;
77
+ /**
78
+ * What network.ts appends to a body it cut at the cap. Defined here and
79
+ * imported there, so the form parser and the cut agree on one string.
80
+ */
81
+ export declare const TRUNCATED_SUFFIX = "...[truncated]";
40
82
  /** Exposed for tests and diagnostics. */
41
83
  export declare const __internals: {
42
84
  isSensitiveKey: typeof isSensitiveKey;
@@ -0,0 +1,23 @@
1
+ /** The version this chunk was built as: the SDK refuses one of another (module-of.ts ownChunk). */
2
+ export { version } from "../package.json";
3
+ /**
4
+ * The request term of a raw body: "" or "graphql:<name>#<documentId>".
5
+ * `subtle` hashes the document (SHA-256).
6
+ */
7
+ export declare function requestTerm(body: string | null | undefined, subtle: SubtleCrypto): Promise<string>;
8
+ /**
9
+ * The requestTerm to record for a body AS THE APP HANDED IT to fetch or
10
+ * XHR -- before redaction, masking or truncation touch it. Known at once
11
+ * unless a document has to be hashed; only then a Promise. What needs no
12
+ * term code (no body, a form, a body that is not text or is longer than
13
+ * MAX_TERM_BODY, text that cannot be a GraphQL request) is
14
+ * termBeforeLoad()'s, which the interceptor asks before it loads this
15
+ * chunk. Where the page has no SubtleCrypto (an insecure context) a
16
+ * GraphQL document cannot be hashed and is "body:*", and every other term
17
+ * needs no hash: the recording is still a canonical-key.v2 document,
18
+ * whose redacted values match as wildcards (spec/canonical-key.v2.json
19
+ * rules.record). It may throw or reject: the interceptor's termFor() is
20
+ * the one place that turns any failure into "no term", so nothing here
21
+ * can reach the page.
22
+ */
23
+ export declare function recordTermFor(body: unknown, subtle: SubtleCrypto | undefined): string | Promise<string>;
@@ -0,0 +1 @@
1
+ var e,t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,l=Object.prototype.hasOwnProperty,u={};((e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:!0})})(u,{recordTermFor:()=>h,requestTerm:()=>g,version:()=>i}),module.exports=(e=u,((e,u,o,i)=>{if(u&&"object"==typeof u||"function"==typeof u)for(let o of n(u))!l.call(e,o)&&void 0!==o&&t(e,o,{get:()=>u[o],enumerable:!(i=r(u,o))||i.enumerable});return e})(t({},"__esModule",{value:!0}),e));var o=/^[\t\n\r ]*\{/;var i="3.1.0-rc.2",s=/^[_A-Za-z]\w*$/,a=["{","query","mutation","subscription","fragment"],f=["query","operationName","variables","extensions"],c=/([\t\n\r ,\uFEFF]+|#[^\n\r]*)|("""[^"\\]*(?:(?:\\"""|\\(?!""")|"(?!""))[^"\\]*)*""")|(""")|("[^"\\]*(?:\\[^][^"\\]*)*")|(\.\.\.|[!$&()[\]{}:=@|])|([_A-Za-z]\w*)|([0-9-](?:(?!\.\.\.)[^\t\n\r ,\uFEFF!$&()[\]{}:=@|"#])*)|((?:(?!\.\.\.)[^\t\n\r ,\uFEFF!$&()[\]{}:=@|"#\w-])+)/y;function p(e,t){return null!==e&&"object"==typeof e&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function y(e){let t;try{t=e?JSON.parse(e):null}catch{return""}if(null===t||"object"!=typeof t||Array.isArray(t))return"";let r=Object.keys(t);if(!r.length||r.some(e=>!f.includes(e)))return"";let n=p(t,"operationName"),l=p(t,"query");if(null!=n&&("string"!=typeof n||!s.test(n))||null!=l&&"string"!=typeof l)return"";let u=n??"",o=p(p(p(t,"extensions"),"persistedQuery"),"sha256Hash");if("string"==typeof o&&/^[0-9A-Fa-f]{64}$/.test(o))return`graphql:${u}#pq`;let i="string"==typeof l?function(e){let t=[],r=[];for(c.lastIndex=0;c.lastIndex<e.length;){let n=c.exec(e);if(!n||n[3])return null;n[1]||(t.push(n[2]||n[4]?'""':n[7]?"0":n[0]),r.push(!!n[6]))}let n=[];for(let e=0;e<t.length;e++){let l=t[e],u="{([".indexOf(l);if(-1!==u){if(n.push("})]"[u]),!u&&!r[e+1]&&"..."!==t[e+1]&&"}"!==t[e+1])return null}else if("})]".includes(l)&&1===l.length&&n.pop()!==l)return null}return a.includes(t[0])&&"}"===t[t.length-1]&&!n.length?t.join(" "):null}(l):null;return null===i?"":[u,i]}async function d([e,t],r){let n=new Uint8Array(await r.digest("SHA-256",(new TextEncoder).encode(t))),l="";for(let e=0;e<8;e++)l+=n[e].toString(16).padStart(2,"0");return`graphql:${e}#${l}`}async function g(e,t){let r=y(e);return"string"==typeof r?r:d(r,t)}function h(e,t){let r=function(e){return null==e||""===e?"":"string"==typeof e?e.length>4194304?"body:*":function(e){return o.test(e)&&(e.includes('"query"')||e.includes("persistedQuery")||e.includes("\\u"))}(e)?null:"":e instanceof URLSearchParams||typeof FormData<"u"&&e instanceof FormData?"":"body:*"}(e);if(null!==r)return r;let n=y(e);return"string"==typeof n?n:t?d(n,t):"body:*"}//# sourceMappingURL=request-term.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/request-term.ts","../src/term-candidate.ts","../package.json"],"names":["request_term_exports","__export","recordTermFor","requestTerm","version","module","exports","OBJECT_START","NAME","STARTS","MEMBERS","LEXEME","own","o","k","Array","isArray","Object","prototype","hasOwnProperty","call","prepare","body","v","JSON","parse","keys","length","some","key","includes","name","query","test","n","hash","text","doc","out","lastIndex","m","exec","push","open","t","at","indexOf","pop","join","normalise","async","hashed","subtle","digest","Uint8Array","TextEncoder","encode","hex","toString","padStart","p","known","couldBeGraphql","URLSearchParams","FormData","termBeforeLoad"],"mappings":"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","sourcesContent":["/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - request term (canonical-key.v2) */\n/* ------------------------------------------------------------------ */\n/*\n * The term spec/canonical-key.v2.json keys a GraphQL request by:\n * \"graphql:<operationName>#<documentId>\", or \"\" when the body is not a\n * GraphQL request. Executed against that file's `term` vectors by\n * __tests__/request-term.test.ts.\n *\n * It is computed HERE, over the RAW body, before redaction, masking or\n * truncation touch it: the stored body may have had a PII pattern\n * redacted inside the document, may be \"[MASKED]\" (strict mode) or may\n * be cut at maxBodySize, and a term derived from it would be wrong or\n * missing. An operation name and a document hash are not user data:\n * every literal (string, block string, number) is blanked before\n * hashing, so input inlined into a document never reaches the hash, and\n * a persisted query's own hash is never recorded.\n *\n * The replay runtime holds a second implementation (packages/replay-\n * runtime/src/canonkey.ts, `graphqlTerm`) held to the same vectors: this\n * package is public and dependency-free, that one is private, and\n * neither may depend on the other. No GraphQL parser: one sticky regex\n * cuts the lexemes, which keeps the code the page downloads small.\n *\n * THIS FILE IS A CHUNK OF ITS OWN (dist/request-term.{mjs,js}, the\n * package's \"./request-term\" export), which network.ts loads the first\n * time a body could be a GraphQL request (term-candidate.ts), and never\n * for a page that sends none. It imports nothing but term-candidate.ts,\n * and nothing in the main bundle imports it but by that name:\n * __tests__/bundle-size.test.ts fails when its lexer is in\n * dist/index.{mjs,js}.\n */\n\nimport { termBeforeLoad } from \"./term-candidate\";\n/** The version this chunk was built as: the SDK refuses one of another (module-of.ts ownChunk). */\nexport { version } from \"../package.json\";\n\nconst NAME = /^[_A-Za-z]\\w*$/;\nconst STARTS = [\"{\", \"query\", \"mutation\", \"subscription\", \"fragment\"];\nconst MEMBERS = [\"query\", \"operationName\", \"variables\", \"extensions\"];\n\n/*\n * One lexeme per match, by the spec's rules.normalisation, in groups:\n * 1 ignored tokens (dropped) 2 a block string 3 an\n * unterminated block string 4 a string 5 a punctuator\n * 6 a NAME run 7 a NUMBER run 8 any other run\n * Anything no alternative matches (an unterminated string) fails the\n * scan. Sticky (y), so a lexeme can only start where the last one ended.\n * Both string alternatives are UNROLLED (a run of plain characters, then\n * one escape or quote at a time), so a long literal is a simple loop and\n * never a backtrack frame per character; and a block string's escaped\n * \\\"\"\" can only be read as the escape -- were its backslash content, the\n * regex would backtrack into it and close a block string the spec says\n * is unterminated.\n */\nconst LEXEME =\n /([\\t\\n\\r ,\\uFEFF]+|#[^\\n\\r]*)|(\"\"\"[^\"\\\\]*(?:(?:\\\\\"\"\"|\\\\(?!\"\"\")|\"(?!\"\"))[^\"\\\\]*)*\"\"\")|(\"\"\")|(\"[^\"\\\\]*(?:\\\\[^][^\"\\\\]*)*\")|(\\.\\.\\.|[!$&()[\\]{}:=@|])|([_A-Za-z]\\w*)|([0-9-](?:(?!\\.\\.\\.)[^\\t\\n\\r ,\\uFEFF!$&()[\\]{}:=@|\"#])*)|((?:(?!\\.\\.\\.)[^\\t\\n\\r ,\\uFEFF!$&()[\\]{}:=@|\"#\\w-])+)/y;\n\n/**\n * The normalised text of a GraphQL document -- lexemes joined by one\n * space, every string blanked to \"\" and every number to 0 -- or null\n * when the text is not a GraphQL document.\n */\nfunction normalise(doc: string): string | null {\n const out: string[] = [];\n const name: boolean[] = [];\n LEXEME.lastIndex = 0;\n while (LEXEME.lastIndex < doc.length) {\n const m = LEXEME.exec(doc);\n if (!m || m[3]) return null;\n if (m[1]) continue;\n out.push(m[2] || m[4] ? '\"\"' : m[7] ? \"0\" : m[0]);\n name.push(!!m[6]);\n }\n // Every opener closes in order; every { opens a selection: a name,\n // '...' or } follows it. A string is \"\" here and a number 0, so no\n // literal can pass for a punctuator or a keyword.\n const open: string[] = [];\n for (let k = 0; k < out.length; k++) {\n const t = out[k] as string;\n const at = \"{([\".indexOf(t);\n if (at !== -1) {\n open.push(\"})]\"[at] as string);\n if (!at && !(name[k + 1] || out[k + 1] === \"...\" || out[k + 1] === \"}\"))\n return null;\n } else if (\"})]\".includes(t) && t.length === 1 && open.pop() !== t)\n return null;\n }\n return STARTS.includes(out[0] as string) &&\n out[out.length - 1] === \"}\" &&\n !open.length\n ? out.join(\" \")\n : null;\n}\n\nfunction own(o: unknown, k: string): unknown {\n return o !== null &&\n typeof o === \"object\" &&\n !Array.isArray(o) &&\n Object.prototype.hasOwnProperty.call(o, k)\n ? (o as Record<string, unknown>)[k]\n : undefined;\n}\n\n/**\n * Everything of the term that needs no hash: \"\" (not a GraphQL request),\n * \"graphql:<name>#pq\" (a persisted query), or [name, normalised text]\n * still to be hashed.\n */\nfunction prepare(body: string | null | undefined): string | [string, string] {\n let v: unknown;\n try {\n v = body ? JSON.parse(body) : null;\n } catch {\n return \"\";\n }\n if (v === null || typeof v !== \"object\" || Array.isArray(v)) return \"\";\n const keys = Object.keys(v);\n if (!keys.length || keys.some((key) => !MEMBERS.includes(key))) return \"\";\n const name = own(v, \"operationName\");\n const query = own(v, \"query\");\n if (name != null && (typeof name !== \"string\" || !NAME.test(name))) return \"\";\n if (query != null && typeof query !== \"string\") return \"\";\n const n = (name as string | null | undefined) ?? \"\";\n const hash = own(own(own(v, \"extensions\"), \"persistedQuery\"), \"sha256Hash\");\n if (typeof hash === \"string\" && /^[0-9A-Fa-f]{64}$/.test(hash))\n return `graphql:${n}#pq`;\n const text = typeof query === \"string\" ? normalise(query) : null;\n return text === null ? \"\" : [n, text];\n}\n\n/** The term of a prepared document: its name and 16 hex of SHA-256. */\nasync function hashed(\n [name, text]: [string, string],\n subtle: SubtleCrypto,\n): Promise<string> {\n const digest = new Uint8Array(\n await subtle.digest(\"SHA-256\", new TextEncoder().encode(text)),\n );\n let hex = \"\";\n for (let k = 0; k < 8; k++)\n hex += (digest[k] as number).toString(16).padStart(2, \"0\");\n return `graphql:${name}#${hex}`;\n}\n\n/**\n * The request term of a raw body: \"\" or \"graphql:<name>#<documentId>\".\n * `subtle` hashes the document (SHA-256).\n */\nexport async function requestTerm(\n body: string | null | undefined,\n subtle: SubtleCrypto,\n): Promise<string> {\n const p = prepare(body);\n return typeof p === \"string\" ? p : hashed(p, subtle);\n}\n\n/**\n * The requestTerm to record for a body AS THE APP HANDED IT to fetch or\n * XHR -- before redaction, masking or truncation touch it. Known at once\n * unless a document has to be hashed; only then a Promise. What needs no\n * term code (no body, a form, a body that is not text or is longer than\n * MAX_TERM_BODY, text that cannot be a GraphQL request) is\n * termBeforeLoad()'s, which the interceptor asks before it loads this\n * chunk. Where the page has no SubtleCrypto (an insecure context) a\n * GraphQL document cannot be hashed and is \"body:*\", and every other term\n * needs no hash: the recording is still a canonical-key.v2 document,\n * whose redacted values match as wildcards (spec/canonical-key.v2.json\n * rules.record). It may throw or reject: the interceptor's termFor() is\n * the one place that turns any failure into \"no term\", so nothing here\n * can reach the page.\n */\nexport function recordTermFor(\n body: unknown,\n subtle: SubtleCrypto | undefined,\n): string | Promise<string> {\n const known = termBeforeLoad(body);\n if (known !== null) return known;\n const p = prepare(body as string);\n if (typeof p === \"string\") return p;\n return subtle ? hashed(p, subtle) : \"body:*\";\n}\n","/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - could a body be a GraphQL request? */\n/* ------------------------------------------------------------------ */\n/*\n * The term code (request-term.ts: the lexer, the document check, the\n * hash) is a chunk of its own, loaded only for a body that passes\n * couldBeGraphql(); every other body is recorded here, at once, and the\n * chunk is never fetched. So the check must be a SUPERSET of what the\n * term code gives a term: a GraphQL body it missed would be recorded ''\n * while replay computes its term from postData(), and the keys would\n * differ.\n *\n * DERIVED FROM THE TERM CODE'S OWN ENTRY CONDITIONS (spec/canonical-\n * key.v2.json rules.term and rules.document; request-term.ts prepare()),\n * not from examples. A body has a term only when:\n * 1. it parses as ONE JSON value with nothing but JSON's whitespace\n * (U+0020, U+0009, U+000A, U+000D) before it -- a byte order mark\n * is refused -- and that value is an OBJECT, so the first character\n * that is not JSON whitespace is `{`; and\n * 2. it has a documentId, which needs a member named `query` (a string\n * that is a document) or a member named `persistedQuery` (inside\n * `extensions`). A member name is a JSON string: written with no\n * escape it is exactly `\"query\"`, quotes included, or holds\n * `persistedQuery`; written with any escape it holds `\\u`, the only\n * JSON escape that yields a letter.\n * So a batch (`[...]`), a raw application/graphql document (`{ me { id\n * } }`, `query Q { ... }`), a form and plain text have no term on either\n * side, and a GET has no body to read (the live term is\n * term(request.postData())). __tests__/term-candidate.test.ts runs every\n * term vector and every e2e GraphQL body through the check.\n */\n\n/** Longer bodies (UTF-16 units) are recorded \"body:*\": bounded work, and no literal long enough to strain a regex engine. */\nexport const MAX_TERM_BODY = 4 * 1024 * 1024;\n\n/** Text that starts as a JSON object does: JSON whitespace, then `{` (condition 1 above). */\nexport const OBJECT_START = /^[\\t\\n\\r ]*\\{/;\n\n/** The first character that is not JSON whitespace. */\nexport const NOT_SPACE = /[^\\t\\n\\r ]/;\n\n/** True when `text` could be a body the term code gives a term (see above). */\nexport function couldBeGraphql(text: string): boolean {\n return (\n OBJECT_START.test(text) &&\n (text.includes('\"query\"') ||\n text.includes(\"persistedQuery\") ||\n text.includes(\"\\\\u\"))\n );\n}\n\n/**\n * The requestTerm of a body AS THE APP HANDED IT to fetch or XHR when it\n * needs no term code: '' for no body, a form, or text that cannot be a\n * GraphQL request; \"body:*\" for a body that is not text (a Blob, a\n * buffer, a stream, a Document) or is longer than MAX_TERM_BODY. null\n * when the body could be a GraphQL request: the term code decides it.\n */\nexport function termBeforeLoad(body: unknown): string | null {\n if (body == null || body === \"\") return \"\";\n if (typeof body === \"string\")\n return body.length > MAX_TERM_BODY\n ? \"body:*\"\n : couldBeGraphql(body)\n ? null\n : \"\";\n // Sent as form text, which is never a JSON object.\n if (\n body instanceof URLSearchParams ||\n (typeof FormData !== \"undefined\" && body instanceof FormData)\n )\n return \"\";\n return \"body:*\";\n}\n","{\n \"name\": \"@keploy/capture-sdk\",\n \"version\": \"3.1.0-rc.2\",\n \"description\": \"Lightweight SDK to capture UI flows from real users - DOM recording, network interception, PII masking\",\n \"main\": \"dist/index.js\",\n \"module\": \"dist/index.bundler.mjs\",\n \"unpkg\": \"dist/index.mjs\",\n \"jsdelivr\": \"dist/index.mjs\",\n \"types\": \"dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./request-term\": {\n \"types\": \"./dist/request-term.d.ts\",\n \"import\": \"./dist/request-term.mjs\",\n \"require\": \"./dist/request-term.js\"\n },\n \"./strict-attributes\": {\n \"types\": \"./dist/strict-attributes.d.ts\",\n \"import\": \"./dist/strict-attributes.mjs\",\n \"require\": \"./dist/strict-attributes.js\"\n },\n \"./body-redact\": {\n \"types\": \"./dist/body-redact.d.ts\",\n \"import\": \"./dist/body-redact.mjs\",\n \"require\": \"./dist/body-redact.js\"\n },\n \"./body-worker-start\": {\n \"types\": \"./dist/body-worker-start.d.ts\",\n \"import\": \"./dist/body-worker-start.mjs\",\n \"require\": \"./dist/body-worker-start.js\"\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\",\n \"request-term/package.json\",\n \"strict-attributes/package.json\",\n \"body-redact/package.json\",\n \"body-worker-start/package.json\",\n \"LICENSE\",\n \"README.md\"\n ],\n \"scripts\": {\n \"build\": \"node scripts/build-main.mjs && node scripts/build-worker.mjs && tsc -p tsconfig.build.json\",\n \"dev\": \"node scripts/build-main.mjs --watch\",\n \"test\": \"vitest run\",\n \"clean\": \"rm -rf dist\",\n \"typecheck\": \"tsc --noEmit\",\n \"prepublishOnly\": \"pnpm run clean && turbo run build --filter=@keploy/capture-sdk --force\"\n },\n \"dependencies\": {\n \"rrweb\": \"^2.1.6\"\n },\n \"devDependencies\": {\n \"@keploy/contract\": \"workspace:*\",\n \"@types/node\": \"~24.13.5\",\n \"jsdom\": \"^30.1.0\",\n \"terser\": \"5.51.2\",\n \"tsup\": \"^8.3.0\",\n \"typescript\": \"^7.0.2\",\n \"vitest\": \"^5.0.1\"\n },\n \"peerDependencies\": {},\n \"keywords\": [\n \"keploy\",\n \"ui-testing\",\n \"session-recording\",\n \"e2e\",\n \"capture\"\n ],\n \"browser\": {\n \"./dist/body-worker-unbundled.mjs\": \"./dist/body-worker-none.mjs\"\n },\n \"alias\": {\n \"@keploy/capture-sdk/body-worker-start\": \"./dist/body-worker-start.mjs\"\n },\n \"license\": \"Apache-2.0\",\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n"]}
@@ -0,0 +1 @@
1
+ var e=/^[\t\n\r ]*\{/;var t="3.1.0-rc.2",n=/^[_A-Za-z]\w*$/,r=["{","query","mutation","subscription","fragment"],l=["query","operationName","variables","extensions"],u=/([\t\n\r ,\uFEFF]+|#[^\n\r]*)|("""[^"\\]*(?:(?:\\"""|\\(?!""")|"(?!""))[^"\\]*)*""")|(""")|("[^"\\]*(?:\\[^][^"\\]*)*")|(\.\.\.|[!$&()[\]{}:=@|])|([_A-Za-z]\w*)|([0-9-](?:(?!\.\.\.)[^\t\n\r ,\uFEFF!$&()[\]{}:=@|"#])*)|((?:(?!\.\.\.)[^\t\n\r ,\uFEFF!$&()[\]{}:=@|"#\w-])+)/y;function i(e,t){return null!==e&&"object"==typeof e&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function o(e){let t;try{t=e?JSON.parse(e):null}catch{return""}if(null===t||"object"!=typeof t||Array.isArray(t))return"";let o=Object.keys(t);if(!o.length||o.some(e=>!l.includes(e)))return"";let s=i(t,"operationName"),a=i(t,"query");if(null!=s&&("string"!=typeof s||!n.test(s))||null!=a&&"string"!=typeof a)return"";let f=s??"",c=i(i(i(t,"extensions"),"persistedQuery"),"sha256Hash");if("string"==typeof c&&/^[0-9A-Fa-f]{64}$/.test(c))return`graphql:${f}#pq`;let y="string"==typeof a?function(e){let t=[],n=[];for(u.lastIndex=0;u.lastIndex<e.length;){let r=u.exec(e);if(!r||r[3])return null;r[1]||(t.push(r[2]||r[4]?'""':r[7]?"0":r[0]),n.push(!!r[6]))}let l=[];for(let e=0;e<t.length;e++){let r=t[e],u="{([".indexOf(r);if(-1!==u){if(l.push("})]"[u]),!u&&!n[e+1]&&"..."!==t[e+1]&&"}"!==t[e+1])return null}else if("})]".includes(r)&&1===r.length&&l.pop()!==r)return null}return r.includes(t[0])&&"}"===t[t.length-1]&&!l.length?t.join(" "):null}(a):null;return null===y?"":[f,y]}async function s([e,t],n){let r=new Uint8Array(await n.digest("SHA-256",(new TextEncoder).encode(t))),l="";for(let e=0;e<8;e++)l+=r[e].toString(16).padStart(2,"0");return`graphql:${e}#${l}`}async function a(e,t){let n=o(e);return"string"==typeof n?n:s(n,t)}function f(t,n){let r=function(t){return null==t||""===t?"":"string"==typeof t?t.length>4194304?"body:*":function(t){return e.test(t)&&(t.includes('"query"')||t.includes("persistedQuery")||t.includes("\\u"))}(t)?null:"":t instanceof URLSearchParams||typeof FormData<"u"&&t instanceof FormData?"":"body:*"}(t);if(null!==r)return r;let l=o(t);return"string"==typeof l?l:n?s(l,n):"body:*"}export{f as recordTermFor,a as requestTerm,t as version};//# sourceMappingURL=request-term.mjs.map