codeplay-common 4.11.37 → 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 (39) hide show
  1. package/README.md +28 -0
  2. package/RELEASE_NOTES.md +13 -13
  3. package/files/buildCodeplay/add-splash-screen.js +1 -1
  4. package/files/buildCodeplay/ensure-current-build.cjs +42 -42
  5. package/files/buildCodeplay/fix-optimize-builld/android-r8-rules.cjs +31 -31
  6. package/files/buildCodeplay/fix-optimize-builld/ffmpeg-jni-rules.cjs +28 -28
  7. package/files/buildCodeplay/fix-optimize-builld/fix-optimize-build.gradle +9 -9
  8. package/files/buildCodeplay/fix-optimize-builld/restore-android-r8-rules.cjs +30 -30
  9. package/files/buildCodeplay/huawei-privacy-entry.js +135 -135
  10. package/files/buildCodeplay/huawei-privacy.css +22 -22
  11. package/files/buildCodeplay/ios-ad-consent.cjs +56 -56
  12. package/files/buildCodeplay/ios-emi-admob-modification.js +25 -25
  13. package/files/buildCodeplay/newly added.txt +89 -89
  14. package/files/buildCodeplay/non-google-billing.pro +3 -3
  15. package/files/buildCodeplay/release-sync.config.json +4 -4
  16. package/files/buildCodeplay/remove-force-kotlin-disable.js +43 -43
  17. package/files/buildCodeplay/ruads.cjs +220 -220
  18. package/files/buildCodeplay/saf-mediastore-dependency.cjs +21 -21
  19. package/files/buildCodeplay/setSplashAnimation.js +2 -2
  20. package/files/buildCodeplay/setup-ruads.cjs +62 -62
  21. package/files/buildCodeplay/splash-setup.cjs +88 -88
  22. package/files/buildCodeplay/store-billing.cjs +43 -43
  23. package/files/buildCodeplay/tests/huawei-live-reload.test.cjs +60 -60
  24. package/files/buildCodeplay/tests/huawei-privacy.test.cjs +49 -49
  25. package/files/scripts-common/collect-startup-profile.js +134 -0
  26. package/files/scripts-common/generate-baseline-profile.js +194 -22
  27. package/files/take-screen-image.js +4414 -4414
  28. package/package.json +1 -1
  29. package/runtime/splash-ready.mjs +52 -52
  30. package/runtime/vk-ads/vk-ad-configuration.json +39 -39
  31. package/scripts/baseline-profile.test.cjs +189 -0
  32. package/scripts/ensure-current-build.test.cjs +76 -76
  33. package/scripts/ios-ad-consent.test.cjs +99 -99
  34. package/scripts/ruads-install.test.cjs +197 -197
  35. package/scripts/ruads-policy.test.cjs +174 -174
  36. package/scripts/saf-mediastore-dependency.test.cjs +44 -44
  37. package/scripts/splash-setup.test.cjs +142 -142
  38. package/scripts/sync-files.js +1 -1
  39. package/scripts/vite-build-settings.test.cjs +93 -93
@@ -1,88 +1,88 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const crypto = require('crypto');
4
- const runtimeImport = "import { hideSplashWhenReady } from 'codeplay-common/runtime/splash-ready.mjs';";
5
- const knownReadyHash = '451fd2e0ca63712e0f771ee0ed03ae5bd3a379f0ca1e75e971cd7acee0802a2b';
6
-
7
- function readSplashOptions(config) {
8
- const options = config.plugins?.CodeplaySplashScreen || {};
9
- const duration = options.exitAnimationDuration ?? 1000;
10
- const timeout = options.readinessTimeout ?? 8000;
11
- const imageSelector = options.readyImageSelector ?? '[data-splash-ready], .t-film-art img';
12
- if (!Number.isInteger(duration) || duration < 0 || duration > 10000) throw new Error('CodeplaySplashScreen.exitAnimationDuration must be an integer from0 to10000.');
13
- if (!Number.isInteger(timeout) || timeout < 1 || timeout > 60000) throw new Error('CodeplaySplashScreen.readinessTimeout must be an integer from1 to60000.');
14
- if (typeof imageSelector !== 'string') throw new Error('CodeplaySplashScreen.readyImageSelector must be a string.');
15
- if (options.migrateLegacyReadiness !== undefined && typeof options.migrateLegacyReadiness !== 'boolean') throw new Error('CodeplaySplashScreen.migrateLegacyReadiness must be boolean.');
16
- return { duration, timeout, imageSelector, migrateLegacy: options.migrateLegacyReadiness === true };
17
- }
18
-
19
- function migrateSplashTheme(content) {
20
- // Repair only the known package default; preserve custom themes and styling.
21
- return content.replace(/(<item\s+name=["']postSplashScreenTheme["']\s*>\s*)@style\/Theme\.AppCompat\.NoActionBar(\s*<\/item>)/g,
22
- '$1@style/Theme.AppCompat.DayNight.NoActionBar$2');
23
- }
24
-
25
- function migrateReadinessSource(source, options) {
26
- if (!/\b(?:var|let|const)\s+capacitorApp\s*=/.test(source)) return { source, status: 'unsupported' };
27
- const handler = / handleSplashscreen:\s*function\s*\(\)\s*\{([\s\S]*?)\r?\n \},/;
28
- const match = source.match(handler);
29
- if (!match) return { source, status: 'unsupported' };
30
- const body = match[1].replace(/\s+/g, '');
31
- const isReady = crypto.createHash('sha256').update(body).digest('hex') === knownReadyHash;
32
- const isManaged = /^if\(!window\.Capacitor\)return;returnhideSplashWhenReady\(\{f7:capacitorApp\.f7,hide:\(\)=>SplashScreen\.hide\(\),imageSelector:"(?:\\.|[^"\\])*",timeout:\d+\}\);$/.test(body)
33
- && source.includes(runtimeImport);
34
- const isLegacy = body === "if(!window.Capacitor)return;setTimeout(()=>{if(window.Capacitor.Plugins?.SplashScreen)window.Capacitor.Plugins.SplashScreen.hide();},2000);"
35
- || body === "if(!window.Capacitor)return;setTimeout(()=>{if(window.Capacitor.Plugins&&window.Capacitor.Plugins.SplashScreen){window.Capacitor.Plugins.SplashScreen.hide();}},2000);";
36
- if (!isReady && !isManaged && !(isLegacy && options.migrateLegacy)) return { source, status: isLegacy ? 'opt-in-required' : 'custom-preserved' };
37
- const newline = source.includes('\r\n') ? '\r\n' : '\n';
38
- const method = [
39
- ' handleSplashscreen: function () {',
40
- ' if (!window.Capacitor) return;',
41
- ' return hideSplashWhenReady({',
42
- ' f7: capacitorApp.f7,',
43
- ' hide: () => SplashScreen.hide(),',
44
- ` imageSelector: ${JSON.stringify(options.imageSelector)},`,
45
- ` timeout: ${options.timeout}`, ' });', ' },'
46
- ].join(newline);
47
- let updated = source.replace(handler, () => method);
48
- if (!updated.includes(runtimeImport)) updated = runtimeImport + newline + updated;
49
- if (!/import\s*\{[^}]*\bSplashScreen\b[^}]*\}\s*from\s*['"]@capacitor\/splash-screen['"]/.test(updated)) {
50
- updated = "import { SplashScreen } from '@capacitor/splash-screen';" + newline + updated;
51
- }
52
- return { source: updated, status: 'managed' };
53
- }
54
-
55
- function syncSplashSetup(projectRoot, { log = console.log } = {}) {
56
- const configPath = path.join(projectRoot, 'capacitor.config.json');
57
- if (!fs.existsSync(configPath)) return;
58
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
59
- const options = readSplashOptions(config);
60
- const theme = path.join(projectRoot, 'buildCodeplay/splashxml/codeplay_splashScreen.xml');
61
- if (fs.existsSync(theme)) {
62
- const content = fs.readFileSync(theme, 'utf8');
63
- const updated = migrateSplashTheme(content);
64
- if (updated !== content) { fs.writeFileSync(theme, updated); log('codeplay-common: repaired legacy splash DayNight theme template; Android sync applies it.'); }
65
- }
66
- const app = path.join(projectRoot, 'src/js/capacitor-app.js');
67
- if (!fs.existsSync(app)) return;
68
- const source = fs.readFileSync(app, 'utf8');
69
- const migrated = migrateReadinessSource(source, options);
70
- if (migrated.status === 'managed') {
71
- if (source !== migrated.source) {
72
- const launch = config.plugins?.SplashScreen;
73
- if (launch?.launchAutoHide !== true || !(launch.launchShowDuration >= options.timeout)) {
74
- log('codeplay-common: readiness migration skipped; set SplashScreen.launchAutoHide=true and launchShowDuration>=readinessTimeout for the native fallback.');
75
- return;
76
- }
77
- const dependency = JSON.parse(fs.readFileSync(path.join(projectRoot, 'package.json'), 'utf8'));
78
- if (!dependency.dependencies?.['@capacitor/splash-screen'] && !dependency.devDependencies?.['@capacitor/splash-screen']) {
79
- log('codeplay-common: readiness migration skipped; @capacitor/splash-screen must be installed.');
80
- return;
81
- }
82
- fs.writeFileSync(app, migrated.source);
83
- log('codeplay-common: connected supported startup handler to shared splash readiness.');
84
- }
85
- } else log(`codeplay-common: splash readiness ${migrated.status}; app startup preserved. See shared splash setup in README.`);
86
- }
87
-
88
- module.exports = { readSplashOptions, migrateSplashTheme, migrateReadinessSource, syncSplashSetup };
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const crypto = require('crypto');
4
+ const runtimeImport = "import { hideSplashWhenReady } from 'codeplay-common/runtime/splash-ready.mjs';";
5
+ const knownReadyHash = '451fd2e0ca63712e0f771ee0ed03ae5bd3a379f0ca1e75e971cd7acee0802a2b';
6
+
7
+ function readSplashOptions(config) {
8
+ const options = config.plugins?.CodeplaySplashScreen || {};
9
+ const duration = options.exitAnimationDuration ?? 1000;
10
+ const timeout = options.readinessTimeout ?? 8000;
11
+ const imageSelector = options.readyImageSelector ?? '[data-splash-ready], .t-film-art img';
12
+ if (!Number.isInteger(duration) || duration < 0 || duration > 10000) throw new Error('CodeplaySplashScreen.exitAnimationDuration must be an integer from0 to10000.');
13
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > 60000) throw new Error('CodeplaySplashScreen.readinessTimeout must be an integer from1 to60000.');
14
+ if (typeof imageSelector !== 'string') throw new Error('CodeplaySplashScreen.readyImageSelector must be a string.');
15
+ if (options.migrateLegacyReadiness !== undefined && typeof options.migrateLegacyReadiness !== 'boolean') throw new Error('CodeplaySplashScreen.migrateLegacyReadiness must be boolean.');
16
+ return { duration, timeout, imageSelector, migrateLegacy: options.migrateLegacyReadiness === true };
17
+ }
18
+
19
+ function migrateSplashTheme(content) {
20
+ // Repair only the known package default; preserve custom themes and styling.
21
+ return content.replace(/(<item\s+name=["']postSplashScreenTheme["']\s*>\s*)@style\/Theme\.AppCompat\.NoActionBar(\s*<\/item>)/g,
22
+ '$1@style/Theme.AppCompat.DayNight.NoActionBar$2');
23
+ }
24
+
25
+ function migrateReadinessSource(source, options) {
26
+ if (!/\b(?:var|let|const)\s+capacitorApp\s*=/.test(source)) return { source, status: 'unsupported' };
27
+ const handler = / handleSplashscreen:\s*function\s*\(\)\s*\{([\s\S]*?)\r?\n \},/;
28
+ const match = source.match(handler);
29
+ if (!match) return { source, status: 'unsupported' };
30
+ const body = match[1].replace(/\s+/g, '');
31
+ const isReady = crypto.createHash('sha256').update(body).digest('hex') === knownReadyHash;
32
+ const isManaged = /^if\(!window\.Capacitor\)return;returnhideSplashWhenReady\(\{f7:capacitorApp\.f7,hide:\(\)=>SplashScreen\.hide\(\),imageSelector:"(?:\\.|[^"\\])*",timeout:\d+\}\);$/.test(body)
33
+ && source.includes(runtimeImport);
34
+ const isLegacy = body === "if(!window.Capacitor)return;setTimeout(()=>{if(window.Capacitor.Plugins?.SplashScreen)window.Capacitor.Plugins.SplashScreen.hide();},2000);"
35
+ || body === "if(!window.Capacitor)return;setTimeout(()=>{if(window.Capacitor.Plugins&&window.Capacitor.Plugins.SplashScreen){window.Capacitor.Plugins.SplashScreen.hide();}},2000);";
36
+ if (!isReady && !isManaged && !(isLegacy && options.migrateLegacy)) return { source, status: isLegacy ? 'opt-in-required' : 'custom-preserved' };
37
+ const newline = source.includes('\r\n') ? '\r\n' : '\n';
38
+ const method = [
39
+ ' handleSplashscreen: function () {',
40
+ ' if (!window.Capacitor) return;',
41
+ ' return hideSplashWhenReady({',
42
+ ' f7: capacitorApp.f7,',
43
+ ' hide: () => SplashScreen.hide(),',
44
+ ` imageSelector: ${JSON.stringify(options.imageSelector)},`,
45
+ ` timeout: ${options.timeout}`, ' });', ' },'
46
+ ].join(newline);
47
+ let updated = source.replace(handler, () => method);
48
+ if (!updated.includes(runtimeImport)) updated = runtimeImport + newline + updated;
49
+ if (!/import\s*\{[^}]*\bSplashScreen\b[^}]*\}\s*from\s*['"]@capacitor\/splash-screen['"]/.test(updated)) {
50
+ updated = "import { SplashScreen } from '@capacitor/splash-screen';" + newline + updated;
51
+ }
52
+ return { source: updated, status: 'managed' };
53
+ }
54
+
55
+ function syncSplashSetup(projectRoot, { log = console.log } = {}) {
56
+ const configPath = path.join(projectRoot, 'capacitor.config.json');
57
+ if (!fs.existsSync(configPath)) return;
58
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
59
+ const options = readSplashOptions(config);
60
+ const theme = path.join(projectRoot, 'buildCodeplay/splashxml/codeplay_splashScreen.xml');
61
+ if (fs.existsSync(theme)) {
62
+ const content = fs.readFileSync(theme, 'utf8');
63
+ const updated = migrateSplashTheme(content);
64
+ if (updated !== content) { fs.writeFileSync(theme, updated); log('codeplay-common: repaired legacy splash DayNight theme template; Android sync applies it.'); }
65
+ }
66
+ const app = path.join(projectRoot, 'src/js/capacitor-app.js');
67
+ if (!fs.existsSync(app)) return;
68
+ const source = fs.readFileSync(app, 'utf8');
69
+ const migrated = migrateReadinessSource(source, options);
70
+ if (migrated.status === 'managed') {
71
+ if (source !== migrated.source) {
72
+ const launch = config.plugins?.SplashScreen;
73
+ if (launch?.launchAutoHide !== true || !(launch.launchShowDuration >= options.timeout)) {
74
+ log('codeplay-common: readiness migration skipped; set SplashScreen.launchAutoHide=true and launchShowDuration>=readinessTimeout for the native fallback.');
75
+ return;
76
+ }
77
+ const dependency = JSON.parse(fs.readFileSync(path.join(projectRoot, 'package.json'), 'utf8'));
78
+ if (!dependency.dependencies?.['@capacitor/splash-screen'] && !dependency.devDependencies?.['@capacitor/splash-screen']) {
79
+ log('codeplay-common: readiness migration skipped; @capacitor/splash-screen must be installed.');
80
+ return;
81
+ }
82
+ fs.writeFileSync(app, migrated.source);
83
+ log('codeplay-common: connected supported startup handler to shared splash readiness.');
84
+ }
85
+ } else log(`codeplay-common: splash readiness ${migrated.status}; app startup preserved. See shared splash setup in README.`);
86
+ }
87
+
88
+ module.exports = { readSplashOptions, migrateSplashTheme, migrateReadinessSource, syncSplashSetup };
@@ -1,43 +1,43 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
-
4
- const start = '// BEGIN CODEPLAY NON-GOOGLE STORE BILLING';
5
- const end = '// END CODEPLAY NON-GOOGLE STORE BILLING';
6
- const block = `${start}
7
- configurations.configureEach {
8
- exclude group: 'com.android.billingclient'
9
- }
10
- android.buildTypes.configureEach {
11
- proguardFile file('../../buildCodeplay/non-google-billing.pro')
12
- }
13
- ${end}`;
14
-
15
- function syncStoreBillingPolicy(projectRoot, storeId, platform = 'android') {
16
- if (platform !== 'android') return false;
17
- const excluded = [4, 10].includes(Number(storeId));
18
- const gradle = path.join(projectRoot, 'android/app/build.gradle');
19
- if (!fs.existsSync(gradle)) return false;
20
- const original = fs.readFileSync(gradle, 'utf8');
21
- const newline = original.includes('\r\n') ? '\r\n' : '\n';
22
- const clean = original.replace(new RegExp(`${start}[\\s\\S]*?${end}\\r?\\n?`, 'g'), '');
23
- const updated = excluded
24
- ? `${clean.trimEnd()}${newline}${newline}${block.replaceAll('\n', newline)}${newline}`
25
- : clean;
26
- let changed = updated !== original;
27
- if (changed) fs.writeFileSync(gradle, updated);
28
-
29
- // The excluded library supplies its own permission. Also remove any explicit
30
- // app declaration; other permissions and supported-store billing stay intact.
31
- const manifest = path.join(projectRoot, 'android/app/src/main/AndroidManifest.xml');
32
- if (excluded && fs.existsSync(manifest)) {
33
- const current = fs.readFileSync(manifest, 'utf8');
34
- const next = current.replace(/^[ \t]*<uses-permission\b(?=[^>]*\bandroid:name\s*=\s*(['"])com\.android\.vending\.BILLING\1)[^>]*\/\s*>[ \t]*(?:\r?\n)?/gm, '');
35
- if (next !== current) {
36
- fs.writeFileSync(manifest, next);
37
- changed = true;
38
- }
39
- }
40
- return changed;
41
- }
42
-
43
- module.exports = { syncStoreBillingPolicy };
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ const start = '// BEGIN CODEPLAY NON-GOOGLE STORE BILLING';
5
+ const end = '// END CODEPLAY NON-GOOGLE STORE BILLING';
6
+ const block = `${start}
7
+ configurations.configureEach {
8
+ exclude group: 'com.android.billingclient'
9
+ }
10
+ android.buildTypes.configureEach {
11
+ proguardFile file('../../buildCodeplay/non-google-billing.pro')
12
+ }
13
+ ${end}`;
14
+
15
+ function syncStoreBillingPolicy(projectRoot, storeId, platform = 'android') {
16
+ if (platform !== 'android') return false;
17
+ const excluded = [4, 10].includes(Number(storeId));
18
+ const gradle = path.join(projectRoot, 'android/app/build.gradle');
19
+ if (!fs.existsSync(gradle)) return false;
20
+ const original = fs.readFileSync(gradle, 'utf8');
21
+ const newline = original.includes('\r\n') ? '\r\n' : '\n';
22
+ const clean = original.replace(new RegExp(`${start}[\\s\\S]*?${end}\\r?\\n?`, 'g'), '');
23
+ const updated = excluded
24
+ ? `${clean.trimEnd()}${newline}${newline}${block.replaceAll('\n', newline)}${newline}`
25
+ : clean;
26
+ let changed = updated !== original;
27
+ if (changed) fs.writeFileSync(gradle, updated);
28
+
29
+ // The excluded library supplies its own permission. Also remove any explicit
30
+ // app declaration; other permissions and supported-store billing stay intact.
31
+ const manifest = path.join(projectRoot, 'android/app/src/main/AndroidManifest.xml');
32
+ if (excluded && fs.existsSync(manifest)) {
33
+ const current = fs.readFileSync(manifest, 'utf8');
34
+ const next = current.replace(/^[ \t]*<uses-permission\b(?=[^>]*\bandroid:name\s*=\s*(['"])com\.android\.vending\.BILLING\1)[^>]*\/\s*>[ \t]*(?:\r?\n)?/gm, '');
35
+ if (next !== current) {
36
+ fs.writeFileSync(manifest, next);
37
+ changed = true;
38
+ }
39
+ }
40
+ return changed;
41
+ }
42
+
43
+ module.exports = { syncStoreBillingPolicy };
@@ -1,60 +1,60 @@
1
- const assert = require('node:assert/strict');
2
- const fs = require('node:fs');
3
- const path = require('node:path');
4
- const { pathToFileURL } = require('node:url');
5
- const { syncHuaweiPrivacy } = require('../huawei-privacy.cjs');
6
- const { syncRuAdsSetup } = require('../setup-ruads.cjs');
7
-
8
- async function main() {
9
- const appRoot = path.resolve(process.argv[2] || '');
10
- const { createServer } = await import(pathToFileURL(path.join(appRoot, 'node_modules/vite/dist/node/index.js')).href);
11
- const tempRoot = path.join(appRoot, 'agent-temp');
12
- fs.mkdirSync(tempRoot, { recursive: true });
13
- const root = fs.mkdtempSync(path.join(tempRoot, 'huawei-live-reload-'));
14
- const previous = process.cwd();
15
- let server;
16
- const write = (file, content) => {
17
- const target = path.join(root, file);
18
- fs.mkdirSync(path.dirname(target), { recursive: true });
19
- fs.writeFileSync(target, content);
20
- };
21
- try {
22
- write('package.json', '{"name":"huawei-fixture","type":"module"}');
23
- write('capacitor.config.json', '{"appName":"Fixture","android":{"APP_UNIQUE_ID":5}}');
24
- write('android/app/src/main/AndroidManifest.xml', '<manifest><application></application></manifest>');
25
- write('src/index.html', '<html><body><script type="module" src="./js/app.js"></script></body></html>');
26
- write('src/js/app.js', 'export const ready = true;');
27
- write('buildCodeplay/huawei-privacy-entry.js', 'export function startHuaweiPrivacy() {}');
28
- write('buildCodeplay/ruads.cjs', fs.readFileSync(path.join(__dirname, '../ruads.cjs'), 'utf8'));
29
- write('vite.config.mjs', 'export default { resolve: { alias: {} } };');
30
- syncHuaweiPrivacy(root, 4);
31
- syncRuAdsSetup(root);
32
- process.chdir(root);
33
- server = await createServer({
34
- configFile: path.join(root, 'vite.config.mjs'),
35
- root: path.join(root, 'src'),
36
- cacheDir: path.join(root, 'cache'),
37
- optimizeDeps: { noDiscovery: true, include: [] },
38
- server: { host: '127.0.0.1', port: 0, open: false },
39
- });
40
- await server.listen();
41
- const origin = 'http://127.0.0.1:' + server.httpServer.address().port;
42
- const response = await fetch(origin + '/buildCodeplay/huawei-privacy-generated.js');
43
- assert.equal(response.status, 200);
44
- const source = await response.text();
45
- assert.match(source, /startHuaweiPrivacy/);
46
- assert.doesNotMatch(source, /<html>/);
47
- const helper = source.match(/from\s+["']([^"']*huawei-privacy-entry\.js[^"']*)["']/)?.[1];
48
- assert.ok(helper);
49
- const dependency = await fetch(new URL(helper, origin));
50
- assert.equal(dependency.status, 200);
51
- assert.match(await dependency.text(), /export function startHuaweiPrivacy/);
52
- console.log('Huawei generated module and relative helper load through the package Vite mapping.');
53
- } finally {
54
- if (server) await server.close();
55
- process.chdir(previous);
56
- assert.equal(path.dirname(path.resolve(root)), path.resolve(tempRoot));
57
- fs.rmSync(root, { recursive: true, force: true });
58
- }
59
- }
60
- main().catch(error => { console.error(error); process.exitCode = 1; });
1
+ const assert = require('node:assert/strict');
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const { pathToFileURL } = require('node:url');
5
+ const { syncHuaweiPrivacy } = require('../huawei-privacy.cjs');
6
+ const { syncRuAdsSetup } = require('../setup-ruads.cjs');
7
+
8
+ async function main() {
9
+ const appRoot = path.resolve(process.argv[2] || '');
10
+ const { createServer } = await import(pathToFileURL(path.join(appRoot, 'node_modules/vite/dist/node/index.js')).href);
11
+ const tempRoot = path.join(appRoot, 'agent-temp');
12
+ fs.mkdirSync(tempRoot, { recursive: true });
13
+ const root = fs.mkdtempSync(path.join(tempRoot, 'huawei-live-reload-'));
14
+ const previous = process.cwd();
15
+ let server;
16
+ const write = (file, content) => {
17
+ const target = path.join(root, file);
18
+ fs.mkdirSync(path.dirname(target), { recursive: true });
19
+ fs.writeFileSync(target, content);
20
+ };
21
+ try {
22
+ write('package.json', '{"name":"huawei-fixture","type":"module"}');
23
+ write('capacitor.config.json', '{"appName":"Fixture","android":{"APP_UNIQUE_ID":5}}');
24
+ write('android/app/src/main/AndroidManifest.xml', '<manifest><application></application></manifest>');
25
+ write('src/index.html', '<html><body><script type="module" src="./js/app.js"></script></body></html>');
26
+ write('src/js/app.js', 'export const ready = true;');
27
+ write('buildCodeplay/huawei-privacy-entry.js', 'export function startHuaweiPrivacy() {}');
28
+ write('buildCodeplay/ruads.cjs', fs.readFileSync(path.join(__dirname, '../ruads.cjs'), 'utf8'));
29
+ write('vite.config.mjs', 'export default { resolve: { alias: {} } };');
30
+ syncHuaweiPrivacy(root, 4);
31
+ syncRuAdsSetup(root);
32
+ process.chdir(root);
33
+ server = await createServer({
34
+ configFile: path.join(root, 'vite.config.mjs'),
35
+ root: path.join(root, 'src'),
36
+ cacheDir: path.join(root, 'cache'),
37
+ optimizeDeps: { noDiscovery: true, include: [] },
38
+ server: { host: '127.0.0.1', port: 0, open: false },
39
+ });
40
+ await server.listen();
41
+ const origin = 'http://127.0.0.1:' + server.httpServer.address().port;
42
+ const response = await fetch(origin + '/buildCodeplay/huawei-privacy-generated.js');
43
+ assert.equal(response.status, 200);
44
+ const source = await response.text();
45
+ assert.match(source, /startHuaweiPrivacy/);
46
+ assert.doesNotMatch(source, /<html>/);
47
+ const helper = source.match(/from\s+["']([^"']*huawei-privacy-entry\.js[^"']*)["']/)?.[1];
48
+ assert.ok(helper);
49
+ const dependency = await fetch(new URL(helper, origin));
50
+ assert.equal(dependency.status, 200);
51
+ assert.match(await dependency.text(), /export function startHuaweiPrivacy/);
52
+ console.log('Huawei generated module and relative helper load through the package Vite mapping.');
53
+ } finally {
54
+ if (server) await server.close();
55
+ process.chdir(previous);
56
+ assert.equal(path.dirname(path.resolve(root)), path.resolve(tempRoot));
57
+ fs.rmSync(root, { recursive: true, force: true });
58
+ }
59
+ }
60
+ main().catch(error => { console.error(error); process.exitCode = 1; });
@@ -1,49 +1,49 @@
1
- const assert = require('node:assert/strict');
2
- const fs = require('node:fs');
3
- const os = require('node:os');
4
- const path = require('node:path');
5
- const { syncHuaweiPrivacy } = require('../huawei-privacy.cjs');
6
-
7
- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codeplay-huawei-privacy-'));
8
- const indexPath = path.join(root, 'src/index.html');
9
- const manifestPath = path.join(root, 'android/app/src/main/AndroidManifest.xml');
10
- const appEntry = path.join(root, 'src/js/app.js');
11
- const wrapperPath = path.join(root, 'buildCodeplay/huawei-privacy-generated.js');
12
-
13
- try {
14
- for (const file of [indexPath, manifestPath, appEntry, wrapperPath]) fs.mkdirSync(path.dirname(file), { recursive: true });
15
- const index = '<html><body><div id="app"></div><script type="module" src="./js/app.js"></script></body></html>\n';
16
- const manifest = '<manifest><application><activity android:name=".MainActivity" /></application></manifest>\n';
17
- fs.writeFileSync(indexPath, index);
18
- fs.writeFileSync(manifestPath, manifest);
19
- fs.writeFileSync(appEntry, 'document.body.dataset.ready = "yes";\n');
20
- fs.writeFileSync(path.join(root, 'capacitor.config.json'), JSON.stringify({ appName: 'Test App', android: { APP_UNIQUE_ID: 2 } }));
21
-
22
- syncHuaweiPrivacy(root, 1);
23
- assert.equal(fs.readFileSync(indexPath, 'utf8'), index);
24
- assert.equal(fs.readFileSync(manifestPath, 'utf8'), manifest);
25
-
26
- const existing = '<manifest><application>\n <meta-data android:name="firebase_analytics_collection_enabled" android:value="true" />\n <activity android:name=".MainActivity" /></application></manifest>\n';
27
- fs.writeFileSync(manifestPath, existing);
28
- syncHuaweiPrivacy(root, 4);
29
- assert.match(fs.readFileSync(manifestPath, 'utf8'), /firebase_analytics_collection_enabled" android:value="false"/);
30
- syncHuaweiPrivacy(root, 1);
31
- assert.equal(fs.readFileSync(manifestPath, 'utf8'), existing);
32
- fs.writeFileSync(manifestPath, manifest);
33
-
34
- syncHuaweiPrivacy(root, 4);
35
- const huaweiIndex = fs.readFileSync(indexPath, 'utf8');
36
- const huaweiManifest = fs.readFileSync(manifestPath, 'utf8');
37
- assert.match(huaweiIndex, /huawei-privacy-generated\.js/);
38
- assert.match(huaweiManifest, /firebase_analytics_collection_enabled" android:value="false"/);
39
- assert.match(fs.readFileSync(wrapperPath, 'utf8'), /import\("\.\.\/src\/js\/app\.js"\)/);
40
- syncHuaweiPrivacy(root, 4);
41
- assert.equal(fs.readFileSync(indexPath, 'utf8'), huaweiIndex);
42
- assert.equal(fs.readFileSync(manifestPath, 'utf8'), huaweiManifest);
43
-
44
- syncHuaweiPrivacy(root, 1);
45
- assert.equal(fs.readFileSync(indexPath, 'utf8'), index);
46
- assert.equal(fs.readFileSync(manifestPath, 'utf8'), manifest);
47
- } finally {
48
- fs.rmSync(root, { recursive: true, force: true });
49
- }
1
+ const assert = require('node:assert/strict');
2
+ const fs = require('node:fs');
3
+ const os = require('node:os');
4
+ const path = require('node:path');
5
+ const { syncHuaweiPrivacy } = require('../huawei-privacy.cjs');
6
+
7
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codeplay-huawei-privacy-'));
8
+ const indexPath = path.join(root, 'src/index.html');
9
+ const manifestPath = path.join(root, 'android/app/src/main/AndroidManifest.xml');
10
+ const appEntry = path.join(root, 'src/js/app.js');
11
+ const wrapperPath = path.join(root, 'buildCodeplay/huawei-privacy-generated.js');
12
+
13
+ try {
14
+ for (const file of [indexPath, manifestPath, appEntry, wrapperPath]) fs.mkdirSync(path.dirname(file), { recursive: true });
15
+ const index = '<html><body><div id="app"></div><script type="module" src="./js/app.js"></script></body></html>\n';
16
+ const manifest = '<manifest><application><activity android:name=".MainActivity" /></application></manifest>\n';
17
+ fs.writeFileSync(indexPath, index);
18
+ fs.writeFileSync(manifestPath, manifest);
19
+ fs.writeFileSync(appEntry, 'document.body.dataset.ready = "yes";\n');
20
+ fs.writeFileSync(path.join(root, 'capacitor.config.json'), JSON.stringify({ appName: 'Test App', android: { APP_UNIQUE_ID: 2 } }));
21
+
22
+ syncHuaweiPrivacy(root, 1);
23
+ assert.equal(fs.readFileSync(indexPath, 'utf8'), index);
24
+ assert.equal(fs.readFileSync(manifestPath, 'utf8'), manifest);
25
+
26
+ const existing = '<manifest><application>\n <meta-data android:name="firebase_analytics_collection_enabled" android:value="true" />\n <activity android:name=".MainActivity" /></application></manifest>\n';
27
+ fs.writeFileSync(manifestPath, existing);
28
+ syncHuaweiPrivacy(root, 4);
29
+ assert.match(fs.readFileSync(manifestPath, 'utf8'), /firebase_analytics_collection_enabled" android:value="false"/);
30
+ syncHuaweiPrivacy(root, 1);
31
+ assert.equal(fs.readFileSync(manifestPath, 'utf8'), existing);
32
+ fs.writeFileSync(manifestPath, manifest);
33
+
34
+ syncHuaweiPrivacy(root, 4);
35
+ const huaweiIndex = fs.readFileSync(indexPath, 'utf8');
36
+ const huaweiManifest = fs.readFileSync(manifestPath, 'utf8');
37
+ assert.match(huaweiIndex, /huawei-privacy-generated\.js/);
38
+ assert.match(huaweiManifest, /firebase_analytics_collection_enabled" android:value="false"/);
39
+ assert.match(fs.readFileSync(wrapperPath, 'utf8'), /import\("\.\.\/src\/js\/app\.js"\)/);
40
+ syncHuaweiPrivacy(root, 4);
41
+ assert.equal(fs.readFileSync(indexPath, 'utf8'), huaweiIndex);
42
+ assert.equal(fs.readFileSync(manifestPath, 'utf8'), huaweiManifest);
43
+
44
+ syncHuaweiPrivacy(root, 1);
45
+ assert.equal(fs.readFileSync(indexPath, 'utf8'), index);
46
+ assert.equal(fs.readFileSync(manifestPath, 'utf8'), manifest);
47
+ } finally {
48
+ fs.rmSync(root, { recursive: true, force: true });
49
+ }
@@ -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 };