@zharp/electron 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,315 @@
1
+ /** Anything JSON can hold. Objects and arrays are sent as they are and shown as JSON. */
2
+ type Attributes = Record<string, unknown>;
3
+ interface ZharpUser {
4
+ /** Sent as `enduser.id`. An ID or an email — whatever identifies the person in your app. */
5
+ id: string | number;
6
+ /** Sent as `enduser.email`. */
7
+ email?: string;
8
+ /** Sent as `enduser.name`. */
9
+ name?: string;
10
+ }
11
+ /** One recorded rrweb event, as `replay.beforeSend` sees it. Declared here so the main types never load rrweb. */
12
+ interface ReplayEvent {
13
+ type: number;
14
+ data: unknown;
15
+ timestamp: number;
16
+ [key: string]: unknown;
17
+ }
18
+ interface ReplayOptions {
19
+ /**
20
+ * Fraction of sessions recorded from start to end, 0 to 1. Default 0. Decided once per
21
+ * session; a session that is not sampled never downloads the recorder.
22
+ */
23
+ sampleRate?: number;
24
+ /**
25
+ * Fraction of the remaining sessions that keep the last minute in memory and upload it —
26
+ * with the rest of the session — only when an error happens. Default 0. `1.0` means every
27
+ * session with an error comes with a replay, at no upload cost for the ones without.
28
+ */
29
+ onErrorSampleRate?: number;
30
+ /**
31
+ * Mask what is typed into every input, textarea and select. Default **true**. Turning it off
32
+ * sends passwords and card numbers unless `blockSelector` covers them.
33
+ */
34
+ maskAllInputs?: boolean;
35
+ /** Mask all text on the page, not just inputs. Default false. */
36
+ maskAllText?: boolean;
37
+ /** Elements left out of the recording entirely (a payment iframe, a private document). */
38
+ blockSelector?: string;
39
+ /** Elements whose text is masked. */
40
+ maskTextSelector?: string;
41
+ /** Called with each batch before it is sent. Return false to drop it. */
42
+ beforeSend?: (events: ReplayEvent[]) => boolean;
43
+ /**
44
+ * Where the script-tag build loads the recorder from. Default: `zharp-replay.min.js` next to
45
+ * `zharp.min.js`. Bundled builds ignore it — the recorder is a lazily imported chunk there.
46
+ */
47
+ recorderUrl?: string;
48
+ }
49
+ /** `captureBodies`: which request and response bodies go on request spans. */
50
+ interface CaptureBodiesOptions {
51
+ /** `errors` (default): failed requests only (status 400 and above, or no response). `all`: every request. */
52
+ mode?: 'errors' | 'all';
53
+ /** Characters kept per body. Default 32768 (32 KB), at most 131072 (128 KB). */
54
+ maxSize?: number;
55
+ /**
56
+ * More keys whose values are replaced with `[Filtered]`, on top of the built-in ones. A string
57
+ * matches a key ignoring case, `-` and `_`; a RegExp is tested against the key as it is.
58
+ */
59
+ redactKeys?: Array<string | RegExp>;
60
+ /**
61
+ * Which requests have their bodies captured, matched like `tracingOrigins`. Default:
62
+ * same-origin requests and `tracingOrigins` — your own APIs, never third parties.
63
+ */
64
+ urls?: Array<string | RegExp>;
65
+ }
66
+ /** `true` is `'errors'`. */
67
+ type CaptureBodies = boolean | 'errors' | 'all' | CaptureBodiesOptions;
68
+ interface BrowserOptions {
69
+ /** The app's key from the Zharp dashboard (`zpk_…`). Safe to ship in a page: it can only send. */
70
+ key: string;
71
+ /** `service.name`, e.g. `checkout-web`. */
72
+ service?: string;
73
+ /** `deployment.environment.name`, e.g. `production`. */
74
+ environment?: string;
75
+ /** `service.version`, e.g. `web@2.3.0` or a commit SHA. */
76
+ release?: string;
77
+ /** Default `https://api.zharp.io/api/v1/otlp`. */
78
+ endpoint?: string;
79
+ /**
80
+ * Hosts (or URL prefixes, or patterns) that get `traceparent` and `baggage` headers, so their
81
+ * spans join the page's trace. Same-origin requests always do. Nothing else does: an unknown
82
+ * header on a third-party request can make it fail CORS.
83
+ *
84
+ * `"api.example.com"` matches that host on any port and scheme; `"https://api.example.com/v2"`
85
+ * matches URLs starting with it; a RegExp is tested against the full URL.
86
+ */
87
+ tracingOrigins?: Array<string | RegExp>;
88
+ /**
89
+ * Traces. Default **true**. `false` is logs only: logs, errors, the user, the session and tags
90
+ * are sent as usual, but no spans are made (no page load, navigation, click or request spans),
91
+ * `fetch` and `XMLHttpRequest` are not patched, and no `traceparent` or `baggage` header is
92
+ * added to any request. `startSpan` just runs its callback. Session replay is independent —
93
+ * it follows `replay` either way; without traces a replay simply has no trace ids linked to it.
94
+ */
95
+ tracing?: boolean;
96
+ /** Fraction of traces to keep, 0 to 1. Default 1. Errors, logs and replays are not affected. */
97
+ sampleRate?: number;
98
+ /** Session replay. Off unless a sample rate is set. */
99
+ replay?: ReplayOptions;
100
+ /**
101
+ * Copy `console.*` calls into Zharp as logs: `true` for all levels, or a list such as
102
+ * `["warn", "error"]`. Default **off** — a page's console is mostly other people's libraries.
103
+ */
104
+ captureConsole?: boolean | Array<'debug' | 'log' | 'info' | 'warn' | 'error'>;
105
+ /**
106
+ * Send the page's logs: its `console` output, every level (or the levels `captureConsole`
107
+ * lists). Default **off**, as in every Zharp SDK. Errors, `Zharp.log`, traces, sessions and
108
+ * replays are sent either way. The same as `captureConsole: true`.
109
+ */
110
+ logs?: boolean;
111
+ /** Spans for clicks that lead to requests. Default true. */
112
+ interactions?: boolean;
113
+ /**
114
+ * Request and response bodies on request spans. Default **off**. `'errors'` (or `true`) keeps
115
+ * them for failed requests only (status 400 and above, or no response); `'all'` for every
116
+ * request. Only your own APIs — same-origin and `tracingOrigins` — unless `urls` is set.
117
+ * Text is capped at 32 KB; files, inline images and binary bodies are described (name, type,
118
+ * size), never sent. Field names are always kept; values under secret-looking keys
119
+ * (`password`, `token`, `authorization`, `card`, …) are replaced with `[Filtered]` before
120
+ * anything is sent. Other personal data in a body is sent as it is: add its keys to `redactKeys`.
121
+ *
122
+ * captureBodies: 'errors'
123
+ * captureBodies: { mode: 'all', redactKeys: ['dateOfBirth'], maxSize: 4096 }
124
+ */
125
+ captureBodies?: CaptureBodies;
126
+ /**
127
+ * Request and response headers on fetch/XHR spans (`http.request.header.*`,
128
+ * `http.response.header.*`), so a failed request shows what was sent and what came back.
129
+ * Default **on**. Secret headers (`authorization`, `cookie`, API keys, tokens…) are recorded as
130
+ * `[Filtered]`. The browser only lets a page read the response headers the server exposes
131
+ * (CORS). `false` turns it off; `{ redact: ['x-tenant'] }` filters more names.
132
+ */
133
+ captureHeaders?: boolean | {
134
+ redact?: Array<string | RegExp>;
135
+ };
136
+ /** URLs never traced (no span, no headers), e.g. analytics beacons. */
137
+ ignoreUrls?: Array<string | RegExp>;
138
+ /** Minutes without activity before a new session starts. Default 30. */
139
+ sessionTimeoutMinutes?: number;
140
+ }
141
+
142
+ type ReplayMode = 'off' | 'session' | 'buffer';
143
+ interface SessionState {
144
+ id: string;
145
+ started: number;
146
+ lastActive: number;
147
+ /** The replay decision, made once per session. Absent until replay has decided. */
148
+ replay?: ReplayMode;
149
+ /** Next replay batch number. Persisted so a reload does not reuse numbers the server already has. */
150
+ seq?: number;
151
+ user?: ZharpUser | null;
152
+ }
153
+ /** Where the session is kept: the tab's sessionStorage on the web, the device on mobile. */
154
+ interface SessionStore {
155
+ get(key: string): string | null;
156
+ set(key: string, value: string): void;
157
+ }
158
+ declare class Session {
159
+ private readonly timeoutMs;
160
+ private readonly store;
161
+ private state;
162
+ private lastWrite;
163
+ private readonly listeners;
164
+ constructor(timeoutMs: number, store?: SessionStore);
165
+ /** The current session, after starting a new one if this one has expired. */
166
+ get current(): SessionState;
167
+ get id(): string;
168
+ /** Something happened: the session is still going. */
169
+ touch(): void;
170
+ /** Start a new session now. The user carries over unless `user` is given. */
171
+ renew(user?: ZharpUser | null): void;
172
+ update(patch: Partial<SessionState>): void;
173
+ /** Called with the new state whenever a session ends and another begins. */
174
+ onRenew(listener: (state: SessionState) => void): void;
175
+ private read;
176
+ private write;
177
+ }
178
+
179
+ declare const SEVERITY: {
180
+ readonly trace: 1;
181
+ readonly debug: 5;
182
+ readonly info: 9;
183
+ readonly warn: 13;
184
+ readonly error: 17;
185
+ readonly fatal: 21;
186
+ };
187
+ type Level = keyof typeof SEVERITY;
188
+ type LogFn = (message: unknown, attributes?: Attributes) => void;
189
+ /** A manual span, as `Zharp.startSpan` hands it to its callback. */
190
+ interface ZharpSpan {
191
+ readonly traceId: string;
192
+ readonly spanId: string;
193
+ setAttribute(key: string, value: unknown): ZharpSpan;
194
+ setAttributes(attributes: Attributes): ZharpSpan;
195
+ }
196
+ /**
197
+ * @internal What a host around the page provides in place of the page's own: @zharp/electron's
198
+ * renderer sends through the main process and shares the main process's session.
199
+ */
200
+ interface BrowserHost {
201
+ /** Used in place of fetch to send each batch. */
202
+ fetch: typeof fetch;
203
+ /** The session, kept elsewhere. */
204
+ session: Session;
205
+ /** More resource attributes (the Electron version, the process). */
206
+ resource?: Record<string, unknown>;
207
+ /** The scope the records are sent under. */
208
+ scope?: {
209
+ name: string;
210
+ version: string;
211
+ };
212
+ }
213
+ declare class ZharpBrowser {
214
+ private readonly host?;
215
+ private running;
216
+ private user;
217
+ constructor(host?: BrowserHost | undefined);
218
+ private readonly tags;
219
+ /** Errors already reported, so one caught by the app and then rethrown is sent once. */
220
+ private readonly reported;
221
+ readonly log: Record<Level, LogFn>;
222
+ get isActive(): boolean;
223
+ /** The current session's ID, e.g. to show on a support page. */
224
+ get sessionId(): string | undefined;
225
+ init(options: BrowserOptions): void;
226
+ private start;
227
+ /** The page load span: from navigation start until the load event, its requests, and a quiet second. */
228
+ private startPageLoad;
229
+ /**
230
+ * Who is using the page: `enduser.id` (and `enduser.email`, `enduser.name`) on everything sent
231
+ * from now on, and in the `baggage` header so the back end's spans and logs carry it too.
232
+ * Call it after login and on every page load while logged in.
233
+ */
234
+ setUser(user: ZharpUser | null): void;
235
+ /** Forget the user and start a new session — call it on logout. */
236
+ clearUser(): void;
237
+ /** An attribute on every span and log from now on. `null` removes it. */
238
+ setTag(key: string, value: string | number | boolean | null | undefined): void;
239
+ /** Report an error you caught. Sent as handled, and grouped into an issue with its other occurrences. */
240
+ captureError(error: unknown, attributes?: Attributes): void;
241
+ /**
242
+ * React 19: the handler for createRoot's (or hydrateRoot's) error options. Each error a render
243
+ * throws is reported once, as a crash, with the component stack — which components were
244
+ * rendering — next to its own stack:
245
+ *
246
+ * createRoot(el, {
247
+ * onUncaughtError: Zharp.reactErrorHandler(),
248
+ * onCaughtError: Zharp.reactErrorHandler(),
249
+ * });
250
+ *
251
+ * React's own reporting (the console) carries on as before; `callback` runs after, for an app
252
+ * that had its own handler there. For React 18, use ZharpErrorBoundary from @zharp/browser/react.
253
+ */
254
+ reactErrorHandler(callback?: (error: unknown, errorInfo: {
255
+ componentStack?: string | null;
256
+ }) => void): (error: unknown, errorInfo?: {
257
+ componentStack?: string | null;
258
+ }) => void;
259
+ /** @internal An error React caught, with the stack of components that were rendering. */
260
+ reportReactError(error: unknown, componentStack?: string | null): void;
261
+ /**
262
+ * Run `fn` in a span named `name`. Requests and logs from its synchronous part belong to it;
263
+ * a promise it returns ends the span when it settles. Errors pass through unchanged.
264
+ */
265
+ startSpan<T>(name: string, fn: (span: ZharpSpan) => T, attributes?: Attributes): T;
266
+ /** Send everything waiting now. */
267
+ flush(): Promise<void>;
268
+ /** Flush and stop: every patch is undone and nothing more is recorded. */
269
+ close(): Promise<void>;
270
+ /** Session, user and tags: on every span and log, as they are when it is sent. */
271
+ private contextAttributes;
272
+ /** The `baggage` header value: session and user, for the back end to copy onto its spans. */
273
+ private baggage;
274
+ private emit;
275
+ private report;
276
+ }
277
+
278
+ /** Sent as `telemetry.sdk.version` and the scope's version. Bumped with package.json. */
279
+ declare const VERSION = "0.1.0";
280
+
281
+ /**
282
+ * @zharp/electron/renderer: errors, logs and traces from a window, sent through the main process.
283
+ *
284
+ * import { Zharp } from '@zharp/electron/renderer';
285
+ * Zharp.init();
286
+ *
287
+ * It is @zharp/browser — uncaught errors and rejections, page loads, fetch and XHR spans with
288
+ * their headers, `traceparent` to your own APIs, the console when asked — with three differences:
289
+ *
290
+ * - Batches go to the main process over IPC and main sends them: no request from the page, so a
291
+ * strict Content-Security-Policy (`connect-src 'self'`) needs no exception, and batches wait in
292
+ * main's queue on disk while the computer is offline.
293
+ * - Every window is in the main process's session, with its user and device ID.
294
+ * - The key, service, release and environment come from `Zharp.init()` in main: nothing to pass
295
+ * here unless a window should differ (`Zharp.init({ captureBodies: 'errors' })`).
296
+ *
297
+ * Needs the preload bridge (added by main's `Zharp.init()`, or `import '@zharp/electron/preload'`
298
+ * in your preload). Without it, it says so once and sends nothing.
299
+ */
300
+
301
+ /** What a window can set for itself; the rest comes from the main process. */
302
+ type RendererOptions = Omit<BrowserOptions, 'key' | 'endpoint' | 'replay' | 'sessionTimeoutMinutes'>;
303
+ declare class ZharpElectronRenderer extends ZharpBrowser {
304
+ private readonly bridged;
305
+ private readonly session;
306
+ private readonly startContext;
307
+ constructor();
308
+ /** Starts the SDK in this window, with the main process's key, service, release and session. */
309
+ init(options?: RendererOptions): void;
310
+ /** The device ID main keeps for this installation. */
311
+ get deviceId(): string | undefined;
312
+ }
313
+ declare const Zharp: ZharpElectronRenderer;
314
+
315
+ export { type Attributes, type CaptureBodies, type CaptureBodiesOptions, type RendererOptions, VERSION, Zharp, ZharpElectronRenderer, type ZharpSpan, type ZharpUser, Zharp as default };