rn-startup-audit 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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +18 -2
  3. package/cli.mjs +214 -0
  4. package/package.json +32 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 JF
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,19 @@
1
- # Temporary Holding Version
1
+ # rn-startup-audit
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
+ Find React Native modules that load eagerly at startup, and time Android cold starts.
4
+
5
+ ```
6
+ npx rn-startup-audit scan <srcDir> [--json]
7
+ npx rn-startup-audit check-lazy <projectRoot> <file...> [--import-support]
8
+ npx rn-startup-audit coldstart <applicationId> [runs=10]
9
+ ```
10
+
11
+ - `scan` lists re-exports Metro's inline requires can't make lazy: `export *`, `export * as ns`, `export { default as X }`.
12
+ - `check-lazy` compiles files with the project's Babel config and then Metro's inline-requires plugin, and lists `require()` calls left at module scope.
13
+ - `coldstart` force-stops and launches an installed app over adb, and reports median first native frame and time to React Native's `Running "<app>"` log line.
14
+
15
+ Node 18+, no dependencies. `check-lazy` uses `@babel/core` and `metro-transform-plugins` from your project.
16
+
17
+ It's also a Claude Code skill: see the [repository](https://github.com/JFyeow99/rn-startup-audit).
18
+
19
+ MIT licensed.
package/cli.mjs ADDED
@@ -0,0 +1,214 @@
1
+ #!/usr/bin/env node
2
+ // Finds React Native modules that load eagerly at startup, and times Android cold starts.
3
+ import { readFileSync, readdirSync } from 'node:fs';
4
+ import { join, relative, resolve } from 'node:path';
5
+ import { createRequire } from 'node:module';
6
+ import { execFileSync } from 'node:child_process';
7
+ import assert from 'node:assert/strict';
8
+
9
+ const USAGE = `usage:
10
+ rn-startup-audit scan <srcDir> [--json]
11
+ list re-exports Metro can't make lazy (export *, export * as, export { default })
12
+ rn-startup-audit check-lazy <projectRoot> <file...> [--import-support]
13
+ compile like Metro and list require() calls left at module scope
14
+ rn-startup-audit coldstart <applicationId> [runs=10]
15
+ cold-start an installed Android app over adb; median first frame and JS start
16
+ rn-startup-audit self-test`;
17
+
18
+ // ---------- scan ----------
19
+
20
+ const SKIP = new Set(['node_modules', 'android', 'ios', '.git', 'build', 'dist', 'coverage', 'Pods', 'vendor', '__tests__', '__mocks__']);
21
+ const SOURCE = /\.(m?js|jsx|tsx?)$/;
22
+ const EAGER = new Set(['star', 'namespace', 'default']);
23
+
24
+ // blanked rather than removed so line numbers stay right
25
+ const blankComments = (src) => src.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, (c) => c.replace(/[^\n]/g, ' '));
26
+
27
+ export function classify(src) {
28
+ const code = blankComments(src);
29
+ const re = /export\s+(\*\s*(?:as\s+(\w+)\s*)?|\{([^}]*)\})\s*from\s*['"]([^'"]+)['"]/g;
30
+ return [...code.matchAll(re)].map((m) => {
31
+ const [, head, ns, names = '', from] = m;
32
+ const line = code.slice(0, m.index).split('\n').length;
33
+ const kind = head.startsWith('*') ? (ns ? 'namespace' : 'star') : /\bdefault\b/.test(names) ? 'default' : 'named';
34
+ return { line, from, kind };
35
+ });
36
+ }
37
+
38
+ function* walk(dir) {
39
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
40
+ if (e.isDirectory()) { if (!SKIP.has(e.name) && !e.name.startsWith('.')) yield* walk(join(dir, e.name)); }
41
+ else if (SOURCE.test(e.name) && !/\.(test|spec)\./.test(e.name) && !e.name.endsWith('.d.ts')) yield join(dir, e.name);
42
+ }
43
+ }
44
+
45
+ function scan([dir, ...flags]) {
46
+ if (!dir) usage();
47
+ const result = [];
48
+ for (const file of walk(dir)) {
49
+ const reexports = classify(readFileSync(file, 'utf8'));
50
+ const eager = reexports.filter((r) => EAGER.has(r.kind));
51
+ if (eager.length) result.push({ file: relative(dir, file).replaceAll('\\', '/'), eager, named: reexports.length - eager.length });
52
+ }
53
+ result.sort((a, b) => b.eager.length - a.eager.length);
54
+ if (flags.includes('--json')) return console.log(JSON.stringify(result, null, 2));
55
+ if (!result.length) return console.log('No eager re-exports found.');
56
+ for (const { file, eager, named } of result) {
57
+ console.log(`${file} (${eager.length} eager, ${named} named)`);
58
+ for (const r of eager) console.log(` L${r.line} ${r.kind.padEnd(9)} ${r.from}`);
59
+ }
60
+ console.log(`\n${result.length} files, ${result.reduce((n, f) => n + f.eager.length, 0)} eager re-exports`);
61
+ }
62
+
63
+ // ---------- check-lazy ----------
64
+
65
+ function checkLazy(args) {
66
+ const importSupport = args.includes('--import-support');
67
+ const [root, ...files] = args.filter((a) => !a.startsWith('--')).map((p) => resolve(p));
68
+ if (!root || !files.length) usage();
69
+
70
+ const projectRequire = createRequire(resolve(root, 'package.json'));
71
+ const via = (chain) => chain.reduce((req, m) => createRequire(req.resolve(`${m}/package.json`)), projectRequire);
72
+ const load = (name, chains) => {
73
+ for (const chain of chains) {
74
+ try { return via(chain)(name); } catch {}
75
+ }
76
+ throw new Error(`Cannot resolve ${name} from ${root}. Run this against an installed React Native project.`);
77
+ };
78
+
79
+ const babel = load('@babel/core', [[]]);
80
+ const plugins = load('metro-transform-plugins', [[], ['metro'], ['react-native', '@react-native/community-cli-plugin', 'metro']]);
81
+ // Metro's own names for these helpers when experimentalImportSupport is on
82
+ const importDefault = '_$$_IMPORT_DEFAULT';
83
+ const importAll = '_$$_IMPORT_ALL';
84
+
85
+ for (const file of files) {
86
+ // pass 1: the project's own Babel config, as Metro's babel transformer runs it
87
+ const { code } = babel.transformFileSync(file, {
88
+ cwd: root,
89
+ root,
90
+ filename: file,
91
+ caller: { name: 'metro', bundler: 'metro', platform: 'android' },
92
+ });
93
+ // pass 2: Metro applies inline requires separately, after pass 1
94
+ const { ast } = babel.transformSync(code, {
95
+ configFile: false,
96
+ babelrc: false,
97
+ filename: file,
98
+ ast: true,
99
+ code: false,
100
+ plugins: [
101
+ ...(importSupport ? [[plugins.importExportPlugin, { importDefault, importAll, resolve: false }]] : []),
102
+ [plugins.inlineRequiresPlugin, { inlineableCalls: [importDefault, importAll] }],
103
+ ],
104
+ });
105
+
106
+ const eager = [];
107
+ babel.traverse(ast, {
108
+ CallExpression(p) {
109
+ if (p.get('callee').isIdentifier({ name: 'require' }) && !p.getFunctionParent()) {
110
+ eager.push(p.node.arguments[0]?.value ?? '<dynamic>');
111
+ }
112
+ },
113
+ });
114
+
115
+ const name = relative(root, file).replaceAll('\\', '/');
116
+ console.log(eager.length ? `${name}: ${eager.length} eager require(s)` : `${name}: all requires lazy`);
117
+ for (const m of eager) console.log(` ${m}`);
118
+ }
119
+ }
120
+
121
+ // ---------- coldstart ----------
122
+
123
+ export const median = (xs) => {
124
+ const s = [...xs].sort((a, b) => a - b);
125
+ const m = s.length >> 1;
126
+ return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
127
+ };
128
+
129
+ export const parseTotalTime = (amOutput) => Number(amOutput.match(/TotalTime:\s*(\d+)/)?.[1] ?? NaN);
130
+
131
+ // ms from the launch intent to RN's `Running "<app>"` log line, from `logcat -v epoch`
132
+ export function parseJsStart(logcat, pkg) {
133
+ let start;
134
+ for (const line of logcat.split(/\r?\n/)) {
135
+ const t = Number(line.match(/^\s*(\d+\.\d+)\s/)?.[1]);
136
+ if (!t) continue;
137
+ if (start === undefined && /START u\d+/.test(line) && line.includes(pkg)) start = t;
138
+ else if (start !== undefined && /Running "/.test(line)) return Math.round((t - start) * 1000);
139
+ }
140
+ return NaN;
141
+ }
142
+
143
+ function coldstart([pkg, runsArg = '10']) {
144
+ if (!pkg) usage();
145
+ const adb = (...a) => execFileSync('adb', a, { encoding: 'utf8' });
146
+ const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
147
+ const activity = adb('shell', 'cmd', 'package', 'resolve-activity', '--brief', pkg).trim().split(/\r?\n/).pop();
148
+ if (!activity.includes('/')) {
149
+ console.error(`No launchable activity for ${pkg}. Is it installed?`);
150
+ process.exit(1);
151
+ }
152
+
153
+ const frame = [];
154
+ const js = [];
155
+ for (let i = 1; i <= Number(runsArg); i++) {
156
+ adb('shell', 'am', 'force-stop', pkg);
157
+ sleep(1500);
158
+ adb('logcat', '-c');
159
+ const total = parseTotalTime(adb('shell', 'am', 'start', '-W', '-n', activity));
160
+ let jsStart = NaN;
161
+ for (let tries = 0; tries < 30 && Number.isNaN(jsStart); tries++) {
162
+ sleep(500);
163
+ jsStart = parseJsStart(adb('logcat', '-d', '-v', 'epoch', '-s', 'ActivityTaskManager:I', 'ActivityManager:I', 'ReactNativeJS:I'), pkg);
164
+ }
165
+ frame.push(total);
166
+ if (!Number.isNaN(jsStart)) js.push(jsStart);
167
+ console.log(`run ${i}: first frame ${total} ms, JS running ${Number.isNaN(jsStart) ? 'not seen' : `${jsStart} ms`}`);
168
+ }
169
+
170
+ const summary = (xs) => `median ${median(xs)} ms (min ${Math.min(...xs)}, max ${Math.max(...xs)}, n=${xs.length})`;
171
+ console.log(`\nfirst native frame: ${summary(frame)}`);
172
+ console.log(js.length ? `JS "Running": ${summary(js)}` : 'JS "Running" line never appeared (console stripped in release?)');
173
+ }
174
+
175
+ // ---------- self-test ----------
176
+
177
+ function selfTest() {
178
+ const src = [
179
+ "export { a, b } from './ab';",
180
+ "export { default as C } from './C';",
181
+ "export * from './star';",
182
+ "export * as api from './api';",
183
+ "// export * from './commented';",
184
+ "export type { T } from './types';",
185
+ "export {\n default,\n} from './multi';",
186
+ ].join('\n');
187
+ assert.deepEqual(classify(src).map((r) => [r.kind, r.from, r.line]), [
188
+ ['named', './ab', 1],
189
+ ['default', './C', 2],
190
+ ['star', './star', 3],
191
+ ['namespace', './api', 4],
192
+ ['default', './multi', 7],
193
+ ]);
194
+
195
+ assert.equal(median([3, 1, 2]), 2);
196
+ assert.equal(median([4, 1, 2, 3]), 2.5);
197
+ assert.equal(parseTotalTime('Status: ok\nTotalTime: 952\nWaitTime: 960'), 952);
198
+ const log = [
199
+ ' 1732700000.100 1 1 I ActivityTaskManager: START u0 {flg=0x10000000 cmp=com.acme/.MainActivity}',
200
+ ' 1732700001.804 2 2 I ReactNativeJS: Running "Acme"',
201
+ ].join('\n');
202
+ assert.equal(parseJsStart(log, 'com.acme'), 1704);
203
+ assert.ok(Number.isNaN(parseJsStart(log, 'com.other')));
204
+ console.log('self-test ok');
205
+ }
206
+
207
+ function usage() {
208
+ console.error(USAGE);
209
+ process.exit(1);
210
+ }
211
+
212
+ const [cmd, ...rest] = process.argv.slice(2);
213
+ const commands = { scan, 'check-lazy': checkLazy, coldstart, 'self-test': selfTest };
214
+ (commands[cmd] ?? usage)(rest);
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "rn-startup-audit",
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": "Find React Native modules that load eagerly at startup (barrel re-exports, default imports) and time Android cold starts.",
5
+ "type": "module",
6
+ "bin": {
7
+ "rn-startup-audit": "cli.mjs"
8
+ },
9
+ "files": [
10
+ "cli.mjs"
11
+ ],
12
+ "engines": {
13
+ "node": ">=18"
14
+ },
15
+ "scripts": {
16
+ "test": "node cli.mjs self-test"
17
+ },
18
+ "keywords": [
19
+ "react-native",
20
+ "metro",
21
+ "performance",
22
+ "startup",
23
+ "barrel-files",
24
+ "inline-requires"
25
+ ],
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/JFyeow99/rn-startup-audit.git",
29
+ "directory": "cli"
30
+ },
31
+ "homepage": "https://github.com/JFyeow99/rn-startup-audit#readme",
32
+ "license": "MIT",
33
+ "author": "JFyeow99"
34
+ }