@blipit/react-native 0.3.0 → 0.5.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/dist/index.js CHANGED
@@ -6,8 +6,410 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
6
6
  });
7
7
 
8
8
  // src/index.ts
9
- import * as Sentry from "@sentry/react-native";
10
- import { Dimensions, Platform as Platform2 } from "react-native";
9
+ import { AppState, Dimensions, Platform as Platform2 } from "react-native";
10
+
11
+ // src/nuggets.ts
12
+ var VERSION = "0.5.0";
13
+ var SDK_NAME = "@blipit/react-native";
14
+ var DEFAULT_ENDPOINT = "https://in.blipit.io";
15
+ var CATEGORIES = /* @__PURE__ */ new Set(["ui.click", "ui.input", "navigation", "http", "console", "query", "custom"]);
16
+ var CRUMB_LEVELS = /* @__PURE__ */ new Set(["error", "warning", "info", "debug"]);
17
+ var TAG_KEY = /[^a-zA-Z0-9_.-]/g;
18
+ var SENSITIVE = /\b((?:[a-zA-Z0-9_-]*(?:token|key|password|secret|auth|session|passwd|api)[a-zA-Z0-9_-]*)=)[^&\s"']+/gi;
19
+ var QUEUE_MAX = 30;
20
+ var truncate = (v, max) => v.length > max ? v.slice(0, max) : v;
21
+ var scrub = (text2) => text2.replace(SENSITIVE, "$1[redacted]");
22
+ function uuid32() {
23
+ let out = "";
24
+ for (let i = 0; i < 32; i++) out += Math.floor(Math.random() * 16).toString(16);
25
+ return `${out.slice(0, 12)}4${out.slice(13, 16)}${"89ab"[Math.floor(Math.random() * 4)]}${out.slice(17)}`;
26
+ }
27
+ var HERMES = /^\s*at (?:(.+?) \()?(?:address at )?(.+?):(\d+):(\d+)\)?\s*$/;
28
+ var JSC = /^\s*(?:(.*?)@)?(.+?):(\d+):(\d+)\s*$/;
29
+ function parseStack(stack) {
30
+ if (!stack) return [];
31
+ const frames = [];
32
+ for (const line of stack.split("\n")) {
33
+ const m = HERMES.exec(line) ?? (/^\s*at /.test(line) ? null : JSC.exec(line));
34
+ if (!m) continue;
35
+ const file = m[2].replace(/\?.*$/, "");
36
+ const frame = { filename: truncate(file, 1024), lineno: Number(m[3]), colno: Number(m[4]), in_app: !/node_modules|\[native code\]/.test(file) };
37
+ if (m[1]) frame.function = truncate(m[1], 512);
38
+ frames.push(frame);
39
+ }
40
+ return frames.reverse().slice(-128);
41
+ }
42
+ function cleanCrumb(c, at) {
43
+ const ts = typeof c.timestamp === "number" ? new Date(c.timestamp < 1e12 ? c.timestamp * 1e3 : c.timestamp).toISOString() : c.timestamp ?? at;
44
+ const out = { timestamp: ts, category: c.category && CATEGORIES.has(c.category) ? c.category : "custom" };
45
+ if (c.message) out.message = truncate(scrub(String(c.message)), 1024);
46
+ if (c.level && CRUMB_LEVELS.has(c.level)) out.level = c.level;
47
+ if (c.data && typeof c.data === "object") out.data = typeof c.data.url === "string" ? { ...c.data, url: scrub(c.data.url) } : c.data;
48
+ return out;
49
+ }
50
+ var Nuggets = class {
51
+ endpoint;
52
+ key;
53
+ user;
54
+ tags = {};
55
+ lastEventId;
56
+ enabled;
57
+ onError;
58
+ crumbs = [];
59
+ queue = [];
60
+ captured = /* @__PURE__ */ new WeakSet();
61
+ timer;
62
+ sending;
63
+ pausedUntil = 0;
64
+ fetcher;
65
+ now;
66
+ options;
67
+ constructor(options) {
68
+ this.options = options;
69
+ this.endpoint = (options.endpoint ?? DEFAULT_ENDPOINT).replace(/\/api\/v1\/events.*$/, "").replace(/\/+$/, "");
70
+ this.key = options.key;
71
+ this.enabled = options.enabled !== false;
72
+ this.fetcher = options.fetch ?? ((...a) => fetch(...a));
73
+ this.now = options.now ?? Date.now;
74
+ try {
75
+ const saved = JSON.parse(options.store?.load() ?? "[]");
76
+ if (Array.isArray(saved)) this.queue = saved.slice(-QUEUE_MAX);
77
+ } catch {
78
+ }
79
+ }
80
+ get pending() {
81
+ return this.queue.length;
82
+ }
83
+ url(path) {
84
+ return `${this.endpoint}${path}`;
85
+ }
86
+ setEnabled(on) {
87
+ this.enabled = on;
88
+ if (!on) {
89
+ this.queue = [];
90
+ this.crumbs = [];
91
+ this.persist();
92
+ }
93
+ }
94
+ setUser(user) {
95
+ if (!user) return void (this.user = void 0);
96
+ const u = {};
97
+ if (user.id !== void 0 && user.id !== null) u.id = truncate(String(user.id), 128);
98
+ if (user.email) u.email = truncate(user.email, 256);
99
+ if (user.username) u.username = truncate(user.username, 128);
100
+ this.user = Object.keys(u).length ? u : void 0;
101
+ }
102
+ setTag(key, value) {
103
+ const k = truncate(String(key).replace(TAG_KEY, "_"), 64);
104
+ if (k && (k in this.tags || Object.keys(this.tags).length < 32)) this.tags[k] = truncate(String(value), 256);
105
+ }
106
+ addBreadcrumb(crumb) {
107
+ if (!this.enabled) return;
108
+ this.crumbs.push(cleanCrumb(crumb, new Date(this.now()).toISOString()));
109
+ const max = Math.min(this.options.maxBreadcrumbs ?? 50, 100);
110
+ while (this.crumbs.length > max) this.crumbs.shift();
111
+ }
112
+ captureException(error, handled = true, level = "error") {
113
+ if (error && typeof error === "object") {
114
+ if (this.captured.has(error)) return void 0;
115
+ this.captured.add(error);
116
+ }
117
+ const err = error instanceof Error ? error : new Error(typeof error === "string" ? error : safeJson(error));
118
+ const exception = { type: truncate(err.name || "Error", 256), value: truncate(scrub(err.message || String(err)), 4096), handled };
119
+ const frames = parseStack(err.stack);
120
+ if (frames.length) exception.stacktrace = { frames };
121
+ return this.capture({ exception, level });
122
+ }
123
+ captureMessage(message, level = "info") {
124
+ return this.capture({ message: truncate(scrub(String(message)), 8192), level });
125
+ }
126
+ captureSecurity(kind, message, level, security) {
127
+ return this.capture({ message: truncate(message, 8192), level, ...security ? { security } : {}, tags: { "security.kind": truncate(kind, 256) } }, false);
128
+ }
129
+ capture(partial, filter = true) {
130
+ if (!this.enabled) return void 0;
131
+ if (filter && this.options.sampleRate !== void 0 && Math.random() >= this.options.sampleRate) return void 0;
132
+ const text2 = partial.exception?.value ?? partial.message ?? "";
133
+ if (filter && (this.options.ignoreErrors ?? []).some((p) => typeof p === "string" ? text2.includes(p) : p.test(text2))) return void 0;
134
+ let event = {
135
+ event_id: uuid32(),
136
+ timestamp: new Date(this.now()).toISOString(),
137
+ platform: "react-native",
138
+ level: "error",
139
+ environment: this.options.environment ?? "production",
140
+ sdk: { name: SDK_NAME, version: VERSION },
141
+ ...partial
142
+ };
143
+ if (this.options.release) event.release = truncate(this.options.release, 256);
144
+ if (this.user) event.user = { ...this.user };
145
+ const tags = { ...this.tags, ...partial.tags };
146
+ if (Object.keys(tags).length) event.tags = tags;
147
+ if (this.crumbs.length) event.breadcrumbs = [...this.crumbs];
148
+ const contexts2 = this.options.contexts?.();
149
+ if (contexts2 && Object.keys(contexts2).length) event.contexts = contexts2;
150
+ if (this.options.beforeSend) {
151
+ const out = this.options.beforeSend(event);
152
+ if (!out) return void 0;
153
+ event = out;
154
+ }
155
+ this.enqueue(event);
156
+ this.lastEventId = event.event_id;
157
+ if (event.exception) this.onError?.(!event.exception.handled);
158
+ return event.event_id;
159
+ }
160
+ enqueue(event) {
161
+ if (!this.enabled) return false;
162
+ this.queue.push(event);
163
+ while (this.queue.length > QUEUE_MAX) this.queue.shift();
164
+ this.persist();
165
+ this.schedule(1e3);
166
+ return true;
167
+ }
168
+ persist() {
169
+ try {
170
+ this.options.store?.save(JSON.stringify(this.queue));
171
+ } catch {
172
+ }
173
+ }
174
+ schedule(ms) {
175
+ if (this.timer) return;
176
+ this.timer = setTimeout(() => {
177
+ this.timer = void 0;
178
+ void this.flush();
179
+ }, Math.max(ms, this.pausedUntil - this.now()));
180
+ this.timer.unref?.();
181
+ }
182
+ async flush() {
183
+ while (this.sending) await this.sending;
184
+ this.sending = this.drain().finally(() => this.sending = void 0);
185
+ return this.sending;
186
+ }
187
+ async drain() {
188
+ while (this.queue.length && this.enabled && this.now() >= this.pausedUntil) {
189
+ const event = this.queue[0];
190
+ const verdict = await this.send(event);
191
+ if (verdict === "retry") return this.schedule(3e4);
192
+ if (verdict === "wait") return this.schedule(0);
193
+ if (this.queue[0] === event) this.queue.shift();
194
+ this.persist();
195
+ }
196
+ }
197
+ post(path, body) {
198
+ return this.fetcher(this.url(path), { method: "POST", headers: { "Content-Type": "application/json", "X-Blipit-Key": this.key }, body: JSON.stringify(body) });
199
+ }
200
+ async send(event) {
201
+ try {
202
+ const res = await this.post("/api/v1/events", event);
203
+ if (res.status === 429) {
204
+ const header = Number(res.headers?.get?.("retry-after"));
205
+ let seconds = Number.isFinite(header) && header > 0 ? header : 0;
206
+ if (!seconds) {
207
+ try {
208
+ seconds = Number(JSON.parse(await res.text()).retry_after) || 60;
209
+ } catch {
210
+ seconds = 60;
211
+ }
212
+ }
213
+ this.pausedUntil = this.now() + Math.min(seconds, 3600) * 1e3;
214
+ return "wait";
215
+ }
216
+ if (res.status >= 500) return "retry";
217
+ if (res.status >= 400 && this.options.debug) console.warn("[blipit] event rejected", res.status);
218
+ return "done";
219
+ } catch {
220
+ return "retry";
221
+ }
222
+ }
223
+ };
224
+ var RANK = { ok: 0, errored: 1, crashed: 2 };
225
+ var Session = class {
226
+ sid = "";
227
+ started = "";
228
+ status = "ok";
229
+ errors = 0;
230
+ core;
231
+ release;
232
+ environment;
233
+ constructor(core2, release, environment) {
234
+ this.core = core2;
235
+ this.release = release;
236
+ this.environment = environment;
237
+ }
238
+ start() {
239
+ if (this.sid) return;
240
+ this.sid = uuid32();
241
+ this.started = (/* @__PURE__ */ new Date()).toISOString();
242
+ this.status = "ok";
243
+ this.errors = 0;
244
+ this.send(false);
245
+ }
246
+ end() {
247
+ if (!this.sid) return;
248
+ this.send(true);
249
+ this.sid = "";
250
+ }
251
+ markError(unhandled) {
252
+ if (!this.sid) return;
253
+ this.errors += 1;
254
+ const next = unhandled ? "crashed" : "errored";
255
+ if (RANK[next] <= RANK[this.status]) return;
256
+ this.status = next;
257
+ this.send(false);
258
+ }
259
+ send(ending) {
260
+ if (!this.core.enabled) return;
261
+ const did = this.core.user?.id ?? this.core.user?.email;
262
+ const status = this.status === "ok" && ending ? "exited" : this.status;
263
+ this.core.post("/api/v1/sessions", { sid: this.sid, did, status, errors: this.errors, started: this.started, release: this.release, environment: this.environment }).catch(() => void 0);
264
+ }
265
+ };
266
+ function safeJson(v) {
267
+ try {
268
+ return JSON.stringify(v) ?? String(v);
269
+ } catch {
270
+ return String(v);
271
+ }
272
+ }
273
+
274
+ // src/instrument.ts
275
+ var done = /* @__PURE__ */ new WeakSet();
276
+ function instrument(core2, g = globalThis) {
277
+ if (done.has(g)) return;
278
+ done.add(g);
279
+ const eu = g.ErrorUtils;
280
+ if (eu?.setGlobalHandler) {
281
+ const prev = eu.getGlobalHandler?.();
282
+ eu.setGlobalHandler((error, isFatal) => {
283
+ const c = core2();
284
+ c?.captureException(error, false, isFatal ? "fatal" : "error");
285
+ if (isFatal) void c?.flush();
286
+ prev?.(error, isFatal);
287
+ });
288
+ }
289
+ const onUnhandled = (_id, reason) => void core2()?.captureException(reason, false);
290
+ if (g.HermesInternal?.enablePromiseRejectionTracker) {
291
+ g.HermesInternal.enablePromiseRejectionTracker({ allRejections: true, onUnhandled });
292
+ } else {
293
+ try {
294
+ __require("promise/setimmediate/rejection-tracking").enable({ allRejections: true, onUnhandled });
295
+ } catch {
296
+ }
297
+ }
298
+ for (const level of ["warn", "error"]) {
299
+ const original = g.console[level];
300
+ if (typeof original !== "function") continue;
301
+ g.console[level] = (...args) => {
302
+ const message = truncate(args.map((a) => typeof a === "string" ? a : a instanceof Error ? a.message : json(a)).join(" "), 1024);
303
+ if (!message.startsWith("[blipit]")) core2()?.addBreadcrumb({ category: "console", level: level === "warn" ? "warning" : "error", message });
304
+ original.apply(g.console, args);
305
+ };
306
+ }
307
+ const proto = g.XMLHttpRequest?.prototype;
308
+ if (proto?.open && proto.send) {
309
+ const open = proto.open;
310
+ const send = proto.send;
311
+ proto.open = function(method, url, ...rest) {
312
+ this._blipit = [String(method).toUpperCase(), String(url)];
313
+ return open.call(this, method, url, ...rest);
314
+ };
315
+ proto.send = function(...args) {
316
+ const meta = this._blipit;
317
+ const c = core2();
318
+ if (c && meta && !meta[1].startsWith(c.endpoint)) {
319
+ const start = Date.now();
320
+ this.addEventListener?.("loadend", () => {
321
+ const status = this.status;
322
+ const url = meta[1].replace(/[?#].*$/, "");
323
+ c.addBreadcrumb({
324
+ category: "http",
325
+ level: !status || status >= 400 ? "error" : "info",
326
+ message: `${meta[0]} ${url} -> ${status || "network error"}`,
327
+ data: { url, method: meta[0], status_code: status || void 0, duration_ms: Date.now() - start }
328
+ });
329
+ });
330
+ }
331
+ return send.apply(this, args);
332
+ };
333
+ }
334
+ }
335
+ function trackNavigation(core2, ref) {
336
+ let last;
337
+ const seen = () => {
338
+ const name = ref.getCurrentRoute()?.name;
339
+ if (!name || name === last) return;
340
+ core2()?.addBreadcrumb({ category: "navigation", message: `Navigated to ${name}`, data: { from: last, to: name } });
341
+ last = name;
342
+ };
343
+ seen();
344
+ return ref.addListener("state", seen);
345
+ }
346
+ function json(v) {
347
+ try {
348
+ return JSON.stringify(v) ?? String(v);
349
+ } catch {
350
+ return String(v);
351
+ }
352
+ }
353
+
354
+ // src/native.ts
355
+ import { NativeModules } from "react-native";
356
+ var bridge = () => NativeModules.BlipitNuggets;
357
+ function nativeInfo() {
358
+ const b = bridge();
359
+ try {
360
+ return b?.getConstants?.() ?? b ?? {};
361
+ } catch {
362
+ return {};
363
+ }
364
+ }
365
+ function nativeStore() {
366
+ const b = bridge();
367
+ if (!b?.save || !b.load) return void 0;
368
+ return {
369
+ load: () => {
370
+ try {
371
+ return b.load();
372
+ } catch {
373
+ return null;
374
+ }
375
+ },
376
+ save: (data) => void b.save(data)
377
+ };
378
+ }
379
+ function defaultRelease(info) {
380
+ if (!info.appId || !info.appVersion) return void 0;
381
+ return `${info.appId}@${info.appVersion}${info.appBuild ? `+${info.appBuild}` : ""}`;
382
+ }
383
+
384
+ // src/boundary.ts
385
+ import { Component, createElement } from "react";
386
+ var report = () => void 0;
387
+ function setBoundaryReporter(fn) {
388
+ report = fn;
389
+ }
390
+ var ErrorBoundary = class extends Component {
391
+ state = { error: null };
392
+ static getDerivedStateFromError(error) {
393
+ return { error };
394
+ }
395
+ componentDidCatch(error) {
396
+ const id = report(error);
397
+ this.props.onError?.(error, id);
398
+ }
399
+ resetError = () => this.setState({ error: null });
400
+ render() {
401
+ if (this.state.error === null) return this.props.children ?? null;
402
+ const { fallback } = this.props;
403
+ if (typeof fallback === "function") return fallback({ error: this.state.error, resetError: this.resetError });
404
+ if (fallback === void 0) throw this.state.error;
405
+ return fallback;
406
+ }
407
+ };
408
+ function wrap(Root, options = {}) {
409
+ const Wrapped = (props) => createElement(ErrorBoundary, options, createElement(Root, props));
410
+ Wrapped.displayName = `Blipit(${Root.displayName ?? Root.name ?? "App"})`;
411
+ return Wrapped;
412
+ }
11
413
 
12
414
  // src/report-strings.ts
13
415
  var REPORT_STRINGS = {
@@ -428,16 +830,23 @@ var ReportClient = class {
428
830
  this.key = key;
429
831
  this.fetcher = fetcher;
430
832
  }
431
- async call(path, init3) {
432
- const res = await this.fetcher(`${this.endpoint}${path}`, { ...init3, headers: { "X-Blipit-Key": this.key, ...init3.headers } });
833
+ async call(path, init2) {
834
+ const res = await this.fetcher(`${this.endpoint}${path}`, { ...init2, headers: { "X-Blipit-Key": this.key, ...init2.headers } });
433
835
  const text2 = await res.text();
434
836
  if (!res.ok) throw new Error(`Blipit returned ${res.status}`);
435
837
  return text2;
436
838
  }
839
+ async settings() {
840
+ return JSON.parse(await this.call("/api/v1/feedback/settings", { method: "GET" }));
841
+ }
842
+ async event(body) {
843
+ const res = await this.fetcher(`${this.endpoint}/api/v1/events`, { method: "POST", headers: { "X-Blipit-Key": this.key, "Content-Type": "application/json" }, body: JSON.stringify(body) });
844
+ return res.ok || res.status >= 400 && res.status < 500 && res.status !== 408 && res.status !== 429;
845
+ }
437
846
  async send(body) {
438
- const json = JSON.parse(await this.call("/api/v1/feedback", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));
439
- if (typeof json.upload_token !== "string") throw new Error("Blipit returned no upload token");
440
- return { id: String(json.id), token: json.upload_token, ref: typeof json.ref === "string" ? json.ref : null };
847
+ const json2 = JSON.parse(await this.call("/api/v1/feedback", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));
848
+ if (typeof json2.upload_token !== "string") throw new Error("Blipit returned no upload token");
849
+ return { id: String(json2.id), token: json2.upload_token, ref: typeof json2.ref === "string" ? json2.ref : null };
441
850
  }
442
851
  async uploadScreenshot(receipt, data, type) {
443
852
  await this.call(`/api/v1/feedback/${encodeURIComponent(receipt.id)}/screenshot?position=0`, { method: "POST", headers: { "Content-Type": type, "X-Blipit-Upload": receipt.token }, body: data });
@@ -483,6 +892,141 @@ function zoomAround(zoom, pan, next, focal, view, image) {
483
892
  }
484
893
  var strokeFor = (image) => Math.max(4, image.width / 130);
485
894
 
895
+ // src/stuck.ts
896
+ var STARTUP = "startup";
897
+ function limitsFrom(value) {
898
+ const v = value;
899
+ if (!v || typeof v.startup_ms !== "number" || typeof v.flow_ms !== "number") return null;
900
+ return { startupMs: v.startup_ms, flowMs: v.flow_ms };
901
+ }
902
+ function cleanName(value, max) {
903
+ if (typeof value !== "string") return null;
904
+ const clean = value.replace(/\s+/g, " ").trim().slice(0, max);
905
+ return clean || null;
906
+ }
907
+ var FlowWatch = class {
908
+ open = /* @__PURE__ */ new Map();
909
+ foreground = false;
910
+ start(name, now) {
911
+ this.open.delete(name);
912
+ this.open.set(name, { step: null, spent: 0, since: this.foreground ? now : null });
913
+ }
914
+ step(name, step) {
915
+ const flow = this.open.get(name);
916
+ if (!flow) return false;
917
+ flow.step = step;
918
+ return true;
919
+ }
920
+ end(name) {
921
+ return this.open.delete(name);
922
+ }
923
+ get empty() {
924
+ return this.open.size === 0;
925
+ }
926
+ setForeground(on, now) {
927
+ if (on === this.foreground) return;
928
+ this.foreground = on;
929
+ for (const flow of this.open.values()) {
930
+ if (on) flow.since = now;
931
+ else {
932
+ flow.spent += now - (flow.since ?? now);
933
+ flow.since = null;
934
+ }
935
+ }
936
+ }
937
+ due(now, limits) {
938
+ if (!limits) return [];
939
+ const out = [];
940
+ for (const [name, flow] of this.open) {
941
+ const waited = flow.spent + (flow.since === null ? 0 : now - flow.since);
942
+ const limit = name === STARTUP ? limits.startupMs : limits.flowMs;
943
+ if (limit > 0 && waited >= limit) {
944
+ out.push({ name, step: flow.step, waitedMs: waited });
945
+ this.open.delete(name);
946
+ }
947
+ }
948
+ return out;
949
+ }
950
+ };
951
+ var hex = (n) => Array.from({ length: n }, () => Math.floor(Math.random() * 16).toString(16)).join("");
952
+ function stuckEvent(flow, trail, info, at = /* @__PURE__ */ new Date()) {
953
+ const kind = flow.name === STARTUP ? "startup" : "flow";
954
+ const stuck2 = { kind, waited_ms: Math.round(flow.waitedMs) };
955
+ if (kind === "flow") stuck2.flow = flow.name;
956
+ if (flow.step) stuck2.step = flow.step;
957
+ return {
958
+ event_id: hex(32),
959
+ timestamp: at.toISOString(),
960
+ platform: "react-native",
961
+ level: "warning",
962
+ message: `stuck: ${kind} ${kind === "flow" ? flow.name : kind}`,
963
+ stuck: stuck2,
964
+ contexts: { os: { name: info.os, version: info.osVersion } },
965
+ sdk: { name: "@blipit/react-native", version: info.version },
966
+ ...trail.length ? { breadcrumbs: trail } : {},
967
+ ...info.release ? { release: info.release } : {},
968
+ ...info.environment ? { environment: info.environment } : {}
969
+ };
970
+ }
971
+ function createStuck(transport, info, clock = Date.now) {
972
+ const watch = new FlowWatch();
973
+ const trail = [];
974
+ const pending = [];
975
+ let limits = null;
976
+ let fetchedAt = -Infinity;
977
+ let timer = null;
978
+ const crumb = (message) => {
979
+ trail.push({ timestamp: (/* @__PURE__ */ new Date()).toISOString(), category: "custom", message });
980
+ if (trail.length > 30) trail.shift();
981
+ };
982
+ const fetchLimits = () => {
983
+ fetchedAt = clock();
984
+ transport.settings().then((s2) => limits = limitsFrom(s2?.stuck) ?? limits, () => void 0);
985
+ };
986
+ const flush2 = () => {
987
+ for (const body of pending.splice(0)) {
988
+ transport.event(body).then(
989
+ (ok) => !ok && pending.length < 10 && pending.push(body),
990
+ () => pending.length < 10 && pending.push(body)
991
+ );
992
+ }
993
+ };
994
+ const tick = () => {
995
+ if (!limits && clock() - fetchedAt > 6e4) fetchLimits();
996
+ for (const flow of watch.due(clock(), limits)) if (pending.length < 10) pending.push(stuckEvent(flow, trail.slice(), info));
997
+ flush2();
998
+ if (watch.empty && timer) {
999
+ clearInterval(timer);
1000
+ timer = null;
1001
+ }
1002
+ };
1003
+ const schedule = () => {
1004
+ if (!timer) timer = setInterval(tick, 1e3);
1005
+ };
1006
+ return {
1007
+ tick,
1008
+ get limits() {
1009
+ return limits;
1010
+ },
1011
+ setForeground(on) {
1012
+ watch.setForeground(on, clock());
1013
+ if (on) schedule();
1014
+ },
1015
+ start(name) {
1016
+ if (!limits && clock() - fetchedAt > 6e4) fetchLimits();
1017
+ watch.start(name, clock());
1018
+ crumb(`flow ${name} started`);
1019
+ schedule();
1020
+ },
1021
+ step(name, step) {
1022
+ if (watch.step(name, step)) crumb(`flow ${name}: ${step}`);
1023
+ },
1024
+ end(name) {
1025
+ if (watch.end(name)) crumb(`flow ${name} finished`);
1026
+ }
1027
+ };
1028
+ }
1029
+
486
1030
  // src/reporter.tsx
487
1031
  import { useEffect, useMemo, useRef, useState } from "react";
488
1032
  import {
@@ -869,8 +1413,8 @@ function Details({ t, lang, shot, flat, shapes, notice, onBack, onDone }) {
869
1413
  uploaded = false;
870
1414
  }
871
1415
  }
872
- const done = receipt.ref ? t("sentRef").replace("{ref}", receipt.ref) : t("sentTitle");
873
- setStatus({ text: uploaded ? done : `${done} \xB7 ${t("noShot")}`, error: !uploaded });
1416
+ const done2 = receipt.ref ? t("sentRef").replace("{ref}", receipt.ref) : t("sentTitle");
1417
+ setStatus({ text: uploaded ? done2 : `${done2} \xB7 ${t("noShot")}`, error: !uploaded });
874
1418
  setTimeout(onDone, 1600);
875
1419
  } catch {
876
1420
  setStatus({ text: t("error"), error: true });
@@ -926,30 +1470,14 @@ var s = StyleSheet.create({
926
1470
  });
927
1471
 
928
1472
  // src/index.ts
929
- import { captureException, captureMessage as captureMessage2, setUser, setTag, addBreadcrumb, flush, wrap } from "@sentry/react-native";
930
- var DEFAULT_ENDPOINT = "https://in.blipit.io";
931
- var VERSION = "0.3.0";
932
- var PACKAGE = { name: "npm:@blipit/react-native", version: VERSION };
933
- function withIdentity(user) {
934
- return (event, hint) => {
935
- try {
936
- const sdk = event.sdk ??= {};
937
- const packages = sdk.packages ?? [];
938
- if (!packages.some((p) => p?.name === PACKAGE.name)) sdk.packages = [...packages, { ...PACKAGE }];
939
- } catch {
940
- }
941
- return user ? user(event, hint) : event;
942
- };
943
- }
944
- function dsn(key, project, endpoint = DEFAULT_ENDPOINT) {
945
- const host = endpoint.split("://").pop().replace(/\/+$/, "");
946
- const scheme = endpoint.startsWith("http://") ? "http" : "https";
947
- return `${scheme}://${key}@${host}/${project}`;
948
- }
1473
+ var SECURITY_KINDS = ["login_failed", "login_succeeded", "login_blocked", "password_reset_requested", "privilege_granted"];
949
1474
  var MISSING_KEY = "[blipit] Blipit.init got no key, so Blipit is off and nothing is sent. Pass the project's public key (app.blipit.io, Keys); with Expo, check that EXPO_PUBLIC_BLIPIT_KEY is set at build time.";
950
1475
  var MISSING_PROJECT = "[blipit] Blipit.init got no project id, so Blipit is off and nothing is sent. Pass project with the id from the project's Keys page at app.blipit.io.";
951
- function init2(options) {
952
- const { key, publicKey, project, endpoint, ...rest } = options ?? {};
1476
+ var core;
1477
+ var session;
1478
+ var appState;
1479
+ function init(options) {
1480
+ const { key, publicKey, project, endpoint, waitForReady, ...rest } = options ?? {};
953
1481
  const k = (key ?? publicKey ?? "").trim();
954
1482
  if (!k) {
955
1483
  console.warn(MISSING_KEY);
@@ -959,16 +1487,83 @@ function init2(options) {
959
1487
  console.warn(MISSING_PROJECT);
960
1488
  return false;
961
1489
  }
962
- Sentry.init({
963
- dsn: dsn(k, project, endpoint),
964
- sendDefaultPii: false,
965
- tracesSampleRate: 0,
966
- ...rest,
967
- beforeSend: withIdentity(rest.beforeSend)
1490
+ const info = nativeInfo();
1491
+ const release = rest.release ?? defaultRelease(info);
1492
+ const base = endpoint ?? DEFAULT_ENDPOINT;
1493
+ session?.end();
1494
+ appState?.remove();
1495
+ core = new Nuggets({ ...rest, key: k, endpoint: base, release, store: nativeStore(), contexts: () => contexts(info.model, info.osVersion) });
1496
+ const c = core;
1497
+ setBoundaryReporter((error) => c.captureException(error, false));
1498
+ instrument(() => core);
1499
+ const native = rest.enableNative !== false ? bridge() : void 0;
1500
+ try {
1501
+ native?.start(k, String(project), rest.environment ?? null, release ?? null, c.endpoint);
1502
+ } catch {
1503
+ }
1504
+ session = release && rest.autoSessionTracking !== false ? new Session(c, release, rest.environment ?? "production") : void 0;
1505
+ c.onError = (unhandled) => session?.markError(unhandled);
1506
+ if (c.enabled) session?.start();
1507
+ appState = AppState?.addEventListener?.("change", (state) => {
1508
+ if (state === "active") {
1509
+ if (c.enabled) session?.start();
1510
+ void c.flush();
1511
+ } else if (state === "background") {
1512
+ session?.end();
1513
+ void c.flush();
1514
+ }
968
1515
  });
969
- configureReporter(new ReportClient(endpoint ?? DEFAULT_ENDPOINT, k), () => deviceContext(rest.release));
1516
+ void c.flush();
1517
+ const reports = new ReportClient(base, k);
1518
+ configureReporter(reports, () => deviceContext(release));
1519
+ reportClient = reports;
1520
+ if (!stuck) {
1521
+ stuck = createStuck(
1522
+ {
1523
+ settings: () => reportClient ? reportClient.settings() : Promise.resolve(null),
1524
+ event: async (body) => (core?.enqueue(body), true)
1525
+ },
1526
+ { release, environment: rest.environment, os: Platform2.OS, osVersion: info.osVersion ?? String(Platform2.Version), version: VERSION }
1527
+ );
1528
+ try {
1529
+ stuck.setForeground(AppState.currentState !== "background");
1530
+ AppState.addEventListener("change", (state) => stuck?.setForeground(state !== "background"));
1531
+ } catch {
1532
+ stuck.setForeground(true);
1533
+ }
1534
+ if (waitForReady) stuck.start(STARTUP);
1535
+ }
1536
+ if (rest.debug) console.log(`[blipit] ${SDK_NAME}@${VERSION} initialized`);
970
1537
  return true;
971
1538
  }
1539
+ var stuck = null;
1540
+ var reportClient;
1541
+ function reportReady() {
1542
+ stuck?.end(STARTUP);
1543
+ }
1544
+ function startFlow(name) {
1545
+ const flow = cleanName(name, 64);
1546
+ if (flow) stuck?.start(flow);
1547
+ }
1548
+ function flowStep(name, step) {
1549
+ const flow = cleanName(name, 64);
1550
+ const s2 = cleanName(step, 128);
1551
+ if (flow && s2) stuck?.step(flow, s2);
1552
+ }
1553
+ function endFlow(name) {
1554
+ const flow = cleanName(name, 64);
1555
+ if (flow) stuck?.end(flow);
1556
+ }
1557
+ function contexts(model, osVersion) {
1558
+ const { width, height } = Dimensions.get("window");
1559
+ const engine = globalThis.HermesInternal ? "hermes" : "jsc";
1560
+ const rn = Platform2.constants?.reactNativeVersion;
1561
+ return {
1562
+ os: { name: Platform2.OS, version: osVersion ?? String(Platform2.Version) },
1563
+ device: { ...model ? { model } : {}, screen: `${Math.round(width)}x${Math.round(height)}` },
1564
+ runtime: { name: engine, ...rn ? { version: `react-native ${rn.major}.${rn.minor}.${rn.patch}` } : {} }
1565
+ };
1566
+ }
972
1567
  function deviceContext(release) {
973
1568
  const { width, height, scale } = Dimensions.get("window");
974
1569
  let language = "";
@@ -981,11 +1576,17 @@ function deviceContext(release) {
981
1576
  }
982
1577
  return {
983
1578
  platform: "react-native",
984
- sdk: { name: PACKAGE.name, version: VERSION },
1579
+ sdk: { name: `npm:${SDK_NAME}`, version: VERSION },
985
1580
  ...release ? { app: { release } } : {},
986
1581
  device: { os: Platform2.OS, os_version: String(Platform2.Version), screen: `${Math.round(width)}x${Math.round(height)}`, dpr: scale, language, timezone, touch: true }
987
1582
  };
988
1583
  }
1584
+ function captureException(error) {
1585
+ return core?.captureException(error, true);
1586
+ }
1587
+ function captureMessage(message, level = "info") {
1588
+ return core?.captureMessage(message, level);
1589
+ }
989
1590
  function captureSecurity(kind, actor, details = {}) {
990
1591
  const context = { kind, actor };
991
1592
  const extra = { outcome: details.outcome, actor_id: details.actorId, ip: details.ip, user_agent: details.userAgent, target: details.target };
@@ -993,26 +1594,80 @@ function captureSecurity(kind, actor, details = {}) {
993
1594
  if (v !== void 0 && v !== null) context[k] = v;
994
1595
  }
995
1596
  const level = kind === "login_failed" || kind === "login_blocked" ? "warning" : "info";
996
- Sentry.withScope((scope) => {
997
- scope.setContext("security", context);
998
- scope.setTag("security.kind", kind);
999
- Sentry.captureMessage(`${kind} for ${actor}`, level);
1000
- });
1597
+ return core?.captureSecurity(kind, `${kind} for ${actor}`, level, SECURITY_KINDS.includes(kind) && actor ? context : void 0);
1598
+ }
1599
+ function setUser(user) {
1600
+ core?.setUser(user);
1601
+ const u = core?.user;
1602
+ try {
1603
+ bridge()?.setUser(u?.id ?? null, u?.email ?? null, u?.username ?? null);
1604
+ } catch {
1605
+ }
1606
+ }
1607
+ function setTag(key, value) {
1608
+ core?.setTag(key, value);
1609
+ try {
1610
+ bridge()?.setTag(key, String(value));
1611
+ } catch {
1612
+ }
1613
+ }
1614
+ function addBreadcrumb(crumb) {
1615
+ core?.addBreadcrumb(crumb);
1616
+ }
1617
+ async function flush(timeout = 2e3) {
1618
+ if (!core) return true;
1619
+ const c = core;
1620
+ let timer;
1621
+ const late = new Promise((r) => timer = setTimeout(() => r(false), timeout));
1622
+ const ok = await Promise.race([c.flush().then(() => c.pending === 0), late]);
1623
+ clearTimeout(timer);
1624
+ return ok;
1625
+ }
1626
+ function setEnabled(on) {
1627
+ if (!core) return;
1628
+ core.setEnabled(on);
1629
+ if (on) session?.start();
1630
+ else session?.end();
1631
+ }
1632
+ var isEnabled = () => core?.enabled ?? false;
1633
+ var lastEventId = () => core?.lastEventId;
1634
+ function setReplayConsent(granted) {
1635
+ try {
1636
+ bridge()?.setReplayConsent(granted);
1637
+ } catch {
1638
+ }
1639
+ }
1640
+ function hasReplayConsent() {
1641
+ try {
1642
+ return bridge()?.hasReplayConsent() === true;
1643
+ } catch {
1644
+ return false;
1645
+ }
1001
1646
  }
1647
+ var trackNavigation2 = (ref) => trackNavigation(() => core, ref);
1002
1648
  export {
1003
1649
  BlipitReporter,
1004
1650
  DEFAULT_ENDPOINT,
1651
+ ErrorBoundary,
1005
1652
  VERSION,
1006
1653
  addBreadcrumb,
1007
1654
  captureException,
1008
- captureMessage2 as captureMessage,
1655
+ captureMessage,
1009
1656
  captureSecurity,
1010
- dsn,
1657
+ endFlow,
1658
+ flowStep,
1011
1659
  flush,
1012
- init2 as init,
1660
+ hasReplayConsent,
1661
+ init,
1662
+ isEnabled,
1663
+ lastEventId,
1664
+ reportReady,
1665
+ setEnabled,
1666
+ setReplayConsent,
1013
1667
  setTag,
1014
1668
  setUser,
1015
1669
  showReport,
1016
- withIdentity,
1670
+ startFlow,
1671
+ trackNavigation2 as trackNavigation,
1017
1672
  wrap
1018
1673
  };