@nagoorkani/session-capture-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,25 @@
1
+ PROPRIETARY SOFTWARE LICENSE
2
+
3
+ Copyright (c) 2026 Nagoorkani2393. All rights reserved.
4
+
5
+ This software, its source code, and its accompanying documentation (the
6
+ "Software") are the proprietary and confidential property of the copyright
7
+ holder.
8
+
9
+ NO LICENSE IS GRANTED. No person or entity is permitted to use, copy, modify,
10
+ merge, publish, distribute, sublicense, reverse engineer, create derivative
11
+ works from, or sell the Software, in whole or in part, by any means, except
12
+ under a separate written agreement signed by the copyright holder.
13
+
14
+ Availability of the Software through a public package registry, source
15
+ repository, or any other distribution channel is for the convenience of
16
+ authorized licensees only. It does not grant any license, right, or permission
17
+ to the general public, and no such license may be implied from that
18
+ availability. Unauthorized use, reproduction, or distribution is prohibited.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
24
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
25
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,42 @@
1
+ # @nagoorkani/session-capture-core
2
+
3
+ Everything the SDK does that is not about a platform. Not published on its own
4
+ and not meant to be installed directly — `@nagoorkani/session-capture-expo` and
5
+ `@nagoorkani/session-capture-vue` are the packages an application uses.
6
+
7
+ ## What is in here
8
+
9
+ Sessions and sampling, batching, the durable send queue and its dispatcher,
10
+ redaction, remote config with its cache, transport and retry, and the error,
11
+ network and performance capture that hangs off globals a browser and a React
12
+ Native runtime both provide.
13
+
14
+ ## What is not
15
+
16
+ Three things, which is the whole reason the platform packages exist:
17
+
18
+ | Seam | Expo | Vue |
19
+ | --- | --- | --- |
20
+ | Where bytes are stored | `expo-file-system` | `localStorage` |
21
+ | Foreground and background | `AppState` | `visibilitychange`, `pagehide` |
22
+ | What the device is | `Platform` | `navigator` |
23
+
24
+ `SdkCore` takes all three by injection, which is also what keeps it testable in
25
+ Node: every test in this package runs without a device or a browser.
26
+
27
+ ## Why not one copy per SDK
28
+
29
+ Redaction and sampling would be the copies that drift. The privacy invariant
30
+ says field SDKs are often months old and cannot be trusted to be current —
31
+ that is about deployed versions, and two copies in one repository is the same
32
+ failure with less excuse.
33
+
34
+ ```bash
35
+ pnpm --filter @nagoorkani/session-capture-core test
36
+ ```
37
+
38
+ ## License
39
+
40
+ Proprietary — all rights reserved. See [LICENSE](./LICENSE). No use, copying,
41
+ modification or distribution is permitted without a written agreement with the
42
+ copyright holder.
@@ -0,0 +1,58 @@
1
+ /**
2
+ * In-memory event batching.
3
+ *
4
+ * Events accumulate until the batch fills or the flush interval elapses,
5
+ * whichever comes first — one HTTP request per batch, never per event.
6
+ *
7
+ * Phase 2 is memory only. Durable queueing, retry, and backpressure are
8
+ * Phase 7; until then a failed flush loses that batch, which is acceptable
9
+ * while there is no endpoint to send to.
10
+ */
11
+ import type { CaptureEvent } from './types.ts';
12
+ export type FlushHandler = (events: CaptureEvent[]) => void | Promise<void>;
13
+ export interface BatcherOptions {
14
+ maxSize: number;
15
+ flushIntervalMs: number;
16
+ onFlush: FlushHandler;
17
+ /**
18
+ * Hard ceiling on buffered events.
19
+ *
20
+ * Without this, an app that captures while offline grows the buffer until
21
+ * the process is OOM-killed — the SDK taking down the host app, which is
22
+ * the one thing it must never do.
23
+ */
24
+ maxBuffered?: number;
25
+ }
26
+ export declare class Batcher {
27
+ private buffer;
28
+ private timer;
29
+ private readonly maxBuffered;
30
+ private droppedCount;
31
+ private readonly options;
32
+ constructor(options: BatcherOptions);
33
+ /** Events discarded due to the buffer ceiling. */
34
+ get dropped(): number;
35
+ get size(): number;
36
+ add(event: CaptureEvent): void;
37
+ /** Send whatever is buffered. No-op when empty. */
38
+ flush(): Promise<void>;
39
+ /**
40
+ * Adopt new batching parameters, e.g. from remote config.
41
+ *
42
+ * A pending timer is left alone deliberately: restarting it on every config
43
+ * fetch would let a short interval keep resetting itself and delay the flush
44
+ * indefinitely. The new interval applies from the next scheduled flush.
45
+ */
46
+ reconfigure(options: Partial<Pick<BatcherOptions, 'maxSize' | 'flushIntervalMs'>>): void;
47
+ /** Stop the timer. Call during teardown; does not flush. */
48
+ stop(): void;
49
+ /**
50
+ * Discard everything buffered and stop the timer.
51
+ *
52
+ * For consent withdrawal and the remote kill switch, where the buffer must
53
+ * not merely go unsent — it must go. Returns how many events were dropped.
54
+ */
55
+ drop(): number;
56
+ private scheduleFlush;
57
+ private clearTimer;
58
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * In-memory event batching.
3
+ *
4
+ * Events accumulate until the batch fills or the flush interval elapses,
5
+ * whichever comes first — one HTTP request per batch, never per event.
6
+ *
7
+ * Phase 2 is memory only. Durable queueing, retry, and backpressure are
8
+ * Phase 7; until then a failed flush loses that batch, which is acceptable
9
+ * while there is no endpoint to send to.
10
+ */
11
+ const DEFAULT_MAX_BUFFERED = 1000;
12
+ export class Batcher {
13
+ constructor(options) {
14
+ this.buffer = [];
15
+ this.timer = null;
16
+ this.droppedCount = 0;
17
+ this.options = options;
18
+ this.maxBuffered = options.maxBuffered ?? DEFAULT_MAX_BUFFERED;
19
+ }
20
+ /** Events discarded due to the buffer ceiling. */
21
+ get dropped() {
22
+ return this.droppedCount;
23
+ }
24
+ get size() {
25
+ return this.buffer.length;
26
+ }
27
+ add(event) {
28
+ if (this.buffer.length >= this.maxBuffered) {
29
+ // Drop oldest. Recent events are the ones near whatever the user is
30
+ // currently reporting, so they are worth more than the backlog.
31
+ this.buffer.shift();
32
+ this.droppedCount += 1;
33
+ }
34
+ this.buffer.push(event);
35
+ if (this.buffer.length >= this.options.maxSize) {
36
+ void this.flush();
37
+ return;
38
+ }
39
+ this.scheduleFlush();
40
+ }
41
+ /** Send whatever is buffered. No-op when empty. */
42
+ async flush() {
43
+ this.clearTimer();
44
+ if (this.buffer.length === 0) {
45
+ return;
46
+ }
47
+ // Detach before awaiting, so events captured during the flush land in the
48
+ // next batch instead of being dropped by the reset below.
49
+ const events = this.buffer;
50
+ this.buffer = [];
51
+ await this.options.onFlush(events);
52
+ }
53
+ /**
54
+ * Adopt new batching parameters, e.g. from remote config.
55
+ *
56
+ * A pending timer is left alone deliberately: restarting it on every config
57
+ * fetch would let a short interval keep resetting itself and delay the flush
58
+ * indefinitely. The new interval applies from the next scheduled flush.
59
+ */
60
+ reconfigure(options) {
61
+ if (options.maxSize !== undefined) {
62
+ this.options.maxSize = options.maxSize;
63
+ }
64
+ if (options.flushIntervalMs !== undefined) {
65
+ this.options.flushIntervalMs = options.flushIntervalMs;
66
+ }
67
+ // A smaller maxSize can leave the buffer already over the new limit.
68
+ if (this.buffer.length >= this.options.maxSize) {
69
+ void this.flush();
70
+ }
71
+ }
72
+ /** Stop the timer. Call during teardown; does not flush. */
73
+ stop() {
74
+ this.clearTimer();
75
+ }
76
+ /**
77
+ * Discard everything buffered and stop the timer.
78
+ *
79
+ * For consent withdrawal and the remote kill switch, where the buffer must
80
+ * not merely go unsent — it must go. Returns how many events were dropped.
81
+ */
82
+ drop() {
83
+ this.clearTimer();
84
+ const dropped = this.buffer.length;
85
+ this.buffer = [];
86
+ return dropped;
87
+ }
88
+ scheduleFlush() {
89
+ if (this.timer !== null) {
90
+ return;
91
+ }
92
+ this.timer = setTimeout(() => {
93
+ this.timer = null;
94
+ void this.flush();
95
+ }, this.options.flushIntervalMs);
96
+ // Never hold the Node event loop open. Harmless in React Native, and it
97
+ // keeps the SDK from hanging a test runner or a CLI that imports it.
98
+ this.timer?.unref?.();
99
+ }
100
+ clearTimer() {
101
+ if (this.timer !== null) {
102
+ clearTimeout(this.timer);
103
+ this.timer = null;
104
+ }
105
+ }
106
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Breadcrumb ring buffer.
3
+ *
4
+ * The session timeline already holds every event in order, so this is not a
5
+ * second copy of the truth — it exists so an *error* is self-contained. The
6
+ * error view needs "what happened just before" without fetching and
7
+ * reassembling the whole session from S3 first.
8
+ *
9
+ * Bounded and compact on purpose: it rides along with every error payload.
10
+ */
11
+ export interface Breadcrumb {
12
+ /** Milliseconds before the error. Relative, so it stays small on the wire. */
13
+ t: number;
14
+ type: string;
15
+ message?: string;
16
+ data?: Record<string, unknown>;
17
+ }
18
+ export declare function addBreadcrumb(type: string, message?: string, data?: Record<string, unknown>, maskedKeys?: readonly string[], now?: number): void;
19
+ /** Snapshot the buffer as offsets relative to `now`, oldest first. */
20
+ export declare function snapshotBreadcrumbs(now?: number): Breadcrumb[];
21
+ export declare function clearBreadcrumbs(): void;
22
+ export declare function breadcrumbCount(): number;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Breadcrumb ring buffer.
3
+ *
4
+ * The session timeline already holds every event in order, so this is not a
5
+ * second copy of the truth — it exists so an *error* is self-contained. The
6
+ * error view needs "what happened just before" without fetching and
7
+ * reassembling the whole session from S3 first.
8
+ *
9
+ * Bounded and compact on purpose: it rides along with every error payload.
10
+ */
11
+ import { redact } from "./redact.js";
12
+ /** Kept small: this is attached to every error, not stored once. */
13
+ const MAX_BREADCRUMBS = 20;
14
+ /** Truncation guard for a single crumb's message. */
15
+ const MAX_MESSAGE_CHARS = 200;
16
+ const buffer = [];
17
+ export function addBreadcrumb(type, message, data, maskedKeys = [], now = Date.now()) {
18
+ if (buffer.length >= MAX_BREADCRUMBS) {
19
+ // Drop oldest. Recent context is what explains the error.
20
+ buffer.shift();
21
+ }
22
+ const crumb = { timestamp: now, type };
23
+ if (message !== undefined) {
24
+ crumb.message = message.slice(0, MAX_MESSAGE_CHARS);
25
+ }
26
+ if (data !== undefined) {
27
+ // Redact here rather than at attach time: an unredacted credential must
28
+ // never sit in memory waiting for an error that may never come.
29
+ crumb.data = redact(data, maskedKeys);
30
+ }
31
+ buffer.push(crumb);
32
+ }
33
+ /** Snapshot the buffer as offsets relative to `now`, oldest first. */
34
+ export function snapshotBreadcrumbs(now = Date.now()) {
35
+ return buffer.map(({ timestamp, ...rest }) => ({
36
+ t: now - timestamp,
37
+ ...rest,
38
+ }));
39
+ }
40
+ export function clearBreadcrumbs() {
41
+ buffer.length = 0;
42
+ }
43
+ export function breadcrumbCount() {
44
+ return buffer.length;
45
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Remote configuration — fetch, sanitize, cache.
3
+ *
4
+ * This is the only channel that can change the behaviour of an SDK already
5
+ * shipped inside someone else's app, and `enabled: false` is the kill switch
6
+ * (section 39). It therefore has to work when the server is unreachable,
7
+ * unreadable, or wrong, without ever throwing into the host app.
8
+ *
9
+ * The fallback ladder, in order: live response, cached copy, compiled
10
+ * defaults.
11
+ */
12
+ import type { FileStore } from './store.ts';
13
+ import { type RemoteConfig } from './types.ts';
14
+ /** How long a config request may hang before it is abandoned. */
15
+ export declare const FETCH_TIMEOUT_MS = 10000;
16
+ /**
17
+ * Bounds, matching the server's own validation in
18
+ * `crates/storage/src/settings.rs`.
19
+ *
20
+ * Duplicated rather than derived because the point is to survive a server that
21
+ * is wrong — a compromised or simply buggy response must not be able to
22
+ * configure the device into a tight request loop.
23
+ */
24
+ export declare const LIMITS: {
25
+ readonly batchSize: {
26
+ readonly min: 1;
27
+ readonly max: 1000;
28
+ };
29
+ readonly flushIntervalMs: {
30
+ readonly min: 1000;
31
+ readonly max: number;
32
+ };
33
+ readonly listEntries: 100;
34
+ };
35
+ /**
36
+ * Coerce an arbitrary payload into a usable config.
37
+ *
38
+ * Field by field, never all-or-nothing: one bad value must not discard the
39
+ * rest of the response, because the rest of the response might be carrying the
40
+ * kill switch.
41
+ */
42
+ export declare function sanitizeConfig(raw: unknown, base?: RemoteConfig): RemoteConfig;
43
+ export interface FetchConfigOptions {
44
+ endpoint: string;
45
+ apiKey: string;
46
+ projectId: string;
47
+ fetchImpl?: typeof fetch;
48
+ timeoutMs?: number;
49
+ }
50
+ /**
51
+ * Fetch live config, or null if it could not be obtained.
52
+ *
53
+ * Null means "keep what you have" — never "fall back to defaults". A network
54
+ * blip must not silently re-enable an SDK that was deliberately killed.
55
+ */
56
+ export declare function fetchRemoteConfig(options: FetchConfigOptions): Promise<RemoteConfig | null>;
57
+ /** Read the cached copy, or null when there isn't a usable one. */
58
+ export declare function loadCachedConfig(store: FileStore): Promise<RemoteConfig | null>;
59
+ /** Persist config so the next cold start begins from it rather than defaults. */
60
+ export declare function saveConfig(store: FileStore, config: RemoteConfig): Promise<void>;
package/dist/config.js ADDED
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Remote configuration — fetch, sanitize, cache.
3
+ *
4
+ * This is the only channel that can change the behaviour of an SDK already
5
+ * shipped inside someone else's app, and `enabled: false` is the kill switch
6
+ * (section 39). It therefore has to work when the server is unreachable,
7
+ * unreadable, or wrong, without ever throwing into the host app.
8
+ *
9
+ * The fallback ladder, in order: live response, cached copy, compiled
10
+ * defaults.
11
+ */
12
+ import { DEFAULT_CONFIG } from "./types.js";
13
+ /** How long a config request may hang before it is abandoned. */
14
+ export const FETCH_TIMEOUT_MS = 10000;
15
+ /**
16
+ * Bounds, matching the server's own validation in
17
+ * `crates/storage/src/settings.rs`.
18
+ *
19
+ * Duplicated rather than derived because the point is to survive a server that
20
+ * is wrong — a compromised or simply buggy response must not be able to
21
+ * configure the device into a tight request loop.
22
+ */
23
+ export const LIMITS = {
24
+ batchSize: { min: 1, max: 1000 },
25
+ flushIntervalMs: { min: 1000, max: 5 * 60 * 1000 },
26
+ listEntries: 100,
27
+ };
28
+ /** The single cache entry, in a directory of its own. See `store-expo.ts`. */
29
+ const CACHE_FILE = 'remote-config.json';
30
+ function clamp(value, min, max) {
31
+ return Math.min(max, Math.max(min, value));
32
+ }
33
+ function asNumber(value, fallback, min, max) {
34
+ return typeof value === 'number' && Number.isFinite(value)
35
+ ? clamp(value, min, max)
36
+ : fallback;
37
+ }
38
+ function asBoolean(value, fallback) {
39
+ return typeof value === 'boolean' ? value : fallback;
40
+ }
41
+ function asStringList(value, fallback) {
42
+ if (!Array.isArray(value))
43
+ return [...fallback];
44
+ return value
45
+ .filter((entry) => typeof entry === 'string' && entry.length > 0)
46
+ .slice(0, LIMITS.listEntries);
47
+ }
48
+ /**
49
+ * Coerce an arbitrary payload into a usable config.
50
+ *
51
+ * Field by field, never all-or-nothing: one bad value must not discard the
52
+ * rest of the response, because the rest of the response might be carrying the
53
+ * kill switch.
54
+ */
55
+ export function sanitizeConfig(raw, base = DEFAULT_CONFIG) {
56
+ if (typeof raw !== 'object' || raw === null) {
57
+ return { ...base };
58
+ }
59
+ const input = raw;
60
+ return {
61
+ enabled: asBoolean(input.enabled, base.enabled),
62
+ sampleRate: asNumber(input.sampleRate, base.sampleRate, 0, 1),
63
+ batchSize: Math.round(asNumber(input.batchSize, base.batchSize, LIMITS.batchSize.min, LIMITS.batchSize.max)),
64
+ flushIntervalMs: Math.round(asNumber(input.flushIntervalMs, base.flushIntervalMs, LIMITS.flushIntervalMs.min, LIMITS.flushIntervalMs.max)),
65
+ maskedKeys: asStringList(input.maskedKeys, base.maskedKeys),
66
+ urlDenyList: asStringList(input.urlDenyList, base.urlDenyList),
67
+ captureBodies: asBoolean(input.captureBodies, base.captureBodies),
68
+ replayEnabled: asBoolean(input.replayEnabled, base.replayEnabled),
69
+ replaySampleRate: asNumber(input.replaySampleRate, base.replaySampleRate, 0, 1),
70
+ configVersion: Math.round(asNumber(input.configVersion, base.configVersion, 0, Number.MAX_SAFE_INTEGER)),
71
+ };
72
+ }
73
+ /**
74
+ * Fetch live config, or null if it could not be obtained.
75
+ *
76
+ * Null means "keep what you have" — never "fall back to defaults". A network
77
+ * blip must not silently re-enable an SDK that was deliberately killed.
78
+ */
79
+ export async function fetchRemoteConfig(options) {
80
+ const doFetch = options.fetchImpl ?? fetch;
81
+ const base = options.endpoint.replace(/\/$/, '');
82
+ // Same origin as the ingest endpoint, so `shouldCapture` already excludes
83
+ // this request from network capture. Capturing our own config poll would be
84
+ // noise at best and a feedback loop at worst.
85
+ const url = `${base}/v1/config?projectId=${encodeURIComponent(options.projectId)}`;
86
+ const controller = new AbortController();
87
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? FETCH_TIMEOUT_MS);
88
+ try {
89
+ const response = await doFetch(url, {
90
+ method: 'GET',
91
+ headers: {
92
+ accept: 'application/json',
93
+ authorization: `Bearer ${options.apiKey}`,
94
+ },
95
+ signal: controller.signal,
96
+ });
97
+ if (!response.ok) {
98
+ return null;
99
+ }
100
+ return sanitizeConfig(await response.json());
101
+ }
102
+ catch {
103
+ // Offline, timed out, or a body that was not JSON. The caller keeps its
104
+ // current config.
105
+ return null;
106
+ }
107
+ finally {
108
+ clearTimeout(timer);
109
+ }
110
+ }
111
+ /** Read the cached copy, or null when there isn't a usable one. */
112
+ export async function loadCachedConfig(store) {
113
+ try {
114
+ const raw = await store.read(CACHE_FILE);
115
+ if (raw === null)
116
+ return null;
117
+ return sanitizeConfig(JSON.parse(raw));
118
+ }
119
+ catch {
120
+ // Corrupt or unreadable. Not worth clearing — the next successful fetch
121
+ // overwrites it.
122
+ return null;
123
+ }
124
+ }
125
+ /** Persist config so the next cold start begins from it rather than defaults. */
126
+ export async function saveConfig(store, config) {
127
+ try {
128
+ await store.write(CACHE_FILE, JSON.stringify(config));
129
+ }
130
+ catch {
131
+ // A cache that cannot be written costs one extra fetch next launch. It is
132
+ // not a reason to fail anything.
133
+ }
134
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The replay frame container.
3
+ *
4
+ * Mirrors `crates/event-schema/src/replay.rs` byte for byte. The two are
5
+ * hand-written in different languages, which is exactly the drift risk
6
+ * section 51 warns about — so the format is documented in one place (the Rust
7
+ * module) and the encoder is pinned by tests on both sides against fixtures
8
+ * that fail if either moves.
9
+ *
10
+ * ```text
11
+ * magic 4 bytes "SCR1" screenshots, "SCR2" DOM events
12
+ * count 4 bytes u32 little-endian
13
+ * per frame:
14
+ * timestamp 8 bytes i64 little-endian, device clock, milliseconds
15
+ * length 4 bytes u32 little-endian
16
+ * payload length bytes
17
+ * ```
18
+ *
19
+ * Two payloads, one framing, because a browser cannot photograph itself: a web
20
+ * recording is DOM mutations rather than screenshots. Everything between the
21
+ * SDK and the player treats a frame as opaque bytes with a timestamp, so both
22
+ * kinds share the same intake, S3 layout, index row and retention.
23
+ */
24
+ /** Screenshots, from the mobile replay package. */
25
+ export declare const MAGIC_SCREENSHOTS = "SCR1";
26
+ /** DOM events, from the web replay package. */
27
+ export declare const MAGIC_DOM = "SCR2";
28
+ export interface ContainerFrame {
29
+ /** Device clock, milliseconds. Display only, as everywhere else. */
30
+ timestamp: number;
31
+ payload: Uint8Array;
32
+ }
33
+ export declare function encodeContainer(magic: typeof MAGIC_SCREENSHOTS | typeof MAGIC_DOM, frames: readonly ContainerFrame[]): Uint8Array;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The replay frame container.
3
+ *
4
+ * Mirrors `crates/event-schema/src/replay.rs` byte for byte. The two are
5
+ * hand-written in different languages, which is exactly the drift risk
6
+ * section 51 warns about — so the format is documented in one place (the Rust
7
+ * module) and the encoder is pinned by tests on both sides against fixtures
8
+ * that fail if either moves.
9
+ *
10
+ * ```text
11
+ * magic 4 bytes "SCR1" screenshots, "SCR2" DOM events
12
+ * count 4 bytes u32 little-endian
13
+ * per frame:
14
+ * timestamp 8 bytes i64 little-endian, device clock, milliseconds
15
+ * length 4 bytes u32 little-endian
16
+ * payload length bytes
17
+ * ```
18
+ *
19
+ * Two payloads, one framing, because a browser cannot photograph itself: a web
20
+ * recording is DOM mutations rather than screenshots. Everything between the
21
+ * SDK and the player treats a frame as opaque bytes with a timestamp, so both
22
+ * kinds share the same intake, S3 layout, index row and retention.
23
+ */
24
+ /** Screenshots, from the mobile replay package. */
25
+ export const MAGIC_SCREENSHOTS = 'SCR1';
26
+ /** DOM events, from the web replay package. */
27
+ export const MAGIC_DOM = 'SCR2';
28
+ export function encodeContainer(magic, frames) {
29
+ const total = 8 + frames.reduce((sum, frame) => sum + 12 + frame.payload.byteLength, 0);
30
+ const out = new Uint8Array(total);
31
+ const view = new DataView(out.buffer);
32
+ for (let i = 0; i < 4; i += 1) {
33
+ out[i] = magic.charCodeAt(i);
34
+ }
35
+ view.setUint32(4, frames.length, true);
36
+ let offset = 8;
37
+ for (const frame of frames) {
38
+ // BigInt because a millisecond epoch does not fit in 32 bits and
39
+ // setUint32 would silently truncate it to 1970-something.
40
+ view.setBigInt64(offset, BigInt(Math.trunc(frame.timestamp)), true);
41
+ offset += 8;
42
+ view.setUint32(offset, frame.payload.byteLength, true);
43
+ offset += 4;
44
+ out.set(frame.payload, offset);
45
+ offset += frame.payload.byteLength;
46
+ }
47
+ return out;
48
+ }