codeplay-common 4.11.35 → 4.11.38

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 (63) hide show
  1. package/CHANGELOG.md +115 -115
  2. package/LICENSE +21 -21
  3. package/README.md +408 -374
  4. package/RELEASE_NOTES.md +97 -97
  5. package/files/buildCodeplay/HUAWEI-PRIVACY.md +9 -9
  6. package/files/buildCodeplay/add-splash-screen.js +255 -255
  7. package/files/buildCodeplay/apk-store-builder.js +97 -97
  8. package/files/buildCodeplay/codeplayBeforeBuild.js +4793 -4793
  9. package/files/buildCodeplay/disabled-ads.mjs +53 -53
  10. package/files/buildCodeplay/ensure-current-build.cjs +42 -42
  11. package/files/buildCodeplay/fix-onesignal-plugin.js +96 -96
  12. package/files/buildCodeplay/huawei-privacy-entry.js +135 -135
  13. package/files/buildCodeplay/huawei-privacy.cjs +102 -92
  14. package/files/buildCodeplay/huawei-privacy.css +22 -22
  15. package/files/buildCodeplay/iap-alias.cjs +116 -116
  16. package/files/buildCodeplay/ios-ad-consent.cjs +56 -56
  17. package/files/buildCodeplay/ios-emi-admob-modification.js +49 -49
  18. package/files/buildCodeplay/manifestModification.js +38 -38
  19. package/files/buildCodeplay/migrate-system-bars.cjs +122 -122
  20. package/files/buildCodeplay/newly added.txt +89 -89
  21. package/files/buildCodeplay/non-google-billing.pro +3 -3
  22. package/files/buildCodeplay/packageidBaseModification.js +528 -528
  23. package/files/buildCodeplay/project-scripts.cjs +69 -69
  24. package/files/buildCodeplay/release-sync.config.json +4 -4
  25. package/files/buildCodeplay/remove-force-kotlin-disable.js +43 -43
  26. package/files/buildCodeplay/ruads.cjs +220 -211
  27. package/files/buildCodeplay/saf-mediastore-dependency.cjs +21 -21
  28. package/files/buildCodeplay/setSplashAnimation.js +226 -226
  29. package/files/buildCodeplay/setup-ruads.cjs +62 -55
  30. package/files/buildCodeplay/splashxml/codeplay_splashScreen.xml +11 -11
  31. package/files/buildCodeplay/store-billing.cjs +43 -43
  32. package/files/buildCodeplay/sync-admob-nextgen.js +219 -219
  33. package/files/buildCodeplay/tests/huawei-live-reload.test.cjs +60 -0
  34. package/files/buildCodeplay/tests/huawei-multiple-entries.test.cjs +80 -0
  35. package/files/buildCodeplay/tests/huawei-privacy.test.cjs +49 -49
  36. package/files/buildCodeplay/tests/huawei-vite.test.cjs +38 -35
  37. package/files/buildCodeplay/versions.json +28 -28
  38. package/files/finalrelease +1365 -1365
  39. package/files/generate-ai-promo-video.js +23 -23
  40. package/files/ionic.config.json +6 -6
  41. package/files/scripts-common/collect-startup-profile.js +134 -0
  42. package/files/scripts-common/generate-baseline-profile.js +194 -22
  43. package/files/scripts-common/run-codeplay-sync-after.js +21 -21
  44. package/files/scripts-common/screenshot/background-decorations.js +120 -120
  45. package/files/scripts-common/screenshot/frame-samples.js +117 -117
  46. package/files/scripts-common/setup-baseline-profile.js +291 -291
  47. package/files/take-screen-image.js +4414 -4414
  48. package/files/take-screen-video.js +644 -644
  49. package/package.json +29 -29
  50. package/runtime/vk-ads/vk-ad-configuration.json +39 -39
  51. package/scripts/baseline-profile.test.cjs +189 -0
  52. package/scripts/ensure-current-build.test.cjs +76 -76
  53. package/scripts/iap-alias.test.cjs +117 -117
  54. package/scripts/ios-ad-consent.test.cjs +99 -99
  55. package/scripts/ruads-install.test.cjs +197 -180
  56. package/scripts/ruads-policy.test.cjs +174 -174
  57. package/scripts/saf-mediastore-dependency.test.cjs +44 -44
  58. package/scripts/squeezeback-config.test.cjs +78 -78
  59. package/scripts/sync-files.js +120 -120
  60. package/scripts/system-bars-package.test.cjs +38 -38
  61. package/scripts/system-bars.test.cjs +93 -93
  62. package/scripts/uninstall.js +2 -2
  63. package/scripts/vite-build-settings.test.cjs +93 -92
@@ -86,8 +86,8 @@ const analysisFrameDirectory = path.join(temporaryDirectory, 'ai-analysis');
86
86
  const endCardBannerPath = path.join(outputVideoDirectory, `${appFilePrefix}-ai-end-card-banner.png`);
87
87
  const promoCopySchemaPath = path.join(temporaryDirectory, 'promo-copy-schema.json');
88
88
  const promoCopyResultPath = path.join(temporaryDirectory, 'promo-copy-result.json');
89
- const ffmpegFallbackDirectory = String(process.env.FFMPEG_BIN || '').trim()
90
- || path.join(projectDirectory, 'tools', 'ffmpeg');
89
+ const ffmpegFallbackDirectory = String(process.env.FFMPEG_BIN || '').trim()
90
+ || path.join(projectDirectory, 'tools', 'ffmpeg');
91
91
  const minimumSceneCount = 7;
92
92
  const minimumSourceDuration = 12;
93
93
  let expectedDuration = 34;
@@ -209,15 +209,15 @@ async function ensureEndCardBanner() {
209
209
  + '- Keep all logos and badge text sharp, correctly proportioned, and completely visible.\n'
210
210
  + '- Match the background colors and visual style to the actual app icon.\n'
211
211
  + '- Create a polished, professional background related to the app’s purpose.\n'
212
- + '- Keep the background subtle so it does not compete with the icon, title, feature text, or download badges.\n'
212
+ + '- Keep the background subtle so it does not compete with the icon, title, feature text, or download badges.\n'
213
213
  + '- Use a balanced landscape composition:\n'
214
214
  + ' - Large actual app icon on the left.\n'
215
215
  + ' - App Store badge followed by Google Play badge on the right.\n'
216
216
  + ' - Maintain comfortable margins and clear space around every element.\n'
217
- + '- Add the application title prominently.\n'
218
- + '- Add concise promotional text describing the application’s actual features, presenting each feature one by one.\n'
219
- + '- Keep the title and feature text sharp, readable, accurate, and visually balanced with the icon and download badges.\n'
220
- + '- Do not invent unsupported features or add unrelated marketing text.\n'
217
+ + '- Add the application title prominently.\n'
218
+ + '- Add concise promotional text describing the application’s actual features, presenting each feature one by one.\n'
219
+ + '- Keep the title and feature text sharp, readable, accurate, and visually balanced with the icon and download badges.\n'
220
+ + '- Do not invent unsupported features or add unrelated marketing text.\n'
221
221
  + '- Do not add watermarks, fake UI, generated symbols, or unrelated decorations.\n'
222
222
  + '- Rounded corners and a subtle shadow may be applied around the app icon, but its internal artwork must remain unchanged.\n'
223
223
  + '- Use image generation only for the background.\n'
@@ -467,12 +467,12 @@ function commandExists(command) {
467
467
  return !result.error && result.status === 0;
468
468
  }
469
469
 
470
- function getExecutable(command) {
471
- const executableName = process.platform === 'win32' ? `${command}.exe` : command;
472
- const fallbackPath = path.join(ffmpegFallbackDirectory, executableName);
473
- if (fs.existsSync(fallbackPath)) return fallbackPath;
474
- return commandExists(command) ? command : '';
475
- }
470
+ function getExecutable(command) {
471
+ const executableName = process.platform === 'win32' ? `${command}.exe` : command;
472
+ const fallbackPath = path.join(ffmpegFallbackDirectory, executableName);
473
+ if (fs.existsSync(fallbackPath)) return fallbackPath;
474
+ return commandExists(command) ? command : '';
475
+ }
476
476
 
477
477
  function detectRedundantStaticRanges(ffmpegCommand, inputPath, sourceDuration) {
478
478
  const minimumStaticDuration = Math.max(2, Math.min(4, sourceDuration / 60));
@@ -640,7 +640,7 @@ function resolvePromoLayout(requestedLayout) {
640
640
  }
641
641
 
642
642
  function getPythonExecutable() {
643
- for (const candidate of ['py', 'python', 'python3']) {
643
+ for (const candidate of ['py', 'python', 'python3']) {
644
644
  const result = spawnSync(candidate, ['-m', 'edge_tts', '--version'], {
645
645
  encoding: 'utf8',
646
646
  windowsHide: true,
@@ -915,7 +915,7 @@ Rules:
915
915
  - footer_keywords must contain exactly 3 distinct, natural app-search phrases, each 2-24 characters.
916
916
  - Generate a YouTube upload title and description from the same verified features.
917
917
  - YouTube title: 40-100 characters, include ${JSON.stringify(appName)} and one strong natural search phrase, without clickbait.
918
- - YouTube description: 350-1500 characters with readable paragraphs. Put the clearest app summary and primary search phrase in the opening two lines, explain the demonstrated features, add a simple call to action, then insert a newline and finish with exactly 3 relevant hashtags on that separate final line. The hashtags must not be appended to the preceding paragraph.
918
+ - YouTube description: 350-1500 characters with readable paragraphs. Put the clearest app summary and primary search phrase in the opening two lines, explain the demonstrated features, add a simple call to action, then insert a newline and finish with exactly 3 relevant hashtags on that separate final line. The hashtags must not be appended to the preceding paragraph.
919
919
  - Do not add download links or URLs; the script will append the verified Google Play URL built from the configured package ID. Do not add chapter timestamps or unsupported availability claims.
920
920
  - Keep YouTube text natural and useful; do not repeat keywords unnaturally.
921
921
  - Avoid prices, ratings, awards, competitor names, unsupported superlatives, and words such as best, guaranteed, or free.
@@ -1025,14 +1025,14 @@ function validatePromoCopy(value) {
1025
1025
  throw new Error(`The final scene must mention the app name ${JSON.stringify(appName)}.`);
1026
1026
  }
1027
1027
 
1028
- const youtubeTitle = cleanGeneratedString(value.youtube.title);
1029
- let youtubeDescription = cleanGeneratedDescription(value.youtube.description);
1030
- const trailingHashtagGroup = youtubeDescription.match(
1031
- /(?:^|\s)(#[\p{L}\p{N}_]+\s+#[\p{L}\p{N}_]+\s+#[\p{L}\p{N}_]+)\s*$/u,
1032
- );
1033
- if (trailingHashtagGroup) {
1034
- youtubeDescription = `${youtubeDescription.slice(0, trailingHashtagGroup.index).trimEnd()}\n${trailingHashtagGroup[1]}`;
1035
- }
1028
+ const youtubeTitle = cleanGeneratedString(value.youtube.title);
1029
+ let youtubeDescription = cleanGeneratedDescription(value.youtube.description);
1030
+ const trailingHashtagGroup = youtubeDescription.match(
1031
+ /(?:^|\s)(#[\p{L}\p{N}_]+\s+#[\p{L}\p{N}_]+\s+#[\p{L}\p{N}_]+)\s*$/u,
1032
+ );
1033
+ if (trailingHashtagGroup) {
1034
+ youtubeDescription = `${youtubeDescription.slice(0, trailingHashtagGroup.index).trimEnd()}\n${trailingHashtagGroup[1]}`;
1035
+ }
1036
1036
  if (youtubeTitle.length < 40 || youtubeTitle.length > 100) {
1037
1037
  throw new Error('YouTube title must be 40-100 characters.');
1038
1038
  }
@@ -1,7 +1,7 @@
1
- {
2
- "name": "merbin-test-app",
3
- "integrations": {
4
- "capacitor": {}
5
- },
6
- "type": "custom"
1
+ {
2
+ "name": "merbin-test-app",
3
+ "integrations": {
4
+ "capacitor": {}
5
+ },
6
+ "type": "custom"
7
7
  }
@@ -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,9 +1,134 @@
1
- const { execFileSync, spawnSync } = require('child_process');
1
+ const { execFile, execFileSync, spawn } = require('child_process');
2
+ const fs = require('fs');
2
3
  const path = require('path');
4
+ const { promisify } = require('util');
3
5
  const { syncGeneratedProfileBackup } = require('./setup-baseline-profile.js');
6
+ const { collectStartupProfile } = require('./collect-startup-profile.js');
4
7
 
5
- function main() {
6
- const devices = execFileSync('adb', ['devices'], { encoding: 'utf8' })
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 })
7
132
  .split(/\r?\n/)
8
133
  .map(line => line.match(/^(.+?)\tdevice\s*$/))
9
134
  .filter(Boolean)
@@ -19,28 +144,75 @@ function main() {
19
144
  : 'No online ADB device. Connect an Android device before generating a Baseline Profile.');
20
145
  }
21
146
 
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',
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.');
31
211
  }
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
212
  }
39
213
  }
40
214
 
41
- try {
42
- main();
43
- } catch (error) {
215
+ main().catch((error) => {
44
216
  console.error(`Baseline Profile generation failed: ${error.message}`);
45
217
  process.exitCode = 1;
46
- }
218
+ });
@@ -1,21 +1,21 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const { execFileSync } = require('child_process');
4
-
5
- const root = path.resolve(__dirname, '..');
6
- const buildDir = path.join(root, 'buildCodeplay');
7
-
8
- function run(scriptPath) {
9
- execFileSync(process.execPath, [scriptPath], { cwd: root, stdio: 'inherit' });
10
- }
11
-
12
- const splashIcon = path.join(root, 'resources', 'splash_icon.png');
13
- if (fs.existsSync(splashIcon)) {
14
- run(path.join(buildDir, 'add-splash-screen.js'));
15
- run(path.join(buildDir, 'setSplashAnimation.js'));
16
- } else {
17
- console.log('ℹ️ Keeping the existing native splash because resources/splash_icon.png is not configured.');
18
- }
19
-
20
- run(path.join(buildDir, 'manifestModification.js'));
21
- run(path.join(__dirname, 'setup-baseline-profile.js'));
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { execFileSync } = require('child_process');
4
+
5
+ const root = path.resolve(__dirname, '..');
6
+ const buildDir = path.join(root, 'buildCodeplay');
7
+
8
+ function run(scriptPath) {
9
+ execFileSync(process.execPath, [scriptPath], { cwd: root, stdio: 'inherit' });
10
+ }
11
+
12
+ const splashIcon = path.join(root, 'resources', 'splash_icon.png');
13
+ if (fs.existsSync(splashIcon)) {
14
+ run(path.join(buildDir, 'add-splash-screen.js'));
15
+ run(path.join(buildDir, 'setSplashAnimation.js'));
16
+ } else {
17
+ console.log('ℹ️ Keeping the existing native splash because resources/splash_icon.png is not configured.');
18
+ }
19
+
20
+ run(path.join(buildDir, 'manifestModification.js'));
21
+ run(path.join(__dirname, 'setup-baseline-profile.js'));