@react-native-harness/platform-android 1.3.0 → 1.4.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/__tests__/crash-diagnostics.test.d.ts +2 -0
  2. package/dist/__tests__/crash-diagnostics.test.d.ts.map +1 -0
  3. package/dist/__tests__/crash-diagnostics.test.js +119 -0
  4. package/dist/__tests__/crash-reporter.test.d.ts +2 -0
  5. package/dist/__tests__/crash-reporter.test.d.ts.map +1 -0
  6. package/dist/__tests__/crash-reporter.test.js +150 -0
  7. package/dist/__tests__/instance.test.js +133 -24
  8. package/dist/adb.d.ts +4 -0
  9. package/dist/adb.d.ts.map +1 -1
  10. package/dist/adb.js +42 -2
  11. package/dist/app-session.d.ts +17 -0
  12. package/dist/app-session.d.ts.map +1 -0
  13. package/dist/app-session.js +209 -0
  14. package/dist/crash-diagnostics.d.ts +40 -0
  15. package/dist/crash-diagnostics.d.ts.map +1 -0
  16. package/dist/crash-diagnostics.js +256 -0
  17. package/dist/crash-reporter.d.ts +12 -0
  18. package/dist/crash-reporter.d.ts.map +1 -0
  19. package/dist/crash-reporter.js +150 -0
  20. package/dist/instance.d.ts +1 -1
  21. package/dist/instance.d.ts.map +1 -1
  22. package/dist/instance.js +32 -59
  23. package/dist/runner.d.ts.map +1 -1
  24. package/dist/runner.js +1 -1
  25. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  26. package/package.json +4 -4
  27. package/src/__tests__/crash-diagnostics.test.ts +144 -0
  28. package/src/__tests__/crash-reporter.test.ts +167 -0
  29. package/src/__tests__/instance.test.ts +174 -31
  30. package/src/adb.ts +61 -2
  31. package/src/app-session.ts +300 -0
  32. package/src/crash-diagnostics.ts +471 -0
  33. package/src/crash-reporter.ts +263 -0
  34. package/src/instance.ts +56 -91
  35. package/src/runner.ts +7 -3
  36. package/test/setup.ts +1 -0
  37. package/src/app-monitor.ts +0 -577
@@ -1,577 +0,0 @@
1
- import {
2
- type AppMonitor,
3
- type AppCrashDetails,
4
- type CrashArtifactWriter,
5
- type CrashDetailsLookupOptions,
6
- type AppMonitorEvent,
7
- type AppMonitorListener,
8
- } from '@react-native-harness/platforms';
9
- import {
10
- escapeRegExp,
11
- getEmitter,
12
- logger,
13
- SubprocessError,
14
- type Subprocess,
15
- } from '@react-native-harness/tools';
16
- import * as adb from './adb.js';
17
- import { androidCrashParser } from './crash-parser.js';
18
-
19
- const androidAppMonitorLogger = logger.child('android-app-monitor');
20
-
21
- const getLogcatArgs = (uid: number, fromTime: string) =>
22
- [
23
- 'logcat',
24
- '-v',
25
- 'threadtime',
26
- '-b',
27
- 'crash',
28
- `--uid=${uid}`,
29
- '-T',
30
- fromTime,
31
- ] as const;
32
- const MAX_RECENT_LOG_LINES = 200;
33
- const MAX_RECENT_CRASH_ARTIFACTS = 10;
34
- const CRASH_ARTIFACT_SETTLE_DELAY_MS = 100;
35
-
36
- const startProcPattern = (bundleId: string) =>
37
- new RegExp(`Start proc (\\d+):${escapeRegExp(bundleId)}(?:/|\\s)`);
38
-
39
- const processPattern = (bundleId: string) =>
40
- new RegExp(`Process:\\s*${escapeRegExp(bundleId)},\\s*PID:\\s*(\\d+)`);
41
-
42
- const nativeCrashPattern = (bundleId: string) =>
43
- new RegExp(`>>>\\s*${escapeRegExp(bundleId)}\\s*<<<`);
44
-
45
- const processDiedPattern = (bundleId: string) =>
46
- new RegExp(
47
- `Process\\s+${escapeRegExp(
48
- bundleId
49
- )}\\s+\\(pid\\s+(\\d+)\\)\\s+has\\s+died`,
50
- 'i'
51
- );
52
-
53
- const getSignal = (line: string) => {
54
- const namedSignalMatch = line.match(/\b(SIG[A-Z0-9]+)\b/);
55
-
56
- if (namedSignalMatch) {
57
- return namedSignalMatch[1];
58
- }
59
-
60
- const signalNumberMatch = line.match(/signal\s+(\d+)/i);
61
-
62
- if (signalNumberMatch) {
63
- return `signal ${signalNumberMatch[1]}`;
64
- }
65
-
66
- return undefined;
67
- };
68
-
69
- const getAndroidLogLineCrashDetails = ({
70
- line,
71
- bundleId,
72
- pid,
73
- }: {
74
- line: string;
75
- bundleId: string;
76
- pid?: number;
77
- }): AppCrashDetails => {
78
- const fatalExceptionMatch = line.match(/FATAL EXCEPTION:\s*(.+)$/i);
79
- const processMatch = line.match(processPattern(bundleId));
80
-
81
- return {
82
- source: 'logs',
83
- summary: line.trim(),
84
- signal: getSignal(line),
85
- exceptionType: fatalExceptionMatch?.[1]?.trim(),
86
- processName: processMatch
87
- ? bundleId
88
- : line.includes(bundleId)
89
- ? bundleId
90
- : undefined,
91
- pid: pid ?? (processMatch ? Number(processMatch[1]) : undefined),
92
- rawLines: [line],
93
- };
94
- };
95
-
96
- type TimedLogLine = {
97
- line: string;
98
- occurredAt: number;
99
- };
100
-
101
- type AndroidCrashArtifact = AppCrashDetails & {
102
- occurredAt: number;
103
- triggerLine: string;
104
- triggerOccurredAt?: number;
105
- };
106
-
107
- const CRASH_BLOCK_HEADER = '--------- beginning of crash';
108
-
109
- const getLatestCrashBlock = (recentLogLines: TimedLogLine[]) => {
110
- const lines = recentLogLines.map(({ line }) => line);
111
- let latestCrashHeaderIndex = -1;
112
-
113
- for (let index = lines.length - 1; index >= 0; index -= 1) {
114
- if (/FATAL EXCEPTION:|Process:\s+.+,\s+PID:/i.test(lines[index])) {
115
- latestCrashHeaderIndex = index;
116
- break;
117
- }
118
- }
119
-
120
- const blockStartIndex = Math.max(
121
- lines.lastIndexOf(CRASH_BLOCK_HEADER),
122
- latestCrashHeaderIndex
123
- );
124
-
125
- if (blockStartIndex === -1) {
126
- return lines;
127
- }
128
-
129
- return lines.slice(blockStartIndex);
130
- };
131
-
132
- const getCrashBlockForArtifact = ({
133
- artifact,
134
- recentLogLines,
135
- }: {
136
- artifact: AndroidCrashArtifact;
137
- recentLogLines: TimedLogLine[];
138
- }): string[] => {
139
- const targetIndex = recentLogLines.findIndex(
140
- ({ line, occurredAt }) =>
141
- line === artifact.triggerLine &&
142
- (artifact.triggerOccurredAt === undefined ||
143
- occurredAt === artifact.triggerOccurredAt)
144
- );
145
-
146
- if (targetIndex === -1) {
147
- return artifact.rawLines ?? [];
148
- }
149
-
150
- let blockStartIndex = targetIndex;
151
-
152
- for (let index = targetIndex; index >= 0; index -= 1) {
153
- const { line } = recentLogLines[index];
154
-
155
- if (line === CRASH_BLOCK_HEADER) {
156
- blockStartIndex = index;
157
- break;
158
- }
159
- }
160
-
161
- let blockEndIndex = recentLogLines.length;
162
-
163
- for (let index = targetIndex + 1; index < recentLogLines.length; index += 1) {
164
- if (recentLogLines[index].line === CRASH_BLOCK_HEADER) {
165
- blockEndIndex = index;
166
- break;
167
- }
168
- }
169
-
170
- return recentLogLines
171
- .slice(blockStartIndex, blockEndIndex)
172
- .map(({ line }) => line);
173
- };
174
-
175
- const hydrateCrashArtifact = ({
176
- artifact,
177
- recentLogLines,
178
- }: {
179
- artifact: AndroidCrashArtifact;
180
- recentLogLines: TimedLogLine[];
181
- }): AppCrashDetails => {
182
- const rawLines = getCrashBlockForArtifact({ artifact, recentLogLines });
183
-
184
- if (rawLines.length === 0) {
185
- return artifact;
186
- }
187
-
188
- const parsedDetails = androidCrashParser.parse({
189
- contents: rawLines.join('\n'),
190
- bundleId: artifact.processName ?? '',
191
- pid: artifact.pid,
192
- });
193
-
194
- return {
195
- ...artifact,
196
- ...parsedDetails,
197
- artifactType: artifact.artifactType,
198
- artifactPath: artifact.artifactPath,
199
- rawLines,
200
- };
201
- };
202
-
203
- const createCrashArtifact = ({
204
- details,
205
- recentLogLines,
206
- }: {
207
- details: AppCrashDetails;
208
- recentLogLines: TimedLogLine[];
209
- }): AndroidCrashArtifact => {
210
- const occurredAt = Date.now();
211
- const rawLines = getLatestCrashBlock(recentLogLines);
212
- const triggerOccurredAt = [...recentLogLines]
213
- .reverse()
214
- .find(({ line }) => line === details.summary)?.occurredAt;
215
- const contents =
216
- rawLines.length > 0
217
- ? rawLines.join('\n')
218
- : (details.rawLines ?? []).join('\n');
219
- const parsedDetails =
220
- details.processName !== undefined
221
- ? androidCrashParser.parse({
222
- contents,
223
- bundleId: details.processName,
224
- pid: details.pid,
225
- })
226
- : details;
227
-
228
- return {
229
- ...parsedDetails,
230
- occurredAt,
231
- triggerLine: details.summary ?? '',
232
- triggerOccurredAt,
233
- artifactType: 'logcat',
234
- rawLines:
235
- rawLines.length > 0
236
- ? rawLines
237
- : parsedDetails.rawLines ?? details.rawLines,
238
- };
239
- };
240
-
241
- const persistCrashArtifact = ({
242
- details,
243
- crashArtifactWriter,
244
- }: {
245
- details: AppCrashDetails;
246
- crashArtifactWriter?: CrashArtifactWriter;
247
- }): AppCrashDetails => {
248
- if (!crashArtifactWriter || details.artifactType !== 'logcat') {
249
- return details;
250
- }
251
-
252
- const artifactBody = details.rawLines?.join('\n');
253
-
254
- if (!artifactBody) {
255
- return details;
256
- }
257
-
258
- return {
259
- ...details,
260
- artifactPath: crashArtifactWriter.persistArtifact({
261
- artifactKind: details.artifactType,
262
- source: {
263
- kind: 'text',
264
- fileName: 'logcat.txt',
265
- text: `${artifactBody}\n`,
266
- },
267
- }),
268
- };
269
- };
270
-
271
- const getLatestCrashArtifact = ({
272
- crashArtifacts,
273
- recentLogLines,
274
- processName,
275
- pid,
276
- occurredAt,
277
- }: CrashDetailsLookupOptions & {
278
- crashArtifacts: AndroidCrashArtifact[];
279
- recentLogLines: TimedLogLine[];
280
- }): AppCrashDetails | null => {
281
- const matchingByPid = pid
282
- ? crashArtifacts.filter((artifact) => artifact.pid === pid)
283
- : [];
284
- const matchingByProcess = processName
285
- ? crashArtifacts.filter((artifact) => artifact.processName === processName)
286
- : [];
287
- const candidates =
288
- matchingByPid.length > 0
289
- ? matchingByPid
290
- : matchingByProcess.length > 0
291
- ? matchingByProcess
292
- : crashArtifacts;
293
- const sortedCandidates = [...candidates].sort(
294
- (left, right) =>
295
- Math.abs(left.occurredAt - occurredAt) -
296
- Math.abs(right.occurredAt - occurredAt)
297
- );
298
-
299
- const artifact = sortedCandidates[0];
300
-
301
- if (!artifact) {
302
- return null;
303
- }
304
-
305
- return hydrateCrashArtifact({
306
- artifact,
307
- recentLogLines,
308
- });
309
- };
310
-
311
- const createAndroidLogEvent = (
312
- line: string,
313
- bundleId: string
314
- ): AppMonitorEvent | null => {
315
- const startMatch = line.match(startProcPattern(bundleId));
316
-
317
- if (startMatch) {
318
- return {
319
- type: 'app_started',
320
- pid: Number(startMatch[1]),
321
- source: 'logs',
322
- line,
323
- };
324
- }
325
-
326
- const processMatch = line.match(processPattern(bundleId));
327
-
328
- if (processMatch) {
329
- return {
330
- type: 'possible_crash',
331
- pid: Number(processMatch[1]),
332
- source: 'logs',
333
- line,
334
- crashDetails: getAndroidLogLineCrashDetails({
335
- line,
336
- bundleId,
337
- pid: Number(processMatch[1]),
338
- }),
339
- };
340
- }
341
-
342
- if (nativeCrashPattern(bundleId).test(line)) {
343
- return {
344
- type: 'possible_crash',
345
- source: 'logs',
346
- line,
347
- crashDetails: getAndroidLogLineCrashDetails({
348
- line,
349
- bundleId,
350
- }),
351
- };
352
- }
353
-
354
- const diedMatch = line.match(processDiedPattern(bundleId));
355
-
356
- if (diedMatch) {
357
- return {
358
- type: 'app_exited',
359
- pid: Number(diedMatch[1]),
360
- source: 'logs',
361
- line,
362
- crashDetails: getAndroidLogLineCrashDetails({
363
- line,
364
- bundleId,
365
- pid: Number(diedMatch[1]),
366
- }),
367
- };
368
- }
369
-
370
- if (
371
- line.includes(bundleId) &&
372
- /fatal|crash|signal 11|signal 6|backtrace/i.test(line)
373
- ) {
374
- return {
375
- type: 'possible_crash',
376
- source: 'logs',
377
- line,
378
- crashDetails: getAndroidLogLineCrashDetails({
379
- line,
380
- bundleId,
381
- }),
382
- };
383
- }
384
-
385
- return null;
386
- };
387
-
388
- export const createAndroidAppMonitor = ({
389
- adbId,
390
- bundleId,
391
- appUid,
392
- crashArtifactWriter,
393
- }: {
394
- adbId: string;
395
- bundleId: string;
396
- appUid: number;
397
- crashArtifactWriter?: CrashArtifactWriter;
398
- }): AndroidAppMonitor => {
399
- const emitter = getEmitter<AppMonitorEvent>();
400
-
401
- let isStarted = false;
402
- let logcatProcess: Subprocess | null = null;
403
- let logTask: Promise<void> | null = null;
404
- let recentLogLines: TimedLogLine[] = [];
405
- let recentCrashArtifacts: AndroidCrashArtifact[] = [];
406
-
407
- const emit = (event: AppMonitorEvent) => {
408
- emitter.emit(event);
409
- };
410
-
411
- const recordLogLine = (line: string) => {
412
- recentLogLines = [
413
- ...recentLogLines,
414
- { line, occurredAt: Date.now() },
415
- ].slice(-MAX_RECENT_LOG_LINES);
416
- };
417
-
418
- const recordCrashArtifact = (details?: AppCrashDetails) => {
419
- if (!details) {
420
- return;
421
- }
422
-
423
- recentCrashArtifacts = [
424
- ...recentCrashArtifacts,
425
- createCrashArtifact({
426
- details,
427
- recentLogLines,
428
- }),
429
- ].slice(-MAX_RECENT_CRASH_ARTIFACTS);
430
- };
431
-
432
- const stopProcess = async (child: Subprocess | null) => {
433
- if (!child) {
434
- return;
435
- }
436
-
437
- try {
438
- (await child.nodeChildProcess).kill();
439
- } catch {
440
- // Ignore termination failures for background monitors.
441
- }
442
- };
443
-
444
- const startLogcat = async () => {
445
- const logcatTimestamp = await adb.getLogcatTimestamp(adbId);
446
-
447
- logcatProcess = adb.startLogcat(
448
- adbId,
449
- getLogcatArgs(appUid, logcatTimestamp)
450
- );
451
-
452
- const currentProcess = logcatProcess;
453
-
454
- if (!currentProcess) {
455
- return;
456
- }
457
-
458
- logTask = (async () => {
459
- try {
460
- for await (const line of currentProcess) {
461
- recordLogLine(line);
462
- emit({ type: 'log', source: 'logs', line });
463
-
464
- const event = createAndroidLogEvent(line, bundleId);
465
-
466
- if (event) {
467
- if (
468
- event.type === 'possible_crash' ||
469
- event.type === 'app_exited'
470
- ) {
471
- recordCrashArtifact(event.crashDetails);
472
- }
473
- emit(event);
474
- }
475
- }
476
- } catch (error) {
477
- if (
478
- !(error instanceof SubprocessError && error.signalName === 'SIGTERM')
479
- ) {
480
- androidAppMonitorLogger.debug(
481
- 'Android logcat monitor stopped',
482
- error
483
- );
484
- }
485
- }
486
- })();
487
- };
488
-
489
- const start = async () => {
490
- if (isStarted) {
491
- return;
492
- }
493
-
494
- try {
495
- await startLogcat();
496
- isStarted = true;
497
- } catch (error) {
498
- const currentProcess = logcatProcess;
499
- const currentTask = logTask;
500
-
501
- logcatProcess = null;
502
- logTask = null;
503
-
504
- await stopProcess(currentProcess);
505
- await currentTask;
506
-
507
- throw error;
508
- }
509
- };
510
-
511
- const stop = async () => {
512
- if (!isStarted) {
513
- return;
514
- }
515
-
516
- isStarted = false;
517
-
518
- const currentProcess = logcatProcess;
519
- const currentTask = logTask;
520
-
521
- logcatProcess = null;
522
- logTask = null;
523
-
524
- await stopProcess(currentProcess);
525
- await currentTask;
526
- };
527
-
528
- const dispose = async () => {
529
- await stop();
530
- emitter.clearAllListeners();
531
- recentLogLines = [];
532
- recentCrashArtifacts = [];
533
- };
534
-
535
- const addListener = (listener: AppMonitorListener) => {
536
- emitter.addListener(listener);
537
- };
538
-
539
- const removeListener = (listener: AppMonitorListener) => {
540
- emitter.removeListener(listener);
541
- };
542
-
543
- return {
544
- start,
545
- stop,
546
- dispose,
547
- addListener,
548
- removeListener,
549
- getCrashDetails: async (options: CrashDetailsLookupOptions) => {
550
- await new Promise((resolve) =>
551
- setTimeout(resolve, CRASH_ARTIFACT_SETTLE_DELAY_MS)
552
- );
553
-
554
- const details = getLatestCrashArtifact({
555
- crashArtifacts: recentCrashArtifacts,
556
- recentLogLines,
557
- ...options,
558
- });
559
-
560
- if (!details) {
561
- return null;
562
- }
563
-
564
- return persistCrashArtifact({
565
- details,
566
- crashArtifactWriter,
567
- });
568
- },
569
- } satisfies AndroidAppMonitor;
570
- };
571
-
572
- export { createAndroidLogEvent };
573
- export type AndroidAppMonitor = AppMonitor & {
574
- getCrashDetails: (
575
- options: CrashDetailsLookupOptions
576
- ) => Promise<AppCrashDetails | null>;
577
- };