@rnperf/sdk 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,122 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Transport = void 0;
4
+ const PROTOCOL_VERSION = 1;
5
+ /**
6
+ * An IPv6 literal must be bracketed inside a URL. This matters in practice:
7
+ * a physical iPhone reaches the development machine over an IPv6 tunnel, and
8
+ * an unbracketed address silently produces an unusable URL.
9
+ */
10
+ function formatHost(host) {
11
+ const bare = host.replace(/^\[|\]$/g, '');
12
+ return bare.includes(':') ? `[${bare}]` : bare;
13
+ }
14
+ /**
15
+ * Reconnecting WebSocket to the daemon. Everything is best-effort: when the
16
+ * daemon is not running the app must behave exactly as if the SDK were absent,
17
+ * so failures are swallowed and retried with backoff rather than surfaced.
18
+ */
19
+ class Transport {
20
+ hello;
21
+ onStatus;
22
+ socket = null;
23
+ url;
24
+ closed = false;
25
+ retryMs = 1000;
26
+ reconnectTimer = null;
27
+ queue = [];
28
+ constructor(host, port, hello, onStatus) {
29
+ this.hello = hello;
30
+ this.onStatus = onStatus;
31
+ this.url = `ws://${formatHost(host)}:${port}/ingest`;
32
+ }
33
+ connect() {
34
+ if (this.closed || this.socket)
35
+ return;
36
+ this.onStatus?.('connecting');
37
+ try {
38
+ const socket = new global.WebSocket(this.url);
39
+ this.socket = socket;
40
+ socket.onopen = () => {
41
+ this.retryMs = 1000;
42
+ this.onStatus?.('connected');
43
+ this.send({
44
+ type: 'hello',
45
+ protocol: PROTOCOL_VERSION,
46
+ startedAt: Date.now(),
47
+ ...this.hello,
48
+ });
49
+ // Replay anything buffered while the daemon was unreachable.
50
+ const pending = this.queue;
51
+ this.queue = [];
52
+ for (const message of pending) {
53
+ try {
54
+ socket.send(message);
55
+ }
56
+ catch { /* dropped */ }
57
+ }
58
+ };
59
+ socket.onclose = () => this.handleDrop();
60
+ socket.onerror = () => this.handleDrop();
61
+ }
62
+ catch {
63
+ this.handleDrop();
64
+ }
65
+ }
66
+ handleDrop() {
67
+ if (this.socket) {
68
+ try {
69
+ this.socket.close();
70
+ }
71
+ catch { /* ignore */ }
72
+ }
73
+ this.socket = null;
74
+ this.onStatus?.('disconnected');
75
+ if (this.closed || this.reconnectTimer)
76
+ return;
77
+ this.reconnectTimer = setTimeout(() => {
78
+ this.reconnectTimer = null;
79
+ this.connect();
80
+ }, this.retryMs);
81
+ // Back off to 30s so a release build with no daemon is not retrying hard.
82
+ this.retryMs = Math.min(this.retryMs * 2, 30_000);
83
+ }
84
+ send(payload) {
85
+ const text = JSON.stringify(payload);
86
+ const socket = this.socket;
87
+ if (socket && socket.readyState === 1) {
88
+ try {
89
+ socket.send(text);
90
+ return;
91
+ }
92
+ catch { /* fall through to buffering */ }
93
+ }
94
+ // Keep only a short tail: stale samples are worth less than live ones.
95
+ this.queue.push(text);
96
+ if (this.queue.length > 60)
97
+ this.queue.shift();
98
+ }
99
+ sendSample(sample) {
100
+ this.send({ type: 'sample', sample });
101
+ }
102
+ sendEvent(event) {
103
+ this.send({ type: 'event', event });
104
+ }
105
+ close() {
106
+ this.closed = true;
107
+ if (this.reconnectTimer)
108
+ clearTimeout(this.reconnectTimer);
109
+ this.reconnectTimer = null;
110
+ try {
111
+ this.send({ type: 'bye' });
112
+ this.socket?.close();
113
+ }
114
+ catch { /* ignore */ }
115
+ this.socket = null;
116
+ }
117
+ get connected() {
118
+ return this.socket?.readyState === 1;
119
+ }
120
+ }
121
+ exports.Transport = Transport;
122
+ //# sourceMappingURL=transport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport.js","sourceRoot":"","sources":["../src/transport.ts"],"names":[],"mappings":";;;AAIA,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAE3B;;;;GAIG;AACH,SAAS,UAAU,CAAC,IAAY;IAC9B,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CA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GD,8BAmGC"}
@@ -0,0 +1,95 @@
1
+ export interface Sample {
2
+ t: number;
3
+ dt: number;
4
+ jsFps?: number;
5
+ jsHeapMB?: number;
6
+ jsHeapTotalMB?: number;
7
+ jsStallMaxMs?: number;
8
+ jsStallCount?: number;
9
+ bridgeCalls?: number;
10
+ screen?: string;
11
+ uiFps?: number;
12
+ uiRefreshHz?: number;
13
+ frameP50Ms?: number;
14
+ frameP95Ms?: number;
15
+ frameP99Ms?: number;
16
+ jankPercent?: number;
17
+ framesRendered?: number;
18
+ rssMB?: number;
19
+ javaHeapMB?: number;
20
+ nativeHeapMB?: number;
21
+ renders?: Record<string, ComponentRenderStat>;
22
+ }
23
+ export interface ComponentRenderStat {
24
+ count: number;
25
+ totalMs: number;
26
+ maxMs: number;
27
+ wasted?: number;
28
+ }
29
+ export type PerfEvent = {
30
+ type: 'mark';
31
+ t: number;
32
+ name: string;
33
+ detail?: unknown;
34
+ } | {
35
+ type: 'measure';
36
+ t: number;
37
+ name: string;
38
+ durationMs: number;
39
+ detail?: unknown;
40
+ } | {
41
+ type: 'screen';
42
+ t: number;
43
+ name: string;
44
+ } | {
45
+ type: 'tti';
46
+ t: number;
47
+ durationMs: number;
48
+ screen?: string;
49
+ } | {
50
+ type: 'log';
51
+ t: number;
52
+ level: 'debug' | 'info' | 'warn' | 'error';
53
+ tag?: string;
54
+ message: string;
55
+ } | {
56
+ type: 'crash';
57
+ t: number;
58
+ message: string;
59
+ stack?: string;
60
+ } | {
61
+ type: 'interaction';
62
+ t: number;
63
+ name: string;
64
+ durationMs: number;
65
+ };
66
+ export interface PerfMonitorOptions {
67
+ /**
68
+ * Daemon host. `'auto'` (the default) derives it from the Metro bundle URL,
69
+ * which is correct for a simulator, an emulator and a real device on Wi-Fi
70
+ * without any configuration.
71
+ */
72
+ host?: string | 'auto';
73
+ port?: number;
74
+ /** How often to report, in ms. Default 1000. */
75
+ intervalMs?: number;
76
+ /** Track per-component render counts and timings. Default true in dev. */
77
+ trackRenders?: boolean;
78
+ /**
79
+ * Measure UI-thread frames with the rnperf native module (CADisplayLink on
80
+ * iOS, Choreographer on Android). Default true; a no-op where the module is
81
+ * not installed.
82
+ */
83
+ trackUiFrames?: boolean;
84
+ /** Count native module calls crossing the bridge. Default true. */
85
+ trackBridge?: boolean;
86
+ /** Report even in a release build. Default false — profiling has a cost. */
87
+ enableInRelease?: boolean;
88
+ /** Reported alongside samples so the daemon can match this app to a session. */
89
+ bundleId?: string;
90
+ appName?: string;
91
+ appVersion?: string;
92
+ /** Called on connection state changes, for your own debug UI. */
93
+ onStatus?: (status: 'connecting' | 'connected' | 'disconnected') => void;
94
+ }
95
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,MAAM;IACrB,CAAC,EAAE,MAAM,CAAC;IACV,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;IAGhB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,OAAO,CAAC,EAAE,MAAM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AE,MAAM,CAAA;CAAE,CAAC;AAEzE,MAAM,WAAW,kBAAkB;IACjC;;;;OAIG;IACH,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IACvB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,gDAAgD;IAChD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,0EAA0E;IAC1E,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB;;;;OAIG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,mEAAmE;IACnE,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,4EAA4E;IAC5E,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,gFAAgF;IAChF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iEAAiE;IACjE,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,YAAY,GAAG,WAAW,GAAG,cAAc,KAAK,IAAI,CAAC;CAC1E"}
package/dist/types.js ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,16 @@
1
+ #import <React/RCTBridgeModule.h>
2
+
3
+ /**
4
+ * Samples the iOS UI thread's real frame cadence with CADisplayLink.
5
+ *
6
+ * This is the one metric no off-device tool can reach: a simulator exposes no
7
+ * Core Animation frame stats, and reading them from a physical device needs an
8
+ * Instruments GUI trace. The display link runs in the app's own process, so it
9
+ * works identically on a simulator and on real hardware.
10
+ *
11
+ * Frames are counted natively and drained once per reporting interval rather
12
+ * than emitted per frame — a bridge event every frame would itself cause the
13
+ * jank this is supposed to measure.
14
+ */
15
+ @interface RNPerfFrameMonitor : NSObject <RCTBridgeModule>
16
+ @end
@@ -0,0 +1,249 @@
1
+ #import "RNPerfFrameMonitor.h"
2
+
3
+ #import <QuartzCore/QuartzCore.h>
4
+ #import <UIKit/UIKit.h>
5
+ #import <mach/mach.h>
6
+ #import <mach/task_info.h>
7
+
8
+ /**
9
+ * Cap on buffered frame intervals. At 120Hz this is five seconds of frames;
10
+ * if JavaScript is blocked for longer than that it will not be polling us
11
+ * either, and an unbounded buffer would grow while the app is already in
12
+ * trouble.
13
+ */
14
+ static const NSUInteger RNPerfMaxBufferedFrames = 600;
15
+
16
+ /**
17
+ * An interval longer than this many refresh periods counts as a dropped frame.
18
+ * Inter-frame deltas sit a hair either side of the budget at steady state, so
19
+ * comparing against the budget exactly would flag ordinary vsync jitter.
20
+ */
21
+ static const double RNPerfJankFactor = 1.5;
22
+
23
+ @implementation RNPerfFrameMonitor {
24
+ CADisplayLink *_displayLink;
25
+ NSMutableArray<NSNumber *> *_intervalsMs;
26
+ CFTimeInterval _lastTimestamp;
27
+ CFTimeInterval _windowStart;
28
+ NSUInteger _droppedFrames;
29
+ NSUInteger _overflowedFrames;
30
+ double _refreshHz;
31
+ BOOL _running;
32
+ }
33
+
34
+ RCT_EXPORT_MODULE(RNPerfFrameMonitor)
35
+
36
+ /**
37
+ * CADisplayLink must be created and invalidated on the main thread, and the
38
+ * callback fires there too. Running every exported method on the main queue
39
+ * means the buffers below are only ever touched from one thread, with no lock.
40
+ */
41
+ - (dispatch_queue_t)methodQueue {
42
+ return dispatch_get_main_queue();
43
+ }
44
+
45
+ + (BOOL)requiresMainQueueSetup {
46
+ return YES;
47
+ }
48
+
49
+ - (instancetype)init {
50
+ if (self = [super init]) {
51
+ _intervalsMs = [NSMutableArray arrayWithCapacity:RNPerfMaxBufferedFrames];
52
+ _refreshHz = 60.0;
53
+ _lastTimestamp = 0;
54
+ _windowStart = 0;
55
+ }
56
+ return self;
57
+ }
58
+
59
+ - (void)dealloc {
60
+ [self teardown];
61
+ }
62
+
63
+ #pragma mark - Exported
64
+
65
+ RCT_EXPORT_METHOD(start) {
66
+ if (_running) {
67
+ return;
68
+ }
69
+ _running = YES;
70
+
71
+ // ProMotion displays run at up to 120Hz, so the frame budget is 8.3ms there,
72
+ // not 16.7ms. Reading the real figure keeps "janky" honest on every device.
73
+ NSInteger maxFps = UIScreen.mainScreen.maximumFramesPerSecond;
74
+ _refreshHz = maxFps > 0 ? (double)maxFps : 60.0;
75
+
76
+ [self resetWindow];
77
+ _lastTimestamp = 0;
78
+
79
+ _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(onFrame:)];
80
+
81
+ // Common modes keeps the link firing while a scroll view is tracking a drag.
82
+ // The default mode would go quiet during exactly the interaction whose jank
83
+ // we most want to catch.
84
+ [_displayLink addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes];
85
+
86
+ [NSNotificationCenter.defaultCenter addObserver:self
87
+ selector:@selector(onBackground)
88
+ name:UIApplicationDidEnterBackgroundNotification
89
+ object:nil];
90
+ [NSNotificationCenter.defaultCenter addObserver:self
91
+ selector:@selector(onForeground)
92
+ name:UIApplicationWillEnterForegroundNotification
93
+ object:nil];
94
+ }
95
+
96
+ RCT_EXPORT_METHOD(stop) {
97
+ [self teardown];
98
+ }
99
+
100
+ /**
101
+ * Returns the window accumulated since the previous call and starts a new one.
102
+ */
103
+ RCT_EXPORT_METHOD(getMetrics:(RCTPromiseResolveBlock)resolve
104
+ reject:(RCTPromiseRejectBlock)reject) {
105
+ NSMutableDictionary *result = [NSMutableDictionary dictionary];
106
+
107
+ result[@"refreshHz"] = @(_refreshHz);
108
+
109
+ double footprintMB = [self physicalFootprintMB];
110
+ if (footprintMB >= 0) {
111
+ result[@"memoryMB"] = @(footprintMB);
112
+ }
113
+
114
+ if (!_running) {
115
+ resolve(result);
116
+ return;
117
+ }
118
+
119
+ CFTimeInterval now = CACurrentMediaTime();
120
+ double elapsedMs = (now - _windowStart) * 1000.0;
121
+ NSUInteger frames = _intervalsMs.count + _overflowedFrames;
122
+
123
+ // Too short a window makes frames-per-second meaningless.
124
+ if (elapsedMs < 100.0 || frames == 0) {
125
+ resolve(result);
126
+ return;
127
+ }
128
+
129
+ result[@"framesRendered"] = @(frames);
130
+ result[@"uiFps"] = @(MIN(_refreshHz, (double)frames / (elapsedMs / 1000.0)));
131
+
132
+ if (_intervalsMs.count > 0) {
133
+ NSArray<NSNumber *> *sorted = [_intervalsMs sortedArrayUsingSelector:@selector(compare:)];
134
+ result[@"frameP50Ms"] = @([RNPerfFrameMonitor quantile:sorted at:0.50]);
135
+ result[@"frameP95Ms"] = @([RNPerfFrameMonitor quantile:sorted at:0.95]);
136
+ result[@"frameP99Ms"] = @([RNPerfFrameMonitor quantile:sorted at:0.99]);
137
+ }
138
+
139
+ // Expected frames for the window, so the percentage is of what the display
140
+ // could have shown rather than of what it managed to.
141
+ double expected = (elapsedMs / 1000.0) * _refreshHz;
142
+ if (expected >= 1.0) {
143
+ double jank = ((double)_droppedFrames / expected) * 100.0;
144
+ result[@"jankPercent"] = @(MIN(100.0, MAX(0.0, jank)));
145
+ }
146
+
147
+ [self resetWindow];
148
+ resolve(result);
149
+ }
150
+
151
+ RCT_EXPORT_METHOD(isAvailable:(RCTPromiseResolveBlock)resolve
152
+ reject:(RCTPromiseRejectBlock)reject) {
153
+ resolve(@YES);
154
+ }
155
+
156
+ #pragma mark - Display link
157
+
158
+ - (void)onFrame:(CADisplayLink *)link {
159
+ if (_lastTimestamp <= 0) {
160
+ // First callback after start or resume: there is no previous frame to
161
+ // measure against, and the gap would be reported as an enormous stall.
162
+ _lastTimestamp = link.timestamp;
163
+ return;
164
+ }
165
+
166
+ double intervalMs = (link.timestamp - _lastTimestamp) * 1000.0;
167
+ _lastTimestamp = link.timestamp;
168
+
169
+ if (intervalMs <= 0) {
170
+ return;
171
+ }
172
+
173
+ double budgetMs = 1000.0 / _refreshHz;
174
+ if (intervalMs > budgetMs * RNPerfJankFactor) {
175
+ // One interval can swallow several refreshes; count every missed one.
176
+ NSUInteger missed = (NSUInteger)llround(intervalMs / budgetMs) - 1;
177
+ _droppedFrames += MAX((NSUInteger)1, missed);
178
+ }
179
+
180
+ if (_intervalsMs.count < RNPerfMaxBufferedFrames) {
181
+ [_intervalsMs addObject:@(intervalMs)];
182
+ } else {
183
+ // Still count the frame towards FPS even once the buffer is full, so a
184
+ // long JS stall does not make the app look idle.
185
+ _overflowedFrames += 1;
186
+ }
187
+ }
188
+
189
+ - (void)onBackground {
190
+ // A backgrounded app stops receiving frames entirely. Left running, the next
191
+ // window would report zero FPS and a multi-second stall that never happened.
192
+ _displayLink.paused = YES;
193
+ }
194
+
195
+ - (void)onForeground {
196
+ _lastTimestamp = 0;
197
+ [self resetWindow];
198
+ _displayLink.paused = NO;
199
+ }
200
+
201
+ #pragma mark - Helpers
202
+
203
+ - (void)resetWindow {
204
+ [_intervalsMs removeAllObjects];
205
+ _droppedFrames = 0;
206
+ _overflowedFrames = 0;
207
+ _windowStart = CACurrentMediaTime();
208
+ }
209
+
210
+ - (void)teardown {
211
+ _running = NO;
212
+ [_displayLink invalidate];
213
+ _displayLink = nil;
214
+ [NSNotificationCenter.defaultCenter removeObserver:self];
215
+ [_intervalsMs removeAllObjects];
216
+ _lastTimestamp = 0;
217
+ }
218
+
219
+ /**
220
+ * Physical footprint: the figure Xcode shows as "Memory" and the one the
221
+ * jetsam killer judges. Resident size alone understates an app's real cost.
222
+ */
223
+ - (double)physicalFootprintMB {
224
+ task_vm_info_data_t info;
225
+ mach_msg_type_number_t count = TASK_VM_INFO_COUNT;
226
+ kern_return_t result = task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&info, &count);
227
+ if (result != KERN_SUCCESS || count < TASK_VM_INFO_REV1_COUNT) {
228
+ return -1;
229
+ }
230
+ return (double)info.phys_footprint / (1024.0 * 1024.0);
231
+ }
232
+
233
+ + (double)quantile:(NSArray<NSNumber *> *)sortedAscending at:(double)q {
234
+ NSUInteger n = sortedAscending.count;
235
+ if (n == 0) {
236
+ return 0;
237
+ }
238
+ if (n == 1) {
239
+ return sortedAscending[0].doubleValue;
240
+ }
241
+ double position = (double)(n - 1) * q;
242
+ NSUInteger low = (NSUInteger)floor(position);
243
+ NSUInteger high = (NSUInteger)ceil(position);
244
+ double a = sortedAscending[low].doubleValue;
245
+ double b = sortedAscending[high].doubleValue;
246
+ return low == high ? a : a + (b - a) * (position - (double)low);
247
+ }
248
+
249
+ @end
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@rnperf/sdk",
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 performance probe for React Native — JS FPS, stalls, heap, component renders, and UI-thread frames via CADisplayLink on iOS",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/VaheSaroyan/react-native-performance-monitor.git",
9
+ "directory": "packages/rn-sdk"
10
+ },
11
+ "homepage": "https://vahesaroyan.github.io/react-native-performance-monitor/",
12
+ "bugs": {
13
+ "url": "https://github.com/VaheSaroyan/react-native-performance-monitor/issues"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "main": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
20
+ "files": [
21
+ "dist",
22
+ "ios",
23
+ "android",
24
+ "RNPerfSDK.podspec",
25
+ "react-native.config.js",
26
+ "README.md"
27
+ ],
28
+ "scripts": {
29
+ "build": "tsc -b",
30
+ "clean": "rm -rf dist *.tsbuildinfo",
31
+ "prepare": "tsc -b"
32
+ },
33
+ "peerDependencies": {
34
+ "react": ">=18",
35
+ "react-native": ">=0.70"
36
+ },
37
+ "peerDependenciesMeta": {
38
+ "react": {
39
+ "optional": false
40
+ },
41
+ "react-native": {
42
+ "optional": false
43
+ }
44
+ },
45
+ "devDependencies": {
46
+ "@rnperf/protocol": "*"
47
+ },
48
+ "keywords": [
49
+ "react-native",
50
+ "performance",
51
+ "profiling",
52
+ "fps",
53
+ "memory"
54
+ ]
55
+ }
@@ -0,0 +1,25 @@
1
+ const path = require('path');
2
+
3
+ /**
4
+ * Autolinking configuration.
5
+ *
6
+ * Note the two different path conventions, which are not interchangeable:
7
+ * the CLI uses `podspecPath` as given, so it must be absolute, while it
8
+ * resolves `sourceDir` with `path.join(packageRoot, sourceDir)`, so an
9
+ * absolute value there produces a nonexistent directory and Android silently
10
+ * fails to link.
11
+ */
12
+ module.exports = {
13
+ dependency: {
14
+ platforms: {
15
+ ios: {
16
+ podspecPath: path.join(__dirname, 'RNPerfSDK.podspec'),
17
+ },
18
+ android: {
19
+ sourceDir: 'android',
20
+ packageImportPath: 'import com.rnperf.sdk.RNPerfFrameMonitorPackage;',
21
+ packageInstance: 'new RNPerfFrameMonitorPackage()',
22
+ },
23
+ },
24
+ },
25
+ };