@astratest/react-native 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kiswani
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,9 @@
1
- # Temporary Holding Version
1
+ # @astratest/react-native
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ```tsx
4
+ import { AstraTest, AstraTestProvider } from "@astratest/react-native";
5
+ AstraTest.start("pk_test_…", { appVersion: "1.4.0" });
6
+ export default () => <AstraTestProvider><App /></AstraTestProvider>;
7
+ ```
8
+
9
+ Records fetch / XMLHttpRequest calls, console output and uncaught errors. Install `react-native-view-shot` for screenshots; wrap password fields and anything private in `<AstraPrivate>`.
@@ -0,0 +1,29 @@
1
+ export type LogLine = {
2
+ level: string;
3
+ message: string;
4
+ at: number;
5
+ };
6
+ export type NetCall = {
7
+ method: string;
8
+ url: string;
9
+ status: number;
10
+ durationMs: number;
11
+ at: number;
12
+ };
13
+ export declare class Ring<T> {
14
+ private cap;
15
+ private q;
16
+ constructor(cap: number);
17
+ push(x: T): void;
18
+ all(): T[];
19
+ }
20
+ export declare const logs: Ring<LogLine>;
21
+ export declare const network: Ring<NetCall>;
22
+ export declare const setOwnHost: (h: string) => void;
23
+ export declare function log(level: string, message: string): void;
24
+ export declare function cleanUrl(u: string): string;
25
+ export declare function record(method: string, url: string, status: number, durationMs: number): void;
26
+ /** Mirrors console.* and uncaught JS errors into the report log. */
27
+ export declare function patchConsole(): void;
28
+ /** fetch() in React Native runs on XMLHttpRequest, so patching it records fetch, axios and the rest. */
29
+ export declare function patchXhr(): void;
package/lib/capture.js ADDED
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setOwnHost = exports.network = exports.logs = exports.Ring = void 0;
4
+ exports.log = log;
5
+ exports.cleanUrl = cleanUrl;
6
+ exports.record = record;
7
+ exports.patchConsole = patchConsole;
8
+ exports.patchXhr = patchXhr;
9
+ class Ring {
10
+ constructor(cap) {
11
+ this.cap = cap;
12
+ this.q = [];
13
+ }
14
+ push(x) { this.q.push(x); if (this.q.length > this.cap)
15
+ this.q.splice(0, this.q.length - this.cap); }
16
+ all() { return this.q.slice(); }
17
+ }
18
+ exports.Ring = Ring;
19
+ exports.logs = new Ring(200);
20
+ exports.network = new Ring(100);
21
+ let ownHost = "astratest.dev";
22
+ const setOwnHost = (h) => { ownHost = h; };
23
+ exports.setOwnHost = setOwnHost;
24
+ const str = (a) => {
25
+ if (typeof a === "string")
26
+ return a;
27
+ if (a instanceof Error)
28
+ return `${a.name}: ${a.message}`;
29
+ try {
30
+ return JSON.stringify(a);
31
+ }
32
+ catch {
33
+ return String(a);
34
+ }
35
+ };
36
+ function log(level, message) {
37
+ const m = message.slice(0, 2000);
38
+ if (!m.trim() || m.startsWith("[AstraTest]"))
39
+ return;
40
+ exports.logs.push({ level, message: m, at: Date.now() });
41
+ }
42
+ function cleanUrl(u) {
43
+ return u.split("#")[0].split("?")[0].slice(0, 500);
44
+ }
45
+ function record(method, url, status, durationMs) {
46
+ if (url.includes(ownHost))
47
+ return;
48
+ exports.network.push({ method: method.toUpperCase(), url: cleanUrl(url), status, durationMs, at: Date.now() });
49
+ }
50
+ let consolePatched = false;
51
+ /** Mirrors console.* and uncaught JS errors into the report log. */
52
+ function patchConsole() {
53
+ if (consolePatched)
54
+ return;
55
+ consolePatched = true;
56
+ for (const level of ["log", "info", "warn", "error"]) {
57
+ const orig = console[level].bind(console);
58
+ console[level] = (...args) => { log(level === "info" ? "log" : level, args.map(str).join(" ")); orig(...args); };
59
+ }
60
+ const EU = globalThis.ErrorUtils;
61
+ if (EU) {
62
+ const prev = EU.getGlobalHandler();
63
+ EU.setGlobalHandler((e, fatal) => { log("error", `${fatal ? "Fatal: " : ""}${str(e)}`); prev(e, fatal); });
64
+ }
65
+ }
66
+ let xhrPatched = false;
67
+ /** fetch() in React Native runs on XMLHttpRequest, so patching it records fetch, axios and the rest. */
68
+ function patchXhr() {
69
+ if (xhrPatched)
70
+ return;
71
+ const X = globalThis.XMLHttpRequest;
72
+ if (!X)
73
+ return;
74
+ xhrPatched = true;
75
+ const open = X.prototype.open, send = X.prototype.send;
76
+ X.prototype.open = function (method, url, ...rest) {
77
+ this.__astra = { m: method, u: String(url), t: 0 };
78
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
79
+ return open.call(this, method, url, ...rest);
80
+ };
81
+ X.prototype.send = function (body) {
82
+ const a = this.__astra;
83
+ if (a) {
84
+ a.t = Date.now();
85
+ this.addEventListener("loadend", () => record(a.m, a.u, this.status, Date.now() - a.t));
86
+ }
87
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
88
+ return send.call(this, body);
89
+ };
90
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,49 @@
1
+ import React from "react";
2
+ export type AstraTestOptions = {
3
+ /** Your app's version, such as "1.4.0". */
4
+ appVersion?: string;
5
+ /** Your build number. */
6
+ build?: string;
7
+ /** Show the floating Report button. Defaults to true for pk_test_ keys, false for pk_live_. */
8
+ showButton?: boolean;
9
+ /** Record fetch / XMLHttpRequest calls (method, URL without query, status, timing). */
10
+ captureNetwork?: boolean;
11
+ /** Attach console output and uncaught errors to reports. */
12
+ captureLogs?: boolean;
13
+ /** Where reports are sent. */
14
+ host?: string;
15
+ };
16
+ export type SentReport = {
17
+ ref: string;
18
+ url?: string;
19
+ title?: string;
20
+ };
21
+ export declare const AstraTest: {
22
+ /** Starts Astra Test. Call once, before your app renders. Then wrap your app in <AstraTestProvider>. */
23
+ start(key: string, options?: AstraTestOptions): void;
24
+ /** Says who is testing, so reports show their name and they can be asked if a fix works. */
25
+ identify(user: {
26
+ id?: string;
27
+ email?: string;
28
+ name?: string;
29
+ }): void;
30
+ /** The test case being run, such as "UAT-02". */
31
+ setTestCase(ref?: string): void;
32
+ /** The screen the user is on, such as "Checkout". Call it from your navigation's state listener. */
33
+ setScreen(name?: string): void;
34
+ /** Adds a line to the log attached to reports. */
35
+ log(message: string, level?: string): void;
36
+ /** Opens the report sheet. */
37
+ showReport(): void;
38
+ /** Sends a report without the sheet, for example from your own feedback form. */
39
+ send(description: string): Promise<SentReport>;
40
+ };
41
+ /** Covers its children in report screenshots. Wrap password fields and anything private in it. */
42
+ export declare function AstraPrivate({ children }: {
43
+ children: React.ReactNode;
44
+ }): React.JSX.Element;
45
+ /** Wrap your whole app in this, inside your providers. Adds the Report button and the report sheet. */
46
+ export declare function AstraTestProvider({ children }: {
47
+ children: React.ReactNode;
48
+ }): React.JSX.Element;
49
+ export default AstraTest;
package/lib/index.js ADDED
@@ -0,0 +1,241 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.AstraTest = void 0;
37
+ exports.AstraPrivate = AstraPrivate;
38
+ exports.AstraTestProvider = AstraTestProvider;
39
+ const react_1 = __importStar(require("react"));
40
+ const react_native_1 = require("react-native");
41
+ const capture_1 = require("./capture");
42
+ const COBALT = "#2F55D4", MIDNIGHT = "#0E1A3D";
43
+ const s = { options: {}, reporter: {} };
44
+ // react-native-view-shot is optional: with it, reports carry a screenshot.
45
+ let captureRef;
46
+ try {
47
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
48
+ captureRef = require("react-native-view-shot").captureRef;
49
+ }
50
+ catch {
51
+ captureRef = undefined;
52
+ }
53
+ exports.AstraTest = {
54
+ /** Starts Astra Test. Call once, before your app renders. Then wrap your app in <AstraTestProvider>. */
55
+ start(key, options = {}) {
56
+ if (s.key)
57
+ return;
58
+ if (!/^pk_(test|live)_[0-9a-f]{24}$/.test(key)) {
59
+ console.warn("[AstraTest] That isn't a project key. Copy it from SDK setup in Astra Test.");
60
+ return;
61
+ }
62
+ s.key = key;
63
+ s.options = options;
64
+ try {
65
+ (0, capture_1.setOwnHost)(new URL(options.host ?? "https://astratest.dev").host);
66
+ }
67
+ catch { /* keep default */ }
68
+ if (options.captureLogs !== false)
69
+ (0, capture_1.patchConsole)();
70
+ if (options.captureNetwork !== false)
71
+ (0, capture_1.patchXhr)();
72
+ if (options.appVersion)
73
+ post("/v1/builds", { key, platform: react_native_1.Platform.OS, version: options.appVersion, build: options.build ?? "" }).catch(() => undefined);
74
+ },
75
+ /** Says who is testing, so reports show their name and they can be asked if a fix works. */
76
+ identify(user) {
77
+ s.reporter = Object.fromEntries(Object.entries(user).filter(([, v]) => !!v));
78
+ },
79
+ /** The test case being run, such as "UAT-02". */
80
+ setTestCase(ref) { s.testCase = ref; },
81
+ /** The screen the user is on, such as "Checkout". Call it from your navigation's state listener. */
82
+ setScreen(name) { s.screen = name; },
83
+ /** Adds a line to the log attached to reports. */
84
+ log(message, level = "log") { (0, capture_1.log)(level, message); },
85
+ /** Opens the report sheet. */
86
+ showReport() { s.open?.(); },
87
+ /** Sends a report without the sheet, for example from your own feedback form. */
88
+ async send(description) { return send(description, await s.capture?.()); },
89
+ };
90
+ function payload(description, screenshot) {
91
+ const { width, height } = react_native_1.Dimensions.get("window");
92
+ const screen = s.screen ?? "App";
93
+ let locale = "en";
94
+ try {
95
+ locale = Intl.DateTimeFormat().resolvedOptions().locale;
96
+ }
97
+ catch { /* Intl missing */ }
98
+ return {
99
+ key: s.key,
100
+ description,
101
+ page: { url: `app://react-native/${screen}`, title: screen },
102
+ device: {
103
+ platform: react_native_1.Platform.OS,
104
+ os: `${react_native_1.Platform.OS === "ios" ? "iOS" : react_native_1.Platform.OS === "android" ? "Android" : react_native_1.Platform.OS} ${react_native_1.Platform.Version}`,
105
+ browser: `React Native${react_native_1.Platform.constants?.reactNativeVersion ? ` ${react_native_1.Platform.constants.reactNativeVersion.major}.${react_native_1.Platform.constants.reactNativeVersion.minor}` : ""}`,
106
+ viewport: `${Math.round(width)} × ${Math.round(height)}`,
107
+ locale,
108
+ appVersion: s.options.appVersion,
109
+ build: s.options.build,
110
+ },
111
+ console: capture_1.logs.all().slice(-60),
112
+ network: capture_1.network.all().slice(-60),
113
+ reporter: Object.keys(s.reporter).length ? s.reporter : undefined,
114
+ testCaseRef: s.testCase,
115
+ screenshot,
116
+ };
117
+ }
118
+ async function post(path, body) {
119
+ const res = await fetch(`${s.options.host ?? "https://astratest.dev"}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
120
+ const j = (await res.json().catch(() => ({})));
121
+ if (!res.ok)
122
+ throw new Error(j.error ?? `Couldn't send the report (${res.status})`);
123
+ return j;
124
+ }
125
+ async function send(description, screenshot) {
126
+ if (!s.key)
127
+ throw new Error("Astra Test isn't started");
128
+ const j = await post("/v1/reports", payload(description, screenshot));
129
+ if (!j.ref)
130
+ throw new Error(j.error ?? "Couldn't send the report");
131
+ return { ref: j.ref, url: j.url, title: j.title };
132
+ }
133
+ const Masking = (0, react_1.createContext)(false);
134
+ /** Covers its children in report screenshots. Wrap password fields and anything private in it. */
135
+ function AstraPrivate({ children }) {
136
+ const masking = (0, react_1.useContext)(Masking);
137
+ return react_1.default.createElement(react_native_1.View, null,
138
+ children,
139
+ masking && react_1.default.createElement(react_native_1.View, { style: [react_native_1.StyleSheet.absoluteFill, { backgroundColor: "#000" }] }));
140
+ }
141
+ /** Wrap your whole app in this, inside your providers. Adds the Report button and the report sheet. */
142
+ function AstraTestProvider({ children }) {
143
+ const root = (0, react_1.useRef)(null);
144
+ const [open, setOpen] = (0, react_1.useState)(false);
145
+ const [masking, setMasking] = (0, react_1.useState)(false);
146
+ const [shot, setShot] = (0, react_1.useState)();
147
+ const [text, setText] = (0, react_1.useState)("");
148
+ const [sending, setSending] = (0, react_1.useState)(false);
149
+ const [error, setError] = (0, react_1.useState)();
150
+ const [sent, setSent] = (0, react_1.useState)();
151
+ const capture = (0, react_1.useCallback)(async () => {
152
+ if (!captureRef || !root.current)
153
+ return undefined;
154
+ setMasking(true);
155
+ await new Promise((r) => setTimeout(r, 60));
156
+ try {
157
+ const b64 = await captureRef(root.current, { format: "jpg", quality: 0.7, result: "base64" });
158
+ return `data:image/jpeg;base64,${b64}`;
159
+ }
160
+ catch {
161
+ return undefined;
162
+ }
163
+ finally {
164
+ setMasking(false);
165
+ }
166
+ }, []);
167
+ const show = (0, react_1.useCallback)(async () => {
168
+ if (!s.key || open)
169
+ return;
170
+ setShot(await capture());
171
+ setText("");
172
+ setError(undefined);
173
+ setSent(undefined);
174
+ setOpen(true);
175
+ }, [capture, open]);
176
+ (0, react_1.useEffect)(() => { s.open = show; s.capture = capture; return () => { s.open = undefined; s.capture = undefined; }; }, [show, capture]);
177
+ const submit = async () => {
178
+ const t = text.trim();
179
+ if (t.length < 3 || sending)
180
+ return;
181
+ setSending(true);
182
+ setError(undefined);
183
+ try {
184
+ setSent(await send(t, shot));
185
+ }
186
+ catch (e) {
187
+ setError(e.message);
188
+ }
189
+ finally {
190
+ setSending(false);
191
+ }
192
+ };
193
+ const showButton = !!s.key && (s.options.showButton ?? s.key.startsWith("pk_test_"));
194
+ const nNet = capture_1.network.all().length, nLog = capture_1.logs.all().length;
195
+ return (react_1.default.createElement(Masking.Provider, { value: masking },
196
+ react_1.default.createElement(react_native_1.View, { ref: root, collapsable: false, style: { flex: 1 } }, children),
197
+ showButton && !open && (react_1.default.createElement(react_native_1.Pressable, { accessibilityLabel: "Report an issue", onPress: show, style: st.fab },
198
+ react_1.default.createElement(react_native_1.Text, { style: st.fabText }, "\u2726 Report"))),
199
+ react_1.default.createElement(react_native_1.Modal, { visible: open, transparent: true, animationType: "slide", onRequestClose: () => setOpen(false) },
200
+ react_1.default.createElement(react_native_1.KeyboardAvoidingView, { behavior: react_native_1.Platform.OS === "ios" ? "padding" : undefined, style: st.backdrop },
201
+ react_1.default.createElement(react_native_1.Pressable, { style: react_native_1.StyleSheet.absoluteFill, onPress: () => setOpen(false) }),
202
+ react_1.default.createElement(react_native_1.View, { style: st.sheet }, sent ? (react_1.default.createElement(react_1.default.Fragment, null,
203
+ react_1.default.createElement(react_native_1.Text, { style: st.sent },
204
+ "\u2713 Sent as ",
205
+ sent.ref),
206
+ react_1.default.createElement(react_native_1.Text, { style: st.muted }, "Thanks. We'll let you know when it's fixed."),
207
+ react_1.default.createElement(react_native_1.Pressable, { onPress: () => setOpen(false), style: st.done },
208
+ react_1.default.createElement(react_native_1.Text, { style: { color: COBALT, fontWeight: "600" } }, "Done")))) : (react_1.default.createElement(react_1.default.Fragment, null,
209
+ react_1.default.createElement(react_native_1.View, { style: st.row },
210
+ react_1.default.createElement(react_native_1.Text, { style: st.title }, "Report an issue"),
211
+ react_1.default.createElement(react_native_1.Pressable, { onPress: () => setOpen(false) },
212
+ react_1.default.createElement(react_native_1.Text, { style: { color: COBALT } }, "Cancel"))),
213
+ react_1.default.createElement(react_native_1.Text, { style: st.label },
214
+ "What happened",
215
+ s.screen ? ` on ${s.screen}` : "",
216
+ "?"),
217
+ react_1.default.createElement(react_native_1.TextInput, { value: text, onChangeText: setText, placeholder: "Say it in your own words", multiline: true, style: st.input, autoFocus: true }),
218
+ react_1.default.createElement(react_native_1.Text, { style: st.muted },
219
+ "Attached: ",
220
+ [shot ? "Screenshot" : null, nNet ? `${nNet} requests` : null, nLog ? `${nLog} log lines` : null, "device details"].filter(Boolean).join(" · ")),
221
+ error && react_1.default.createElement(react_native_1.Text, { style: st.error }, error),
222
+ react_1.default.createElement(react_native_1.Pressable, { onPress: submit, disabled: sending || text.trim().length < 3, style: [st.send, { opacity: sending || text.trim().length < 3 ? 0.45 : 1 }] },
223
+ react_1.default.createElement(react_native_1.Text, { style: st.sendText }, sending ? "Sending…" : "Send report")))))))));
224
+ }
225
+ const st = react_native_1.StyleSheet.create({
226
+ fab: { position: "absolute", right: 16, bottom: 40, backgroundColor: MIDNIGHT, paddingHorizontal: 16, paddingVertical: 10, borderRadius: 999, elevation: 6, shadowColor: "#000", shadowOpacity: 0.25, shadowRadius: 8, shadowOffset: { width: 0, height: 3 } },
227
+ fabText: { color: "#fff", fontWeight: "600", fontSize: 14 },
228
+ backdrop: { flex: 1, justifyContent: "flex-end", backgroundColor: "rgba(0,0,0,0.4)" },
229
+ sheet: { backgroundColor: "#fff", borderTopLeftRadius: 18, borderTopRightRadius: 18, padding: 20, paddingBottom: 34, gap: 10 },
230
+ row: { flexDirection: "row", justifyContent: "space-between", alignItems: "center" },
231
+ title: { fontSize: 18, fontWeight: "700", color: "#0F1115" },
232
+ label: { fontSize: 12, color: "#646B78", marginTop: 6 },
233
+ input: { minHeight: 90, borderWidth: 1, borderColor: "#8A909C", borderRadius: 8, padding: 10, fontSize: 15, textAlignVertical: "top" },
234
+ muted: { fontSize: 12, color: "#646B78" },
235
+ error: { fontSize: 13, color: "#B42318" },
236
+ send: { backgroundColor: COBALT, borderRadius: 10, height: 46, alignItems: "center", justifyContent: "center", marginTop: 4 },
237
+ sendText: { color: "#fff", fontWeight: "600", fontSize: 15 },
238
+ sent: { fontSize: 17, fontWeight: "700", color: "#0E7C66" },
239
+ done: { alignSelf: "flex-end", padding: 8 },
240
+ });
241
+ exports.default = exports.AstraTest;
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@astratest/react-native",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "In-app bug reporting for Astra Test. Testers report from inside your app; a screenshot, requests, logs and device details are attached.",
5
+ "main": "lib/index.js",
6
+ "types": "lib/index.d.ts",
7
+ "files": [
8
+ "lib",
9
+ "src",
10
+ "README.md",
11
+ "LICENSE"
12
+ ],
13
+ "license": "MIT",
14
+ "homepage": "https://astratest.dev",
15
+ "scripts": {
16
+ "build": "tsc",
17
+ "typecheck": "tsc --noEmit",
18
+ "test": "node test/payload.test.mjs",
19
+ "prepublishOnly": "tsc && node test/payload.test.mjs"
20
+ },
21
+ "peerDependencies": {
22
+ "react": ">=18",
23
+ "react-native": ">=0.72",
24
+ "react-native-view-shot": ">=3.6"
25
+ },
26
+ "peerDependenciesMeta": {
27
+ "react-native-view-shot": {
28
+ "optional": true
29
+ }
30
+ },
31
+ "devDependencies": {
32
+ "@types/react": "^18.3.12",
33
+ "react": "18.3.1",
34
+ "react-native": "0.76.5",
35
+ "typescript": "^5.6.3"
36
+ },
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "https://github.com/Kiswani/astra-test-react-native"
40
+ },
41
+ "keywords": [
42
+ "bug reporting",
43
+ "uat",
44
+ "feedback",
45
+ "react-native",
46
+ "astra test"
47
+ ],
48
+ "publishConfig": {
49
+ "access": "public"
50
+ }
51
+ }
package/src/capture.ts ADDED
@@ -0,0 +1,75 @@
1
+ export type LogLine = { level: string; message: string; at: number };
2
+ export type NetCall = { method: string; url: string; status: number; durationMs: number; at: number };
3
+
4
+ export class Ring<T> {
5
+ private q: T[] = [];
6
+ constructor(private cap: number) {}
7
+ push(x: T) { this.q.push(x); if (this.q.length > this.cap) this.q.splice(0, this.q.length - this.cap); }
8
+ all() { return this.q.slice(); }
9
+ }
10
+
11
+ export const logs = new Ring<LogLine>(200);
12
+ export const network = new Ring<NetCall>(100);
13
+ let ownHost = "astratest.dev";
14
+ export const setOwnHost = (h: string) => { ownHost = h; };
15
+
16
+ const str = (a: unknown) => {
17
+ if (typeof a === "string") return a;
18
+ if (a instanceof Error) return `${a.name}: ${a.message}`;
19
+ try { return JSON.stringify(a); } catch { return String(a); }
20
+ };
21
+
22
+ export function log(level: string, message: string) {
23
+ const m = message.slice(0, 2000);
24
+ if (!m.trim() || m.startsWith("[AstraTest]")) return;
25
+ logs.push({ level, message: m, at: Date.now() });
26
+ }
27
+
28
+ export function cleanUrl(u: string) {
29
+ return u.split("#")[0].split("?")[0].slice(0, 500);
30
+ }
31
+
32
+ export function record(method: string, url: string, status: number, durationMs: number) {
33
+ if (url.includes(ownHost)) return;
34
+ network.push({ method: method.toUpperCase(), url: cleanUrl(url), status, durationMs, at: Date.now() });
35
+ }
36
+
37
+ let consolePatched = false;
38
+ /** Mirrors console.* and uncaught JS errors into the report log. */
39
+ export function patchConsole() {
40
+ if (consolePatched) return;
41
+ consolePatched = true;
42
+ for (const level of ["log", "info", "warn", "error"] as const) {
43
+ const orig = console[level].bind(console);
44
+ console[level] = (...args: unknown[]) => { log(level === "info" ? "log" : level, args.map(str).join(" ")); orig(...args); };
45
+ }
46
+ const EU = (globalThis as { ErrorUtils?: { getGlobalHandler(): (e: unknown, fatal?: boolean) => void; setGlobalHandler(h: (e: unknown, fatal?: boolean) => void): void } }).ErrorUtils;
47
+ if (EU) {
48
+ const prev = EU.getGlobalHandler();
49
+ EU.setGlobalHandler((e, fatal) => { log("error", `${fatal ? "Fatal: " : ""}${str(e)}`); prev(e, fatal); });
50
+ }
51
+ }
52
+
53
+ let xhrPatched = false;
54
+ /** fetch() in React Native runs on XMLHttpRequest, so patching it records fetch, axios and the rest. */
55
+ export function patchXhr() {
56
+ if (xhrPatched) return;
57
+ const X = (globalThis as { XMLHttpRequest?: { prototype: XMLHttpRequest } }).XMLHttpRequest;
58
+ if (!X) return;
59
+ xhrPatched = true;
60
+ const open = X.prototype.open, send = X.prototype.send;
61
+ X.prototype.open = function (this: XMLHttpRequest & { __astra?: { m: string; u: string; t: number } }, method: string, url: string | URL, ...rest: unknown[]) {
62
+ this.__astra = { m: method, u: String(url), t: 0 };
63
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
64
+ return (open as any).call(this, method, url, ...rest);
65
+ } as typeof open;
66
+ X.prototype.send = function (this: XMLHttpRequest & { __astra?: { m: string; u: string; t: number } }, body?: unknown) {
67
+ const a = this.__astra;
68
+ if (a) {
69
+ a.t = Date.now();
70
+ this.addEventListener("loadend", () => record(a.m, a.u, this.status, Date.now() - a.t));
71
+ }
72
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
73
+ return (send as any).call(this, body);
74
+ };
75
+ }
package/src/index.tsx ADDED
@@ -0,0 +1,209 @@
1
+ import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from "react";
2
+ import { Dimensions, KeyboardAvoidingView, Modal, Platform, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
3
+ import { log as addLog, logs, network, patchConsole, patchXhr, setOwnHost } from "./capture";
4
+
5
+ export type AstraTestOptions = {
6
+ /** Your app's version, such as "1.4.0". */
7
+ appVersion?: string;
8
+ /** Your build number. */
9
+ build?: string;
10
+ /** Show the floating Report button. Defaults to true for pk_test_ keys, false for pk_live_. */
11
+ showButton?: boolean;
12
+ /** Record fetch / XMLHttpRequest calls (method, URL without query, status, timing). */
13
+ captureNetwork?: boolean;
14
+ /** Attach console output and uncaught errors to reports. */
15
+ captureLogs?: boolean;
16
+ /** Where reports are sent. */
17
+ host?: string;
18
+ };
19
+
20
+ export type SentReport = { ref: string; url?: string; title?: string };
21
+
22
+ const COBALT = "#2F55D4", MIDNIGHT = "#0E1A3D";
23
+ const s: { key?: string; options: AstraTestOptions; reporter: Record<string, string>; testCase?: string; screen?: string; open?: () => void; capture?: () => Promise<string | undefined> } = { options: {}, reporter: {} };
24
+
25
+ // react-native-view-shot is optional: with it, reports carry a screenshot.
26
+ let captureRef: ((ref: unknown, opts: object) => Promise<string>) | undefined;
27
+ try {
28
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
29
+ captureRef = require("react-native-view-shot").captureRef;
30
+ } catch {
31
+ captureRef = undefined;
32
+ }
33
+
34
+ export const AstraTest = {
35
+ /** Starts Astra Test. Call once, before your app renders. Then wrap your app in <AstraTestProvider>. */
36
+ start(key: string, options: AstraTestOptions = {}) {
37
+ if (s.key) return;
38
+ if (!/^pk_(test|live)_[0-9a-f]{24}$/.test(key)) { console.warn("[AstraTest] That isn't a project key. Copy it from SDK setup in Astra Test."); return; }
39
+ s.key = key; s.options = options;
40
+ try { setOwnHost(new URL(options.host ?? "https://astratest.dev").host); } catch { /* keep default */ }
41
+ if (options.captureLogs !== false) patchConsole();
42
+ if (options.captureNetwork !== false) patchXhr();
43
+ if (options.appVersion) post("/v1/builds", { key, platform: Platform.OS, version: options.appVersion, build: options.build ?? "" }).catch(() => undefined);
44
+ },
45
+ /** Says who is testing, so reports show their name and they can be asked if a fix works. */
46
+ identify(user: { id?: string; email?: string; name?: string }) {
47
+ s.reporter = Object.fromEntries(Object.entries(user).filter(([, v]) => !!v)) as Record<string, string>;
48
+ },
49
+ /** The test case being run, such as "UAT-02". */
50
+ setTestCase(ref?: string) { s.testCase = ref; },
51
+ /** The screen the user is on, such as "Checkout". Call it from your navigation's state listener. */
52
+ setScreen(name?: string) { s.screen = name; },
53
+ /** Adds a line to the log attached to reports. */
54
+ log(message: string, level = "log") { addLog(level, message); },
55
+ /** Opens the report sheet. */
56
+ showReport() { s.open?.(); },
57
+ /** Sends a report without the sheet, for example from your own feedback form. */
58
+ async send(description: string): Promise<SentReport> { return send(description, await s.capture?.()); },
59
+ };
60
+
61
+ function payload(description: string, screenshot?: string) {
62
+ const { width, height } = Dimensions.get("window");
63
+ const screen = s.screen ?? "App";
64
+ let locale = "en";
65
+ try { locale = Intl.DateTimeFormat().resolvedOptions().locale; } catch { /* Intl missing */ }
66
+ return {
67
+ key: s.key,
68
+ description,
69
+ page: { url: `app://react-native/${screen}`, title: screen },
70
+ device: {
71
+ platform: Platform.OS,
72
+ os: `${Platform.OS === "ios" ? "iOS" : Platform.OS === "android" ? "Android" : Platform.OS} ${Platform.Version}`,
73
+ browser: `React Native${(Platform.constants as { reactNativeVersion?: { major: number; minor: number } })?.reactNativeVersion ? ` ${(Platform.constants as { reactNativeVersion: { major: number; minor: number } }).reactNativeVersion.major}.${(Platform.constants as { reactNativeVersion: { major: number; minor: number } }).reactNativeVersion.minor}` : ""}`,
74
+ viewport: `${Math.round(width)} × ${Math.round(height)}`,
75
+ locale,
76
+ appVersion: s.options.appVersion,
77
+ build: s.options.build,
78
+ },
79
+ console: logs.all().slice(-60),
80
+ network: network.all().slice(-60),
81
+ reporter: Object.keys(s.reporter).length ? s.reporter : undefined,
82
+ testCaseRef: s.testCase,
83
+ screenshot,
84
+ };
85
+ }
86
+
87
+ async function post(path: string, body: object) {
88
+ const res = await fetch(`${s.options.host ?? "https://astratest.dev"}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
89
+ const j = (await res.json().catch(() => ({}))) as { ref?: string; url?: string; title?: string; error?: string };
90
+ if (!res.ok) throw new Error(j.error ?? `Couldn't send the report (${res.status})`);
91
+ return j;
92
+ }
93
+
94
+ async function send(description: string, screenshot?: string): Promise<SentReport> {
95
+ if (!s.key) throw new Error("Astra Test isn't started");
96
+ const j = await post("/v1/reports", payload(description, screenshot));
97
+ if (!j.ref) throw new Error(j.error ?? "Couldn't send the report");
98
+ return { ref: j.ref, url: j.url, title: j.title };
99
+ }
100
+
101
+ const Masking = createContext(false);
102
+
103
+ /** Covers its children in report screenshots. Wrap password fields and anything private in it. */
104
+ export function AstraPrivate({ children }: { children: React.ReactNode }) {
105
+ const masking = useContext(Masking);
106
+ return <View>{children}{masking && <View style={[StyleSheet.absoluteFill, { backgroundColor: "#000" }]} />}</View>;
107
+ }
108
+
109
+ /** Wrap your whole app in this, inside your providers. Adds the Report button and the report sheet. */
110
+ export function AstraTestProvider({ children }: { children: React.ReactNode }) {
111
+ const root = useRef<View>(null);
112
+ const [open, setOpen] = useState(false);
113
+ const [masking, setMasking] = useState(false);
114
+ const [shot, setShot] = useState<string>();
115
+ const [text, setText] = useState("");
116
+ const [sending, setSending] = useState(false);
117
+ const [error, setError] = useState<string>();
118
+ const [sent, setSent] = useState<SentReport>();
119
+
120
+ const capture = useCallback(async () => {
121
+ if (!captureRef || !root.current) return undefined;
122
+ setMasking(true);
123
+ await new Promise((r) => setTimeout(r, 60));
124
+ try {
125
+ const b64 = await captureRef(root.current, { format: "jpg", quality: 0.7, result: "base64" });
126
+ return `data:image/jpeg;base64,${b64}`;
127
+ } catch {
128
+ return undefined;
129
+ } finally {
130
+ setMasking(false);
131
+ }
132
+ }, []);
133
+
134
+ const show = useCallback(async () => {
135
+ if (!s.key || open) return;
136
+ setShot(await capture());
137
+ setText(""); setError(undefined); setSent(undefined); setOpen(true);
138
+ }, [capture, open]);
139
+
140
+ useEffect(() => { s.open = show; s.capture = capture; return () => { s.open = undefined; s.capture = undefined; }; }, [show, capture]);
141
+
142
+ const submit = async () => {
143
+ const t = text.trim();
144
+ if (t.length < 3 || sending) return;
145
+ setSending(true); setError(undefined);
146
+ try { setSent(await send(t, shot)); } catch (e) { setError((e as Error).message); } finally { setSending(false); }
147
+ };
148
+
149
+ const showButton = !!s.key && (s.options.showButton ?? s.key.startsWith("pk_test_"));
150
+ const nNet = network.all().length, nLog = logs.all().length;
151
+
152
+ return (
153
+ <Masking.Provider value={masking}>
154
+ <View ref={root} collapsable={false} style={{ flex: 1 }}>{children}</View>
155
+ {showButton && !open && (
156
+ <Pressable accessibilityLabel="Report an issue" onPress={show} style={st.fab}>
157
+ <Text style={st.fabText}>✦ Report</Text>
158
+ </Pressable>
159
+ )}
160
+ <Modal visible={open} transparent animationType="slide" onRequestClose={() => setOpen(false)}>
161
+ <KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : undefined} style={st.backdrop}>
162
+ <Pressable style={StyleSheet.absoluteFill} onPress={() => setOpen(false)} />
163
+ <View style={st.sheet}>
164
+ {sent ? (
165
+ <>
166
+ <Text style={st.sent}>✓ Sent as {sent.ref}</Text>
167
+ <Text style={st.muted}>Thanks. We'll let you know when it's fixed.</Text>
168
+ <Pressable onPress={() => setOpen(false)} style={st.done}><Text style={{ color: COBALT, fontWeight: "600" }}>Done</Text></Pressable>
169
+ </>
170
+ ) : (
171
+ <>
172
+ <View style={st.row}>
173
+ <Text style={st.title}>Report an issue</Text>
174
+ <Pressable onPress={() => setOpen(false)}><Text style={{ color: COBALT }}>Cancel</Text></Pressable>
175
+ </View>
176
+ <Text style={st.label}>What happened{s.screen ? ` on ${s.screen}` : ""}?</Text>
177
+ <TextInput value={text} onChangeText={setText} placeholder="Say it in your own words" multiline style={st.input} autoFocus />
178
+ <Text style={st.muted}>Attached: {[shot ? "Screenshot" : null, nNet ? `${nNet} requests` : null, nLog ? `${nLog} log lines` : null, "device details"].filter(Boolean).join(" · ")}</Text>
179
+ {error && <Text style={st.error}>{error}</Text>}
180
+ <Pressable onPress={submit} disabled={sending || text.trim().length < 3} style={[st.send, { opacity: sending || text.trim().length < 3 ? 0.45 : 1 }]}>
181
+ <Text style={st.sendText}>{sending ? "Sending…" : "Send report"}</Text>
182
+ </Pressable>
183
+ </>
184
+ )}
185
+ </View>
186
+ </KeyboardAvoidingView>
187
+ </Modal>
188
+ </Masking.Provider>
189
+ );
190
+ }
191
+
192
+ const st = StyleSheet.create({
193
+ fab: { position: "absolute", right: 16, bottom: 40, backgroundColor: MIDNIGHT, paddingHorizontal: 16, paddingVertical: 10, borderRadius: 999, elevation: 6, shadowColor: "#000", shadowOpacity: 0.25, shadowRadius: 8, shadowOffset: { width: 0, height: 3 } },
194
+ fabText: { color: "#fff", fontWeight: "600", fontSize: 14 },
195
+ backdrop: { flex: 1, justifyContent: "flex-end", backgroundColor: "rgba(0,0,0,0.4)" },
196
+ sheet: { backgroundColor: "#fff", borderTopLeftRadius: 18, borderTopRightRadius: 18, padding: 20, paddingBottom: 34, gap: 10 },
197
+ row: { flexDirection: "row", justifyContent: "space-between", alignItems: "center" },
198
+ title: { fontSize: 18, fontWeight: "700", color: "#0F1115" },
199
+ label: { fontSize: 12, color: "#646B78", marginTop: 6 },
200
+ input: { minHeight: 90, borderWidth: 1, borderColor: "#8A909C", borderRadius: 8, padding: 10, fontSize: 15, textAlignVertical: "top" },
201
+ muted: { fontSize: 12, color: "#646B78" },
202
+ error: { fontSize: 13, color: "#B42318" },
203
+ send: { backgroundColor: COBALT, borderRadius: 10, height: 46, alignItems: "center", justifyContent: "center", marginTop: 4 },
204
+ sendText: { color: "#fff", fontWeight: "600", fontSize: 15 },
205
+ sent: { fontSize: 17, fontWeight: "700", color: "#0E7C66" },
206
+ done: { alignSelf: "flex-end", padding: 8 },
207
+ });
208
+
209
+ export default AstraTest;