codeplay-common 4.11.37 → 4.11.39

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/README.md CHANGED
@@ -11,6 +11,34 @@ sync/update hooks add its missing AndroidX DocumentFile dependency to plugin met
11
11
  Existing dependency versions are preserved. After upgrading from an affected version,
12
12
  run `npx cap sync android` once to regenerate the native dependencies.
13
13
 
14
+ ## Baseline Profile generation
15
+
16
+ Package installation updates `scripts-common/generate-baseline-profile.js` and
17
+ `scripts-common/collect-startup-profile.js` in consuming apps. Generate each app's
18
+ own profiles with `npm run baseline-profile:generate` after its existing Baseline
19
+ Profile setup and production web-asset preparation.
20
+
21
+ The generator temporarily disables the copied Android live-reload URL, profiles
22
+ bundled web assets, and restores the original configuration afterward. It selects
23
+ one online ADB device (`ANDROID_SERIAL` can select it explicitly), reports elapsed
24
+ time, and uses a 20-minute timeout. Set `BASELINE_PROFILE_TIMEOUT_MINUTES` to change
25
+ that limit. A recovery backup is kept under `agent-temp/baseline-profile/` while the
26
+ configuration is temporarily changed.
27
+
28
+ If the device freezes the instrumentation runner, collection switches to Android's
29
+ host-driven ADB workflow, which requires Android 14 or later. To use it directly:
30
+
31
+ ```sh
32
+ npm run baseline-profile:generate -- --host
33
+ ```
34
+
35
+ Host collection builds and installs the app's `nonMinifiedRelease` profiling APK,
36
+ requires three matching startup captures within 15 iterations, and saves
37
+ `baselineProfiles/baseline-prof.txt` and `baselineProfiles/startup-prof.txt`. Existing
38
+ setup helpers synchronize these into Android's generated profile directory.
39
+ Temporary captures stay under `agent-temp/`. Installation does not generate profiles
40
+ or copy one app's profile into another app; run generation separately in each app.
41
+
14
42
  ## VK / RuStore builds (4.11.23)
15
43
 
16
44
  Before-build 7.8 preserves the original Vite build settings when adding tree-shaking
@@ -176,7 +204,7 @@ App package scripts run local files: node buildCodeplay/codeplayBeforeBuild.js,
176
204
 
177
205
  Installation migrates both legacy versioned filenames and the temporary node_modules runner commands to these local paths. It removes only superseded versioned build scripts, preserves app-owned release configuration and splash XML overrides, and keeps screenshot data and custom helpers. The root finalrelease script is also copied as a local implementation.
178
206
 
179
- After this update is installed, `npm run build` checks the app's `buildCodeplay/` folder for version-suffixed files before preparing the build. If any exist, it runs `npm uninstall codeplay-common` followed by `npm install codeplay-common`, then runs the refreshed before-build script before continuing. A failed command or remaining versioned files stops the build. Unrecognized legacy files must be migrated manually; they are not deleted automatically.
207
+ After this update is installed, `npm run build` checks for a missing or incomplete `codeplay-common` package and version-suffixed files in the app's `buildCodeplay/` folder before loading build dependencies. Recovery uses `npm install` for an existing dependency declaration, preserving its version range or local source; if the declaration is also missing, it uses `npm install codeplay-common`. Updates no longer uninstall the package first, so cancellation does not deliberately remove the dependency declaration. If npm skips lifecycle scripts and legacy files remain, the existing package installer refreshes the templates. The refreshed before-build script then runs in a new process. A failed command, incomplete package or remaining versioned files stops the build. Unrecognized legacy files must be migrated manually; they are not deleted automatically.
180
208
 
181
209
  Before-build includes the automatic IAP startup and Home Pro-button migrations. IAP and AdMob ZIPs are downloaded directly from https://htmlcodeplay.com/code-play-plugin/ using the existing update flow. No plugin ZIPs are bundled in this npm package. App-specific configuration and designs remain in the app.
182
210
 
@@ -1,3 +1,4 @@
1
+ // Version 8.6: recover interrupted codeplay-common installations without uninstalling first.
1
2
  // Version 8.5: require the Squeezeback native plugin only for explicitly enabled apps.
2
3
  // Version 8.4: migrate Squeezeback and coarse-location configuration defaults.
3
4
  // Version 8.3: update the system-bars package to the latest npm release before migration.
@@ -19,7 +20,7 @@
19
20
  // Version 6.7: deferred IAP startup, ownership-safe ads, and unified store preparation.
20
21
  // Version 6.7: migrate AdMob files to ZIP-distributed folder packages.
21
22
  // Version 6.7: recreate failed WebViews, defer background recovery, and suppress foreground recovery toasts.
22
- // Reinstall legacy build templates before loading dependencies or changing the app.
23
+ // Restore missing dependencies and legacy templates before loading app build modules.
23
24
  try {
24
25
  if (require('./ensure-current-build.cjs').ensureCurrentBuild()) process.exit(0);
25
26
  } catch (error) {
@@ -566,7 +567,6 @@ function checkPackageVersion() {
566
567
  console.log(`${packageName} is outdated (installed: ${installedVersion}, latest: ${latestVersion}). Updating now...`);
567
568
 
568
569
  try {
569
- execSync(`npm uninstall ${packageName}`, { stdio: 'inherit' });
570
570
  execSync(`npm install ${packageName}`, { stdio: 'inherit' });
571
571
  console.log(`${packageName} successfully updated.`);
572
572
  } catch (err) {
@@ -1,42 +1,70 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const { execSync, execFileSync } = require('child_process');
4
-
5
- function findVersionedBuildFiles(projectRoot) {
6
- const directory = path.join(projectRoot, 'buildCodeplay');
7
- if (!fs.existsSync(directory)) return [];
8
- return fs.readdirSync(directory, { withFileTypes: true })
9
- .filter(entry => entry.isFile() && /-\d+(?:\.\d+)*(?:-beta-\d+)?\.[^.]+$/i.test(entry.name))
10
- .map(entry => entry.name);
11
- }
12
-
13
- function ensureCurrentBuild(options = {}) {
14
- const projectRoot = path.resolve(options.projectRoot || process.cwd());
15
- const legacyFiles = findVersionedBuildFiles(projectRoot);
16
- if (!legacyFiles.length) return false;
17
-
18
- console.log(`Legacy buildCodeplay files found: ${legacyFiles.join(', ')}. Reinstalling codeplay-common before continuing.`);
19
- const runNpm = options.runNpm || (command => execSync(command, { cwd: projectRoot, stdio: 'inherit' }));
20
- runNpm('npm uninstall codeplay-common');
21
- runNpm('npm install codeplay-common');
22
-
23
- // Postinstall replaces the scripts and removes recognized legacy files.
24
- // Do not run stale code or retry indefinitely if migration did not finish.
25
- const remaining = findVersionedBuildFiles(projectRoot);
26
- if (remaining.length) {
27
- throw new Error(`Legacy buildCodeplay files remain after reinstall: ${remaining.join(', ')}. Build stopped; migrate these files before retrying.`);
28
- }
29
- const entrypoint = path.join(projectRoot, 'buildCodeplay', 'codeplayBeforeBuild.js');
30
- if (!fs.existsSync(entrypoint)) throw new Error('codeplayBeforeBuild.js is missing after reinstall. Build stopped.');
31
-
32
- // The current process loaded the old templates. Finish preparation in a fresh
33
- // process before the caller's remaining build commands are allowed to run.
34
- const runBeforeBuild = options.runBeforeBuild || (script => execFileSync(process.execPath, [script, ...process.argv.slice(2)], {
35
- cwd: projectRoot,
36
- stdio: 'inherit',
37
- }));
38
- runBeforeBuild(entrypoint);
39
- return true;
40
- }
41
-
42
- module.exports = { ensureCurrentBuild, findVersionedBuildFiles };
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { execSync, execFileSync } = require('child_process');
4
+
5
+ function findVersionedBuildFiles(projectRoot) {
6
+ const directory = path.join(projectRoot, 'buildCodeplay');
7
+ if (!fs.existsSync(directory)) return [];
8
+ return fs.readdirSync(directory, { withFileTypes: true })
9
+ .filter(entry => entry.isFile() && /-\d+(?:\.\d+)*(?:-beta-\d+)?\.[^.]+$/i.test(entry.name))
10
+ .map(entry => entry.name);
11
+ }
12
+
13
+ function ensureCurrentBuild(options = {}) {
14
+ const projectRoot = path.resolve(options.projectRoot || process.cwd());
15
+ const legacyFiles = findVersionedBuildFiles(projectRoot);
16
+ const packageRoot = path.join(projectRoot, 'node_modules', 'codeplay-common');
17
+ const installer = path.join(packageRoot, 'scripts', 'sync-files.js');
18
+ function isPackageInstalled() {
19
+ try {
20
+ const pkg = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'));
21
+ return pkg?.name === 'codeplay-common' && typeof pkg.version === 'string' && pkg.version.length > 0 && fs.existsSync(installer);
22
+ } catch (error) {
23
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR' || error instanceof SyntaxError) return false;
24
+ throw error;
25
+ }
26
+ }
27
+ if (isPackageInstalled() && !legacyFiles.length) return false;
28
+
29
+ console.log(legacyFiles.length
30
+ ? `Legacy buildCodeplay files found: ${legacyFiles.join(', ')}. Restoring codeplay-common before continuing.`
31
+ : 'codeplay-common is missing or incomplete. Restoring it before loading build dependencies.');
32
+ const appPackage = JSON.parse(fs.readFileSync(path.join(projectRoot, 'package.json'), 'utf8'));
33
+ const declaredPackage = appPackage.dependencies?.['codeplay-common'] || appPackage.devDependencies?.['codeplay-common'] || appPackage.optionalDependencies?.['codeplay-common'];
34
+ const runNpm = options.runNpm || (command => execSync(command, { cwd: projectRoot, stdio: 'inherit' }));
35
+ // Preserve existing dependency specifications, including local packages. Never
36
+ // uninstall first: cancellation must not remove the manifest declaration.
37
+ runNpm(declaredPackage ? 'npm install' : 'npm install codeplay-common');
38
+ if (!isPackageInstalled()) throw new Error('codeplay-common is still missing or incomplete after npm install. Build stopped.');
39
+
40
+ // npm can skip postinstall when the installed package already satisfies the
41
+ // manifest. Run the existing installer if legacy templates still need migration.
42
+ if (findVersionedBuildFiles(projectRoot).length) {
43
+ const runInstaller = options.runInstaller || (script => execFileSync(process.execPath, [script], {
44
+ cwd: projectRoot,
45
+ env: { ...process.env, INIT_CWD: projectRoot },
46
+ stdio: 'inherit',
47
+ }));
48
+ runInstaller(installer);
49
+ }
50
+
51
+ // Postinstall replaces the scripts and removes recognized legacy files.
52
+ // Do not run stale code or retry indefinitely if migration did not finish.
53
+ const remaining = findVersionedBuildFiles(projectRoot);
54
+ if (remaining.length) {
55
+ throw new Error(`Legacy buildCodeplay files remain after reinstall: ${remaining.join(', ')}. Build stopped; migrate these files before retrying.`);
56
+ }
57
+ const entrypoint = path.join(projectRoot, 'buildCodeplay', 'codeplayBeforeBuild.js');
58
+ if (!fs.existsSync(entrypoint)) throw new Error('codeplayBeforeBuild.js is missing after reinstall. Build stopped.');
59
+
60
+ // The current process loaded the old templates. Finish preparation in a fresh
61
+ // process before the caller's remaining build commands are allowed to run.
62
+ const runBeforeBuild = options.runBeforeBuild || (script => execFileSync(process.execPath, [script, ...process.argv.slice(2)], {
63
+ cwd: projectRoot,
64
+ stdio: 'inherit',
65
+ }));
66
+ runBeforeBuild(entrypoint);
67
+ return true;
68
+ }
69
+
70
+ module.exports = { ensureCurrentBuild, findVersionedBuildFiles };
@@ -0,0 +1,134 @@
1
+ const { execFile } = require('child_process');
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const { promisify } = require('util');
5
+ const { setTimeout: delay } = require('timers/promises');
6
+ const AdmZip = require('adm-zip');
7
+
8
+ const execFileAsync = promisify(execFile);
9
+
10
+ function normalizeProfile(rawProfile) {
11
+ // Match Macrobenchmark's portable HRF filtering: exclude arrays and inline caches.
12
+ return [...new Set(rawProfile.split(/\r?\n/).map(line => line.trim()).filter(line =>
13
+ !line.includes('+') && /^[HSP]*L[^;]+;(?:->.+)?$/.test(line)
14
+ ))].sort().join('\n');
15
+ }
16
+
17
+ async function collectStartupProfile({ serial, appId, apkPath, rootDir, timeoutMinutes, deadline }) {
18
+ if (!/^[a-zA-Z_][\w]*(\.[a-zA-Z_][\w]*)+$/.test(appId)) {
19
+ throw new Error('Invalid application ID for host-driven profile collection.');
20
+ }
21
+ const apk = new AdmZip(apkPath);
22
+ const config = JSON.parse(apk.readAsText('assets/capacitor.config.json'));
23
+ if (config.appId !== appId || config.server?.url || !apk.getEntry('assets/public/index.html')) {
24
+ throw new Error('The profiling APK must contain the correct app and bundled web assets with no server.url.');
25
+ }
26
+
27
+ const controller = new AbortController();
28
+ const cancel = () => controller.abort(new Error('Host-driven profile collection cancelled.'));
29
+ const timeout = setTimeout(() => {
30
+ controller.abort(new Error(`Host-driven profile collection exceeded ${timeoutMinutes} minutes.`));
31
+ }, Math.max(0, (deadline ?? Date.now() + timeoutMinutes * 60000) - Date.now()));
32
+ process.on('SIGINT', cancel);
33
+ process.on('SIGTERM', cancel);
34
+ const adb = async (args, commandTimeout = 30000) => {
35
+ const result = await execFileAsync('adb', ['-s', serial, ...args], {
36
+ encoding: 'utf8',
37
+ maxBuffer: 32 * 1024 * 1024,
38
+ timeout: commandTimeout,
39
+ signal: controller.signal,
40
+ });
41
+ return result.stdout.trim();
42
+ };
43
+ const receiver = `${appId}/androidx.profileinstaller.ProfileInstallReceiver`;
44
+ const broadcast = async (action, resultCode, extras = []) => {
45
+ const result = await adb(['shell', 'am', 'broadcast', '-a', `androidx.profileinstaller.action.${action}`, ...extras, receiver]);
46
+ if (!new RegExp(`result=${resultCode}\\b`).test(result)) {
47
+ throw new Error(`ProfileInstaller ${action} did not return ${resultCode}: ${result}`);
48
+ }
49
+ };
50
+ let skipFileWritten = false;
51
+ try {
52
+ const sdk = Number(await adb(['shell', 'getprop', 'ro.build.version.sdk']));
53
+ if (sdk < 34) throw new Error('Host-driven profile collection requires Android 14 or later.');
54
+ console.log('Using Android\'s ADB profile collection workflow without the instrumentation runner.');
55
+ const installResult = await adb(['install', '-r', apkPath], 120000);
56
+ if (!/\bSuccess\b/.test(installResult)) throw new Error(`Profiling APK installation failed: ${installResult}`);
57
+ const resolution = await adb(['shell', 'cmd', 'package', 'resolve-activity', '--brief',
58
+ '-a', 'android.intent.action.MAIN', '-c', 'android.intent.category.LAUNCHER', appId]);
59
+ const component = resolution.split(/\r?\n/).find(line => line.startsWith(`${appId}/`));
60
+ if (!component || !/^[\w.$]+\/[\w.$]+$/.test(component)) {
61
+ throw new Error(`Could not resolve the app's launch activity: ${resolution}`);
62
+ }
63
+ const activity = component.split('/')[1];
64
+ const activityDescriptor = `L${(activity.startsWith('.') ? appId + activity : activity).replace(/\./g, '/')};`;
65
+ await broadcast('SKIP_FILE', 10, ['-e', 'EXTRA_SKIP_FILE_OPERATION', 'WRITE_SKIP_FILE']);
66
+ skipFileWritten = true;
67
+ await adb(['shell', 'am', 'force-stop', appId]);
68
+ const reset = await adb(['shell', 'cmd', 'package', 'compile', '-f', '-m', 'verify', appId], 120000);
69
+ if (!/\bSuccess\b/.test(reset)) throw new Error(`Could not reset app compilation: ${reset}`);
70
+ const clear = await adb(['shell', 'pm', 'art', 'clear-app-profiles', appId]);
71
+ if (!/Profiles cleared/.test(clear)) throw new Error(`Could not clear previous runtime profiles: ${clear}`);
72
+
73
+ const tempDir = path.join(rootDir, 'agent-temp', 'baseline-profile', 'host-collection');
74
+ fs.mkdirSync(tempDir, { recursive: true });
75
+ let lastProfile = '';
76
+ let stableCount = 0;
77
+ for (let iteration = 1; iteration <= 15; iteration += 1) {
78
+ console.log(`Startup profile iteration ${iteration}/15: launching bundled app.`);
79
+ const launch = await adb(['shell', 'am', 'start', '-W', '-n', component]);
80
+ if (!/Status: ok/.test(launch) || /Error:/.test(launch)) throw new Error(`App launch failed: ${launch}`);
81
+ // Android's documented workflow requires at least five seconds before saving.
82
+ await delay(6000, undefined, { signal: controller.signal });
83
+ if (iteration === 1) {
84
+ const screenshot = await execFileAsync('adb', ['-s', serial, 'exec-out', 'screencap', '-p'], {
85
+ encoding: 'buffer', maxBuffer: 32 * 1024 * 1024, timeout: 10000, signal: controller.signal,
86
+ });
87
+ fs.writeFileSync(path.join(tempDir, 'startup.png'), screenshot.stdout);
88
+ }
89
+ await broadcast('SAVE_PROFILE', 12);
90
+ await delay(1100, undefined, { signal: controller.signal });
91
+ await adb(['shell', 'am', 'force-stop', appId]);
92
+ const compile = await adb(['shell', 'cmd', 'package', 'compile', '-f', '-m', 'speed-profile', appId], 120000);
93
+ if (!/\bSuccess\b/.test(compile)) throw new Error(`Profile compilation failed: ${compile}`);
94
+ await adb(['shell', 'pm', 'dump-profiles', '--dump-classes-and-methods', appId]);
95
+ const rawProfile = await adb(['exec-out', 'cat', `/data/misc/profman/${appId}-primary.prof.txt`]);
96
+ fs.writeFileSync(path.join(tempDir, `iteration-${iteration}.txt`), rawProfile);
97
+ const profile = normalizeProfile(rawProfile);
98
+ if (!profile.includes(activityDescriptor) || !profile.includes('Lcom/getcapacitor/Bridge;')) {
99
+ throw new Error('The collected profile is missing the app launch activity or Capacitor bridge.');
100
+ }
101
+ stableCount = profile === lastProfile ? stableCount + 1 : 1;
102
+ lastProfile = profile;
103
+ console.log(`Startup profile iteration ${iteration}: ${profile.split('\n').length} rules; ${stableCount}/3 matching captures.`);
104
+ if (stableCount === 3) break;
105
+ }
106
+ if (stableCount < 3) throw new Error('Startup profile did not stabilize within 15 iterations. Existing profile files were preserved.');
107
+ controller.signal.throwIfAborted();
108
+ const outputDir = path.join(rootDir, 'baselineProfiles');
109
+ fs.mkdirSync(outputDir, { recursive: true });
110
+ // This journey only exercises startup, so both profile inputs cover that same journey.
111
+ for (const fileName of ['baseline-prof.txt', 'startup-prof.txt']) {
112
+ fs.writeFileSync(path.join(outputDir, fileName), `${lastProfile}\n`);
113
+ }
114
+ console.log(`Generated stable startup and baseline profiles in ${outputDir}`);
115
+ } catch (error) {
116
+ throw controller.signal.aborted ? controller.signal.reason : error;
117
+ } finally {
118
+ clearTimeout(timeout);
119
+ process.removeListener('SIGINT', cancel);
120
+ process.removeListener('SIGTERM', cancel);
121
+ if (skipFileWritten) {
122
+ try {
123
+ // Cleanup must still run when the collection signal was cancelled.
124
+ await execFileAsync('adb', ['-s', serial, 'shell', 'am', 'broadcast', '-a',
125
+ 'androidx.profileinstaller.action.SKIP_FILE', '-e', 'EXTRA_SKIP_FILE_OPERATION',
126
+ 'DELETE_SKIP_FILE', receiver], { timeout: 10000 });
127
+ } catch (error) {
128
+ console.error(`Could not restore automatic profile installation: ${error.message}`);
129
+ }
130
+ }
131
+ }
132
+ }
133
+
134
+ module.exports = { collectStartupProfile, normalizeProfile };
@@ -1,46 +1,218 @@
1
- const { execFileSync, spawnSync } = require('child_process');
2
- const path = require('path');
3
- const { syncGeneratedProfileBackup } = require('./setup-baseline-profile.js');
4
-
5
- function main() {
6
- const devices = execFileSync('adb', ['devices'], { encoding: 'utf8' })
7
- .split(/\r?\n/)
8
- .map(line => line.match(/^(.+?)\tdevice\s*$/))
9
- .filter(Boolean)
10
- .map(match => match[1]);
11
- const requestedSerial = process.env.ANDROID_SERIAL?.trim();
12
- if (requestedSerial?.includes(',')) {
13
- throw new Error('Set ANDROID_SERIAL to one device connection for Baseline Profile generation.');
14
- }
15
- const serial = requestedSerial || devices[0];
16
- if (!serial || !devices.includes(serial)) {
17
- throw new Error(requestedSerial
18
- ? `ADB device is not online: ${requestedSerial}`
19
- : 'No online ADB device. Connect an Android device before generating a Baseline Profile.');
20
- }
21
-
22
- console.log(`Generating Baseline Profile using one ADB connection: ${serial}`);
23
- const args = [':app:generateBaselineProfile', '--console=plain'];
24
- const result = spawnSync(
25
- process.platform === 'win32' ? 'cmd.exe' : './gradlew',
26
- process.platform === 'win32' ? ['/d', '/s', '/c', `gradlew.bat ${args.join(' ')}`] : args,
27
- {
28
- cwd: path.resolve(__dirname, '..', 'android'),
29
- env: { ...process.env, ANDROID_SERIAL: serial },
30
- stdio: 'inherit',
31
- }
32
- );
33
- if (result.error) throw result.error;
34
- if (result.signal) throw new Error(`Baseline Profile generation stopped by ${result.signal}.`);
35
- process.exitCode = result.status ?? 1;
36
- if (process.exitCode === 0) {
37
- syncGeneratedProfileBackup({ backupOnly: true });
38
- }
39
- }
40
-
41
- try {
42
- main();
43
- } catch (error) {
44
- console.error(`Baseline Profile generation failed: ${error.message}`);
45
- process.exitCode = 1;
46
- }
1
+ const { execFile, execFileSync, spawn } = require('child_process');
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const { promisify } = require('util');
5
+ const { syncGeneratedProfileBackup } = require('./setup-baseline-profile.js');
6
+ const { collectStartupProfile } = require('./collect-startup-profile.js');
7
+
8
+ const rootDir = path.resolve(__dirname, '..');
9
+ const androidDir = path.join(rootDir, 'android');
10
+ const execFileAsync = promisify(execFile);
11
+
12
+ async function getFrozenTestProcess(serial, testPackage) {
13
+ const readDevice = async (args) => {
14
+ const result = await execFileAsync('adb', ['-s', serial, 'shell', ...args], {
15
+ encoding: 'utf8',
16
+ timeout: 5000,
17
+ });
18
+ return result.stdout.trim();
19
+ };
20
+ try {
21
+ const pid = await readDevice(['pidof', testPackage]);
22
+ if (!/^\d+$/.test(pid)) return null;
23
+ const groups = await readDevice(['cat', `/proc/${pid}/cgroup`]);
24
+ const group = groups.match(/^0::(\/uid_\d+\/pid_\d+)$/m)?.[1];
25
+ if (!group) return null;
26
+ const frozen = await readDevice(['cat', `/sys/fs/cgroup${group}/cgroup.freeze`]);
27
+ return frozen === '1' ? pid : null;
28
+ } catch {
29
+ // The runner may not be installed/running yet, or the device may restrict cgroup reads.
30
+ return null;
31
+ }
32
+ }
33
+
34
+ function runGradle(args, serial, timeoutMinutes, testPackage) {
35
+ return new Promise((resolve, reject) => {
36
+ const child = spawn(
37
+ process.platform === 'win32' ? 'cmd.exe' : './gradlew',
38
+ process.platform === 'win32' ? ['/d', '/s', '/c', `gradlew.bat ${args.join(' ')}`] : args,
39
+ {
40
+ cwd: androidDir,
41
+ env: { ...process.env, ANDROID_SERIAL: serial },
42
+ stdio: 'inherit',
43
+ detached: process.platform !== 'win32',
44
+ }
45
+ );
46
+ let stopReason;
47
+ let finished = false;
48
+ let checkingFreeze = false;
49
+ let frozenPid = null;
50
+ const stop = (reason, code) => {
51
+ if (stopReason) return;
52
+ stopReason = new Error(reason);
53
+ stopReason.code = code;
54
+ try {
55
+ if (process.platform === 'win32') {
56
+ execFileSync('taskkill', ['/pid', String(child.pid), '/t', '/f'], {
57
+ stdio: 'ignore',
58
+ timeout: 10000,
59
+ });
60
+ } else {
61
+ process.kill(-child.pid, 'SIGKILL');
62
+ }
63
+ } catch (error) {
64
+ // The child may already have exited before cancellation reached it.
65
+ if (child.exitCode === null && error.code !== 'ESRCH') {
66
+ console.error(`Unable to stop Gradle: ${error.message}`);
67
+ }
68
+ }
69
+ try {
70
+ execFileSync('adb', ['-s', serial, 'shell', 'am', 'force-stop', testPackage], {
71
+ stdio: 'ignore',
72
+ timeout: 10000,
73
+ });
74
+ } catch (error) {
75
+ console.error(`Unable to stop device instrumentation: ${error.message}`);
76
+ }
77
+ };
78
+ const onInterrupt = () => stop('Baseline Profile generation cancelled.');
79
+ const startedAt = Date.now();
80
+ const freezeMonitor = setInterval(async () => {
81
+ if (finished || stopReason || checkingFreeze) return;
82
+ checkingFreeze = true;
83
+ try {
84
+ const pid = await getFrozenTestProcess(serial, testPackage);
85
+ if (finished || stopReason) return;
86
+ if (pid && pid === frozenPid) {
87
+ stop(`Android has frozen the Baseline Profile test runner (${testPackage}, PID ${pid}).`, 'BASELINE_TEST_FROZEN');
88
+ } else if (pid) {
89
+ console.log(`Test runner PID ${pid} is frozen by the device; checking again before stopping.`);
90
+ }
91
+ frozenPid = pid;
92
+ } finally {
93
+ checkingFreeze = false;
94
+ }
95
+ }, 10000);
96
+ const progress = setInterval(() => {
97
+ const minutes = Math.floor((Date.now() - startedAt) / 60000);
98
+ console.log(`Baseline Profile run: ${minutes} minute(s) elapsed. The single test stays at 0/1 until collection finishes.`);
99
+ }, 60000);
100
+ const timeout = setTimeout(() => {
101
+ stop(`Baseline Profile generation exceeded ${timeoutMinutes} minutes. Check the test log under android/baselineprofile/build/outputs/androidTest-results/connected/ for the last Benchmark step. Set BASELINE_PROFILE_TIMEOUT_MINUTES to allow a longer run.`);
102
+ }, timeoutMinutes * 60000);
103
+ process.on('SIGINT', onInterrupt);
104
+ process.on('SIGTERM', onInterrupt);
105
+ const cleanup = () => {
106
+ finished = true;
107
+ clearInterval(freezeMonitor);
108
+ clearInterval(progress);
109
+ clearTimeout(timeout);
110
+ process.removeListener('SIGINT', onInterrupt);
111
+ process.removeListener('SIGTERM', onInterrupt);
112
+ };
113
+ child.once('error', (error) => {
114
+ cleanup();
115
+ reject(error);
116
+ });
117
+ child.once('close', (status, signal) => {
118
+ cleanup();
119
+ if (stopReason) reject(stopReason);
120
+ else if (signal) reject(new Error(`Baseline Profile generation stopped by ${signal}.`));
121
+ else resolve(status ?? 1);
122
+ });
123
+ });
124
+ }
125
+
126
+ async function main() {
127
+ const timeoutMinutes = Number(process.env.BASELINE_PROFILE_TIMEOUT_MINUTES || 20);
128
+ if (!Number.isInteger(timeoutMinutes) || timeoutMinutes < 1 || timeoutMinutes > 1440) {
129
+ throw new Error('BASELINE_PROFILE_TIMEOUT_MINUTES must be a whole number between 1 and 1440.');
130
+ }
131
+ const devices = execFileSync('adb', ['devices'], { encoding: 'utf8', timeout: 10000 })
132
+ .split(/\r?\n/)
133
+ .map(line => line.match(/^(.+?)\tdevice\s*$/))
134
+ .filter(Boolean)
135
+ .map(match => match[1]);
136
+ const requestedSerial = process.env.ANDROID_SERIAL?.trim();
137
+ if (requestedSerial?.includes(',')) {
138
+ throw new Error('Set ANDROID_SERIAL to one device connection for Baseline Profile generation.');
139
+ }
140
+ const serial = requestedSerial || devices[0];
141
+ if (!serial || !devices.includes(serial)) {
142
+ throw new Error(requestedSerial
143
+ ? `ADB device is not online: ${requestedSerial}`
144
+ : 'No online ADB device. Connect an Android device before generating a Baseline Profile.');
145
+ }
146
+
147
+ const configPath = path.join(androidDir, 'app', 'src', 'main', 'assets', 'capacitor.config.json');
148
+ const backupPath = path.join(rootDir, 'agent-temp', 'baseline-profile', 'capacitor.config.original.json');
149
+ if (fs.existsSync(backupPath)) {
150
+ throw new Error(`A previous run left a config backup at ${backupPath}. Confirm that run has stopped, restore it to ${configPath}, then remove the backup before retrying.`);
151
+ }
152
+ const originalConfig = fs.readFileSync(configPath);
153
+ const config = JSON.parse(originalConfig.toString('utf8'));
154
+ const sourceConfig = JSON.parse(fs.readFileSync(path.join(rootDir, 'capacitor.config.json'), 'utf8'));
155
+ if (config.appId !== sourceConfig.appId) {
156
+ throw new Error('Android assets belong to a different appId. Copy the correct production web assets before generating a Baseline Profile.');
157
+ }
158
+ const indexPath = path.join(path.dirname(configPath), 'public', 'index.html');
159
+ if (!fs.existsSync(indexPath) || /\/@vite\/client|vite\/dist\/client/.test(fs.readFileSync(indexPath, 'utf8'))) {
160
+ throw new Error('Bundled production web assets are missing or contain the Vite development client. Build and copy production web assets before generating a Baseline Profile.');
161
+ }
162
+
163
+ let offlineConfig;
164
+ try {
165
+ if (config.server?.url) {
166
+ delete config.server.url;
167
+ offlineConfig = Buffer.from(`${JSON.stringify(config, null, 2)}\n`);
168
+ fs.mkdirSync(path.dirname(backupPath), { recursive: true });
169
+ fs.writeFileSync(backupPath, originalConfig, { flag: 'wx' });
170
+ fs.writeFileSync(configPath, offlineConfig);
171
+ console.log('Temporarily disabled the Android live-reload URL. Profiling bundled web assets.');
172
+ }
173
+
174
+ const hostMode = process.argv.includes('--host');
175
+ const deadline = Date.now() + timeoutMinutes * 60000;
176
+ console.log(`Generating Baseline Profile using one ADB connection: ${serial}`);
177
+ console.log(hostMode
178
+ ? `Host-driven collection runs up to 15 startup iterations. Overall timeout: ${timeoutMinutes} minutes.`
179
+ : `Collection runs up to 15 iterations inside one test; 0/1 is the test count. Overall timeout: ${timeoutMinutes} minutes.`);
180
+ // Exit the Gradle JVM after each run so UTP log handles cannot persist in a reused daemon.
181
+ const args = [hostMode ? ':app:assembleNonMinifiedRelease' : ':app:generateBaselineProfile', '--console=plain', '--no-daemon'];
182
+ let needsHostCollection = hostMode;
183
+ try {
184
+ process.exitCode = await runGradle(args, serial, timeoutMinutes, `${config.appId}.baselineprofile`);
185
+ if (process.exitCode !== 0) {
186
+ throw new Error(`Gradle exited with code ${process.exitCode}. Check the test output above for the failing step.`);
187
+ }
188
+ } catch (error) {
189
+ if (error.code !== 'BASELINE_TEST_FROZEN') throw error;
190
+ console.log(`${error.message} Switching to host-driven collection.`);
191
+ needsHostCollection = true;
192
+ }
193
+ if (needsHostCollection) {
194
+ await collectStartupProfile({
195
+ serial, appId: config.appId, rootDir, timeoutMinutes, deadline,
196
+ apkPath: path.join(androidDir, 'app', 'build', 'outputs', 'apk', 'nonMinifiedRelease', 'app-nonMinifiedRelease.apk'),
197
+ });
198
+ syncGeneratedProfileBackup();
199
+ process.exitCode = 0;
200
+ } else {
201
+ syncGeneratedProfileBackup({ backupOnly: true });
202
+ }
203
+ } finally {
204
+ if (offlineConfig && fs.existsSync(backupPath)) {
205
+ if (!fs.readFileSync(configPath).equals(offlineConfig)) {
206
+ throw new Error(`Android config changed during profiling. Original config preserved at ${backupPath}; restore it after reviewing the changes.`);
207
+ }
208
+ fs.writeFileSync(configPath, originalConfig);
209
+ fs.unlinkSync(backupPath);
210
+ console.log('Restored the original Android live-reload configuration.');
211
+ }
212
+ }
213
+ }
214
+
215
+ main().catch((error) => {
216
+ console.error(`Baseline Profile generation failed: ${error.message}`);
217
+ process.exitCode = 1;
218
+ });