codeplay-common 4.11.41-alpha.0 → 4.11.41-alpha.3

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 (29) hide show
  1. package/README.md +42 -19
  2. package/files/buildCodeplay/codeplayBeforeBuild.js +22 -6
  3. package/files/buildCodeplay/project-scripts.cjs +2 -0
  4. package/files/patches/catalog/capacitor-admob-nextgen+1.6.0.patch +219 -0
  5. package/files/patches/catalog/capacitor-admob-nextgen+1.6.2-beta.patch +209 -0
  6. package/files/scripts-common/setup-baseline-profile.js +18 -15
  7. package/package.json +3 -3
  8. package/scripts/capacitor-9-migration.test.cjs +174 -0
  9. package/scripts/prepare-capacitor-9.cjs +113 -14
  10. package/scripts/saf-mediastore-dependency.test.cjs +3 -2
  11. package/scripts/squeezeback-config.test.cjs +38 -4
  12. package/scripts/sync-files.js +19 -6
  13. package/migration/capacitor-8-to-9-migration.md +0 -49
  14. package/migration/patches/capacitor-admob-nextgen+1.6.0.patch +0 -10
  15. /package/{migration/patches → files/patches/catalog}/@byteowls+capacitor-filesharer+7.0.0.patch +0 -0
  16. /package/{migration/patches → files/patches/catalog}/@capacitor-community+file-opener+8.0.0.patch +0 -0
  17. /package/{migration/patches → files/patches/catalog}/@capacitor-community+in-app-review+8.0.0.patch +0 -0
  18. /package/{migration/patches → files/patches/catalog}/@capacitor-community+native-audio+8.0.0.patch +0 -0
  19. /package/{migration/patches → files/patches/catalog}/@capacitor-community+play-integrity+8.0.0.patch +0 -0
  20. /package/{migration/patches → files/patches/catalog}/@capacitor-community+privacy-screen+8.0.0.patch +0 -0
  21. /package/{migration/patches → files/patches/catalog}/@capacitor-community+safe-area+7.0.0-alpha.1.patch +0 -0
  22. /package/{migration/patches → files/patches/catalog}/@capacitor-community+speech-recognition+7.0.1.patch +0 -0
  23. /package/{migration/patches → files/patches/catalog}/@capacitor-community+text-to-speech+8.0.0.patch +0 -0
  24. /package/{migration/patches → files/patches/catalog}/@mozartec+capacitor-microphone+7.1.0.patch +0 -0
  25. /package/{migration/patches → files/patches/catalog}/@ottimis+capacitor-volumes+7.0.0.patch +0 -0
  26. /package/{migration/patches → files/patches/catalog}/@whiteguru+capacitor-plugin-media+8.0.1.patch +0 -0
  27. /package/{migration/patches → files/patches/catalog}/capacitor-music-controls-plugin+8.0.0.patch +0 -0
  28. /package/{migration/patches → files/patches/catalog}/capacitor-native-biometric+4.2.2.patch +0 -0
  29. /package/{migration/patches → files/patches/catalog}/capacitor-voice-recorder+7.0.6.patch +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codeplay-common",
3
- "version": "4.11.41-alpha.0",
3
+ "version": "4.11.41-alpha.3",
4
4
  "description": "Common build scripts and files",
5
5
  "scripts": {
6
6
  "postinstall": "node scripts/sync-files.js",
@@ -9,6 +9,7 @@
9
9
  },
10
10
  "dependencies": {
11
11
  "adm-zip": "^0.6.1",
12
+ "patch-package": "^8.0.1",
12
13
  "plist": "^3.1.0",
13
14
  "terser": "^5.51.4"
14
15
  },
@@ -25,7 +26,6 @@
25
26
  "CHANGELOG.md",
26
27
  "RELEASE_NOTES.md",
27
28
  "LICENSE",
28
- "runtime/",
29
- "migration/"
29
+ "runtime/"
30
30
  ]
31
31
  }
@@ -0,0 +1,174 @@
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 os = require('node:os');
6
+ const { execFileSync } = require('node:child_process');
7
+ const { prepare } = require('./prepare-capacitor-9.cjs');
8
+ const { install } = require('./sync-files.js');
9
+
10
+ function fixture(t, coreVersion) {
11
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codeplay-cap9-'));
12
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
13
+ const write = (name, value) => {
14
+ const target = path.join(root, name);
15
+ fs.mkdirSync(path.dirname(target), { recursive: true });
16
+ fs.writeFileSync(target, typeof value === 'string' || Buffer.isBuffer(value) ? value : JSON.stringify(value, null, 2));
17
+ };
18
+ write('package.json', {
19
+ name: 'migration-fixture',
20
+ scripts: {
21
+ 'capacitor:sync:after': 'node buildCodeplay/setSplashAnimation.js && node scripts-common/run-codeplay-sync-after.js',
22
+ 'legacy-only': 'node buildCodeplay/setSplashAnimation.js',
23
+ },
24
+ });
25
+ write('node_modules/@capacitor/core/package.json', { version: coreVersion });
26
+ return { root, write, read: name => fs.readFileSync(path.join(root, name), 'utf8') };
27
+ }
28
+
29
+ function writeAdmobPatchPreimage(f) {
30
+ const patch = fs.readFileSync(path.resolve(__dirname, '../files/patches/catalog/capacitor-admob-nextgen+1.6.2-beta.patch'), 'utf8');
31
+ let file;
32
+ let lines = [];
33
+ let oldLine = -1;
34
+ const flush = () => { if (file) f.write(file, lines.map(line => line ?? '').join('\n') + '\n'); };
35
+ for (const line of patch.split('\n')) {
36
+ const next = line.match(/^diff --git a\/(node_modules\/[^ ]+) b\//);
37
+ if (next) {
38
+ flush();
39
+ file = next[1];
40
+ lines = [];
41
+ oldLine = -1;
42
+ continue;
43
+ }
44
+ const hunk = line.match(/^@@ -(\d+)(?:,\d+)? \+/);
45
+ if (hunk) { oldLine = Number(hunk[1]) - 1; continue; }
46
+ if (oldLine >= 0 && (line.startsWith(' ') || line.startsWith('-'))) lines[oldLine++] = line.slice(1);
47
+ }
48
+ flush();
49
+ f.write('node_modules/capacitor-admob-nextgen/android/src/main/java/com/emi/plugins/admob/AdMobNextGenPlugin.java',
50
+ 'call.getData().has("tagForChildDirectedTreatment");\ncall.getData().has("tagForUnderAgeOfConsent");\n');
51
+ }
52
+
53
+ test('Capacitor 8 preparation is a no-op', t => {
54
+ const f = fixture(t, '8.6.2');
55
+ const before = f.read('package.json');
56
+ assert.equal(prepare(f.root, 'if-cap9').apply, false);
57
+ assert.equal(f.read('package.json'), before);
58
+ });
59
+
60
+ test('Capacitor 9 preparation removes only the obsolete splash writer', t => {
61
+ const f = fixture(t, '9.0.0');
62
+ for (let attempt = 0; attempt < 2; attempt += 1) prepare(f.root, 'if-cap9');
63
+ const scripts = JSON.parse(f.read('package.json')).scripts;
64
+ assert.equal(scripts['capacitor:sync:after'], 'node scripts-common/run-codeplay-sync-after.js');
65
+ assert.equal(scripts['legacy-only'], undefined);
66
+ });
67
+
68
+ test('installing codeplay-common into a Capacitor 9 app removes the splash hook', t => {
69
+ const f = fixture(t, '9.0.0');
70
+ f.write('package.json', {
71
+ name: 'migration-fixture', dependencies: { '@capacitor/core': '^9.0.0' },
72
+ scripts: { 'capacitor:sync:after': 'node buildCodeplay/setSplashAnimation.js && node scripts-common/run-codeplay-sync-after.js' },
73
+ });
74
+ f.write('capacitor.config.json', { appId: 'org.example.app', appName: 'Fixture', webDir: 'www' });
75
+ install({ projectRoot: f.root });
76
+ const scripts = JSON.parse(f.read('package.json')).scripts;
77
+ assert.equal(scripts['capacitor:sync:after'], 'node scripts-common/run-codeplay-sync-after.js');
78
+ assert.match(scripts['capacitor:sync:before'], /prepare-capacitor-9\.cjs --apply-if-cap9/);
79
+ });
80
+
81
+ test('beta AdMob selects the banner/inset patch without the upstream API fix', t => {
82
+ const f = fixture(t, '9.0.0');
83
+ f.write('node_modules/capacitor-admob-nextgen/package.json', { version: '1.6.2-beta' });
84
+ const result = prepare(f.root);
85
+ assert.ok(result.selected.includes('capacitor-admob-nextgen+1.6.2-beta.patch'));
86
+ const patch = fs.readFileSync(path.resolve(__dirname, '../files/patches/catalog/capacitor-admob-nextgen+1.6.2-beta.patch'), 'utf8');
87
+ assert.match(patch, /getEffectiveSystemInset/);
88
+ assert.doesNotMatch(patch, /hasOption\(/);
89
+ });
90
+
91
+ for (const version of ['1.6.2', '1.6.3-beta', '1.7.0']) {
92
+ test(`AdMob ${version} without a reviewed inset patch stops migration`, t => {
93
+ const f = fixture(t, '9.0.0');
94
+ f.write('node_modules/capacitor-admob-nextgen/package.json', { version });
95
+ assert.throws(() => prepare(f.root, 'if-cap9'), /API or banner\/inset source differs/);
96
+ });
97
+ }
98
+
99
+ test('newer AdMob reuses the inset patch when every Java hunk still fits', t => {
100
+ const f = fixture(t, '9.0.0');
101
+ f.write('node_modules/capacitor-admob-nextgen/package.json', { version: '1.6.3' });
102
+ writeAdmobPatchPreimage(f);
103
+ const result = prepare(f.root, 'if-cap9');
104
+ assert.ok(result.selected.includes('capacitor-admob-nextgen+1.6.3.patch'));
105
+ assert.match(result.review.join(' '), /Reused the tested banner\/inset patch/);
106
+ assert.ok(fs.existsSync(path.join(f.root, 'patches/active/capacitor-admob-nextgen+1.6.3.patch')));
107
+ assert.match(f.read('node_modules/capacitor-admob-nextgen/android/src/main/java/com/emi/plugins/admob/banner/BannerExecutor.java'), /getEffectiveSystemInset/);
108
+ assert.ok(prepare(f.root, 'if-cap9').selected.includes('capacitor-admob-nextgen+1.6.3.patch'));
109
+ });
110
+
111
+ test('newer AdMob replaces the known beta patch after source verification', t => {
112
+ const f = fixture(t, '9.0.0');
113
+ f.write('node_modules/capacitor-admob-nextgen/package.json', { version: '1.6.3' });
114
+ writeAdmobPatchPreimage(f);
115
+ const oldName = 'capacitor-admob-nextgen+1.6.2-beta.patch';
116
+ f.write(`patches/active/${oldName}`, fs.readFileSync(path.resolve(__dirname, '../files/patches/catalog', oldName)));
117
+ prepare(f.root, 'if-cap9');
118
+ assert.equal(fs.existsSync(path.join(f.root, 'patches/active', oldName)), false);
119
+ assert.ok(fs.existsSync(path.join(f.root, 'patches/active/capacitor-admob-nextgen+1.6.3.patch')));
120
+ });
121
+
122
+ test('newer AdMob stops when a banner source line changes', t => {
123
+ const f = fixture(t, '9.0.0');
124
+ f.write('node_modules/capacitor-admob-nextgen/package.json', { version: '1.6.3' });
125
+ writeAdmobPatchPreimage(f);
126
+ const name = 'node_modules/capacitor-admob-nextgen/android/src/main/java/com/emi/plugins/admob/banner/BannerExecutor.java';
127
+ f.write(name, f.read(name).replace('bannerParams.setMargins(0, 0, 0, systemSafeBottom);', 'bannerParams.setMargins(0, 0, 0, 99);'));
128
+ assert.throws(() => prepare(f.root), /API or banner\/inset source differs/);
129
+ });
130
+
131
+ test('newer AdMob stops if the upstream Capacitor API fix is absent', t => {
132
+ const f = fixture(t, '9.0.0');
133
+ f.write('node_modules/capacitor-admob-nextgen/package.json', { version: '1.6.3' });
134
+ writeAdmobPatchPreimage(f);
135
+ const name = 'node_modules/capacitor-admob-nextgen/android/src/main/java/com/emi/plugins/admob/AdMobNextGenPlugin.java';
136
+ f.write(name, f.read(name).replace('call.getData().has("tagForChildDirectedTreatment")', 'call.hasOption("tagForChildDirectedTreatment")'));
137
+ assert.throws(() => prepare(f.root), /API or banner\/inset source differs/);
138
+ });
139
+
140
+ test('app-specific AdMob patch is retained for manual review', t => {
141
+ const f = fixture(t, '9.0.0');
142
+ f.write('node_modules/capacitor-admob-nextgen/package.json', { version: '1.6.2-beta' });
143
+ const name = 'capacitor-admob-nextgen+1.6.0.patch';
144
+ f.write(`patches/active/${name}`, 'custom banner changes');
145
+ assert.throws(() => prepare(f.root, 'if-cap9'), /unrecognized changes/);
146
+ assert.equal(f.read(`patches/active/${name}`), 'custom banner changes');
147
+ });
148
+
149
+ test('baseline setup upgrades AGP 9 plugin and deduplicates module wiring', t => {
150
+ const f = fixture(t, '9.0.0');
151
+ f.write('capacitor.config.json', { appId: 'org.example.app' });
152
+ f.write('android/build.gradle', "dependencies {\n classpath 'com.android.tools.build:gradle:9.4.1'\n classpath 'androidx.baselineprofile:androidx.baselineprofile.gradle.plugin:1.4.1'\n}\n");
153
+ f.write('android/settings.gradle', "include ':app'\ninclude ':baselineprofile'\nproject(':baselineprofile').projectDir = new File('./baselineprofile/')\ninclude ':baselineprofile'\nproject(':baselineprofile').projectDir = new File('./baselineprofile/')\n");
154
+ f.write('android/app/build.gradle', "apply plugin: 'com.android.application'\napply from: 'capacitor.build.gradle'\ndependencies {\n}\n");
155
+ const script = path.resolve(__dirname, '../files/scripts-common/setup-baseline-profile.js');
156
+ fs.mkdirSync(path.join(f.root, 'scripts-common'), { recursive: true });
157
+ fs.copyFileSync(script, path.join(f.root, 'scripts-common/setup-baseline-profile.js'));
158
+ for (let attempt = 0; attempt < 2; attempt += 1) {
159
+ execFileSync(process.execPath, [path.join(f.root, 'scripts-common/setup-baseline-profile.js')], { cwd: f.root });
160
+ }
161
+ assert.match(f.read('android/build.gradle'), /androidx\.baselineprofile\.gradle\.plugin:1\.5\.0/);
162
+ assert.equal((f.read('android/settings.gradle').match(/include ':baselineprofile'/g) || []).length, 1);
163
+ });
164
+
165
+ test('Capacitor 9 preparation runs the bundled baseline helper before sync', t => {
166
+ const f = fixture(t, '9.0.0');
167
+ f.write('capacitor.config.json', { appId: 'org.example.app' });
168
+ f.write('android/build.gradle', "dependencies { classpath 'com.android.tools.build:gradle:9.4.1' }\n");
169
+ f.write('android/settings.gradle', "include ':app'\ninclude ':baselineprofile'\nproject(':baselineprofile').projectDir = new File('./baselineprofile/')\n");
170
+ f.write('android/app/build.gradle', "apply plugin: 'com.android.application'\napply plugin: 'androidx.baselineprofile'\napply from: 'capacitor.build.gradle'\ndependencies {\n}\n");
171
+ f.write('scripts-common/setup-baseline-profile.js', fs.readFileSync(path.resolve(__dirname, '../files/scripts-common/setup-baseline-profile.js')));
172
+ prepare(f.root, 'if-cap9');
173
+ assert.match(f.read('android/build.gradle'), /androidx\.baselineprofile\.gradle\.plugin:1\.5\.0/);
174
+ });
@@ -1,15 +1,54 @@
1
1
  const fs = require('fs');
2
2
  const path = require('path');
3
+ const { execFileSync } = require('child_process');
4
+
5
+ function hasFixedAdmobApi(version) {
6
+ const parsed = version?.match(/^(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/);
7
+ if (!parsed) return false;
8
+ const [major, minor, patch] = parsed.slice(1, 4).map(Number);
9
+ return major > 1 || (major === 1 && (minor > 6 || (minor === 6 && patch >= 2)));
10
+ }
11
+
12
+ function comparableAdmobPatch(value) {
13
+ return value.toString().replace(/\r\n/g, '\n').replace(/^\+ +$/gm, '+')
14
+ .replace('@@ -448,11 +476,11 @@', '@@ -448,10 +476,10 @@')
15
+ .replace(/\n \n$/, '\n');
16
+ }
17
+
18
+ function prepareBaselineProfile(root) {
19
+ const android = path.join(root, 'android');
20
+ const module = path.join(android, 'baselineprofile');
21
+ const appGradle = path.join(android, 'app', 'build.gradle');
22
+ const usesBaseline = fs.existsSync(module) || (fs.existsSync(appGradle) && fs.readFileSync(appGradle, 'utf8').includes("apply plugin: 'androidx.baselineprofile'"));
23
+ if (!usesBaseline) return;
24
+ const helper = path.join(root, 'scripts-common', 'setup-baseline-profile.js');
25
+ if (!fs.existsSync(helper)) throw new Error('Baseline profile setup helper is missing; reinstall codeplay-common before Capacitor 9 sync.');
26
+ require(helper).main();
27
+ }
3
28
 
4
29
  function prepare(root, apply = false) {
5
30
  const packageFile = path.join(root, 'package.json');
6
31
  const pkg = JSON.parse(fs.readFileSync(packageFile, 'utf8'));
7
32
  const coreFile = path.join(root, 'node_modules/@capacitor/core/package.json');
8
33
  const coreVersion = fs.existsSync(coreFile) ? JSON.parse(fs.readFileSync(coreFile, 'utf8')).version : null;
34
+ if (apply === 'if-cap9' && !coreVersion?.startsWith('9.')) return { selected: [], review: [], apply: false };
35
+ if (apply === 'if-cap9') apply = true;
9
36
  if (apply && !coreVersion?.startsWith('9.')) throw new Error('Apply patches only after installing Capacitor 9 in this app.');
10
- const catalog = path.resolve(__dirname, '../migration/patches');
37
+ if (apply && pkg.scripts) {
38
+ for (const [key, command] of Object.entries(pkg.scripts)) {
39
+ if (typeof command !== 'string') continue;
40
+ const parts = command.split(/\s*&&\s*/);
41
+ const safe = parts.filter(part => !/^node\s+(?:\.\/)?buildCodeplay\/setSplashAnimation(?:-\d+(?:\.\d+)*)?\.js$/.test(part));
42
+ if (safe.length !== parts.length) {
43
+ if (safe.length) pkg.scripts[key] = safe.join(' && ');
44
+ else delete pkg.scripts[key];
45
+ }
46
+ }
47
+ }
48
+ const catalog = path.resolve(__dirname, '../files/patches/catalog');
11
49
  const active = path.join(root, 'patches/active');
12
50
  const selected = [];
51
+ const selectedSources = new Map();
13
52
  const review = [];
14
53
  if (!coreVersion?.startsWith('9.')) review.push(`Capacitor core ${coreVersion || 'not installed'}; upgrade before applying or building.`);
15
54
  const nativeWriters = /(?:setSplashAnimation|add-splash-screen|splash-setup)\.\w+|BridgeWebViewClient\.java|plugin\/SystemBars\.java/;
@@ -34,37 +73,97 @@ function prepare(root, apply = false) {
34
73
  if (!fs.existsSync(installed)) continue;
35
74
  const actual = JSON.parse(fs.readFileSync(installed, 'utf8')).version;
36
75
  if (actual !== version) {
76
+ if (apply && dependency === 'capacitor-admob-nextgen' && /^\d+\.\d+\.\d+/.test(actual)) {
77
+ const [major, minor] = actual.split('.').map(Number);
78
+ if (major < 1 || (major === 1 && minor < 6)) {
79
+ throw new Error(`capacitor-admob-nextgen ${actual} must be upgraded to 1.6.0 before the Capacitor 9 patch can be applied. Update package.json and the lockfile, then run npm install again.`);
80
+ }
81
+ }
37
82
  review.push(`${dependency}: installed ${actual}; catalog patch ${version}. Check upstream before changing versions.`);
38
83
  continue;
39
84
  }
40
85
  selected.push(name);
86
+ selectedSources.set(name, path.join(catalog, name));
41
87
  }
42
- if (apply) {
43
- if (!fs.existsSync(path.join(root, 'node_modules/patch-package/package.json'))) {
44
- throw new Error('Install patch-package in this app before --apply.');
88
+ const admobFile = path.join(root, 'node_modules/capacitor-admob-nextgen/package.json');
89
+ if (fs.existsSync(admobFile)) {
90
+ const admobVersion = JSON.parse(fs.readFileSync(admobFile, 'utf8')).version;
91
+ if (coreVersion?.startsWith('9.') && !selected.includes(`capacitor-admob-nextgen+${admobVersion}.patch`)) {
92
+ const pluginJava = path.join(root, 'node_modules/capacitor-admob-nextgen/android/src/main/java/com/emi/plugins/admob/AdMobNextGenPlugin.java');
93
+ const source = fs.existsSync(pluginJava) ? fs.readFileSync(pluginJava, 'utf8') : '';
94
+ const apiFixed = ['tagForChildDirectedTreatment', 'tagForUnderAgeOfConsent'].every(key =>
95
+ source.includes(`call.getData().has("${key}")`) && !source.includes(`call.hasOption("${key}")`));
96
+ const template = path.join(catalog, 'capacitor-admob-nextgen+1.6.2-beta.patch');
97
+ let patchFits = false;
98
+ if (hasFixedAdmobApi(admobVersion) && apiFixed && fs.existsSync(template)) {
99
+ for (const direction of [[], ['--reverse']]) {
100
+ try {
101
+ execFileSync('git', ['apply', ...direction, '--check', template], { cwd: root, stdio: 'pipe' });
102
+ patchFits = true;
103
+ break;
104
+ } catch { /* A changed banner hunk requires manual review. */ }
105
+ }
106
+ }
107
+ if (!patchFits) throw new Error(`capacitor-admob-nextgen ${admobVersion}: the Capacitor API or banner/inset source differs from the tested patch. Review this release before continuing.`);
108
+ const name = `capacitor-admob-nextgen+${admobVersion}.patch`;
109
+ selected.push(name);
110
+ selectedSources.set(name, template);
111
+ review.push(`Reused the tested banner/inset patch for AdMob ${admobVersion} after verifying its Java API and every patch hunk.`);
45
112
  }
113
+ }
114
+ if (apply) {
115
+ prepareBaselineProfile(root);
116
+ const patchPackage = require.resolve('patch-package/index.js', { paths: [__dirname] });
46
117
  const existing = fs.existsSync(active) ? fs.readdirSync(active) : [];
118
+ for (const name of existing.filter(name => name.endsWith('.patch'))) {
119
+ const match = name.match(/^(.*)\+([^+]+)\.patch$/);
120
+ if (!match) throw new Error(`Invalid active patch name: ${name}`);
121
+ const dependency = match[1].startsWith('@') ? match[1].replace('+', '/') : match[1];
122
+ const installed = path.join(root, 'node_modules', dependency, 'package.json');
123
+ const installedVersion = fs.existsSync(installed) ? JSON.parse(fs.readFileSync(installed, 'utf8')).version : null;
124
+ if (installedVersion !== match[2]) {
125
+ if (dependency === 'capacitor-admob-nextgen' && selected.includes(`capacitor-admob-nextgen+${installedVersion}.patch`)) {
126
+ const activeFile = path.join(active, name);
127
+ const sharedFile = path.join(catalog, name);
128
+ const oldPatch = fs.readFileSync(activeFile);
129
+ const knownFile = fs.existsSync(sharedFile) ? sharedFile : path.join(catalog, 'capacitor-admob-nextgen+1.6.2-beta.patch');
130
+ const sharedPatch = fs.existsSync(knownFile) ? fs.readFileSync(knownFile) : null;
131
+ const bannerMarker = 'diff --git a/node_modules/capacitor-admob-nextgen/android/src/main/java/com/emi/plugins/admob/banner/BannerExecutor.java';
132
+ const apiOnly = match[2] === '1.6.0' ? sharedPatch?.toString().split(bannerMarker)[0] : null;
133
+ if (sharedPatch && (comparableAdmobPatch(oldPatch) === comparableAdmobPatch(sharedPatch) ||
134
+ (apiOnly && comparableAdmobPatch(oldPatch) === comparableAdmobPatch(apiOnly)))) {
135
+ fs.unlinkSync(activeFile);
136
+ existing.splice(existing.indexOf(name), 1);
137
+ review.push(`Replaced the known ${name} with the ${installedVersion} banner/inset patch.`);
138
+ continue;
139
+ }
140
+ throw new Error(`Active ${name} contains unrecognized changes. Review and port them to ${installedVersion} before removing this patch.`);
141
+ }
142
+ throw new Error(`Active patch ${name} targets ${match[2]}, but ${dependency} is ${installedVersion || 'not installed'}. Review the newer plugin and remove or regenerate this patch before continuing.`);
143
+ }
144
+ }
47
145
  for (const name of selected) {
48
146
  const target = path.join(active, name);
49
- const source = path.join(catalog, name);
147
+ const source = selectedSources.get(name);
50
148
  const related = existing.filter(file => file !== name && file.startsWith(name.replace(/\+[^+]+\.patch$/, '+')) && file.endsWith('.patch'));
51
149
  if (related.length) throw new Error(`Conflicting active patch for ${name}: ${related.join(', ')}`);
52
150
  if (fs.existsSync(target) && !fs.readFileSync(target).equals(fs.readFileSync(source))) {
53
- throw new Error(`Existing app patch differs; preserved ${target}`);
151
+ review.push(`Preserved app-specific active patch: ${target}`);
54
152
  }
55
153
  }
56
154
  fs.mkdirSync(active, { recursive: true });
57
155
  for (const name of selected) {
58
156
  const target = path.join(active, name);
59
- if (!fs.existsSync(target)) fs.copyFileSync(path.join(catalog, name), target);
157
+ if (!fs.existsSync(target)) fs.copyFileSync(selectedSources.get(name), target);
60
158
  }
61
- if (selected.length) {
62
- const command = 'patch-package --patch-dir patches/active --error-on-fail';
159
+ if (fs.readdirSync(active).some(name => name.endsWith('.patch'))) {
160
+ const command = 'node node_modules/codeplay-common/scripts/prepare-capacitor-9.cjs --apply';
63
161
  if (!pkg.scripts) pkg.scripts = {};
64
162
  if (!pkg.scripts.postinstall) pkg.scripts.postinstall = command;
65
- else if (!pkg.scripts.postinstall.includes(command)) pkg.scripts.postinstall += ` && ${command}`;
66
- fs.writeFileSync(packageFile, JSON.stringify(pkg, null, 2) + '\n');
163
+ else if (!pkg.scripts.postinstall.includes(command)) pkg.scripts.postinstall = `${command} && ${pkg.scripts.postinstall}`;
164
+ execFileSync(process.execPath, [patchPackage, '--patch-dir', 'patches/active', '--error-on-fail'], { cwd: root, stdio: 'inherit' });
67
165
  }
166
+ fs.writeFileSync(packageFile, JSON.stringify(pkg, null, 2) + '\n');
68
167
  }
69
168
  return { selected, review, apply };
70
169
  }
@@ -72,11 +171,11 @@ function prepare(root, apply = false) {
72
171
  if (require.main === module) {
73
172
  try {
74
173
  const root = process.cwd();
75
- const result = prepare(root, process.argv.includes('--apply'));
174
+ const result = prepare(root, process.argv.includes('--apply-if-cap9') ? 'if-cap9' : process.argv.includes('--apply'));
76
175
  console.log(`${result.apply ? 'Prepared' : 'Would prepare'} ${result.selected.length} version-matched patches: ${result.selected.join(', ') || 'none'}`);
77
176
  for (const item of result.review) console.warn(`Review: ${item}`);
78
- if (result.apply) console.log('Run npm install (or npx patch-package --patch-dir patches/active --error-on-fail) and verify the native builds.');
177
+ if (result.apply) console.log('Installed matching patches in patches/active and applied them before the native build.');
79
178
  } catch (error) { console.error(error.message); process.exitCode = 1; }
80
179
  }
81
180
 
82
- module.exports = { prepare };
181
+ module.exports = { prepare, hasFixedAdmobApi };
@@ -38,7 +38,8 @@ test('SAF metadata repair is conditional, preserves versions and survives repeat
38
38
 
39
39
  test('sync and update hooks preserve custom commands without duplicating repair', () => {
40
40
  const scripts = updateBuildScripts({ 'capacitor:sync:before': 'node custom.js' });
41
- assert.equal(scripts['capacitor:sync:before'], 'node buildCodeplay/saf-mediastore-dependency.cjs && node custom.js');
42
- assert.equal(scripts['capacitor:update:before'], 'node buildCodeplay/saf-mediastore-dependency.cjs');
41
+ const prepare = 'node node_modules/codeplay-common/scripts/prepare-capacitor-9.cjs --apply-if-cap9';
42
+ assert.equal(scripts['capacitor:sync:before'], `${prepare} && node buildCodeplay/saf-mediastore-dependency.cjs && node custom.js`);
43
+ assert.equal(scripts['capacitor:update:before'], `${prepare} && node buildCodeplay/saf-mediastore-dependency.cjs`);
43
44
  assert.deepEqual(updateBuildScripts(scripts), scripts);
44
45
  });
@@ -58,21 +58,55 @@ test('legacy app settings are retained with current app settings taking priority
58
58
  });
59
59
 
60
60
  for (const enabled of [undefined, false, true]) {
61
- for (const installed of [null, '1.6.0', '1.6.1-beta', '1.7.0']) {
61
+ for (const installed of [null, '1.6.0', '1.6.1-beta', '1.6.2-beta', '1.7.0']) {
62
62
  test(`native plugin: installed=${installed}, squeezebackEnabled=${enabled}`, () => {
63
63
  const commands = [];
64
64
  const start = script.indexOf('const syncAdmobNextgenPackage =');
65
65
  const code = script.slice(start, script.indexOf('const downloadOptionalCodeplayFile', start));
66
66
  vm.runInNewContext(code + '\nsyncAdmobNextgenPackage();', {
67
- fs: { existsSync: () => true }, packageJsonPath: 'package.json',
67
+ fs: { existsSync: () => true }, path, process, packageJsonPath: 'package.json',
68
68
  isPackageAvailable: () => false, getInstalledVersion: () => installed,
69
+ getLatestVersion: () => '1.6.0',
69
70
  getAdmobJsonPath: () => 'config.json', readJsonSafe: () => ({ config: { squeezebackEnabled: enabled } }),
70
71
  compareVersionStrings: (a, b) => a.localeCompare(b, undefined, { numeric: true }),
71
72
  runNpmCommand: command => commands.push(command), console: { log() {}, warn() {} }
72
73
  });
73
- const update = !installed || (enabled === true && installed === '1.6.0');
74
+ const update = !installed || (enabled === true && ['1.6.0', '1.6.1-beta'].includes(installed));
74
75
  assert.deepEqual(commands, update
75
- ? [`npm install capacitor-admob-nextgen${enabled === true ? '@^1.6.1-beta' : ''}`] : []);
76
+ ? [`npm install capacitor-admob-nextgen${enabled === true ? '@1.6.2-beta' : ''}`] : []);
76
77
  });
77
78
  }
78
79
  }
80
+
81
+ for (const installed of ['1.6.0', '1.6.1-beta', '1.6.2-beta', '1.6.2', '1.7.0']) {
82
+ test(`stable AdMob fix: installed=${installed}`, () => {
83
+ const commands = [];
84
+ const start = script.indexOf('const syncAdmobNextgenPackage =');
85
+ const code = script.slice(start, script.indexOf('const downloadOptionalCodeplayFile', start));
86
+ vm.runInNewContext(code + '\nsyncAdmobNextgenPackage();', {
87
+ fs: { existsSync: () => true }, path, process, packageJsonPath: 'package.json',
88
+ isPackageAvailable: () => false, getInstalledVersion: () => installed,
89
+ getLatestVersion: () => '1.6.2',
90
+ getAdmobJsonPath: () => 'config.json', readJsonSafe: () => ({ config: { squeezebackEnabled: true } }),
91
+ compareVersionStrings: (a, b) => a.localeCompare(b, undefined, { numeric: true }),
92
+ runNpmCommand: command => commands.push(command), console: { log() {}, warn() {} }
93
+ });
94
+ assert.deepEqual(commands, installed === '1.6.2' || installed === '1.7.0'
95
+ ? [] : ['npm install capacitor-admob-nextgen@1.6.2']);
96
+ });
97
+ }
98
+
99
+ test('stable AdMob is selected for source-checked patch preparation', () => {
100
+ const commands = [];
101
+ const start = script.indexOf('const syncAdmobNextgenPackage =');
102
+ const code = script.slice(start, script.indexOf('const downloadOptionalCodeplayFile', start));
103
+ vm.runInNewContext(code + '\nsyncAdmobNextgenPackage();', {
104
+ fs: { existsSync: value => value === 'package.json' }, path, process, packageJsonPath: 'package.json',
105
+ isPackageAvailable: () => false, getInstalledVersion: () => '1.6.2-beta',
106
+ getLatestVersion: () => '1.6.2', getAdmobJsonPath: () => 'config.json',
107
+ readJsonSafe: () => ({ config: { squeezebackEnabled: true } }),
108
+ compareVersionStrings: (a, b) => a.localeCompare(b, undefined, { numeric: true }),
109
+ runNpmCommand: command => commands.push(command), console: { log() {}, warn() {} }
110
+ });
111
+ assert.deepEqual(commands, ['npm install capacitor-admob-nextgen@1.6.2']);
112
+ });
@@ -96,14 +96,21 @@ function install(options = {}) {
96
96
  fs.copyFileSync(path.join(commonFiles, 'finalrelease'), path.join(projectRoot, 'finalrelease'));
97
97
  if (options.copyAssets !== false) {
98
98
  for (const name of fs.readdirSync(commonFiles)) {
99
- if (name === 'buildCodeplay' || name === 'scripts-screenshot') continue;
99
+ if (name === 'buildCodeplay' || name === 'scripts-screenshot' || name === 'patches') continue;
100
100
  fs.cpSync(path.join(commonFiles, name), path.join(projectRoot, name), { recursive: true });
101
101
  }
102
- }
103
- const guide = path.join(projectRoot, 'AGENTS', 'capacitor-8-to-9-migration.md');
104
- if (!fs.existsSync(guide)) {
105
- fs.mkdirSync(path.dirname(guide), { recursive: true });
106
- fs.copyFileSync(path.resolve(__dirname, '../migration/capacitor-8-to-9-migration.md'), guide);
102
+ const patchCatalog = path.join(commonFiles, 'patches', 'catalog');
103
+ const appCatalog = path.join(projectRoot, 'patches', 'catalog');
104
+ fs.mkdirSync(appCatalog, { recursive: true });
105
+ for (const name of fs.readdirSync(patchCatalog)) {
106
+ const source = path.join(patchCatalog, name);
107
+ const target = path.join(appCatalog, name);
108
+ if (!fs.statSync(source).isFile()) continue;
109
+ if (!fs.existsSync(target)) fs.copyFileSync(source, target);
110
+ else if (!fs.statSync(target).isFile() || !fs.readFileSync(target).equals(fs.readFileSync(source))) {
111
+ console.warn(`codeplay-common: preserved app-specific catalog patch ${target}`);
112
+ }
113
+ }
107
114
  }
108
115
  if (!capacitor9) require('../files/buildCodeplay/splash-setup.cjs').syncSplashSetup(projectRoot);
109
116
  require('../files/buildCodeplay/setup-ruads.cjs').syncRuAdsSetup(projectRoot, {
@@ -116,6 +123,12 @@ function install(options = {}) {
116
123
  pkg.scripts = scripts;
117
124
  require('../files/buildCodeplay/saf-mediastore-dependency.cjs').syncSafMediastoreDependency(projectRoot);
118
125
  fs.writeFileSync(packagePath, JSON.stringify(pkg, null, 2) + '\n');
126
+ if (capacitor9 && fs.existsSync(path.join(projectRoot, 'node_modules', '@capacitor', 'core', 'package.json'))) {
127
+ const result = require('./prepare-capacitor-9.cjs').prepare(projectRoot, true);
128
+ for (const item of result.review) console.warn(`codeplay-common patch review: ${item}`);
129
+ } else if (capacitor9) {
130
+ console.warn('codeplay-common: Capacitor core is not installed yet; patch setup will run before the next build.');
131
+ }
119
132
  // Cleanup happens only after replacement assets and package commands exist.
120
133
  removeVersionedBuildScripts(projectRoot);
121
134
  console.log('codeplay-common: unversioned build scripts copied to app buildCodeplay; app-owned settings preserved.');
@@ -1,49 +0,0 @@
1
- # Capacitor 8 to 9 migration playbook
2
-
3
- Use this checklist separately for each app. Installing `codeplay-common` only installs build helpers, this guide, and a version-specific patch catalog. A Markdown file cannot execute a migration. The developer or coding agent must follow the steps below, review every native diff, and test each app. Do not copy this app's package IDs, store IDs, native customizations, plugin list, or SDK choices into another app without inspecting it first. Source: https://capacitorjs.com/docs/updating/9-0
4
-
5
- ## Shared alpha package and patch preparation
6
-
7
- 1. Install `codeplay-common@alpha` in a disposable branch or test copy. The alpha installer copies this guide into `AGENTS/` only when the file is absent, and preserves an existing app guide. It does **not** run `cap migrate`, edit app native templates, select patches, or build an app automatically. Pin the tested alpha version for each app instead of using a floating range in production.
8
- 2. After updating the app's dependencies and running `npm install`, inspect exact installed versions with `npm ls --depth=0`. Run `node node_modules/codeplay-common/scripts/prepare-capacitor-9.cjs` for a read-only patch selection and legacy native-writer report. The catalog does not apply to absent plugins or different versions. Resolve reported writer call sites before sync/build.
9
- 3. If the selection is correct, install `patch-package` in the app, then run `node node_modules/codeplay-common/scripts/prepare-capacitor-9.cjs --apply`. This copies only exact-version patches to `patches/active/` and adds its command to an existing `postinstall` without deleting that script. Run the postinstall command and check `git diff`; keep app-specific patches that differ from the shared catalog under app ownership. Inspect newer plugin releases before carrying a patch forward. A lower `capacitor-admob-nextgen` version must be upgraded to **1.6.0** before selecting its compatibility patch.
10
- 4. For this Maths app, the existing AdMob patch additionally contains later banner layout fixes. The shared alpha catalog intentionally contains only the two-line Capacitor 9 `hasOption()` API fix. Do not replace this app's active AdMob patch with the shared one.
11
-
12
- ## Preparation
13
-
14
- 1. Read that app's `AGENTS.md` and linked instructions. Record its clean Git status, Node version, Java version, Android SDK path, Gradle/AGP versions, iOS deployment target, and installed Capacitor and Cordova plugins.
15
- 2. Search build, install, and sync scripts for writes to `android/`, `ios/`, and `node_modules/`. Classify each write as app-owned configuration, generated native integration, or a workaround for an older Capacitor version. Preserve app-owned behavior; remove obsolete core/native workarounds. Search every call site before deleting a script.
16
- 3. Record the intended ADB serial and use `adb -s <serial>` for **every** ADB operation. Never use unqualified `adb`, `cap run`, or an install script that chooses a device implicitly when another device is connected.
17
- 4. Keep temporary downloads, build logs, screenshots, and APK copies under `agent-temp/`. Follow that app's native-file authorization rule. Do not edit generated web output by hand.
18
-
19
- ## Upgrade and native sync
20
-
21
- 1. Use Node 24 or later and Java 21. Upgrade `@capacitor/cli`, `core`, `android`, `ios`, and every official `@capacitor/*` plugin to major 9. Check every community plugin's peer range and native Gradle/Swift compatibility; an npm install succeeding is insufficient. Keep the app's lockfile in sync.
22
- 2. Run `npx cap migrate` and read every warning. Review its diff before accepting generated changes. Then run `npx cap sync android` and `npx cap sync ios` after the plugin set is final.
23
- 3. Android: use the Gradle and AGP versions required by the current Capacitor guide, install the matching compile SDK/build tools, set the guide's minimum and target SDKs, and check `android/variables.gradle`, root/app Gradle files, wrapper files, and `gradle.properties`. Remove old direct Cordova module wiring from `settings.gradle` and `app/build.gradle`; Capacitor 9 generates conditional wiring in `capacitor.settings.gradle` and `app/capacitor.build.gradle`. Keep actual Cordova plugins and store-specific billing/ads exclusions.
24
- 4. Check old plugin Gradle files for unsupported `proguard-android.txt`, standalone Kotlin plugin, old `core-ktx`, `jcenter()`, and removed Capacitor APIs. Prefer a compatible plugin release. If none exists and the plugin is used, carry a narrow, reproducible dependency patch with its reason documented. Reapply and verify it after a clean install.
25
- 5. Compare `MainActivity` with the installed Capacitor 9 template and remove obsolete app-specific Java behavior. Search `postinstall`, `capacitor:sync:*`, before-build scripts, and Gradle hooks for old `setSplashAnimation.js`, `add-splash-screen.js`, `splash-setup.cjs`, `BridgeWebViewClient.java`, and `SystemBars.java` writers. Remove or disable their callers so the next install/build/sync does not restore obsolete code. Keep the native launch splash from the Capacitor 9 template unless that app explicitly needs custom behavior. Confirm edge-to-edge and `SystemBars.insetsHandling` together on device. Keep app-owned manifest, notification icon, resource, R8, store, TV, and baseline-profile modifications; update their integration for AGP 9. A baseline-profile Gradle plugin at 1.5.0 or later is needed for this app's AGP 9 build.
26
- 6. iOS: set deployment target 16.0, use Xcode 27 or later, migrate to SwiftUI `App.swift`/`CapacitorView.swift`, adapt `AppDelegate`, empty the old `SceneDelegate` window/URL code, remove `Main.storyboard`, and check Xcode target file references and `Info.plist`. Confirm URL, universal-link, notification, ad consent, orientation, and custom plugin behavior on an iOS device. Windows cannot complete this validation.
27
-
28
- ## Validation and handoff
29
-
30
- 1. Run `npm ls --depth=0`, JavaScript syntax checks, `git diff --check`, and an Android Gradle build. Check warnings and errors from every plugin module. Verify a web build using the relevant store mode without hand-editing `www`.
31
- 2. Inspect merged manifests and packaged assets/classes for each store variant whose billing or ads are excluded. Check that the package ID and signing key match the installed app before upgrading it; preserve app data when possible.
32
- 3. Install only with `adb -s <serial> install -r <apk>`. Confirm startup, native bridge, splash, status/navigation bars and both landscape edges, keyboard, notifications, purchases, ads, and relevant plugin flows. Record any unavailable device or platform checks explicitly.
33
- 4. Before building a Play internal-test AAB, increase the app's `versionCode` beyond every version already uploaded to Play and advance `versionName` using that app's version scheme. Sign with its existing Play upload key; verify the AAB manifest's actual version values, packaged web/Cordova assets, and signing certificate before handing it off. Do not reuse a prior Play build code for a revised migration test.
34
- 5. Save concise durable validation results under `AI-Logs/` and update `Version-history.md` under Unreleased. Do not declare iOS complete until an Xcode build and device check pass.
35
-
36
- ## Findings from this app
37
-
38
- - Capacitor 9's Cordova wiring is conditional. This app still uses Cordova plugins, so its generated files include that runtime.
39
- - `@capacitor-community/in-app-review` 8.0.0 has no major-9 release and uses the removed default ProGuard file. `patches/active/@capacitor-community+in-app-review+8.0.0.patch` changes that single Gradle call and `postinstall` reapplies it.
40
- - For `capacitor-admob-nextgen`, update older installations to 1.6.0 before applying the single `patches/active/capacitor-admob-nextgen+1.6.0.patch`. Version 1.6.0 calls the removed `PluginCall.hasOption()` API; the patch uses `call.getData().has()` for the two optional privacy flags. Recheck whether an upstream release fixes this before patching a newer version.
41
- - `patches/catalog/` holds version-specific patches for other apps. Select only patches matching an app's installed versions; see `patches/README.md`. The catalog patches passed isolated Capacitor 9 Android debug/release Java compilation but still require each app's native release and runtime checks. Update the owned RuStore ads package upstream instead of copying a patch.
42
- - The former `setSplashAnimation.js` sync hook replaced all of `MainActivity`; removing every caller avoids restoring Capacitor 8-era native code.
43
- - This app's `MainActivity.java` matches the Capacitor 9 Android template exactly except for `package maths.formulas;`. Its old custom splash exit animation was removed.
44
- - The default Capacitor 9 `AppTheme.NoActionBarLaunch`, `styles.xml`, splash.png assets, and Gradle wrapper properties were restored. The custom `Theme.Codeplay.SplashScreen`, its sync script, the manual startup hide timer, and `launchShowDuration: 0` were removed so the stock launch splash can be evaluated. `splash_icon.png` is retained only for LocalNotifications.largeIcon. The TV banner, launcher resources, app identity, plugin-generated Gradle files, and notification assets remain app-specific. Baseline-profile, R8, and store build rules are deliberate exceptions to the template at the user's request.
45
- - When using a temporary Vite output directory for a test APK, route it through `npx cap copy android` so Cordova's JavaScript runtime and plugin files are generated. Directly copying Vite output into native assets omits those files. Restore the source `webDir` and native generated assets after the APK is built.
46
- - This app's pre-Android-15 custom inset listener was removed after migration. Capacitor 9 `SystemBars.insetsHandling=css` now provides the inset values, and `src/assets/css/app.less` maps them to the existing layout variables. Keep this mapping when migrating related layouts; test older Android versions separately.
47
- - Play Console can still show its edge-to-edge recommendation for an optimized release even when the Capacitor 9 template calls `EdgeToEdge.enable(this)`: R8 may inline that call into `MainActivity.onCreate`. Check the release mapping before changing UI code. In this app, a narrow `-keep` rule for `androidx.activity.EdgeToEdge.enable(ComponentActivity)` retained the entry point in release code; the later production 8.1 (89) dashboard screenshot no longer showed those recommendations. This is an observed result, not proof that every device or later dependency build will pass. Do not add the rule to other apps without checking their own release mapping and Play result.
48
- - Play's deprecated edge-to-edge API warning for version 88 points mainly to AndroidX Activity/Core compatibility code. `WindowCompat.enableEdgeToEdge()` in AndroidX Core 1.19.1 still calls `setStatusBarColor` and `setNavigationBarColor`, so swapping the entry point does not remove that warning. Preserve working Android 14+ insets and bar contrast while assessing future AndroidX updates.
49
- - If Java's Gradle wrapper download times out, download the specified Gradle distribution with an available HTTP client and regenerate the wrapper from that distribution. Keep the chosen Gradle version aligned with AGP.
@@ -1,10 +0,0 @@
1
- diff --git a/node_modules/capacitor-admob-nextgen/android/src/main/java/com/emi/plugins/admob/AdMobNextGenPlugin.java b/node_modules/capacitor-admob-nextgen/android/src/main/java/com/emi/plugins/admob/AdMobNextGenPlugin.java
2
- --- a/node_modules/capacitor-admob-nextgen/android/src/main/java/com/emi/plugins/admob/AdMobNextGenPlugin.java
3
- +++ b/node_modules/capacitor-admob-nextgen/android/src/main/java/com/emi/plugins/admob/AdMobNextGenPlugin.java
4
- @@ -185,4 +185,4 @@ public class AdMobNextGenPlugin extends Plugin {
5
- String maxAdContentRating = call.getString("maxAdContentRating", "");
6
- - Boolean tagForChildDirectedTreatment = call.hasOption("tagForChildDirectedTreatment") ? call.getBoolean("tagForChildDirectedTreatment") : null;
7
- - Boolean tagForUnderAgeOfConsent = call.hasOption("tagForUnderAgeOfConsent") ? call.getBoolean("tagForUnderAgeOfConsent") : null;
8
- + Boolean tagForChildDirectedTreatment = call.getData().has("tagForChildDirectedTreatment") ? call.getBoolean("tagForChildDirectedTreatment") : null;
9
- + Boolean tagForUnderAgeOfConsent = call.getData().has("tagForUnderAgeOfConsent") ? call.getBoolean("tagForUnderAgeOfConsent") : null;
10
- Boolean isTesting = call.getBoolean("isTesting", false);