codeplay-common 4.11.38 → 4.11.40

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 (40) hide show
  1. package/README.md +1 -1
  2. package/RELEASE_NOTES.md +13 -13
  3. package/files/buildCodeplay/add-splash-screen.js +1 -1
  4. package/files/buildCodeplay/codeplayBeforeBuild.js +2 -2
  5. package/files/buildCodeplay/ensure-current-build.cjs +32 -4
  6. package/files/buildCodeplay/fix-optimize-builld/android-r8-rules.cjs +31 -31
  7. package/files/buildCodeplay/fix-optimize-builld/ffmpeg-jni-rules.cjs +28 -28
  8. package/files/buildCodeplay/fix-optimize-builld/fix-optimize-build.gradle +9 -9
  9. package/files/buildCodeplay/fix-optimize-builld/restore-android-r8-rules.cjs +30 -30
  10. package/files/buildCodeplay/huawei-privacy-entry.js +135 -135
  11. package/files/buildCodeplay/huawei-privacy.css +22 -22
  12. package/files/buildCodeplay/ios-ad-consent.cjs +56 -56
  13. package/files/buildCodeplay/ios-emi-admob-modification.js +25 -25
  14. package/files/buildCodeplay/newly added.txt +89 -89
  15. package/files/buildCodeplay/non-google-billing.pro +3 -3
  16. package/files/buildCodeplay/release-sync.config.json +4 -4
  17. package/files/buildCodeplay/remove-force-kotlin-disable.js +43 -43
  18. package/files/buildCodeplay/ruads.cjs +220 -220
  19. package/files/buildCodeplay/saf-mediastore-dependency.cjs +21 -21
  20. package/files/buildCodeplay/setSplashAnimation.js +2 -2
  21. package/files/buildCodeplay/setup-ruads.cjs +62 -62
  22. package/files/buildCodeplay/splash-setup.cjs +88 -88
  23. package/files/buildCodeplay/store-billing.cjs +43 -43
  24. package/files/buildCodeplay/tests/huawei-live-reload.test.cjs +60 -60
  25. package/files/buildCodeplay/tests/huawei-privacy.test.cjs +49 -49
  26. package/files/scripts-common/collect-startup-profile.js +134 -134
  27. package/files/scripts-common/generate-baseline-profile.js +218 -218
  28. package/files/take-screen-image.js +4552 -4414
  29. package/package.json +1 -1
  30. package/runtime/splash-ready.mjs +52 -52
  31. package/runtime/vk-ads/vk-ad-configuration.json +39 -39
  32. package/scripts/baseline-profile.test.cjs +189 -189
  33. package/scripts/ensure-current-build.test.cjs +128 -28
  34. package/scripts/ios-ad-consent.test.cjs +99 -99
  35. package/scripts/ruads-install.test.cjs +197 -197
  36. package/scripts/ruads-policy.test.cjs +174 -174
  37. package/scripts/saf-mediastore-dependency.test.cjs +44 -44
  38. package/scripts/splash-setup.test.cjs +142 -142
  39. package/scripts/sync-files.js +1 -1
  40. package/scripts/vite-build-settings.test.cjs +93 -93
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codeplay-common",
3
- "version": "4.11.38",
3
+ "version": "4.11.40",
4
4
  "description": "Common build scripts and files",
5
5
  "scripts": {
6
6
  "postinstall": "node scripts/sync-files.js",
@@ -1,52 +1,52 @@
1
- // Framework7 and Capacitor stay owned by the consuming app; no extra dependency.
2
- const registrations = new WeakMap();
3
-
4
- export function hideSplashWhenReady({ f7, hide, imageSelector = '[data-splash-ready], .t-film-art img', timeout = 8000 }) {
5
- if (!f7 || typeof f7.on !== 'function' || typeof f7.off !== 'function' || typeof hide !== 'function') {
6
- throw new TypeError('Splash readiness requires Framework7 and a hide callback.');
7
- }
8
- if (!Number.isInteger(timeout) || timeout < 1 || timeout > 60000) throw new TypeError('Invalid splash readiness timeout.');
9
- if (typeof imageSelector !== 'string') throw new TypeError('Invalid splash image selector.');
10
- if (registrations.has(f7)) return registrations.get(f7);
11
- let finished = false;
12
- let preparing = false;
13
- let image;
14
- const detachImage = () => {
15
- image?.removeEventListener('load', onImageReady);
16
- image?.removeEventListener('error', onImageReady);
17
- };
18
- const finish = () => {
19
- if (finished) return;
20
- finished = true;
21
- clearTimeout(fallback);
22
- f7.off('pageAfterIn', onPageReady);
23
- detachImage();
24
- // Plugin availability differs by platform; failed native hiding must not
25
- // create an unhandled rejection. The native launch timeout is the backup.
26
- try { Promise.resolve(hide()).catch(() => {}); } catch {}
27
- };
28
- const onImageReady = () => {
29
- if (finished) return;
30
- detachImage();
31
- if (image.naturalWidth > 0 && typeof image.decode === 'function') {
32
- Promise.resolve().then(() => image.decode()).catch(() => {}).then(finish);
33
- } else finish();
34
- };
35
- const onPageReady = page => {
36
- if (finished || preparing || !page?.el?.closest('.view-main')) return;
37
- preparing = true;
38
- try { image = imageSelector ? page.el.querySelector(imageSelector) : null; } catch { finish(); return; }
39
- if (!image) finish();
40
- else if (image.complete) onImageReady();
41
- else {
42
- image.addEventListener('load', onImageReady, { once: true });
43
- image.addEventListener('error', onImageReady, { once: true });
44
- }
45
- };
46
- const fallback = setTimeout(finish, timeout);
47
- registrations.set(f7, finish);
48
- f7.on('pageAfterIn', onPageReady);
49
- const currentPage = f7.views?.main?.router?.currentPageEl;
50
- if (currentPage) onPageReady({ el: currentPage });
51
- return finish;
52
- }
1
+ // Framework7 and Capacitor stay owned by the consuming app; no extra dependency.
2
+ const registrations = new WeakMap();
3
+
4
+ export function hideSplashWhenReady({ f7, hide, imageSelector = '[data-splash-ready], .t-film-art img', timeout = 8000 }) {
5
+ if (!f7 || typeof f7.on !== 'function' || typeof f7.off !== 'function' || typeof hide !== 'function') {
6
+ throw new TypeError('Splash readiness requires Framework7 and a hide callback.');
7
+ }
8
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > 60000) throw new TypeError('Invalid splash readiness timeout.');
9
+ if (typeof imageSelector !== 'string') throw new TypeError('Invalid splash image selector.');
10
+ if (registrations.has(f7)) return registrations.get(f7);
11
+ let finished = false;
12
+ let preparing = false;
13
+ let image;
14
+ const detachImage = () => {
15
+ image?.removeEventListener('load', onImageReady);
16
+ image?.removeEventListener('error', onImageReady);
17
+ };
18
+ const finish = () => {
19
+ if (finished) return;
20
+ finished = true;
21
+ clearTimeout(fallback);
22
+ f7.off('pageAfterIn', onPageReady);
23
+ detachImage();
24
+ // Plugin availability differs by platform; failed native hiding must not
25
+ // create an unhandled rejection. The native launch timeout is the backup.
26
+ try { Promise.resolve(hide()).catch(() => {}); } catch {}
27
+ };
28
+ const onImageReady = () => {
29
+ if (finished) return;
30
+ detachImage();
31
+ if (image.naturalWidth > 0 && typeof image.decode === 'function') {
32
+ Promise.resolve().then(() => image.decode()).catch(() => {}).then(finish);
33
+ } else finish();
34
+ };
35
+ const onPageReady = page => {
36
+ if (finished || preparing || !page?.el?.closest('.view-main')) return;
37
+ preparing = true;
38
+ try { image = imageSelector ? page.el.querySelector(imageSelector) : null; } catch { finish(); return; }
39
+ if (!image) finish();
40
+ else if (image.complete) onImageReady();
41
+ else {
42
+ image.addEventListener('load', onImageReady, { once: true });
43
+ image.addEventListener('error', onImageReady, { once: true });
44
+ }
45
+ };
46
+ const fallback = setTimeout(finish, timeout);
47
+ registrations.set(f7, finish);
48
+ f7.on('pageAfterIn', onPageReady);
49
+ const currentPage = f7.views?.main?.router?.currentPageEl;
50
+ if (currentPage) onPageReady({ el: currentPage });
51
+ return finish;
52
+ }
@@ -1,39 +1,39 @@
1
- {
2
- "VERSION": "1.2",
3
- "android": {
4
- "HuaweiStore": {
5
- "appId": 0,
6
- "bannerSlotId": 0,
7
- "interstitialSlotId": 0,
8
- "rewardedSlotId": 0
9
- },
10
- "RuStore": {
11
- "appId": 0,
12
- "bannerSlotId": 0,
13
- "interstitialSlotId": 0,
14
- "rewardedSlotId": 0
15
- }
16
- },
17
- "config": {
18
- "isTesting": false,
19
- "bannerEnabled": true,
20
- "bannerSize": "320x50",
21
- "bannerDisabledPages": [],
22
- "bannerStartupDelayMs": 3000,
23
- "interstitialEnabled": true,
24
- "interstitialStartupDelayMs": 30000,
25
- "minimumClick": 2,
26
- "interstitialFirstTimeOutMs": 252000,
27
- "interstitialTimeOutMs": 360000,
28
- "interstitialPerSession": 8,
29
- "rewardVideoEnabled": true,
30
- "userAgeRestricted": false,
31
- "retryDelayMs": 30000,
32
- "debug": false
33
- },
34
- "testid": {
35
- "bannerSlotId": 794557,
36
- "interstitialSlotId": 6481,
37
- "rewardedSlotId": 45101
38
- }
39
- }
1
+ {
2
+ "VERSION": "1.2",
3
+ "android": {
4
+ "HuaweiStore": {
5
+ "appId": 0,
6
+ "bannerSlotId": 0,
7
+ "interstitialSlotId": 0,
8
+ "rewardedSlotId": 0
9
+ },
10
+ "RuStore": {
11
+ "appId": 0,
12
+ "bannerSlotId": 0,
13
+ "interstitialSlotId": 0,
14
+ "rewardedSlotId": 0
15
+ }
16
+ },
17
+ "config": {
18
+ "isTesting": false,
19
+ "bannerEnabled": true,
20
+ "bannerSize": "320x50",
21
+ "bannerDisabledPages": [],
22
+ "bannerStartupDelayMs": 3000,
23
+ "interstitialEnabled": true,
24
+ "interstitialStartupDelayMs": 30000,
25
+ "minimumClick": 2,
26
+ "interstitialFirstTimeOutMs": 252000,
27
+ "interstitialTimeOutMs": 360000,
28
+ "interstitialPerSession": 8,
29
+ "rewardVideoEnabled": true,
30
+ "userAgeRestricted": false,
31
+ "retryDelayMs": 30000,
32
+ "debug": false
33
+ },
34
+ "testid": {
35
+ "bannerSlotId": 794557,
36
+ "interstitialSlotId": 6481,
37
+ "rewardedSlotId": 45101
38
+ }
39
+ }
@@ -1,189 +1,189 @@
1
- const { test } = require('node:test');
2
- const assert = require('node:assert/strict');
3
- const fs = require('node:fs');
4
- const path = require('node:path');
5
- const vm = require('node:vm');
6
- const { EventEmitter } = require('node:events');
7
- const { install } = require('./sync-files.js');
8
-
9
- const templateDir = path.resolve(__dirname, '../files/scripts-common');
10
- const generator = fs.readFileSync(path.join(templateDir, 'generate-baseline-profile.js'), 'utf8');
11
- const collector = fs.readFileSync(path.join(templateDir, 'collect-startup-profile.js'), 'utf8');
12
- const appId = 'org.example.notes';
13
-
14
- function fixture(t) {
15
- const base = path.resolve(__dirname, '../agent-temp/baseline-profile-tests');
16
- fs.mkdirSync(base, { recursive: true });
17
- const root = fs.mkdtempSync(path.join(base, 'case-'));
18
- t.after(() => {
19
- assert.ok(path.resolve(root).startsWith(base + path.sep));
20
- fs.rmSync(root, { recursive: true, force: true });
21
- });
22
- const write = (name, content) => {
23
- const file = path.join(root, name);
24
- fs.mkdirSync(path.dirname(file), { recursive: true });
25
- fs.writeFileSync(file, typeof content === 'string' ? content : JSON.stringify(content));
26
- };
27
- const nativeConfig = 'android/app/src/main/assets/capacitor.config.json';
28
- write('package.json', { name: 'baseline-consumer', scripts: {}, dependencies: {} });
29
- write('capacitor.config.json', { appId, plugins: {}, appOwned: 'preserve' });
30
- write(nativeConfig, `{"appId":"${appId}","server":{"url":"http://192.0.2.1:5173","hostname":"localhost"}}\r\n`);
31
- write('android/app/src/main/assets/public/index.html', '<script src="./assets/app.js"></script>');
32
- return { root, write, nativeConfig, read: name => fs.readFileSync(path.join(root, name), 'utf8') };
33
- }
34
-
35
- test('package updates distribute both scripts and preserve per-app config, commands and profiles', t => {
36
- const f = fixture(t);
37
- f.write('package.json', { name: 'consumer', scripts: { 'baseline-profile:generate': 'cd android && gradlew.bat :app:generateBaselineProfile --console=plain' } });
38
- f.write('scripts-common/generate-baseline-profile.js', '// previous generator');
39
- f.write('baselineProfiles/baseline-prof.txt', 'Lorg/example/notes/Existing;\n');
40
- const originalNative = f.read(f.nativeConfig);
41
- for (let attempt = 0; attempt < 2; attempt += 1) {
42
- install({ projectRoot: f.root });
43
- assert.equal(f.read('scripts-common/generate-baseline-profile.js'), generator);
44
- assert.equal(f.read('scripts-common/collect-startup-profile.js'), collector);
45
- assert.equal(f.read('scripts-common/setup-baseline-profile.js'), fs.readFileSync(path.join(templateDir, 'setup-baseline-profile.js'), 'utf8'));
46
- assert.equal(f.read(f.nativeConfig), originalNative);
47
- assert.equal(JSON.parse(f.read('capacitor.config.json')).appId, appId);
48
- assert.equal(JSON.parse(f.read('capacitor.config.json')).appOwned, 'preserve');
49
- assert.equal(f.read('baselineProfiles/baseline-prof.txt'), 'Lorg/example/notes/Existing;\n');
50
- assert.equal(JSON.parse(f.read('package.json')).scripts['baseline-profile:generate'], 'node scripts-common/generate-baseline-profile.js');
51
- }
52
- f.write('package.json', { name: 'consumer', scripts: { 'baseline-profile:generate': 'node custom-profile.cjs' } });
53
- install({ projectRoot: f.root });
54
- assert.equal(JSON.parse(f.read('package.json')).scripts['baseline-profile:generate'], 'node custom-profile.cjs');
55
- });
56
-
57
- async function runGenerator(f, mode) {
58
- const state = { collected: 0, synced: [], tasks: [] };
59
- const proc = { env: {}, argv: ['node', 'generator', ...(mode === 'host' ? ['--host'] : [])], platform: 'win32' };
60
- const code = generator.slice(0, generator.lastIndexOf('main().catch'));
61
- const context = {
62
- __dirname: path.join(f.root, 'scripts-common'), Buffer, process: proc,
63
- console: { log() {}, error() {} }, setTimeout, clearTimeout, setInterval, clearInterval,
64
- executeGradle: async args => {
65
- state.tasks.push(args);
66
- if (mode === 'frozen' || mode === 'failed') {
67
- const error = new Error('simulated Gradle failure');
68
- error.code = mode === 'frozen' ? 'BASELINE_TEST_FROZEN' : 'OTHER_FAILURE';
69
- throw error;
70
- }
71
- return 0;
72
- },
73
- require: id => {
74
- if (id === 'child_process') return { ...require(id), execFileSync: () => 'List of devices attached\nSERIAL\tdevice\n' };
75
- if (id === './setup-baseline-profile.js') return { syncGeneratedProfileBackup: options => state.synced.push(options?.backupOnly ?? false) };
76
- if (id === './collect-startup-profile.js') return { collectStartupProfile: async options => {
77
- state.collected += 1;
78
- assert.equal(options.appId, appId);
79
- assert.equal(options.serial, 'SERIAL');
80
- assert.ok(options.deadline > Date.now());
81
- const config = JSON.parse(f.read(f.nativeConfig));
82
- assert.equal(config.server.url, undefined);
83
- assert.equal(config.server.hostname, 'localhost');
84
- } };
85
- return require(id);
86
- },
87
- };
88
- const promise = vm.runInNewContext(code + '\nrunGradle = executeGradle; main();', context);
89
- if (mode === 'failed') await assert.rejects(promise, /simulated Gradle failure/);
90
- else await promise;
91
- return state;
92
- }
93
-
94
- for (const mode of ['normal', 'frozen', 'host', 'failed']) {
95
- test(`${mode} generation preserves config and selects the correct collection path`, async t => {
96
- const f = fixture(t);
97
- const original = f.read(f.nativeConfig);
98
- const result = await runGenerator(f, mode);
99
- assert.equal(f.read(f.nativeConfig), original);
100
- assert.equal(fs.existsSync(path.join(f.root, 'agent-temp/baseline-profile/capacitor.config.original.json')), false);
101
- assert.equal(result.collected, mode === 'frozen' || mode === 'host' ? 1 : 0);
102
- assert.deepEqual(result.synced, mode === 'failed' ? [] : [mode === 'normal']);
103
- assert.equal(result.tasks[0][0], mode === 'host' ? ':app:assembleNonMinifiedRelease' : ':app:generateBaselineProfile');
104
- assert.ok(result.tasks[0].includes('--no-daemon'));
105
- });
106
- }
107
-
108
- function loadCollector(f, options = {}) {
109
- const commands = [];
110
- const proc = new EventEmitter();
111
- let launches = 0;
112
- const goodProfile = `SPLorg/example/notes/Launcher;->onCreate(Landroid/os/Bundle;)V\nLcom/getcapacitor/Bridge;\n`;
113
- const execute = async (_command, args, settings = {}) => {
114
- if (settings.signal?.aborted) throw settings.signal.reason;
115
- commands.push(args);
116
- const command = args.slice(2).join(' ');
117
- let stdout = '';
118
- if (command.includes('ro.build.version.sdk')) stdout = String(options.sdk ?? 35);
119
- else if (command.startsWith('install ')) stdout = 'Success';
120
- else if (command.includes('resolve-activity')) stdout = `${appId}/.Launcher`;
121
- else if (command.includes('WRITE_SKIP_FILE')) stdout = 'Broadcast completed: result=10';
122
- else if (command.includes('DELETE_SKIP_FILE')) stdout = 'Broadcast completed: result=11';
123
- else if (command.includes('clear-app-profiles')) stdout = 'Profiles cleared';
124
- else if (command.includes('package compile')) stdout = 'Success';
125
- else if (command.includes('am start')) { launches += 1; stdout = 'Status: ok'; }
126
- else if (command.includes('SAVE_PROFILE')) stdout = `Broadcast completed: result=${options.saveFails ? 0 : 12}`;
127
- else if (command.includes('screencap')) stdout = Buffer.from('diagnostic screenshot');
128
- else if (command.includes('exec-out cat')) stdout = options.missingActivity ? 'Lcom/getcapacitor/Bridge;' :
129
- goodProfile + (options.unstable ? `HLorg/example/notes/Changing;->iteration${launches}()V\n` : '');
130
- return { stdout, stderr: '' };
131
- };
132
- const module = { exports: {} };
133
- vm.runInNewContext(collector, {
134
- module, Buffer, AbortController, process: proc, console: { log() {}, error() {} },
135
- setTimeout: (callback, milliseconds) => { if (options.expired) { assert.equal(milliseconds, 0); callback(); } return 1; },
136
- clearTimeout() {},
137
- require: id => {
138
- if (id === 'child_process') return {};
139
- if (id === 'util') return { promisify: () => execute };
140
- if (id === 'timers/promises') return { setTimeout: async () => { if (options.cancel) proc.emit('SIGINT'); } };
141
- if (id === 'adm-zip') return class {
142
- readAsText() { return JSON.stringify({ appId, server: options.liveUrl ? { url: 'http://192.0.2.1:5173' } : {} }); }
143
- getEntry() { return true; }
144
- };
145
- return require(id);
146
- },
147
- });
148
- return { ...module.exports, commands, proc, launches: () => launches };
149
- }
150
-
151
- test('host collection saves stable app-specific profiles and cleans up profile installation', async t => {
152
- const f = fixture(t);
153
- const host = loadCollector(f);
154
- await host.collectStartupProfile({ serial: 'SERIAL', appId, rootDir: f.root, apkPath: 'fixture.apk', timeoutMinutes: 20 });
155
- assert.equal(host.launches(), 3);
156
- assert.equal(f.read('baselineProfiles/baseline-prof.txt'), f.read('baselineProfiles/startup-prof.txt'));
157
- assert.match(f.read('baselineProfiles/baseline-prof.txt'), /Lorg\/example\/notes\/Launcher;/);
158
- assert.ok(host.commands.every(args => args[0] === '-s' && args[1] === 'SERIAL'));
159
- assert.ok(host.commands.some(args => args.includes('DELETE_SKIP_FILE')));
160
- assert.equal(host.proc.listenerCount('SIGINT'), 0);
161
- assert.equal(host.proc.listenerCount('SIGTERM'), 0);
162
- assert.equal(host.normalizeProfile('[Lbad/Array;\nHLbad/Cache;->call()V+inline\nLgood/A;\nLgood/A;'), 'Lgood/A;');
163
- });
164
-
165
- for (const [options, message] of [
166
- [{ sdk: 33 }, /Android 14/],
167
- [{ liveUrl: true }, /no server.url/],
168
- [{ missingActivity: true }, /missing the app launch activity/],
169
- [{ unstable: true }, /did not stabilize/],
170
- [{ saveFails: true }, /did not return 12/],
171
- [{ cancel: true }, /cancelled/],
172
- [{ expired: true }, /exceeded 20 minutes/],
173
- ]) {
174
- test(`host failure ${JSON.stringify(options)} preserves existing profiles`, async t => {
175
- const f = fixture(t);
176
- f.write('baselineProfiles/baseline-prof.txt', 'original baseline');
177
- f.write('baselineProfiles/startup-prof.txt', 'original startup');
178
- const host = loadCollector(f, options);
179
- await assert.rejects(host.collectStartupProfile({ serial: 'SERIAL', appId, rootDir: f.root,
180
- apkPath: 'fixture.apk', timeoutMinutes: 20, ...(options.expired ? { deadline: 1 } : {}) }), message);
181
- assert.equal(f.read('baselineProfiles/baseline-prof.txt'), 'original baseline');
182
- assert.equal(f.read('baselineProfiles/startup-prof.txt'), 'original startup');
183
- if (host.commands.some(args => args.includes('WRITE_SKIP_FILE'))) {
184
- assert.ok(host.commands.some(args => args.includes('DELETE_SKIP_FILE')));
185
- }
186
- assert.equal(host.proc.listenerCount('SIGINT'), 0);
187
- assert.equal(host.proc.listenerCount('SIGTERM'), 0);
188
- });
189
- }
1
+ const { test } = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const vm = require('node:vm');
6
+ const { EventEmitter } = require('node:events');
7
+ const { install } = require('./sync-files.js');
8
+
9
+ const templateDir = path.resolve(__dirname, '../files/scripts-common');
10
+ const generator = fs.readFileSync(path.join(templateDir, 'generate-baseline-profile.js'), 'utf8');
11
+ const collector = fs.readFileSync(path.join(templateDir, 'collect-startup-profile.js'), 'utf8');
12
+ const appId = 'org.example.notes';
13
+
14
+ function fixture(t) {
15
+ const base = path.resolve(__dirname, '../agent-temp/baseline-profile-tests');
16
+ fs.mkdirSync(base, { recursive: true });
17
+ const root = fs.mkdtempSync(path.join(base, 'case-'));
18
+ t.after(() => {
19
+ assert.ok(path.resolve(root).startsWith(base + path.sep));
20
+ fs.rmSync(root, { recursive: true, force: true });
21
+ });
22
+ const write = (name, content) => {
23
+ const file = path.join(root, name);
24
+ fs.mkdirSync(path.dirname(file), { recursive: true });
25
+ fs.writeFileSync(file, typeof content === 'string' ? content : JSON.stringify(content));
26
+ };
27
+ const nativeConfig = 'android/app/src/main/assets/capacitor.config.json';
28
+ write('package.json', { name: 'baseline-consumer', scripts: {}, dependencies: {} });
29
+ write('capacitor.config.json', { appId, plugins: {}, appOwned: 'preserve' });
30
+ write(nativeConfig, `{"appId":"${appId}","server":{"url":"http://192.0.2.1:5173","hostname":"localhost"}}\r\n`);
31
+ write('android/app/src/main/assets/public/index.html', '<script src="./assets/app.js"></script>');
32
+ return { root, write, nativeConfig, read: name => fs.readFileSync(path.join(root, name), 'utf8') };
33
+ }
34
+
35
+ test('package updates distribute both scripts and preserve per-app config, commands and profiles', t => {
36
+ const f = fixture(t);
37
+ f.write('package.json', { name: 'consumer', scripts: { 'baseline-profile:generate': 'cd android && gradlew.bat :app:generateBaselineProfile --console=plain' } });
38
+ f.write('scripts-common/generate-baseline-profile.js', '// previous generator');
39
+ f.write('baselineProfiles/baseline-prof.txt', 'Lorg/example/notes/Existing;\n');
40
+ const originalNative = f.read(f.nativeConfig);
41
+ for (let attempt = 0; attempt < 2; attempt += 1) {
42
+ install({ projectRoot: f.root });
43
+ assert.equal(f.read('scripts-common/generate-baseline-profile.js'), generator);
44
+ assert.equal(f.read('scripts-common/collect-startup-profile.js'), collector);
45
+ assert.equal(f.read('scripts-common/setup-baseline-profile.js'), fs.readFileSync(path.join(templateDir, 'setup-baseline-profile.js'), 'utf8'));
46
+ assert.equal(f.read(f.nativeConfig), originalNative);
47
+ assert.equal(JSON.parse(f.read('capacitor.config.json')).appId, appId);
48
+ assert.equal(JSON.parse(f.read('capacitor.config.json')).appOwned, 'preserve');
49
+ assert.equal(f.read('baselineProfiles/baseline-prof.txt'), 'Lorg/example/notes/Existing;\n');
50
+ assert.equal(JSON.parse(f.read('package.json')).scripts['baseline-profile:generate'], 'node scripts-common/generate-baseline-profile.js');
51
+ }
52
+ f.write('package.json', { name: 'consumer', scripts: { 'baseline-profile:generate': 'node custom-profile.cjs' } });
53
+ install({ projectRoot: f.root });
54
+ assert.equal(JSON.parse(f.read('package.json')).scripts['baseline-profile:generate'], 'node custom-profile.cjs');
55
+ });
56
+
57
+ async function runGenerator(f, mode) {
58
+ const state = { collected: 0, synced: [], tasks: [] };
59
+ const proc = { env: {}, argv: ['node', 'generator', ...(mode === 'host' ? ['--host'] : [])], platform: 'win32' };
60
+ const code = generator.slice(0, generator.lastIndexOf('main().catch'));
61
+ const context = {
62
+ __dirname: path.join(f.root, 'scripts-common'), Buffer, process: proc,
63
+ console: { log() {}, error() {} }, setTimeout, clearTimeout, setInterval, clearInterval,
64
+ executeGradle: async args => {
65
+ state.tasks.push(args);
66
+ if (mode === 'frozen' || mode === 'failed') {
67
+ const error = new Error('simulated Gradle failure');
68
+ error.code = mode === 'frozen' ? 'BASELINE_TEST_FROZEN' : 'OTHER_FAILURE';
69
+ throw error;
70
+ }
71
+ return 0;
72
+ },
73
+ require: id => {
74
+ if (id === 'child_process') return { ...require(id), execFileSync: () => 'List of devices attached\nSERIAL\tdevice\n' };
75
+ if (id === './setup-baseline-profile.js') return { syncGeneratedProfileBackup: options => state.synced.push(options?.backupOnly ?? false) };
76
+ if (id === './collect-startup-profile.js') return { collectStartupProfile: async options => {
77
+ state.collected += 1;
78
+ assert.equal(options.appId, appId);
79
+ assert.equal(options.serial, 'SERIAL');
80
+ assert.ok(options.deadline > Date.now());
81
+ const config = JSON.parse(f.read(f.nativeConfig));
82
+ assert.equal(config.server.url, undefined);
83
+ assert.equal(config.server.hostname, 'localhost');
84
+ } };
85
+ return require(id);
86
+ },
87
+ };
88
+ const promise = vm.runInNewContext(code + '\nrunGradle = executeGradle; main();', context);
89
+ if (mode === 'failed') await assert.rejects(promise, /simulated Gradle failure/);
90
+ else await promise;
91
+ return state;
92
+ }
93
+
94
+ for (const mode of ['normal', 'frozen', 'host', 'failed']) {
95
+ test(`${mode} generation preserves config and selects the correct collection path`, async t => {
96
+ const f = fixture(t);
97
+ const original = f.read(f.nativeConfig);
98
+ const result = await runGenerator(f, mode);
99
+ assert.equal(f.read(f.nativeConfig), original);
100
+ assert.equal(fs.existsSync(path.join(f.root, 'agent-temp/baseline-profile/capacitor.config.original.json')), false);
101
+ assert.equal(result.collected, mode === 'frozen' || mode === 'host' ? 1 : 0);
102
+ assert.deepEqual(result.synced, mode === 'failed' ? [] : [mode === 'normal']);
103
+ assert.equal(result.tasks[0][0], mode === 'host' ? ':app:assembleNonMinifiedRelease' : ':app:generateBaselineProfile');
104
+ assert.ok(result.tasks[0].includes('--no-daemon'));
105
+ });
106
+ }
107
+
108
+ function loadCollector(f, options = {}) {
109
+ const commands = [];
110
+ const proc = new EventEmitter();
111
+ let launches = 0;
112
+ const goodProfile = `SPLorg/example/notes/Launcher;->onCreate(Landroid/os/Bundle;)V\nLcom/getcapacitor/Bridge;\n`;
113
+ const execute = async (_command, args, settings = {}) => {
114
+ if (settings.signal?.aborted) throw settings.signal.reason;
115
+ commands.push(args);
116
+ const command = args.slice(2).join(' ');
117
+ let stdout = '';
118
+ if (command.includes('ro.build.version.sdk')) stdout = String(options.sdk ?? 35);
119
+ else if (command.startsWith('install ')) stdout = 'Success';
120
+ else if (command.includes('resolve-activity')) stdout = `${appId}/.Launcher`;
121
+ else if (command.includes('WRITE_SKIP_FILE')) stdout = 'Broadcast completed: result=10';
122
+ else if (command.includes('DELETE_SKIP_FILE')) stdout = 'Broadcast completed: result=11';
123
+ else if (command.includes('clear-app-profiles')) stdout = 'Profiles cleared';
124
+ else if (command.includes('package compile')) stdout = 'Success';
125
+ else if (command.includes('am start')) { launches += 1; stdout = 'Status: ok'; }
126
+ else if (command.includes('SAVE_PROFILE')) stdout = `Broadcast completed: result=${options.saveFails ? 0 : 12}`;
127
+ else if (command.includes('screencap')) stdout = Buffer.from('diagnostic screenshot');
128
+ else if (command.includes('exec-out cat')) stdout = options.missingActivity ? 'Lcom/getcapacitor/Bridge;' :
129
+ goodProfile + (options.unstable ? `HLorg/example/notes/Changing;->iteration${launches}()V\n` : '');
130
+ return { stdout, stderr: '' };
131
+ };
132
+ const module = { exports: {} };
133
+ vm.runInNewContext(collector, {
134
+ module, Buffer, AbortController, process: proc, console: { log() {}, error() {} },
135
+ setTimeout: (callback, milliseconds) => { if (options.expired) { assert.equal(milliseconds, 0); callback(); } return 1; },
136
+ clearTimeout() {},
137
+ require: id => {
138
+ if (id === 'child_process') return {};
139
+ if (id === 'util') return { promisify: () => execute };
140
+ if (id === 'timers/promises') return { setTimeout: async () => { if (options.cancel) proc.emit('SIGINT'); } };
141
+ if (id === 'adm-zip') return class {
142
+ readAsText() { return JSON.stringify({ appId, server: options.liveUrl ? { url: 'http://192.0.2.1:5173' } : {} }); }
143
+ getEntry() { return true; }
144
+ };
145
+ return require(id);
146
+ },
147
+ });
148
+ return { ...module.exports, commands, proc, launches: () => launches };
149
+ }
150
+
151
+ test('host collection saves stable app-specific profiles and cleans up profile installation', async t => {
152
+ const f = fixture(t);
153
+ const host = loadCollector(f);
154
+ await host.collectStartupProfile({ serial: 'SERIAL', appId, rootDir: f.root, apkPath: 'fixture.apk', timeoutMinutes: 20 });
155
+ assert.equal(host.launches(), 3);
156
+ assert.equal(f.read('baselineProfiles/baseline-prof.txt'), f.read('baselineProfiles/startup-prof.txt'));
157
+ assert.match(f.read('baselineProfiles/baseline-prof.txt'), /Lorg\/example\/notes\/Launcher;/);
158
+ assert.ok(host.commands.every(args => args[0] === '-s' && args[1] === 'SERIAL'));
159
+ assert.ok(host.commands.some(args => args.includes('DELETE_SKIP_FILE')));
160
+ assert.equal(host.proc.listenerCount('SIGINT'), 0);
161
+ assert.equal(host.proc.listenerCount('SIGTERM'), 0);
162
+ assert.equal(host.normalizeProfile('[Lbad/Array;\nHLbad/Cache;->call()V+inline\nLgood/A;\nLgood/A;'), 'Lgood/A;');
163
+ });
164
+
165
+ for (const [options, message] of [
166
+ [{ sdk: 33 }, /Android 14/],
167
+ [{ liveUrl: true }, /no server.url/],
168
+ [{ missingActivity: true }, /missing the app launch activity/],
169
+ [{ unstable: true }, /did not stabilize/],
170
+ [{ saveFails: true }, /did not return 12/],
171
+ [{ cancel: true }, /cancelled/],
172
+ [{ expired: true }, /exceeded 20 minutes/],
173
+ ]) {
174
+ test(`host failure ${JSON.stringify(options)} preserves existing profiles`, async t => {
175
+ const f = fixture(t);
176
+ f.write('baselineProfiles/baseline-prof.txt', 'original baseline');
177
+ f.write('baselineProfiles/startup-prof.txt', 'original startup');
178
+ const host = loadCollector(f, options);
179
+ await assert.rejects(host.collectStartupProfile({ serial: 'SERIAL', appId, rootDir: f.root,
180
+ apkPath: 'fixture.apk', timeoutMinutes: 20, ...(options.expired ? { deadline: 1 } : {}) }), message);
181
+ assert.equal(f.read('baselineProfiles/baseline-prof.txt'), 'original baseline');
182
+ assert.equal(f.read('baselineProfiles/startup-prof.txt'), 'original startup');
183
+ if (host.commands.some(args => args.includes('WRITE_SKIP_FILE'))) {
184
+ assert.ok(host.commands.some(args => args.includes('DELETE_SKIP_FILE')));
185
+ }
186
+ assert.equal(host.proc.listenerCount('SIGINT'), 0);
187
+ assert.equal(host.proc.listenerCount('SIGTERM'), 0);
188
+ });
189
+ }