codeplay-common 1.8.7 → 1.8.8

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