codeplay-common 4.11.34 → 4.11.37

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 (47) hide show
  1. package/CHANGELOG.md +115 -115
  2. package/LICENSE +21 -21
  3. package/README.md +6 -0
  4. package/RELEASE_NOTES.md +110 -110
  5. package/files/buildCodeplay/HUAWEI-PRIVACY.md +9 -9
  6. package/files/buildCodeplay/add-splash-screen.js +256 -256
  7. package/files/buildCodeplay/apk-store-builder.js +97 -97
  8. package/files/buildCodeplay/fix-onesignal-plugin.js +96 -96
  9. package/files/buildCodeplay/fix-optimize-builld/android-r8-rules.cjs +31 -31
  10. package/files/buildCodeplay/fix-optimize-builld/ffmpeg-jni-rules.cjs +28 -28
  11. package/files/buildCodeplay/fix-optimize-builld/fix-optimize-build.gradle +9 -9
  12. package/files/buildCodeplay/fix-optimize-builld/restore-android-r8-rules.cjs +30 -30
  13. package/files/buildCodeplay/huawei-privacy.cjs +102 -92
  14. package/files/buildCodeplay/iap-alias.cjs +116 -108
  15. package/files/buildCodeplay/ios-emi-admob-modification.js +24 -24
  16. package/files/buildCodeplay/manifestModification.js +38 -38
  17. package/files/buildCodeplay/migrate-system-bars.cjs +122 -122
  18. package/files/buildCodeplay/packageidBaseModification.js +528 -528
  19. package/files/buildCodeplay/project-scripts.cjs +69 -69
  20. package/files/buildCodeplay/ruads.cjs +10 -1
  21. package/files/buildCodeplay/setSplashAnimation.js +228 -228
  22. package/files/buildCodeplay/setup-ruads.cjs +9 -2
  23. package/files/buildCodeplay/splash-setup.cjs +88 -88
  24. package/files/buildCodeplay/splashxml/codeplay_splashScreen.xml +11 -11
  25. package/files/buildCodeplay/sync-admob-nextgen.js +219 -219
  26. package/files/buildCodeplay/tests/huawei-live-reload.test.cjs +60 -0
  27. package/files/buildCodeplay/tests/huawei-multiple-entries.test.cjs +80 -0
  28. package/files/buildCodeplay/tests/huawei-vite.test.cjs +38 -35
  29. package/files/buildCodeplay/versions.json +28 -28
  30. package/files/finalrelease +1365 -1365
  31. package/files/generate-ai-promo-video.js +23 -23
  32. package/files/ionic.config.json +6 -6
  33. package/files/scripts-common/run-codeplay-sync-after.js +21 -21
  34. package/files/scripts-common/screenshot/background-decorations.js +120 -120
  35. package/files/scripts-common/screenshot/frame-samples.js +117 -117
  36. package/files/scripts-common/setup-baseline-profile.js +291 -291
  37. package/files/take-screen-video.js +644 -644
  38. package/package.json +1 -1
  39. package/runtime/splash-ready.mjs +52 -52
  40. package/scripts/iap-alias.test.cjs +117 -78
  41. package/scripts/ruads-install.test.cjs +20 -3
  42. package/scripts/splash-setup.test.cjs +142 -142
  43. package/scripts/sync-files.js +119 -119
  44. package/scripts/system-bars-package.test.cjs +37 -37
  45. package/scripts/system-bars.test.cjs +93 -93
  46. package/scripts/uninstall.js +2 -2
  47. package/scripts/vite-build-settings.test.cjs +1 -0
@@ -1,219 +1,219 @@
1
- // AdMob packages version the folder; filenames inside it stay stable.
2
- const fs = require('fs');
3
- const path = require('path');
4
- const https = require('https');
5
-
6
- const PACKAGE_PATTERN = /^admob-nextgen-(\d+(?:\.\d+)*)$/;
7
- const REQUIRED_FILES = ['admob-emi-nextgen.js', 'app-open-state.js'];
8
- const SERVER = 'https://htmlcodeplay.com/code-play-plugin/';
9
-
10
- function compareVersions(a, b) {
11
- const left = String(a).split('.').map(Number);
12
- const right = String(b).split('.').map(Number);
13
- for (let i = 0; i < Math.max(left.length, right.length); i++) {
14
- const difference = (left[i] || 0) - (right[i] || 0);
15
- if (difference) return difference;
16
- }
17
- return 0;
18
- }
19
-
20
- function isComplete(directory) {
21
- return REQUIRED_FILES.every(file => fs.existsSync(path.join(directory, file))
22
- && fs.statSync(path.join(directory, file)).isFile()
23
- && fs.statSync(path.join(directory, file)).size > 0);
24
- }
25
-
26
- function findLatestPackage(adsDirectory) {
27
- if (!fs.existsSync(adsDirectory)) return null;
28
- return fs.readdirSync(adsDirectory).filter(name => PACKAGE_PATTERN.test(name)
29
- && isComplete(path.join(adsDirectory, name)))
30
- .sort((a, b) => compareVersions(b.match(PACKAGE_PATTERN)[1], a.match(PACKAGE_PATTERN)[1]))[0] || null;
31
- }
32
-
33
- function request(url, redirects = 0) {
34
- return new Promise((resolve, reject) => {
35
- const req = https.get(url, { timeout: 10000 }, response => {
36
- if ([301, 302, 303, 307, 308].includes(response.statusCode) && response.headers.location) {
37
- response.resume();
38
- if (redirects >= 3) return reject(new Error('Too many AdMob download redirects.'));
39
- const target = new URL(response.headers.location, url);
40
- if (target.protocol !== 'https:') return reject(new Error('AdMob downloads require HTTPS.'));
41
- resolve(request(target.href, redirects + 1));
42
- return;
43
- }
44
- if (response.statusCode !== 200) {
45
- response.resume();
46
- reject(new Error(`AdMob download returned HTTP ${response.statusCode}.`));
47
- return;
48
- }
49
- const chunks = [];
50
- response.on('data', chunk => chunks.push(chunk));
51
- response.on('error', reject);
52
- response.on('end', () => resolve(Buffer.concat(chunks)));
53
- });
54
- req.on('timeout', () => req.destroy(new Error('AdMob download timed out.')));
55
- req.on('error', reject);
56
- });
57
- }
58
-
59
- function extractPackage(buffer, destination, packageName, AdmZip = require('adm-zip')) {
60
- const zip = new AdmZip(buffer);
61
- const entries = zip.getEntries();
62
- const wrapped = entries.some(entry => entry.entryName === `${packageName}/admob-emi-nextgen.js`);
63
- for (const entry of entries) {
64
- let name = entry.entryName;
65
- if (name.includes('\\') || name.startsWith('/') || name.split('/').includes('..')
66
- || /^[a-z]:/i.test(name) || ((entry.header.attr >>> 16) & 0xf000) === 0xa000) {
67
- throw new Error(`Unsafe AdMob ZIP entry: ${name}`);
68
- }
69
- if (wrapped) {
70
- if (name === `${packageName}/`) continue;
71
- if (!name.startsWith(`${packageName}/`)) throw new Error('Mixed AdMob ZIP roots.');
72
- name = name.slice(packageName.length + 1);
73
- }
74
- if (!name) continue;
75
- const target = path.resolve(destination, name);
76
- if (!target.startsWith(path.resolve(destination) + path.sep)) throw new Error('Invalid AdMob ZIP path.');
77
- if (entry.isDirectory) fs.mkdirSync(target, { recursive: true });
78
- else {
79
- fs.mkdirSync(path.dirname(target), { recursive: true });
80
- fs.writeFileSync(target, entry.getData());
81
- }
82
- }
83
- if (!isComplete(destination)) throw new Error('AdMob ZIP must contain the controller and app-open-state.js.');
84
- }
85
-
86
- function sourceFiles(directory) {
87
- if (!fs.existsSync(directory)) return [];
88
- return fs.readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
89
- if (['node_modules', '.git', 'android', 'ios', 'www', 'agent-temp'].includes(entry.name)) return [];
90
- const fullPath = path.join(directory, entry.name);
91
- if (entry.isDirectory()) return sourceFiles(fullPath);
92
- return entry.isFile() && /\.(?:js|mjs|cjs|ts|f7|vue|jsx|tsx)$/.test(entry.name) ? [fullPath] : [];
93
- });
94
- }
95
-
96
- function syncImports(projectRoot, packageName) {
97
- const adsDirectory = path.join(projectRoot, 'src', 'js', 'Ads');
98
- const targetDirectory = path.join(adsDirectory, packageName);
99
- if (!isComplete(targetDirectory)) throw new Error('Cannot migrate imports to an incomplete AdMob package.');
100
- const files = sourceFiles(path.join(projectRoot, 'src'));
101
- for (const name of ['vite.config.js', 'vite.config.mjs', 'vite.config.ts']) {
102
- const file = path.join(projectRoot, name);
103
- if (fs.existsSync(file)) files.push(file);
104
- }
105
- const updates = [];
106
- for (const file of files) {
107
- const original = fs.readFileSync(file, 'utf8');
108
- const next = original.replace(/(['"`])([^'"`\r\n]+)\1/g, (match, quote, specifier) => {
109
- if (!/admob-(?:emi-nextgen|app-open-state|nextgen)-|(?:^|\/)test-admob\.js(?:[?#]|$)/.test(specifier)) return match;
110
- if (specifier.includes('${')) throw new Error(`Computed AdMob import needs migration before cleanup: ${file}`);
111
- const suffixIndex = specifier.search(/[?#]/);
112
- const suffix = suffixIndex < 0 ? '' : specifier.slice(suffixIndex);
113
- specifier = suffixIndex < 0 ? specifier : specifier.slice(0, suffixIndex);
114
- let resolved;
115
- if (specifier.startsWith('@/')) resolved = path.resolve(projectRoot, 'src', specifier.slice(2));
116
- else if (specifier.startsWith('./') || specifier.startsWith('../')) resolved = path.resolve(path.dirname(file), specifier);
117
- else return match;
118
- const relative = path.relative(adsDirectory, resolved).split(path.sep).join('/');
119
- let name;
120
- if (/^admob-emi-nextgen-\d+(?:\.\d+)*\.js$/.test(relative)) name = REQUIRED_FILES[0];
121
- else if (/^admob-app-open-state-\d+(?:\.\d+)*\.js$/.test(relative)) name = REQUIRED_FILES[1];
122
- else if (relative === 'test-admob.js') name = 'test-admob.js';
123
- else {
124
- const folderFile = relative.match(/^admob-nextgen-\d+(?:\.\d+)*\/(.+)$/);
125
- if (!folderFile) return match;
126
- name = folderFile[1];
127
- }
128
- const target = path.join(targetDirectory, name);
129
- if (!fs.existsSync(target)) throw new Error(`AdMob import target missing: ${target}`);
130
- let replacement = specifier.startsWith('@/')
131
- ? `@/js/Ads/${packageName}/${name}`
132
- : path.relative(path.dirname(file), target).split(path.sep).join('/');
133
- if (!specifier.startsWith('@/') && !replacement.startsWith('.')) replacement = './' + replacement;
134
- return quote + replacement + suffix + quote;
135
- });
136
- if (next !== original) updates.push({ file, next });
137
- }
138
- // Plan every replacement before writing or removing any legacy source.
139
- for (const { file, next } of updates) fs.writeFileSync(file, next, 'utf8');
140
- return updates.map(update => path.relative(projectRoot, update.file));
141
- }
142
-
143
- function syncPackageDependencies(projectRoot, packageName) {
144
- const adsDirectory = path.join(projectRoot, 'src', 'js', 'Ads');
145
- const controller = path.join(adsDirectory, packageName, REQUIRED_FILES[0]);
146
- const iapFolders = fs.readdirSync(adsDirectory).filter(name => /^IAP-\d+(?:\.\d+)*$/.test(name)
147
- && fs.existsSync(path.join(adsDirectory, name, 'firebase-analytics.js')))
148
- .sort((a, b) => compareVersions(b.slice(4), a.slice(4)));
149
- const original = fs.readFileSync(controller, 'utf8');
150
- let next = original.replace(/(['"])\.\.?\/admob-ad-configuration-nextgen\.json\1/g,
151
- (match, quote) => `${quote}../admob-ad-configuration-nextgen.json${quote}`);
152
- if (iapFolders.length) next = next.replace(/(['"])\.\.?\/IAP-\d+(?:\.\d+)*\/(?:firebase-analytics|IAP-state)\.js\1/g,
153
- (match, quote) => `${quote}../${iapFolders[0]}/${match.includes('IAP-state') ? 'IAP-state.js' : 'firebase-analytics.js'}${quote}`);
154
- if (next !== original) fs.writeFileSync(controller, next, 'utf8');
155
- }
156
-
157
- async function syncAdmobNextgen(options = {}) {
158
- const projectRoot = path.resolve(options.projectRoot || process.cwd());
159
- const adsDirectory = path.join(projectRoot, 'src', 'js', 'Ads');
160
- if (!fs.existsSync(adsDirectory)) return null;
161
- const log = options.log || console.log;
162
- const fetch = options.request || request;
163
- let latest = findLatestPackage(adsDirectory);
164
- let versions = options.versions;
165
- if (versions === undefined) {
166
- try { versions = JSON.parse((await fetch(SERVER + 'versions.json')).toString('utf8')); }
167
- catch (error) { log(`AdMob: server unavailable; retaining the installed package. ${error.message}`); }
168
- }
169
- // New manifests use admob-nextgen. Accept the previous key only at folder versions >= 4.0.
170
- const advertisedVersion = String(versions?.['admob-nextgen'] || versions?.['admob-emi-nextgen'] || '');
171
- // IAP 4.6 requires the synchronous ownership gate in AdMob 4.1 or newer.
172
- const remoteVersion = /^\d+(?:\.\d+)*$/.test(advertisedVersion) && compareVersions(advertisedVersion, '4.1') >= 0
173
- ? advertisedVersion : '4.1';
174
- const candidates = [];
175
- if (/^\d+(?:\.\d+)*$/.test(remoteVersion) && compareVersions(remoteVersion, '4.0') >= 0) {
176
- candidates.push({ version: remoteVersion });
177
- }
178
- for (const candidate of candidates) {
179
- if (latest && compareVersions(latest.match(PACKAGE_PATTERN)[1], candidate.version) >= 0) break;
180
- const name = `admob-nextgen-${candidate.version}`;
181
- const temporaryRoot = path.join(projectRoot, 'agent-temp', 'admob-package-sync');
182
- fs.mkdirSync(temporaryRoot, { recursive: true });
183
- const staging = fs.mkdtempSync(path.join(temporaryRoot, 'package-'));
184
- try {
185
- const buffer = await fetch(SERVER + name + '.zip');
186
- extractPackage(buffer, staging, name, options.AdmZip);
187
- const destination = path.join(adsDirectory, name);
188
- if (fs.existsSync(destination)) throw new Error(`Incomplete AdMob package already exists: ${destination}`);
189
- fs.renameSync(staging, destination);
190
- latest = name;
191
- log(`AdMob: installed ${name}.`);
192
- } catch (error) {
193
- log(`AdMob: could not install ${name}: ${error.message}`);
194
- } finally {
195
- fs.rmSync(staging, { recursive: true, force: true });
196
- }
197
- }
198
- if (!latest) throw new Error('No complete AdMob folder package is available. Check admob-nextgen in the live versions.json and its ZIP on htmlcodeplay.com; existing files were preserved.');
199
- if (compareVersions(latest.match(PACKAGE_PATTERN)[1], '4.1') < 0) throw new Error('Deferred IAP startup requires admob-nextgen-4.1 or newer; existing sources were preserved.');
200
- syncPackageDependencies(projectRoot, latest);
201
- const changed = syncImports(projectRoot, latest);
202
- // Remove only this plugin's superseded files after the new imports are in place.
203
- for (const entry of fs.readdirSync(adsDirectory, { withFileTypes: true })) {
204
- if (entry.isFile() && /^admob-(?:emi-nextgen|app-open-state)-\d+(?:\.\d+)*\.js$/.test(entry.name)) {
205
- fs.unlinkSync(path.join(adsDirectory, entry.name));
206
- } else if (entry.isDirectory() && PACKAGE_PATTERN.test(entry.name) && entry.name !== latest) {
207
- fs.rmSync(path.join(adsDirectory, entry.name), { recursive: true });
208
- }
209
- }
210
- log(`AdMob: ${latest} ready; migrated ${changed.length} file(s).`);
211
- return latest;
212
- }
213
-
214
- module.exports = { syncAdmobNextgen, syncImports, findLatestPackage, compareVersions, extractPackage };
215
-
216
- if (require.main === module) syncAdmobNextgen().catch(error => {
217
- console.error(error.message);
218
- process.exitCode = 1;
219
- });
1
+ // AdMob packages version the folder; filenames inside it stay stable.
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const https = require('https');
5
+
6
+ const PACKAGE_PATTERN = /^admob-nextgen-(\d+(?:\.\d+)*)$/;
7
+ const REQUIRED_FILES = ['admob-emi-nextgen.js', 'app-open-state.js'];
8
+ const SERVER = 'https://htmlcodeplay.com/code-play-plugin/';
9
+
10
+ function compareVersions(a, b) {
11
+ const left = String(a).split('.').map(Number);
12
+ const right = String(b).split('.').map(Number);
13
+ for (let i = 0; i < Math.max(left.length, right.length); i++) {
14
+ const difference = (left[i] || 0) - (right[i] || 0);
15
+ if (difference) return difference;
16
+ }
17
+ return 0;
18
+ }
19
+
20
+ function isComplete(directory) {
21
+ return REQUIRED_FILES.every(file => fs.existsSync(path.join(directory, file))
22
+ && fs.statSync(path.join(directory, file)).isFile()
23
+ && fs.statSync(path.join(directory, file)).size > 0);
24
+ }
25
+
26
+ function findLatestPackage(adsDirectory) {
27
+ if (!fs.existsSync(adsDirectory)) return null;
28
+ return fs.readdirSync(adsDirectory).filter(name => PACKAGE_PATTERN.test(name)
29
+ && isComplete(path.join(adsDirectory, name)))
30
+ .sort((a, b) => compareVersions(b.match(PACKAGE_PATTERN)[1], a.match(PACKAGE_PATTERN)[1]))[0] || null;
31
+ }
32
+
33
+ function request(url, redirects = 0) {
34
+ return new Promise((resolve, reject) => {
35
+ const req = https.get(url, { timeout: 10000 }, response => {
36
+ if ([301, 302, 303, 307, 308].includes(response.statusCode) && response.headers.location) {
37
+ response.resume();
38
+ if (redirects >= 3) return reject(new Error('Too many AdMob download redirects.'));
39
+ const target = new URL(response.headers.location, url);
40
+ if (target.protocol !== 'https:') return reject(new Error('AdMob downloads require HTTPS.'));
41
+ resolve(request(target.href, redirects + 1));
42
+ return;
43
+ }
44
+ if (response.statusCode !== 200) {
45
+ response.resume();
46
+ reject(new Error(`AdMob download returned HTTP ${response.statusCode}.`));
47
+ return;
48
+ }
49
+ const chunks = [];
50
+ response.on('data', chunk => chunks.push(chunk));
51
+ response.on('error', reject);
52
+ response.on('end', () => resolve(Buffer.concat(chunks)));
53
+ });
54
+ req.on('timeout', () => req.destroy(new Error('AdMob download timed out.')));
55
+ req.on('error', reject);
56
+ });
57
+ }
58
+
59
+ function extractPackage(buffer, destination, packageName, AdmZip = require('adm-zip')) {
60
+ const zip = new AdmZip(buffer);
61
+ const entries = zip.getEntries();
62
+ const wrapped = entries.some(entry => entry.entryName === `${packageName}/admob-emi-nextgen.js`);
63
+ for (const entry of entries) {
64
+ let name = entry.entryName;
65
+ if (name.includes('\\') || name.startsWith('/') || name.split('/').includes('..')
66
+ || /^[a-z]:/i.test(name) || ((entry.header.attr >>> 16) & 0xf000) === 0xa000) {
67
+ throw new Error(`Unsafe AdMob ZIP entry: ${name}`);
68
+ }
69
+ if (wrapped) {
70
+ if (name === `${packageName}/`) continue;
71
+ if (!name.startsWith(`${packageName}/`)) throw new Error('Mixed AdMob ZIP roots.');
72
+ name = name.slice(packageName.length + 1);
73
+ }
74
+ if (!name) continue;
75
+ const target = path.resolve(destination, name);
76
+ if (!target.startsWith(path.resolve(destination) + path.sep)) throw new Error('Invalid AdMob ZIP path.');
77
+ if (entry.isDirectory) fs.mkdirSync(target, { recursive: true });
78
+ else {
79
+ fs.mkdirSync(path.dirname(target), { recursive: true });
80
+ fs.writeFileSync(target, entry.getData());
81
+ }
82
+ }
83
+ if (!isComplete(destination)) throw new Error('AdMob ZIP must contain the controller and app-open-state.js.');
84
+ }
85
+
86
+ function sourceFiles(directory) {
87
+ if (!fs.existsSync(directory)) return [];
88
+ return fs.readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
89
+ if (['node_modules', '.git', 'android', 'ios', 'www', 'agent-temp'].includes(entry.name)) return [];
90
+ const fullPath = path.join(directory, entry.name);
91
+ if (entry.isDirectory()) return sourceFiles(fullPath);
92
+ return entry.isFile() && /\.(?:js|mjs|cjs|ts|f7|vue|jsx|tsx)$/.test(entry.name) ? [fullPath] : [];
93
+ });
94
+ }
95
+
96
+ function syncImports(projectRoot, packageName) {
97
+ const adsDirectory = path.join(projectRoot, 'src', 'js', 'Ads');
98
+ const targetDirectory = path.join(adsDirectory, packageName);
99
+ if (!isComplete(targetDirectory)) throw new Error('Cannot migrate imports to an incomplete AdMob package.');
100
+ const files = sourceFiles(path.join(projectRoot, 'src'));
101
+ for (const name of ['vite.config.js', 'vite.config.mjs', 'vite.config.ts']) {
102
+ const file = path.join(projectRoot, name);
103
+ if (fs.existsSync(file)) files.push(file);
104
+ }
105
+ const updates = [];
106
+ for (const file of files) {
107
+ const original = fs.readFileSync(file, 'utf8');
108
+ const next = original.replace(/(['"`])([^'"`\r\n]+)\1/g, (match, quote, specifier) => {
109
+ if (!/admob-(?:emi-nextgen|app-open-state|nextgen)-|(?:^|\/)test-admob\.js(?:[?#]|$)/.test(specifier)) return match;
110
+ if (specifier.includes('${')) throw new Error(`Computed AdMob import needs migration before cleanup: ${file}`);
111
+ const suffixIndex = specifier.search(/[?#]/);
112
+ const suffix = suffixIndex < 0 ? '' : specifier.slice(suffixIndex);
113
+ specifier = suffixIndex < 0 ? specifier : specifier.slice(0, suffixIndex);
114
+ let resolved;
115
+ if (specifier.startsWith('@/')) resolved = path.resolve(projectRoot, 'src', specifier.slice(2));
116
+ else if (specifier.startsWith('./') || specifier.startsWith('../')) resolved = path.resolve(path.dirname(file), specifier);
117
+ else return match;
118
+ const relative = path.relative(adsDirectory, resolved).split(path.sep).join('/');
119
+ let name;
120
+ if (/^admob-emi-nextgen-\d+(?:\.\d+)*\.js$/.test(relative)) name = REQUIRED_FILES[0];
121
+ else if (/^admob-app-open-state-\d+(?:\.\d+)*\.js$/.test(relative)) name = REQUIRED_FILES[1];
122
+ else if (relative === 'test-admob.js') name = 'test-admob.js';
123
+ else {
124
+ const folderFile = relative.match(/^admob-nextgen-\d+(?:\.\d+)*\/(.+)$/);
125
+ if (!folderFile) return match;
126
+ name = folderFile[1];
127
+ }
128
+ const target = path.join(targetDirectory, name);
129
+ if (!fs.existsSync(target)) throw new Error(`AdMob import target missing: ${target}`);
130
+ let replacement = specifier.startsWith('@/')
131
+ ? `@/js/Ads/${packageName}/${name}`
132
+ : path.relative(path.dirname(file), target).split(path.sep).join('/');
133
+ if (!specifier.startsWith('@/') && !replacement.startsWith('.')) replacement = './' + replacement;
134
+ return quote + replacement + suffix + quote;
135
+ });
136
+ if (next !== original) updates.push({ file, next });
137
+ }
138
+ // Plan every replacement before writing or removing any legacy source.
139
+ for (const { file, next } of updates) fs.writeFileSync(file, next, 'utf8');
140
+ return updates.map(update => path.relative(projectRoot, update.file));
141
+ }
142
+
143
+ function syncPackageDependencies(projectRoot, packageName) {
144
+ const adsDirectory = path.join(projectRoot, 'src', 'js', 'Ads');
145
+ const controller = path.join(adsDirectory, packageName, REQUIRED_FILES[0]);
146
+ const iapFolders = fs.readdirSync(adsDirectory).filter(name => /^IAP-\d+(?:\.\d+)*$/.test(name)
147
+ && fs.existsSync(path.join(adsDirectory, name, 'firebase-analytics.js')))
148
+ .sort((a, b) => compareVersions(b.slice(4), a.slice(4)));
149
+ const original = fs.readFileSync(controller, 'utf8');
150
+ let next = original.replace(/(['"])\.\.?\/admob-ad-configuration-nextgen\.json\1/g,
151
+ (match, quote) => `${quote}../admob-ad-configuration-nextgen.json${quote}`);
152
+ if (iapFolders.length) next = next.replace(/(['"])\.\.?\/IAP-\d+(?:\.\d+)*\/(?:firebase-analytics|IAP-state)\.js\1/g,
153
+ (match, quote) => `${quote}../${iapFolders[0]}/${match.includes('IAP-state') ? 'IAP-state.js' : 'firebase-analytics.js'}${quote}`);
154
+ if (next !== original) fs.writeFileSync(controller, next, 'utf8');
155
+ }
156
+
157
+ async function syncAdmobNextgen(options = {}) {
158
+ const projectRoot = path.resolve(options.projectRoot || process.cwd());
159
+ const adsDirectory = path.join(projectRoot, 'src', 'js', 'Ads');
160
+ if (!fs.existsSync(adsDirectory)) return null;
161
+ const log = options.log || console.log;
162
+ const fetch = options.request || request;
163
+ let latest = findLatestPackage(adsDirectory);
164
+ let versions = options.versions;
165
+ if (versions === undefined) {
166
+ try { versions = JSON.parse((await fetch(SERVER + 'versions.json')).toString('utf8')); }
167
+ catch (error) { log(`AdMob: server unavailable; retaining the installed package. ${error.message}`); }
168
+ }
169
+ // New manifests use admob-nextgen. Accept the previous key only at folder versions >= 4.0.
170
+ const advertisedVersion = String(versions?.['admob-nextgen'] || versions?.['admob-emi-nextgen'] || '');
171
+ // IAP 4.6 requires the synchronous ownership gate in AdMob 4.1 or newer.
172
+ const remoteVersion = /^\d+(?:\.\d+)*$/.test(advertisedVersion) && compareVersions(advertisedVersion, '4.1') >= 0
173
+ ? advertisedVersion : '4.1';
174
+ const candidates = [];
175
+ if (/^\d+(?:\.\d+)*$/.test(remoteVersion) && compareVersions(remoteVersion, '4.0') >= 0) {
176
+ candidates.push({ version: remoteVersion });
177
+ }
178
+ for (const candidate of candidates) {
179
+ if (latest && compareVersions(latest.match(PACKAGE_PATTERN)[1], candidate.version) >= 0) break;
180
+ const name = `admob-nextgen-${candidate.version}`;
181
+ const temporaryRoot = path.join(projectRoot, 'agent-temp', 'admob-package-sync');
182
+ fs.mkdirSync(temporaryRoot, { recursive: true });
183
+ const staging = fs.mkdtempSync(path.join(temporaryRoot, 'package-'));
184
+ try {
185
+ const buffer = await fetch(SERVER + name + '.zip');
186
+ extractPackage(buffer, staging, name, options.AdmZip);
187
+ const destination = path.join(adsDirectory, name);
188
+ if (fs.existsSync(destination)) throw new Error(`Incomplete AdMob package already exists: ${destination}`);
189
+ fs.renameSync(staging, destination);
190
+ latest = name;
191
+ log(`AdMob: installed ${name}.`);
192
+ } catch (error) {
193
+ log(`AdMob: could not install ${name}: ${error.message}`);
194
+ } finally {
195
+ fs.rmSync(staging, { recursive: true, force: true });
196
+ }
197
+ }
198
+ if (!latest) throw new Error('No complete AdMob folder package is available. Check admob-nextgen in the live versions.json and its ZIP on htmlcodeplay.com; existing files were preserved.');
199
+ if (compareVersions(latest.match(PACKAGE_PATTERN)[1], '4.1') < 0) throw new Error('Deferred IAP startup requires admob-nextgen-4.1 or newer; existing sources were preserved.');
200
+ syncPackageDependencies(projectRoot, latest);
201
+ const changed = syncImports(projectRoot, latest);
202
+ // Remove only this plugin's superseded files after the new imports are in place.
203
+ for (const entry of fs.readdirSync(adsDirectory, { withFileTypes: true })) {
204
+ if (entry.isFile() && /^admob-(?:emi-nextgen|app-open-state)-\d+(?:\.\d+)*\.js$/.test(entry.name)) {
205
+ fs.unlinkSync(path.join(adsDirectory, entry.name));
206
+ } else if (entry.isDirectory() && PACKAGE_PATTERN.test(entry.name) && entry.name !== latest) {
207
+ fs.rmSync(path.join(adsDirectory, entry.name), { recursive: true });
208
+ }
209
+ }
210
+ log(`AdMob: ${latest} ready; migrated ${changed.length} file(s).`);
211
+ return latest;
212
+ }
213
+
214
+ module.exports = { syncAdmobNextgen, syncImports, findLatestPackage, compareVersions, extractPackage };
215
+
216
+ if (require.main === module) syncAdmobNextgen().catch(error => {
217
+ console.error(error.message);
218
+ process.exitCode = 1;
219
+ });
@@ -0,0 +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; });
@@ -0,0 +1,80 @@
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 { syncHuaweiPrivacy } = require('../huawei-privacy.cjs');
7
+
8
+ function fixture(t, html) {
9
+ const base = path.resolve(process.env.CODEPLAY_TEST_ROOT || path.join(__dirname, '../../../agent-temp'));
10
+ fs.mkdirSync(base, { recursive: true });
11
+ const root = fs.mkdtempSync(path.join(base, 'huawei-modules-'));
12
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
13
+ const write = (file, text) => {
14
+ const target = path.join(root, file);
15
+ fs.mkdirSync(path.dirname(target), { recursive: true });
16
+ fs.writeFileSync(target, text);
17
+ };
18
+ const read = file => fs.readFileSync(path.join(root, file), 'utf8');
19
+ write('src/index.html', html);
20
+ write('src/js/app.js', 'export const app = true;');
21
+ write('src/js/common.js', 'export const common = true;');
22
+ write('buildCodeplay/.keep', '');
23
+ write('android/app/src/main/AndroidManifest.xml', '<manifest><application></application></manifest>');
24
+ write('capacitor.config.json', JSON.stringify({ appName: 'Test', android: { APP_UNIQUE_ID: 2 } }));
25
+ return { root, write, read };
26
+ }
27
+
28
+ const html = `<html><body>
29
+ <!-- <script type="module" src="./missing-example.js"></script> -->
30
+ <script type="module" src="./js/app.js"></script>
31
+ <script type='module' src='./js/common.js'></script>
32
+ <script src="./jquery.js"></script>
33
+ </body></html>`;
34
+
35
+ test('multiple module entries wait for consent, run in document order and restore exactly', async t => {
36
+ const f = fixture(t, html);
37
+ syncHuaweiPrivacy(f.root, 4);
38
+ const enabled = f.read('src/index.html');
39
+ const wrapper = f.read('buildCodeplay/huawei-privacy-generated.js');
40
+ assert.equal((enabled.match(/huawei-privacy-generated.js/g) || []).length, 1);
41
+ assert.match(enabled, /type='application\/x-codeplay-huawei-module'/);
42
+ assert.ok(enabled.includes('<script src="./jquery.js"></script>'));
43
+ let consent;
44
+ const imports = [];
45
+ vm.runInNewContext(wrapper.replace(/^import .*;\n/m, '').replace(/\bimport\(/g, 'load('), {
46
+ startHuaweiPrivacy: options => { consent = options; },
47
+ load: async entry => { imports.push(entry); },
48
+ });
49
+ assert.deepEqual(imports, []);
50
+ await consent.startApp();
51
+ assert.deepEqual(imports, ['../src/js/app.js', '../src/js/common.js']);
52
+ syncHuaweiPrivacy(f.root, 4);
53
+ assert.equal(f.read('src/index.html'), enabled);
54
+ assert.equal(f.read('buildCodeplay/huawei-privacy-generated.js'), wrapper);
55
+ syncHuaweiPrivacy(f.root, 1);
56
+ assert.equal(f.read('src/index.html'), html);
57
+ syncHuaweiPrivacy(f.root, 4);
58
+ assert.equal(f.read('src/index.html'), enabled);
59
+ });
60
+
61
+ test('upgrades an existing single-entry wrapper and includes a newly added module', t => {
62
+ const f = fixture(t, html.replace("<script type='module' src='./js/common.js'></script>", ''));
63
+ syncHuaweiPrivacy(f.root, 4);
64
+ f.write('src/index.html', f.read('src/index.html').replace('</body>', '<script type="module" src="./js/common.js"></script></body>'));
65
+ syncHuaweiPrivacy(f.root, 4);
66
+ assert.match(f.read('buildCodeplay/huawei-privacy-generated.js'), /await import\("\.\.\/src\/js\/common.js"\)/);
67
+ assert.match(f.read('src/index.html'), /type="application\/x-codeplay-huawei-module"/);
68
+ });
69
+
70
+ test('missing or unsupported secondary entries fail without partial changes', t => {
71
+ for (const entry of ['./missing.js', '../outside.js', 'https://example.com/app.js']) {
72
+ const f = fixture(t, html.replace('./js/common.js', entry));
73
+ const before = f.read('src/index.html');
74
+ const manifest = f.read('android/app/src/main/AndroidManifest.xml');
75
+ assert.throws(() => syncHuaweiPrivacy(f.root, 4), /Huawei privacy: (unsupported app entry|app entry .* was not found)/);
76
+ assert.equal(f.read('src/index.html'), before);
77
+ assert.equal(f.read('android/app/src/main/AndroidManifest.xml'), manifest);
78
+ assert.equal(fs.existsSync(path.join(f.root, 'buildCodeplay/huawei-privacy-generated.js')), false);
79
+ }
80
+ });