codeplay-common 1.3.0 → 1.3.2

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