codeplay-common 1.8.3 → 1.8.5

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.
@@ -1,689 +1,693 @@
1
- import { existsSync, readFileSync, readdirSync, promises, constants, writeFileSync, unlinkSync, mkdirSync, renameSync } from 'fs';
2
- import { join, resolve } from 'path';
3
- import { execSync } from 'child_process';
4
- import { createInterface } from 'readline';
5
-
6
- import { fileURLToPath } from 'url';
7
- import { dirname } from 'path';
8
-
9
- // Define a mapping between store IDs and store names
10
- const storeNames = {
11
- "1": "PlayStore",
12
- "2": "SamsungStore",
13
- "7": "AmazonStore"
14
- };
15
-
16
- let _appPackageId;
17
-
18
- let isAdmobFound = false;
19
-
20
- const amazonMinSdkVersion=23;
21
-
22
- const androidManifestPath = join("android", "app", "src", "main", "AndroidManifest.xml");
23
-
24
-
25
-
26
- const __filename = fileURLToPath(import.meta.url);
27
- const __dirname = dirname(__filename);
28
-
29
- function fileExists(filePath) {
30
- return existsSync(filePath);
31
- }
32
-
33
-
34
- const capacitorConfigPath = join(process.cwd(), 'capacitor.config.json');
35
-
36
- function getAdMobConfig() {
37
- if (!fileExists(capacitorConfigPath)) {
38
- throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
39
- }
40
-
41
- const config = JSON.parse(readFileSync(capacitorConfigPath, 'utf8'));
42
- const admobConfig = config.plugins?.AdMob;
43
-
44
- _appPackageId=config.appId;
45
-
46
- if (!admobConfig) {
47
- throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
48
- }
49
-
50
- // Default to true if ADMOB_ENABLED is not specified
51
- const isEnabled = admobConfig.ADMOB_ENABLED !== false;
52
-
53
- if (!isEnabled) {
54
- return { ADMOB_ENABLED: false }; // Skip further validation
55
- }
56
-
57
- if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
58
- throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
59
- }
60
-
61
- return {
62
- ADMOB_ENABLED: true,
63
- APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
64
- APP_ID_IOS: admobConfig.APP_ID_IOS,
65
- USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
66
- };
67
- }
68
-
69
-
70
-
71
- const _capacitorConfig = getAdMobConfig();
72
-
73
- const _isADMOB_ENABLED=_capacitorConfig.ADMOB_ENABLED;
74
-
75
- // Proceed only if ADMOB_ENABLED is true
76
- //if (_capacitorConfig.ADMOB_ENABLED)
77
-
78
-
79
- const admobConfigPath = join('src', 'js','Ads', 'admob-ad-configuration.json');
80
- let admobConfig;
81
-
82
- if (_isADMOB_ENABLED)
83
- {
84
- try
85
- {
86
- admobConfig = JSON.parse(readFileSync(admobConfigPath, 'utf8'));
87
- }
88
- catch (err)
89
- {
90
- console.error("❌ Failed to read admob-ad-configuration.json", err);
91
- process.exit(1);
92
- }
93
- }
94
-
95
-
96
-
97
-
98
-
99
-
100
-
101
-
102
-
103
-
104
-
105
-
106
-
107
-
108
-
109
-
110
-
111
-
112
-
113
-
114
-
115
-
116
- const checkCommonFileStoreId=()=>{
117
- const possibleConfigFiles = ['vite.config.mjs', 'vite.config.js'];
118
- let viteConfigPath;
119
- for (const configFile of possibleConfigFiles) {
120
- const fullPath = resolve( configFile);
121
- if (existsSync(fullPath)) {
122
- viteConfigPath = fullPath;
123
- break;
124
- }
125
- }
126
-
127
- if (!viteConfigPath) {
128
- console.error('❌ Error: No vite.config.mjs or vite.config.js file found.');
129
- process.exit(1);
130
- }
131
-
132
- try {
133
- // Read vite config file
134
- const viteConfigContent = readFileSync(viteConfigPath, 'utf-8');
135
-
136
- // Extract @common alias path
137
- const aliasPattern = /'@common':\s*path\.resolve\(__dirname,\s*'(.+?)'\)/;
138
- const match = viteConfigContent.match(aliasPattern);
139
-
140
- if (!match) {
141
- console.error(`❌ Error: @common alias not found in ${viteConfigPath}`);
142
- process.exit(1);
143
- }
144
-
145
- const commonFilePath = match[1];
146
- const resolvedCommonPath = resolve(__dirname, commonFilePath);
147
-
148
- // Read the common file content
149
- if (!existsSync(resolvedCommonPath)) {
150
- console.error(`❌ Error: Resolved common file does not exist: ${resolvedCommonPath}`);
151
- process.exit(1);
152
- }
153
-
154
- const commonFileContent = readFileSync(resolvedCommonPath, 'utf-8');
155
-
156
- // Check for the _storeid export line
157
- const storeIdPattern = /export\s+let\s+_storeid\s*=\s*import\.meta\.env\.VITE_STORE_ID\s*\|\|\s*1\s*;/;
158
- if (!storeIdPattern.test(commonFileContent)) {
159
- console.error(`❌ Error: _storeid value is wrong in ${commonFilePath}`);
160
- process.exit(1);
161
- }
162
-
163
- console.log(commonFilePath,'Success - No problem found');
164
- } catch (error) {
165
- console.error('❌ Error:', error);
166
- process.exit(1);
167
- }
168
-
169
- }
170
-
171
- const checkIsTestingInAdmob=()=>{
172
-
173
- if (admobConfig.config && admobConfig.config.isTesting === true) {
174
- console.error(`❌ Problem found while generating the AAB file. Please change "isTesting: true" to "isTesting: false" in the "admob-ad-configuration.json" file.`);
175
- process.exit(1); // Exit with an error code to halt the process
176
- } else {
177
- console.log('✅ No problem found. "isTesting" is either already false or not defined.');
178
- }
179
- }
180
-
181
- const checkIsAdsDisableByReturnStatement=()=>{
182
-
183
-
184
- const adsFolder = join('src', 'js', 'Ads');
185
- const filePattern = /^admob-emi-(\d+\.)+\d+\.js$/;
186
-
187
- // Step 1: Find the admob file
188
- const files = readdirSync(adsFolder);
189
- const admobFile = files.find(f => filePattern.test(f));
190
-
191
- if (!admobFile) {
192
- console.log('❌ No Admob file found.');
193
- process.exit(1);
194
- }
195
-
196
- const filePath = join(adsFolder, admobFile);
197
- const content = readFileSync(filePath, 'utf-8');
198
-
199
- // Step 2: Extract the adsOnDeviceReady function body
200
- const functionRegex = /async\s+function\s+adsOnDeviceReady\s*\([^)]*\)\s*{([\s\S]*?)^}/m;
201
- const match = content.match(functionRegex);
202
-
203
- if (!match) {
204
- console.log(`❌ Function 'adsOnDeviceReady' not found in file: ${admobFile}`);
205
- process.exit(1);
206
- }
207
-
208
- const body = match[1];
209
- const lines = body.split('\n').map(line => line.trim());
210
-
211
- // Step 3: Skip blank lines and comments, get the first real code line
212
- let firstCodeLine = '';
213
- for (const line of lines) {
214
- if (line === '' || line.startsWith('//')) continue;
215
- firstCodeLine = line;
216
- break;
217
- }
218
-
219
- // Step 4: Block if it's any of the unwanted returns
220
- const badReturnPattern = /^return\s*(true|false)?\s*;?$/;
221
-
222
- if (badReturnPattern.test(firstCodeLine)) {
223
- console.log(`❌ BLOCKED in file '${admobFile}': First active line in 'adsOnDeviceReady' is '${firstCodeLine}'`);
224
- process.exit(2);
225
- } else {
226
- console.log(`✅ Safe: No early return (true/false) found in 'adsOnDeviceReady' of file '${admobFile}'.`);
227
- }
228
- }
229
-
230
-
231
-
232
- const addPermission_AD_ID=async()=>{
233
-
234
- const admobPluginXmlPath = join('node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
235
-
236
-
237
- //let isAdmobFound = false;
238
- try {
239
- await promises.access(admobPluginXmlPath, constants.F_OK);
240
- isAdmobFound = true;
241
- } catch (err) {
242
- isAdmobFound = false;
243
- }
244
-
245
-
246
- if (isAdmobFound) {
247
- // Check if AndroidManifest.xml exists
248
- if (existsSync(androidManifestPath)) {
249
- // Read the content of AndroidManifest.xml
250
- let manifestContent = readFileSync(androidManifestPath, 'utf8');
251
-
252
- // Check if the ad_id permission already exists
253
- const adIdPermission = '<uses-permission android:name="com.google.android.gms.permission.AD_ID" />';
254
- if (!manifestContent.includes(adIdPermission)) {
255
- console.log("ad_id permission not found. Adding to AndroidManifest.xml.");
256
-
257
- // Add the ad_id permission before the closing </manifest> tag
258
- manifestContent = manifestContent.replace('</manifest>', ` ${adIdPermission}\n</manifest>`);
259
-
260
- // Write the updated manifest content back to AndroidManifest.xml
261
- writeFileSync(androidManifestPath, manifestContent, 'utf8');
262
- console.log("✅ ad_id permission added successfully.");
263
- } else {
264
- console.log("ℹ️ ad_id permission already exists in AndroidManifest.xml.");
265
- }
266
- } else {
267
- console.error("❌ AndroidManifest.xml not found at the specified path.");
268
- }
269
- } else {
270
- console.log("\x1b[33m%s\x1b[0m", "⚠️ No admob found, so permission.AD_ID is not added");
271
- }
272
- }
273
-
274
-
275
-
276
-
277
-
278
-
279
-
280
-
281
-
282
-
283
-
284
- checkCommonFileStoreId();
285
-
286
-
287
-
288
- if (_isADMOB_ENABLED)
289
- {
290
- checkIsTestingInAdmob();
291
- checkIsAdsDisableByReturnStatement()
292
-
293
- await addPermission_AD_ID()
294
- }
295
-
296
-
297
-
298
-
299
-
300
-
301
- const { playstore, samsung, amazon } = (_isADMOB_ENABLED && admobConfig.IAP) ? admobConfig.IAP : { playstore: false, samsung: false, amazon: false };
302
- console.log(`ℹ️ IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
303
-
304
-
305
-
306
-
307
-
308
-
309
- // Get the store ID from the command line arguments
310
- const storeIdArg = process.argv[2]; // Get the store ID from the command line
311
- const storeIds = storeIdArg ? [storeIdArg] : ["1", "2", "7"]; // If a specific ID is provided, use it; otherwise, use all store IDs
312
-
313
- // Store the original minSdkVersion globally
314
- let originalMinSdkVersion;
315
-
316
- // Remove any existing AAB files before starting the build process
317
- const aabDirectory = join("android", "app", "build", "outputs", "bundle", "release");
318
- if (existsSync(aabDirectory)) {
319
- const files = readdirSync(aabDirectory).filter(file => file.endsWith('.aab'));
320
- files.forEach(file => {
321
- const filePath = join(aabDirectory, file);
322
- unlinkSync(filePath);
323
- console.log(`ℹ️ Deleted existing AAB file: ${file}`);
324
- });
325
- }
326
-
327
- const aabOutputDir = join("AAB");
328
- if (!existsSync(aabOutputDir)) {
329
- mkdirSync(aabOutputDir);
330
- console.log(`Created directory: ${aabOutputDir}`);
331
- }
332
-
333
- if (existsSync(aabOutputDir)) {
334
- const files = readdirSync(aabOutputDir).filter(file => file.endsWith('.aab'));
335
- files.forEach(file => {
336
- const filePath = join(aabOutputDir, file);
337
- unlinkSync(filePath);
338
- console.log(`Deleted existing AAB file: ${file}`);
339
- });
340
- }
341
-
342
-
343
- // Extract version code and version name from build.gradle
344
- const gradleFilePath = join("android", "app", "build.gradle");
345
- const gradleContent = readFileSync(gradleFilePath, 'utf8');
346
-
347
- const versionCodeMatch = gradleContent.match(/versionCode\s+(\d+)/);
348
- const versionNameMatch = gradleContent.match(/versionName\s+"([^"]+)"/);
349
-
350
- const versionCode = versionCodeMatch ? versionCodeMatch[1] : '';
351
- const versionName = versionNameMatch ? versionNameMatch[1] : '';
352
-
353
- // Display the current versionCode and versionName
354
- console.log(`Current versionCode: ${versionCode}`);
355
- console.log(`Current versionName: ${versionName}`);
356
-
357
- // Create an interface for user input
358
- const rl = createInterface({
359
- input: process.stdin,
360
- output: process.stdout
361
- });
362
-
363
- // Ask for new versionCode
364
- rl.question('Enter new versionCode (press enter to keep current): ', (newVersionCode) => {
365
- const finalVersionCode = newVersionCode || versionCode; // Use existing if no input
366
-
367
- // Ask for new versionName
368
- rl.question('Enter new versionName (press enter to keep current): ', (newVersionName) => {
369
- const finalVersionName = newVersionName || versionName; // Use existing if no input
370
-
371
- // Log the final version details
372
- console.log(`📦 Final versionCode: ${finalVersionCode}`);
373
- console.log(`📝 Final versionName: ${finalVersionName}`);
374
-
375
-
376
-
377
- // Update build.gradle with the new version details
378
- let updatedGradleContent = gradleContent
379
- .replace(/versionCode\s+\d+/, `versionCode ${finalVersionCode}`)
380
- .replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"`);
381
-
382
- // Check if resConfigs "en" already exists
383
- const resConfigsLine = ' resConfigs "en"';
384
- if (!updatedGradleContent.includes(resConfigsLine)) {
385
- // Add resConfigs "en" below versionName
386
- updatedGradleContent = updatedGradleContent.replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"\n${resConfigsLine}`);
387
- } else {
388
- console.log('ℹ️ resConfigs "en" already exists in build.gradle.');
389
- }
390
-
391
-
392
-
393
-
394
-
395
-
396
- if (/minifyEnabled\s+false/.test(updatedGradleContent)) {
397
- updatedGradleContent = updatedGradleContent.replace(/minifyEnabled\s+false/, 'minifyEnabled true');
398
- console.log('Replaced minifyEnabled false with true.');
399
- } else if (!/minifyEnabled\s+true/.test(updatedGradleContent)) {
400
- // Only insert if minifyEnabled (true or false) is NOT present
401
- if (/buildTypes\s*{[\s\S]*?release\s*{/.test(updatedGradleContent)) {
402
- updatedGradleContent = updatedGradleContent.replace(
403
- /(buildTypes\s*{[\s\S]*?release\s*{)/,
404
- '$1\n minifyEnabled true'
405
- );
406
- console.log('✅ Inserted minifyEnabled true into release block.');
407
- } else {
408
- console.log('⚠️ Warning: buildTypes > release block not found. minifyEnabled was not added.');
409
- }
410
- } else {
411
- console.log('ℹ️ minifyEnabled true already present. No change needed.');
412
- }
413
-
414
-
415
-
416
-
417
-
418
-
419
- // Write the updated gradle content back to build.gradle
420
- writeFileSync(gradleFilePath, updatedGradleContent, 'utf8');
421
- console.log(`✅ Updated build.gradle with versionCode: ${finalVersionCode}, versionName: ${finalVersionName}, resConfigs "en" and "minifyEnabled true"`);
422
-
423
- storeIds.forEach((id) => {
424
- console.log(`ℹ️ Building for Store ID ${id}`);
425
-
426
- // Set the environment variable for store ID
427
- process.env.VITE_STORE_ID = id;
428
-
429
- // Conditionally set the new file name
430
- let newFileName;
431
- let storeName = storeNames[id];
432
-
433
- managePackages(storeName);
434
-
435
- if (storeName === "SamsungStore") {
436
- // For SamsungStore, rename to versionCode value only
437
- newFileName = `${finalVersionCode}.aab`;
438
- } else {
439
- // For other stores, use the standard naming format
440
- newFileName = `app-release-signed-${storeName}-b${finalVersionCode}-v${finalVersionName}.aab`;
441
- }
442
-
443
- //storeName="amazon"
444
- const checkFullPath = join("AAB", newFileName); // Update to point to the new AAB directory
445
-
446
- // Modify minSdkVersion in variables.gradle for SamsungStore
447
- const variablesGradleFilePath = join("android", "variables.gradle");
448
- let variablesGradleContent = readFileSync(variablesGradleFilePath, 'utf8');
449
-
450
- // Extract the current minSdkVersion
451
- const minSdkVersionMatch = variablesGradleContent.match(/minSdkVersion\s*=\s*(\d+)/);
452
- const currentMinSdkVersion = minSdkVersionMatch ? parseInt(minSdkVersionMatch[1], 10) : null;
453
-
454
- // Store the original minSdkVersion (only on the first iteration)
455
- if (!originalMinSdkVersion) {
456
- originalMinSdkVersion = currentMinSdkVersion;
457
- }
458
- try {
459
- // Modify the minSdkVersion based on the store
460
- if (storeName === "SamsungStore" || storeName === "PlayStore" ||
461
- _appPackageId=="vfx.green.editor" || _appPackageId=="audio.music.sound.editor" || _appPackageId=="video.to.gif.maker") {
462
- if (currentMinSdkVersion !== 24) {
463
- variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, 'minSdkVersion = 24');
464
- console.log('minSdkVersion updated to 24 for SamsungStore & PlayStore');
465
- writeFileSync(variablesGradleFilePath, variablesGradleContent);
466
- }
467
- } else {
468
- // For PlayStore and AmazonStore, ensure minSdkVersion is originalMinSdkVersion
469
- //if (currentMinSdkVersion !== originalMinSdkVersion) {
470
- variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, `minSdkVersion = ${amazonMinSdkVersion}`);
471
- console.log(`minSdkVersion reverted to ${amazonMinSdkVersion} for ${storeName}`);
472
- writeFileSync(variablesGradleFilePath, variablesGradleContent);
473
- //}
474
- }
475
-
476
-
477
-
478
- // Run the Node.js script to modify plugin.xml
479
- if (isAdmobFound) {
480
- execSync('node buildCodeplay/modify-plugin-xml.js', { stdio: 'inherit' });
481
- } else {
482
- console.log("\x1b[33m%s\x1b[0m", "Seems to Pro Version [No ads found]");
483
- }
484
-
485
- // Run the Vite build
486
- execSync(`npm run build:storeid${id}`, { stdio: 'inherit' });
487
-
488
-
489
-
490
- // Copy the built files to the appropriate folder
491
- const src = join("www", "*");
492
- const dest = join("android", "app", "src", "main", "assets", "public");
493
-
494
- // Use 'xcopy' command for Windows
495
- execSync(`xcopy ${src} ${dest} /E /I /Y`, { stdio: 'inherit' });
496
-
497
- // Build Android AAB file
498
- //child_process.execSync('cd android && ./gradlew bundleRelease', { stdio: 'inherit' });
499
-
500
-
501
- // Build Android AAB file with Capacitor
502
- execSync('npx cap sync android', { stdio: 'inherit' });
503
- execSync('npx cap build android --androidreleasetype=AAB', { stdio: 'inherit' });
504
-
505
-
506
-
507
- variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, 'minSdkVersion = 24');
508
- console.log('minSdkVersion revert to 24 (default)');
509
- writeFileSync(variablesGradleFilePath, variablesGradleContent);
510
-
511
-
512
- // Rename the output AAB file
513
- const oldFilePath = join(aabDirectory, "app-release-signed.aab");
514
- if (existsSync(oldFilePath)) {
515
- renameSync(oldFilePath, checkFullPath);
516
- console.log(`✅ Renamed output AAB file to: ${newFileName}`);
517
- } else {
518
- console.error("❌ AAB file not found after build.");
519
- }
520
-
521
- } catch (error) {
522
- console.error(`❌ Error during build for Store ID ${id}:`, error);
523
- process.exit(1);
524
- }
525
- });
526
-
527
- rl.close(); // Close the readline interface after all operations
528
- });
529
- });
530
-
531
-
532
-
533
-
534
-
535
- function managePackages(store) {
536
- console.log(`IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
537
-
538
- let install = "";
539
- let uninstall = "";
540
-
541
-
542
-
543
- let manifestContent = readFileSync(androidManifestPath, 'utf-8');
544
-
545
- const permissionsToRemove = [
546
- 'com.android.vending.BILLING',
547
- 'com.samsung.android.iap.permission.BILLING'
548
- ];
549
-
550
-
551
- permissionsToRemove.forEach(permission => {
552
- const permissionRegex = new RegExp(`^\\s*<uses-permission\\s+android:name="${permission}"\\s*/?>\\s*[\r\n]?`, 'm');
553
- if (permissionRegex.test(manifestContent)) {
554
- manifestContent = manifestContent.replace(permissionRegex, '');
555
- console.log(`✅ Removed <uses-permission android:name="${permission}" /> from AndroidManifest.xml`);
556
- }
557
- });
558
-
559
- // Write the updated content back to the file
560
- writeFileSync(androidManifestPath, manifestContent, 'utf-8');
561
-
562
-
563
-
564
- if ((playstore && store === "PlayStore") || (amazon && store === "AmazonStore")) {
565
- install = '@revenuecat/purchases-capacitor';
566
- uninstall = 'cordova-plugin-samsungiap';
567
-
568
- // Update AndroidManifest.xml for PlayStore
569
- if(playstore)
570
- updateAndroidManifest(store,
571
- '<uses-permission android:name="com.android.vending.BILLING" />');
572
-
573
- } else if (samsung && store === "SamsungStore") {
574
- install = 'cordova-plugin-samsungiap';
575
- uninstall = '@revenuecat/purchases-capacitor';
576
-
577
- // Update AndroidManifest.xml for SamsungStore
578
- updateAndroidManifest(store,
579
- '<uses-permission android:name="com.samsung.android.iap.permission.BILLING" />');
580
-
581
- } else {
582
- console.log("No valid store specified or no configurations found. Both plugins will be uninstalled.");
583
- try {
584
- execSync(`npm uninstall cordova-plugin-samsungiap`, { stdio: 'inherit' });
585
- execSync(`npm uninstall @revenuecat/purchases-capacitor`, { stdio: 'inherit' });
586
- console.log(`✅ Both plugins uninstalled successfully.`);
587
- } catch (err) {
588
- console.error("❌ Error uninstalling plugins:", err);
589
- }
590
- return;
591
- }
592
-
593
- console.log(`⚠️ Installing ${install} and uninstalling ${uninstall} for ${store}...`);
594
- try {
595
- if (install) {
596
- execSync(`npm install ${install}`, { stdio: 'inherit' });
597
- }
598
- if (uninstall) {
599
- execSync(`npm uninstall ${uninstall}`, { stdio: 'inherit' });
600
- }
601
- console.log(`✅ ${install} installed and ${uninstall} uninstalled successfully.`);
602
- } catch (err) {
603
- console.error(`❌ Error managing packages for ${store}:`, err);
604
- }
605
- }
606
-
607
-
608
-
609
- function updateAndroidManifest(store, addPermission) {
610
- try {
611
- if (!existsSync(androidManifestPath)) {
612
- console.error("❌ AndroidManifest.xml file not found!");
613
- return;
614
- }
615
-
616
- // Read the content of the AndroidManifest.xml
617
- let manifestContent = readFileSync(androidManifestPath, 'utf-8');
618
-
619
- // Normalize line endings to `\n` for consistent processing
620
- manifestContent = manifestContent.replace(/\r\n/g, '\n');
621
-
622
- // Check if the permission is already present
623
- if (manifestContent.includes(addPermission.trim())) {
624
- console.log(`${addPermission} is already in the AndroidManifest.xml. Skipping addition.`);
625
- return; // Skip if the permission is already present
626
- }
627
-
628
- // Insert the permission before the closing </manifest> tag
629
- const closingTag = '</manifest>';
630
- const formattedPermission = ` ${addPermission.trim()}\n`;
631
- if (manifestContent.includes(closingTag)) {
632
- manifestContent = manifestContent.replace(
633
- closingTag,
634
- `${formattedPermission}${closingTag}`
635
- );
636
- console.log(`✅ Added ${addPermission} before </manifest> tag.`);
637
- } else {
638
- console.warn(`⚠️ </manifest> tag not found. Adding ${addPermission} at the end of the file.`);
639
- manifestContent += `\n${formattedPermission}`;
640
- }
641
-
642
- // Normalize line endings back to `\r\n` and write the updated content
643
- manifestContent = manifestContent.replace(/\n/g, '\r\n');
644
- writeFileSync(androidManifestPath, manifestContent, 'utf-8');
645
- console.log(`✅ AndroidManifest.xml updated successfully for ${store}`);
646
- } catch (err) {
647
- console.error(`❌ Error updating AndroidManifest.xml for ${store}:`, err);
648
- }
649
- }
650
-
651
-
652
-
653
- /* function updateAndroidManifest1(store, addPermission) {
654
- try {
655
- if (!fs.existsSync(androidManifestPath)) {
656
- console.error("AndroidManifest.xml file not found!");
657
- return;
658
- }
659
-
660
- let manifestContent = fs.readFileSync(androidManifestPath, 'utf-8');
661
-
662
-
663
-
664
- // Add the required permission if not already present
665
- if (!manifestContent.includes(addPermission)) {
666
- const manifestLines = manifestContent.split('\n');
667
- const insertIndex = manifestLines.findIndex(line => line.trim().startsWith('<application'));
668
- if (insertIndex > -1) {
669
- manifestLines.splice(insertIndex, 0, ` ${addPermission}`);
670
- manifestContent = manifestLines.join('\n');
671
- console.log(`Added ${addPermission} to AndroidManifest.xml`);
672
- }
673
- }
674
-
675
- // Write the updated content back to the file
676
- fs.writeFileSync(androidManifestPath, manifestContent, 'utf-8');
677
- console.log(`AndroidManifest.xml updated successfully for ${store}`);
678
- } catch (err) {
679
- console.error(`Error updating AndroidManifest.xml for ${store}:`, err);
680
- }
681
- } */
682
-
683
-
684
-
685
-
686
-
687
-
688
-
689
-
1
+ import { existsSync, readFileSync, readdirSync, promises, constants, writeFileSync, unlinkSync, mkdirSync, renameSync } from 'fs';
2
+ import { join, resolve } from 'path';
3
+ import { execSync } from 'child_process';
4
+ import { createInterface } from 'readline';
5
+
6
+ import { fileURLToPath } from 'url';
7
+ import { dirname } from 'path';
8
+
9
+ // Define a mapping between store IDs and store names
10
+ const storeNames = {
11
+ "1": "PlayStore",
12
+ "2": "SamsungStore",
13
+ "7": "AmazonStore"
14
+ };
15
+
16
+ let _appPackageId;
17
+
18
+ let isAdmobFound = false;
19
+
20
+ const amazonMinSdkVersion=23;
21
+
22
+ const androidManifestPath = join("android", "app", "src", "main", "AndroidManifest.xml");
23
+
24
+
25
+
26
+ const __filename = fileURLToPath(import.meta.url);
27
+ const __dirname = dirname(__filename);
28
+
29
+ function fileExists(filePath) {
30
+ return existsSync(filePath);
31
+ }
32
+
33
+
34
+ const capacitorConfigPath = join(process.cwd(), 'capacitor.config.json');
35
+
36
+ function getAdMobConfig() {
37
+ if (!fileExists(capacitorConfigPath)) {
38
+ throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
39
+ }
40
+
41
+ const config = JSON.parse(readFileSync(capacitorConfigPath, 'utf8'));
42
+ const admobConfig = config.plugins?.AdMob;
43
+
44
+ _appPackageId=config.appId;
45
+
46
+ if (!admobConfig) {
47
+ throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
48
+ }
49
+
50
+ // Default to true if ADMOB_ENABLED is not specified
51
+ const isEnabled = admobConfig.ADMOB_ENABLED !== false;
52
+
53
+ if (!isEnabled) {
54
+ return { ADMOB_ENABLED: false }; // Skip further validation
55
+ }
56
+
57
+ if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
58
+ throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
59
+ }
60
+
61
+ return {
62
+ ADMOB_ENABLED: true,
63
+ APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
64
+ APP_ID_IOS: admobConfig.APP_ID_IOS,
65
+ USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
66
+ };
67
+ }
68
+
69
+
70
+
71
+ const _capacitorConfig = getAdMobConfig();
72
+
73
+ const _isADMOB_ENABLED=_capacitorConfig.ADMOB_ENABLED;
74
+
75
+ // Proceed only if ADMOB_ENABLED is true
76
+ //if (_capacitorConfig.ADMOB_ENABLED)
77
+
78
+
79
+ const admobConfigPath = join('src', 'js','Ads', 'admob-ad-configuration.json');
80
+ let admobConfig;
81
+
82
+ if (_isADMOB_ENABLED)
83
+ {
84
+ try
85
+ {
86
+ admobConfig = JSON.parse(readFileSync(admobConfigPath, 'utf8'));
87
+ }
88
+ catch (err)
89
+ {
90
+ console.error("❌ Failed to read admob-ad-configuration.json", err);
91
+ process.exit(1);
92
+ }
93
+ }
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+
110
+
111
+
112
+
113
+
114
+
115
+
116
+ const checkCommonFileStoreId=()=>{
117
+ const possibleConfigFiles = ['vite.config.mjs', 'vite.config.js'];
118
+ let viteConfigPath;
119
+ for (const configFile of possibleConfigFiles) {
120
+ const fullPath = resolve( configFile);
121
+ if (existsSync(fullPath)) {
122
+ viteConfigPath = fullPath;
123
+ break;
124
+ }
125
+ }
126
+
127
+ if (!viteConfigPath) {
128
+ console.error('❌ Error: No vite.config.mjs or vite.config.js file found.');
129
+ process.exit(1);
130
+ }
131
+
132
+ try {
133
+ // Read vite config file
134
+ const viteConfigContent = readFileSync(viteConfigPath, 'utf-8');
135
+
136
+ // Extract @common alias path
137
+ const aliasPattern = /'@common':\s*path\.resolve\(__dirname,\s*'(.+?)'\)/;
138
+ const match = viteConfigContent.match(aliasPattern);
139
+
140
+ if (!match) {
141
+ console.error(`❌ Error: @common alias not found in ${viteConfigPath}`);
142
+ process.exit(1);
143
+ }
144
+
145
+ const commonFilePath = match[1];
146
+ const resolvedCommonPath = resolve(__dirname, commonFilePath);
147
+
148
+ // Read the common file content
149
+ if (!existsSync(resolvedCommonPath)) {
150
+ console.error(`❌ Error: Resolved common file does not exist: ${resolvedCommonPath}`);
151
+ process.exit(1);
152
+ }
153
+
154
+ const commonFileContent = readFileSync(resolvedCommonPath, 'utf-8');
155
+
156
+ // Check for the _storeid export line
157
+ const storeIdPattern = /export\s+let\s+_storeid\s*=\s*import\.meta\.env\.VITE_STORE_ID\s*\|\|\s*1\s*;/;
158
+ if (!storeIdPattern.test(commonFileContent)) {
159
+ console.error(`❌ Error: _storeid value is wrong in ${commonFilePath}`);
160
+ process.exit(1);
161
+ }
162
+
163
+ console.log(commonFilePath,'Success - No problem found');
164
+ } catch (error) {
165
+ console.error('❌ Error:', error);
166
+ process.exit(1);
167
+ }
168
+
169
+ }
170
+
171
+ const checkIsTestingInAdmob=()=>{
172
+
173
+ if (admobConfig.config && admobConfig.config.isTesting === true) {
174
+ console.error(`❌ Problem found while generating the AAB file. Please change "isTesting: true" to "isTesting: false" in the "admob-ad-configuration.json" file.`);
175
+ process.exit(1); // Exit with an error code to halt the process
176
+ } else {
177
+ console.log('✅ No problem found. "isTesting" is either already false or not defined.');
178
+ }
179
+ }
180
+
181
+ const checkIsAdsDisableByReturnStatement=()=>{
182
+
183
+
184
+ const adsFolder = join('src', 'js', 'Ads');
185
+ const filePattern = /^admob-emi-(\d+\.)+\d+\.js$/;
186
+
187
+ // Step 1: Find the admob file
188
+ const files = readdirSync(adsFolder);
189
+ const admobFile = files.find(f => filePattern.test(f));
190
+
191
+ if (!admobFile) {
192
+ console.log('❌ No Admob file found.');
193
+ process.exit(1);
194
+ }
195
+
196
+ const filePath = join(adsFolder, admobFile);
197
+ const content = readFileSync(filePath, 'utf-8');
198
+
199
+ // Step 2: Extract the adsOnDeviceReady function body
200
+ const functionRegex = /async\s+function\s+adsOnDeviceReady\s*\([^)]*\)\s*{([\s\S]*?)^}/m;
201
+ const match = content.match(functionRegex);
202
+
203
+ if (!match) {
204
+ console.log(`❌ Function 'adsOnDeviceReady' not found in file: ${admobFile}`);
205
+ process.exit(1);
206
+ }
207
+
208
+ const body = match[1];
209
+ const lines = body.split('\n').map(line => line.trim());
210
+
211
+ // Step 3: Skip blank lines and comments, get the first real code line
212
+ let firstCodeLine = '';
213
+ for (const line of lines) {
214
+ if (line === '' || line.startsWith('//')) continue;
215
+ firstCodeLine = line;
216
+ break;
217
+ }
218
+
219
+ // Step 4: Block if it's any of the unwanted returns
220
+ const badReturnPattern = /^return\s*(true|false)?\s*;?$/;
221
+
222
+ if (badReturnPattern.test(firstCodeLine)) {
223
+ console.log(`❌ BLOCKED in file '${admobFile}': First active line in 'adsOnDeviceReady' is '${firstCodeLine}'`);
224
+ process.exit(2);
225
+ } else {
226
+ console.log(`✅ Safe: No early return (true/false) found in 'adsOnDeviceReady' of file '${admobFile}'.`);
227
+ }
228
+ }
229
+
230
+
231
+
232
+ const addPermission_AD_ID=async()=>{
233
+
234
+ const admobPluginXmlPath = join('node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
235
+
236
+
237
+ //let isAdmobFound = false;
238
+ try {
239
+ await promises.access(admobPluginXmlPath, constants.F_OK);
240
+ isAdmobFound = true;
241
+ } catch (err) {
242
+ isAdmobFound = false;
243
+ }
244
+
245
+
246
+ if (isAdmobFound) {
247
+ // Check if AndroidManifest.xml exists
248
+ if (existsSync(androidManifestPath)) {
249
+ // Read the content of AndroidManifest.xml
250
+ let manifestContent = readFileSync(androidManifestPath, 'utf8');
251
+
252
+ // Check if the ad_id permission already exists
253
+ const adIdPermission = '<uses-permission android:name="com.google.android.gms.permission.AD_ID" />';
254
+ if (!manifestContent.includes(adIdPermission)) {
255
+ console.log("ad_id permission not found. Adding to AndroidManifest.xml.");
256
+
257
+ // Add the ad_id permission before the closing </manifest> tag
258
+ manifestContent = manifestContent.replace('</manifest>', ` ${adIdPermission}\n</manifest>`);
259
+
260
+ // Write the updated manifest content back to AndroidManifest.xml
261
+ writeFileSync(androidManifestPath, manifestContent, 'utf8');
262
+ console.log("✅ ad_id permission added successfully.");
263
+ } else {
264
+ console.log("ℹ️ ad_id permission already exists in AndroidManifest.xml.");
265
+ }
266
+ } else {
267
+ console.error("❌ AndroidManifest.xml not found at the specified path.");
268
+ }
269
+ } else {
270
+ console.log("\x1b[33m%s\x1b[0m", "⚠️ No admob found, so permission.AD_ID is not added");
271
+ }
272
+ }
273
+
274
+
275
+
276
+
277
+
278
+
279
+
280
+
281
+
282
+
283
+
284
+ checkCommonFileStoreId();
285
+
286
+
287
+
288
+ if (_isADMOB_ENABLED)
289
+ {
290
+ checkIsTestingInAdmob();
291
+ checkIsAdsDisableByReturnStatement()
292
+
293
+ await addPermission_AD_ID()
294
+ }
295
+
296
+
297
+
298
+
299
+
300
+
301
+ const { playstore, samsung, amazon } = (_isADMOB_ENABLED && admobConfig.IAP) ? admobConfig.IAP : { playstore: false, samsung: false, amazon: false };
302
+ console.log(`ℹ️ IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
303
+
304
+
305
+
306
+
307
+
308
+
309
+ // Get the store ID from the command line arguments
310
+ const storeIdArg = process.argv[2]; // Get the store ID from the command line
311
+ const storeIds = storeIdArg ? [storeIdArg] : ["1", "2", "7"]; // If a specific ID is provided, use it; otherwise, use all store IDs
312
+
313
+ // Store the original minSdkVersion globally
314
+ let originalMinSdkVersion;
315
+
316
+ // Remove any existing AAB files before starting the build process
317
+ const aabDirectory = join("android", "app", "build", "outputs", "bundle", "release");
318
+ if (existsSync(aabDirectory)) {
319
+ const files = readdirSync(aabDirectory).filter(file => file.endsWith('.aab'));
320
+ files.forEach(file => {
321
+ const filePath = join(aabDirectory, file);
322
+ unlinkSync(filePath);
323
+ console.log(`ℹ️ Deleted existing AAB file: ${file}`);
324
+ });
325
+ }
326
+
327
+ const aabOutputDir = join("AAB");
328
+ if (!existsSync(aabOutputDir)) {
329
+ mkdirSync(aabOutputDir);
330
+ console.log(`Created directory: ${aabOutputDir}`);
331
+ }
332
+
333
+ if (existsSync(aabOutputDir)) {
334
+ const files = readdirSync(aabOutputDir).filter(file => file.endsWith('.aab'));
335
+ files.forEach(file => {
336
+ const filePath = join(aabOutputDir, file);
337
+ unlinkSync(filePath);
338
+ console.log(`Deleted existing AAB file: ${file}`);
339
+ });
340
+ }
341
+
342
+
343
+ // Extract version code and version name from build.gradle
344
+ const gradleFilePath = join("android", "app", "build.gradle");
345
+ const gradleContent = readFileSync(gradleFilePath, 'utf8');
346
+
347
+ const versionCodeMatch = gradleContent.match(/versionCode\s+(\d+)/);
348
+ const versionNameMatch = gradleContent.match(/versionName\s+"([^"]+)"/);
349
+
350
+ const versionCode = versionCodeMatch ? versionCodeMatch[1] : '';
351
+ const versionName = versionNameMatch ? versionNameMatch[1] : '';
352
+
353
+ // Display the current versionCode and versionName
354
+ console.log(`Current versionCode: ${versionCode}`);
355
+ console.log(`Current versionName: ${versionName}`);
356
+
357
+ // Create an interface for user input
358
+ const rl = createInterface({
359
+ input: process.stdin,
360
+ output: process.stdout
361
+ });
362
+
363
+ // Ask for new versionCode
364
+ rl.question('Enter new versionCode (press enter to keep current): ', (newVersionCode) => {
365
+ const finalVersionCode = newVersionCode || versionCode; // Use existing if no input
366
+
367
+ // Ask for new versionName
368
+ rl.question('Enter new versionName (press enter to keep current): ', (newVersionName) => {
369
+ const finalVersionName = newVersionName || versionName; // Use existing if no input
370
+
371
+ // Log the final version details
372
+ console.log(`📦 Final versionCode: ${finalVersionCode}`);
373
+ console.log(`📝 Final versionName: ${finalVersionName}`);
374
+
375
+
376
+
377
+ // Update build.gradle with the new version details
378
+ let updatedGradleContent = gradleContent
379
+ .replace(/versionCode\s+\d+/, `versionCode ${finalVersionCode}`)
380
+ .replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"`);
381
+
382
+ // Check if resConfigs "en" already exists
383
+ const resConfigsLine = ' resConfigs "en"';
384
+ if (!updatedGradleContent.includes(resConfigsLine)) {
385
+ // Add resConfigs "en" below versionName
386
+ updatedGradleContent = updatedGradleContent.replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"\n${resConfigsLine}`);
387
+ } else {
388
+ console.log('ℹ️ resConfigs "en" already exists in build.gradle.');
389
+ }
390
+
391
+
392
+
393
+
394
+
395
+
396
+ if (/minifyEnabled\s+false/.test(updatedGradleContent)) {
397
+ updatedGradleContent = updatedGradleContent.replace(/minifyEnabled\s+false/, 'minifyEnabled true');
398
+ console.log('Replaced minifyEnabled false with true.');
399
+ } else if (!/minifyEnabled\s+true/.test(updatedGradleContent)) {
400
+ // Only insert if minifyEnabled (true or false) is NOT present
401
+ if (/buildTypes\s*{[\s\S]*?release\s*{/.test(updatedGradleContent)) {
402
+ updatedGradleContent = updatedGradleContent.replace(
403
+ /(buildTypes\s*{[\s\S]*?release\s*{)/,
404
+ '$1\n minifyEnabled true'
405
+ );
406
+ console.log('✅ Inserted minifyEnabled true into release block.');
407
+ } else {
408
+ console.log('⚠️ Warning: buildTypes > release block not found. minifyEnabled was not added.');
409
+ }
410
+ } else {
411
+ console.log('ℹ️ minifyEnabled true already present. No change needed.');
412
+ }
413
+
414
+
415
+
416
+
417
+
418
+
419
+ // Write the updated gradle content back to build.gradle
420
+ writeFileSync(gradleFilePath, updatedGradleContent, 'utf8');
421
+ console.log(`✅ Updated build.gradle with versionCode: ${finalVersionCode}, versionName: ${finalVersionName}, resConfigs "en" and "minifyEnabled true"`);
422
+
423
+ storeIds.forEach((id) => {
424
+ console.log(`ℹ️ Building for Store ID ${id}`);
425
+
426
+ // Set the environment variable for store ID
427
+ process.env.VITE_STORE_ID = id;
428
+
429
+ // Conditionally set the new file name
430
+ let newFileName;
431
+ let storeName = storeNames[id];
432
+
433
+ managePackages(storeName);
434
+
435
+ if (storeName === "SamsungStore") {
436
+ // For SamsungStore, rename to versionCode value only
437
+ newFileName = `${finalVersionCode}.aab`;
438
+ } else {
439
+ // For other stores, use the standard naming format
440
+ newFileName = `app-release-signed-${storeName}-b${finalVersionCode}-v${finalVersionName}.aab`;
441
+ }
442
+
443
+ //storeName="amazon"
444
+ const checkFullPath = join("AAB", newFileName); // Update to point to the new AAB directory
445
+
446
+ // Modify minSdkVersion in variables.gradle for SamsungStore
447
+ const variablesGradleFilePath = join("android", "variables.gradle");
448
+ let variablesGradleContent = readFileSync(variablesGradleFilePath, 'utf8');
449
+
450
+ // Extract the current minSdkVersion
451
+ const minSdkVersionMatch = variablesGradleContent.match(/minSdkVersion\s*=\s*(\d+)/);
452
+ const currentMinSdkVersion = minSdkVersionMatch ? parseInt(minSdkVersionMatch[1], 10) : null;
453
+
454
+ // Store the original minSdkVersion (only on the first iteration)
455
+ if (!originalMinSdkVersion) {
456
+ originalMinSdkVersion = currentMinSdkVersion;
457
+ }
458
+ try {
459
+ // Modify the minSdkVersion based on the store
460
+
461
+
462
+ if(currentMinSdkVersion==23 || currentMinSdkVersion==24)
463
+ {
464
+ if (storeName === "SamsungStore" || storeName === "PlayStore" ||
465
+ _appPackageId=="vfx.green.editor" || _appPackageId=="audio.music.sound.editor" || _appPackageId=="video.to.gif.maker") {
466
+ if (currentMinSdkVersion !== 24) {
467
+ variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, 'minSdkVersion = 24');
468
+ console.log('minSdkVersion updated to 24 for SamsungStore & PlayStore');
469
+ writeFileSync(variablesGradleFilePath, variablesGradleContent);
470
+ }
471
+ } else {
472
+ // For PlayStore and AmazonStore, ensure minSdkVersion is originalMinSdkVersion
473
+ //if (currentMinSdkVersion !== originalMinSdkVersion) {
474
+ variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, `minSdkVersion = ${amazonMinSdkVersion}`);
475
+ console.log(`minSdkVersion reverted to ${amazonMinSdkVersion} for ${storeName}`);
476
+ writeFileSync(variablesGradleFilePath, variablesGradleContent);
477
+ //}
478
+ }
479
+ }
480
+
481
+
482
+ // Run the Node.js script to modify plugin.xml
483
+ if (isAdmobFound) {
484
+ execSync('node buildCodeplay/modify-plugin-xml.js', { stdio: 'inherit' });
485
+ } else {
486
+ console.log("\x1b[33m%s\x1b[0m", "Seems to Pro Version [No ads found]");
487
+ }
488
+
489
+ // Run the Vite build
490
+ execSync(`npm run build:storeid${id}`, { stdio: 'inherit' });
491
+
492
+
493
+
494
+ // Copy the built files to the appropriate folder
495
+ const src = join("www", "*");
496
+ const dest = join("android", "app", "src", "main", "assets", "public");
497
+
498
+ // Use 'xcopy' command for Windows
499
+ execSync(`xcopy ${src} ${dest} /E /I /Y`, { stdio: 'inherit' });
500
+
501
+ // Build Android AAB file
502
+ //child_process.execSync('cd android && ./gradlew bundleRelease', { stdio: 'inherit' });
503
+
504
+
505
+ // Build Android AAB file with Capacitor
506
+ execSync('npx cap sync android', { stdio: 'inherit' });
507
+ execSync('npx cap build android --androidreleasetype=AAB', { stdio: 'inherit' });
508
+
509
+
510
+
511
+ variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, 'minSdkVersion = 24');
512
+ console.log('minSdkVersion revert to 24 (default)');
513
+ writeFileSync(variablesGradleFilePath, variablesGradleContent);
514
+
515
+
516
+ // Rename the output AAB file
517
+ const oldFilePath = join(aabDirectory, "app-release-signed.aab");
518
+ if (existsSync(oldFilePath)) {
519
+ renameSync(oldFilePath, checkFullPath);
520
+ console.log(`✅ Renamed output AAB file to: ${newFileName}`);
521
+ } else {
522
+ console.error("❌ AAB file not found after build.");
523
+ }
524
+
525
+ } catch (error) {
526
+ console.error(`❌ Error during build for Store ID ${id}:`, error);
527
+ process.exit(1);
528
+ }
529
+ });
530
+
531
+ rl.close(); // Close the readline interface after all operations
532
+ });
533
+ });
534
+
535
+
536
+
537
+
538
+
539
+ function managePackages(store) {
540
+ console.log(`IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
541
+
542
+ let install = "";
543
+ let uninstall = "";
544
+
545
+
546
+
547
+ let manifestContent = readFileSync(androidManifestPath, 'utf-8');
548
+
549
+ const permissionsToRemove = [
550
+ 'com.android.vending.BILLING',
551
+ 'com.samsung.android.iap.permission.BILLING'
552
+ ];
553
+
554
+
555
+ permissionsToRemove.forEach(permission => {
556
+ const permissionRegex = new RegExp(`^\\s*<uses-permission\\s+android:name="${permission}"\\s*/?>\\s*[\r\n]?`, 'm');
557
+ if (permissionRegex.test(manifestContent)) {
558
+ manifestContent = manifestContent.replace(permissionRegex, '');
559
+ console.log(`✅ Removed <uses-permission android:name="${permission}" /> from AndroidManifest.xml`);
560
+ }
561
+ });
562
+
563
+ // Write the updated content back to the file
564
+ writeFileSync(androidManifestPath, manifestContent, 'utf-8');
565
+
566
+
567
+
568
+ if ((playstore && store === "PlayStore") || (amazon && store === "AmazonStore")) {
569
+ install = '@revenuecat/purchases-capacitor';
570
+ uninstall = 'cordova-plugin-samsungiap';
571
+
572
+ // Update AndroidManifest.xml for PlayStore
573
+ if(playstore)
574
+ updateAndroidManifest(store,
575
+ '<uses-permission android:name="com.android.vending.BILLING" />');
576
+
577
+ } else if (samsung && store === "SamsungStore") {
578
+ install = 'cordova-plugin-samsungiap';
579
+ uninstall = '@revenuecat/purchases-capacitor';
580
+
581
+ // Update AndroidManifest.xml for SamsungStore
582
+ updateAndroidManifest(store,
583
+ '<uses-permission android:name="com.samsung.android.iap.permission.BILLING" />');
584
+
585
+ } else {
586
+ console.log("No valid store specified or no configurations found. Both plugins will be uninstalled.");
587
+ try {
588
+ execSync(`npm uninstall cordova-plugin-samsungiap`, { stdio: 'inherit' });
589
+ execSync(`npm uninstall @revenuecat/purchases-capacitor`, { stdio: 'inherit' });
590
+ console.log(`✅ Both plugins uninstalled successfully.`);
591
+ } catch (err) {
592
+ console.error("❌ Error uninstalling plugins:", err);
593
+ }
594
+ return;
595
+ }
596
+
597
+ console.log(`⚠️ Installing ${install} and uninstalling ${uninstall} for ${store}...`);
598
+ try {
599
+ if (install) {
600
+ execSync(`npm install ${install}`, { stdio: 'inherit' });
601
+ }
602
+ if (uninstall) {
603
+ execSync(`npm uninstall ${uninstall}`, { stdio: 'inherit' });
604
+ }
605
+ console.log(`✅ ${install} installed and ${uninstall} uninstalled successfully.`);
606
+ } catch (err) {
607
+ console.error(`❌ Error managing packages for ${store}:`, err);
608
+ }
609
+ }
610
+
611
+
612
+
613
+ function updateAndroidManifest(store, addPermission) {
614
+ try {
615
+ if (!existsSync(androidManifestPath)) {
616
+ console.error("❌ AndroidManifest.xml file not found!");
617
+ return;
618
+ }
619
+
620
+ // Read the content of the AndroidManifest.xml
621
+ let manifestContent = readFileSync(androidManifestPath, 'utf-8');
622
+
623
+ // Normalize line endings to `\n` for consistent processing
624
+ manifestContent = manifestContent.replace(/\r\n/g, '\n');
625
+
626
+ // Check if the permission is already present
627
+ if (manifestContent.includes(addPermission.trim())) {
628
+ console.log(`${addPermission} is already in the AndroidManifest.xml. Skipping addition.`);
629
+ return; // Skip if the permission is already present
630
+ }
631
+
632
+ // Insert the permission before the closing </manifest> tag
633
+ const closingTag = '</manifest>';
634
+ const formattedPermission = ` ${addPermission.trim()}\n`;
635
+ if (manifestContent.includes(closingTag)) {
636
+ manifestContent = manifestContent.replace(
637
+ closingTag,
638
+ `${formattedPermission}${closingTag}`
639
+ );
640
+ console.log(`✅ Added ${addPermission} before </manifest> tag.`);
641
+ } else {
642
+ console.warn(`⚠️ </manifest> tag not found. Adding ${addPermission} at the end of the file.`);
643
+ manifestContent += `\n${formattedPermission}`;
644
+ }
645
+
646
+ // Normalize line endings back to `\r\n` and write the updated content
647
+ manifestContent = manifestContent.replace(/\n/g, '\r\n');
648
+ writeFileSync(androidManifestPath, manifestContent, 'utf-8');
649
+ console.log(`✅ AndroidManifest.xml updated successfully for ${store}`);
650
+ } catch (err) {
651
+ console.error(`❌ Error updating AndroidManifest.xml for ${store}:`, err);
652
+ }
653
+ }
654
+
655
+
656
+
657
+ /* function updateAndroidManifest1(store, addPermission) {
658
+ try {
659
+ if (!fs.existsSync(androidManifestPath)) {
660
+ console.error("AndroidManifest.xml file not found!");
661
+ return;
662
+ }
663
+
664
+ let manifestContent = fs.readFileSync(androidManifestPath, 'utf-8');
665
+
666
+
667
+
668
+ // Add the required permission if not already present
669
+ if (!manifestContent.includes(addPermission)) {
670
+ const manifestLines = manifestContent.split('\n');
671
+ const insertIndex = manifestLines.findIndex(line => line.trim().startsWith('<application'));
672
+ if (insertIndex > -1) {
673
+ manifestLines.splice(insertIndex, 0, ` ${addPermission}`);
674
+ manifestContent = manifestLines.join('\n');
675
+ console.log(`Added ${addPermission} to AndroidManifest.xml`);
676
+ }
677
+ }
678
+
679
+ // Write the updated content back to the file
680
+ fs.writeFileSync(androidManifestPath, manifestContent, 'utf-8');
681
+ console.log(`AndroidManifest.xml updated successfully for ${store}`);
682
+ } catch (err) {
683
+ console.error(`Error updating AndroidManifest.xml for ${store}:`, err);
684
+ }
685
+ } */
686
+
687
+
688
+
689
+
690
+
691
+
692
+
693
+