codeplay-common 4.9.7 → 4.10.0

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,1360 +1,1233 @@
1
- /*
2
- Can be run like
3
- node finalrelease
4
- node finalrelease 1
5
- node finalrelease "1,2,7"
6
- */
7
-
8
- import { existsSync, readFileSync, readdirSync, promises, constants, writeFileSync, unlinkSync, mkdirSync, renameSync } from 'fs';
9
- import { join, resolve } from 'path';
10
- import { execSync, execFileSync } from 'child_process';
11
- import { createInterface } from 'readline';
12
-
13
- import { fileURLToPath } from 'url';
14
- import { dirname } from 'path';
15
-
16
- /* const path = require('path');
17
- const fs = require('fs'); */
18
-
19
- import fs from 'fs';
20
- import path from 'path';
21
-
22
- const __filename = fileURLToPath(import.meta.url);
23
- const __dirname = dirname(__filename);
24
-
25
- function stripJavaScriptComments(content) {
26
- let result = '';
27
- let state = 'code';
28
-
29
- for (let index = 0; index < content.length; index++) {
30
- const character = content[index];
31
- const nextCharacter = content[index + 1];
32
-
33
- if (state === 'lineComment') {
34
- if (character === '\n') {
35
- result += character;
36
- state = 'code';
37
- } else {
38
- result += ' ';
39
- }
40
- continue;
41
- }
42
-
43
- if (state === 'blockComment') {
44
- if (character === '*' && nextCharacter === '/') {
45
- result += ' ';
46
- index++;
47
- state = 'code';
48
- } else {
49
- result += character === '\n' ? '\n' : ' ';
50
- }
51
- continue;
52
- }
53
-
54
- if (state !== 'code') {
55
- result += character;
56
-
57
- if (character === '\\') {
58
- if (nextCharacter !== undefined) {
59
- result += nextCharacter;
60
- index++;
61
- }
62
- } else if (
63
- (state === 'singleQuote' && character === "'") ||
64
- (state === 'doubleQuote' && character === '"') ||
65
- (state === 'templateLiteral' && character === '`')
66
- ) {
67
- state = 'code';
68
- }
69
- continue;
70
- }
71
-
72
- if (character === '/' && nextCharacter === '/') {
73
- result += ' ';
74
- index++;
75
- state = 'lineComment';
76
- } else if (character === '/' && nextCharacter === '*') {
77
- result += ' ';
78
- index++;
79
- state = 'blockComment';
80
- } else {
81
- result += character;
82
-
83
- if (character === "'") state = 'singleQuote';
84
- else if (character === '"') state = 'doubleQuote';
85
- else if (character === '`') state = 'templateLiteral';
86
- }
87
- }
88
-
89
- return result;
90
- }
91
-
92
- function checkProductionAdmobAlias() {
93
- const possibleConfigFiles = ['vite.config.mjs', 'vite.config.js'];
94
- const viteConfigPath = possibleConfigFiles
95
- .map(configFile => resolve(__dirname, configFile))
96
- .find(filePath => existsSync(filePath));
97
-
98
- if (!viteConfigPath) {
99
- console.error('❌ FINAL RELEASE BLOCKED: No vite.config.mjs or vite.config.js file found.');
100
- process.exit(1);
101
- }
102
-
103
- const viteConfigContent = stripJavaScriptComments(readFileSync(viteConfigPath, 'utf8'));
104
- const aliasPattern = /(['"])@admob\1\s*:\s*path\.resolve\(\s*__dirname\s*,\s*(['"])([^'"\r\n]+)\2\s*\)/g;
105
- const activeAliases = [...viteConfigContent.matchAll(aliasPattern)].map(match => match[3]);
106
- const productionAliasPattern = /^\.\/src\/js\/Ads\/admob-emi-nextgen-\d+(?:\.\d+)+\.js$/;
107
-
108
- if (activeAliases.length === 0) {
109
- console.error('❌ FINAL RELEASE BLOCKED: The production @admob alias is commented out or missing in the Vite config.');
110
- console.error(" Enable: '@admob': path.resolve(__dirname, './src/js/Ads/admob-emi-nextgen-x.x.js')");
111
- process.exit(1);
112
- }
113
-
114
- if (activeAliases.length > 1) {
115
- console.error('❌ FINAL RELEASE BLOCKED: Multiple active @admob aliases were found in the Vite config.');
116
- console.error(' Keep exactly one active production admob-emi-nextgen-x.x.js alias.');
117
- process.exit(1);
118
- }
119
-
120
- const activeAlias = activeAliases[0];
121
- if (!productionAliasPattern.test(activeAlias)) {
122
- console.error(`❌ FINAL RELEASE BLOCKED: @admob currently points to '${activeAlias}'.`);
123
- console.error(" It must point to './src/js/Ads/admob-emi-nextgen-x.x.js', not a test AdMob file.");
124
- process.exit(1);
125
- }
126
-
127
- const productionAdmobPath = resolve(__dirname, activeAlias);
128
- if (!existsSync(productionAdmobPath)) {
129
- console.error(`❌ FINAL RELEASE BLOCKED: The production @admob file does not exist: ${productionAdmobPath}`);
130
- process.exit(1);
131
- }
132
-
133
- console.log(`✅ Production @admob alias verified: ${activeAlias}`);
134
- }
135
-
136
- // This must be the first release validation so test/no-ad builds cannot proceed.
137
- checkProductionAdmobAlias();
138
-
139
- // Define a mapping between store IDs and store names
140
- /* const storeNames = {
141
- "1": "PlayStore",
142
- "2": "SamsungStore",
143
- "7": "AmazonStore"
144
- }; */
145
-
146
-
147
- const isOnlyOneAPK = false; // 🔥 change to false for normal behavior
148
-
149
- const storeNames = {
150
- "1": "PlayStore",
151
- "2": "SamsungStore",
152
- "7": "AmazonStore",
153
-
154
- "3": "MiStore",
155
- "4": "HuaweiStore",
156
- "5": "OppoStore",
157
- //"6": "iOSStore",
158
- "8": "VivoStore"
159
- };
160
-
161
-
162
- //1=> PlayStore 2=> SamsungStore 3=>MiStore 4=>HuaweiStore 5=>OppoStore 6=>iOSStore 7=> AmazonStore 8=> VivoStore
163
-
164
-
165
-
166
-
167
-
168
-
169
-
170
- let isAdmobFound = false;
171
-
172
- const amazonMinSdkVersion=24;
173
-
174
- const androidManifestPath = join("android", "app", "src", "main", "AndroidManifest.xml");
175
-
176
-
177
- const configPath = path.join(process.cwd(), 'capacitor.config.json');
178
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
179
-
180
- const _appUniqueId = config.android?.APP_UNIQUE_ID;
181
- const _appName=config.appName;
182
- const _appPackageId=config.appId;
183
-
184
- const releaseSyncConfigPath = join(__dirname, 'buildCodeplay', 'release-sync.config.json');
185
- let releaseSyncConfig = {};
186
- if (existsSync(releaseSyncConfigPath)) {
187
- try {
188
- releaseSyncConfig = JSON.parse(readFileSync(releaseSyncConfigPath, 'utf8'));
189
- } catch (error) {
190
- console.warn(`⚠️ Could not read ${releaseSyncConfigPath}: ${error.message}`);
191
- }
192
- }
193
- const RELEASE_SYNC_URL = process.env.CODEPLAY_RELEASE_SYNC_URL || releaseSyncConfig.url || 'https://htmlcodeplay.com/codeplay/api/v1/release/sync';
194
- const RELEASE_SYNC_TOKEN = process.env.CODEPLAY_RELEASE_SYNC_TOKEN || releaseSyncConfig.token || '';
195
- const RELEASE_PLATFORM_IDS = { PlayStore: 1, SamsungStore: 13, AmazonStore: 17, MiStore: 15, HuaweiStore: 12, OppoStore: 14, VivoStore: 16 };
196
-
197
- function syncReleaseToCodeplay(storeName, finalVersionName, finalVersionCode, releasedDate) {
198
- if (!RELEASE_SYNC_TOKEN) {
199
- console.warn(`⚠️ Codeplay release sync skipped: add a token to ${releaseSyncConfigPath}.`);
200
- return;
201
- }
202
- const payload = JSON.stringify({
203
- app_name: _appName,
204
- package_id: _appPackageId,
205
- version_name: String(finalVersionName),
206
- version_code: String(finalVersionCode),
207
- released_date: releasedDate,
208
- language_id: 0,
209
- language_name: 'Capacitor+ Framework 7',
210
- notes: 'Automated release update',
211
- status: 1,
212
- folder_name: path.basename(process.cwd()),
213
- app_unique_id: String(_appUniqueId || ''),
214
- platform_id: RELEASE_PLATFORM_IDS[storeName],
215
- });
216
- try {
217
- const response = execFileSync('curl.exe', ['-sS', '--fail-with-body', '-X', 'POST', RELEASE_SYNC_URL,
218
- '-H', 'Content-Type: application/json', '-H', `X-Release-Token: ${RELEASE_SYNC_TOKEN}`, '--data-binary', payload],
219
- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
220
- console.log(`✅ Codeplay sync (${storeName}): ${response.trim()}`);
221
- } catch (error) {
222
- console.warn(`⚠️ Codeplay sync failed for ${storeName}; continuing release builds: ${error.message}`);
223
- }
224
- }
225
-
226
- const FLOWCHART_API_APP_ID = 228;
227
- const FLOWCHART_SHARED_PATH = join('public', 'src', 'shared.js');
228
- const FLOWCHART_PLAY_API_BASE = 'https://htmlcodeplay.com/appfiles/128FlowChart';
229
- const FLOWCHART_OTHER_STORE_API_BASE = 'https://htmlcodeplay.com/appfiles/128FlowChart/otherapi';
230
- const FLOWCHART_OTHER_STORE_API_HASH = 'd1a3774529b74206ae2117f9c25f258e485a1f7348620e769db19c2796aa1fdf';
231
- const flowchartSharedOriginal = existsSync(FLOWCHART_SHARED_PATH)
232
- ? readFileSync(FLOWCHART_SHARED_PATH, 'utf8')
233
- : null;
234
-
235
- function applyFlowchartStoreApi(storeId) {
236
- if (String(_appUniqueId) !== String(FLOWCHART_API_APP_ID) || !flowchartSharedOriginal) return false;
237
- const apiBase = String(storeId) === '1' ? FLOWCHART_PLAY_API_BASE : FLOWCHART_OTHER_STORE_API_BASE;
238
- const accessHash = String(storeId) === '1' ? '' : FLOWCHART_OTHER_STORE_API_HASH;
239
- const apiBaseMarker = /const FLOWCHART_API_BASE = "[^"]*";/;
240
- const accessHashMarker = /const FLOWCHART_API_ACCESS_HASH = "[^"]*";/;
241
-
242
- if (!apiBaseMarker.test(flowchartSharedOriginal) || !accessHashMarker.test(flowchartSharedOriginal)) {
243
- throw new Error(`Flowchart API configuration markers were not found in ${FLOWCHART_SHARED_PATH}.`);
244
- }
245
-
246
- const updated = flowchartSharedOriginal
247
- .replace(apiBaseMarker, `const FLOWCHART_API_BASE = "${apiBase}";`)
248
- .replace(accessHashMarker, `const FLOWCHART_API_ACCESS_HASH = "${accessHash}";`);
249
- writeFileSync(FLOWCHART_SHARED_PATH, updated, 'utf8');
250
- console.log(`✅ App 228 API endpoint configured for Store ID ${storeId}.`);
251
- return true;
252
- }
253
-
254
- function restoreFlowchartStoreApi() {
255
- if (String(_appUniqueId) === String(FLOWCHART_API_APP_ID) && flowchartSharedOriginal) {
256
- writeFileSync(FLOWCHART_SHARED_PATH, flowchartSharedOriginal, 'utf8');
257
- }
258
- }
259
-
260
-
261
-
262
- function fileExists(filePath) {
263
- return existsSync(filePath);
264
- }
265
-
266
-
267
- const ffmpegPluginXmlPath = path.join(__dirname, 'node_modules', 'codeplay-fmpg', 'plugin.xml');
268
- const capacitorConfigPath = join(process.cwd(), 'capacitor.config.json');
269
-
270
-
271
-
272
- function isFfmpegUsed() {
273
- try {
274
- const xmlContent = fs.readFileSync(ffmpegPluginXmlPath, 'utf8');
275
- // Simple check: if plugin.xml exists and contains <plugin> tag (or any FFmpeg-specific tag)
276
- return /<plugin\b/.test(xmlContent);
277
- } catch (err) {
278
- console.log('⚠️ FFmpeg plugin not found:', err.message);
279
- return false;
280
- }
281
- }
282
-
283
- const _isffmpegUsed = isFfmpegUsed();
284
-
285
- function getAdMobConfig() {
286
- if (!fileExists(capacitorConfigPath)) {
287
- throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
288
- }
289
-
290
- const config = JSON.parse(readFileSync(capacitorConfigPath, 'utf8'));
291
- const admobConfig = config.plugins?.AdMob;
292
-
293
- //_appPackageId=config.appId;
294
-
295
- if (!admobConfig) {
296
- throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
297
- }
298
-
299
- // Default to true if ADMOB_ENABLED is not specified
300
- const isEnabled = admobConfig.ADMOB_ENABLED !== false;
301
-
302
- if (!isEnabled) {
303
- return { ADMOB_ENABLED: false }; // Skip further validation
304
- }
305
-
306
- if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
307
- throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
308
- }
309
-
310
- return {
311
- ADMOB_ENABLED: true,
312
- APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
313
- APP_ID_IOS: admobConfig.APP_ID_IOS,
314
- USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
315
- };
316
- }
317
-
318
-
319
-
320
- const _capacitorConfig = getAdMobConfig();
321
-
322
- const _isADMOB_ENABLED=_capacitorConfig.ADMOB_ENABLED;
323
- isAdmobFound = _isADMOB_ENABLED;
324
-
325
- // Proceed only if ADMOB_ENABLED is true
326
- //if (_capacitorConfig.ADMOB_ENABLED)
327
-
328
-
329
- const admobConfigPath = join('src', 'js','Ads', 'admob-ad-configuration-nextgen.json');
330
- let admobConfig;
331
-
332
- if (_isADMOB_ENABLED)
333
- {
334
- try
335
- {
336
- admobConfig = JSON.parse(readFileSync(admobConfigPath, 'utf8'));
337
- }
338
- catch (err)
339
- {
340
- console.error("❌ Failed to read admob-ad-configuration.json", err);
341
- process.exit(1);
342
- }
343
- }
344
-
345
-
346
-
347
-
348
-
349
- function updateIOSVersion(versionCode, versionName) {
350
-
351
- const pbxprojPath = join("ios", "App", "App.xcodeproj", "project.pbxproj");
352
-
353
- // 🔥 Single check only
354
- if (!existsSync(pbxprojPath)) {
355
- console.warn("⚠️ iOS project not found, skipping version update");
356
- return;
357
- }
358
-
359
-
360
- let content = readFileSync(pbxprojPath, 'utf8');
361
-
362
- // Update MARKETING_VERSION
363
- content = content.replace(
364
- /MARKETING_VERSION = .*?;/g,
365
- `MARKETING_VERSION = ${versionName};`
366
- );
367
-
368
- // Update CURRENT_PROJECT_VERSION
369
- /* content = content.replace(
370
- /CURRENT_PROJECT_VERSION = .*?;/g,
371
- `CURRENT_PROJECT_VERSION = ${versionCode};`
372
- ); */
373
-
374
- writeFileSync(pbxprojPath, content, 'utf8');
375
-
376
- console.log(`🍏 iOS updated via Xcode settings → version: ${versionName}, build: ${versionCode}`);
377
- }
378
-
379
-
380
-
381
-
382
-
383
-
384
-
385
-
386
-
387
-
388
-
389
-
390
-
391
-
392
-
393
-
394
-
395
-
396
-
397
-
398
-
399
- const checkCommonFileStoreId=()=>{
400
- const possibleConfigFiles = ['vite.config.mjs', 'vite.config.js'];
401
- let viteConfigPath;
402
- for (const configFile of possibleConfigFiles) {
403
- const fullPath = resolve( configFile);
404
- if (existsSync(fullPath)) {
405
- viteConfigPath = fullPath;
406
- break;
407
- }
408
- }
409
-
410
- if (!viteConfigPath) {
411
- console.error('❌ Error: No vite.config.mjs or vite.config.js file found.');
412
- process.exit(1);
413
- }
414
-
415
- try {
416
- // Read vite config file
417
- const viteConfigContent = readFileSync(viteConfigPath, 'utf-8');
418
-
419
- // Extract @common alias path
420
- const aliasPattern = /'@common':\s*path\.resolve\(__dirname,\s*'(.+?)'\)/;
421
- const match = viteConfigContent.match(aliasPattern);
422
-
423
- if (!match) {
424
- console.error(`❌ Error: @common alias not found in ${viteConfigPath}`);
425
- process.exit(1);
426
- }
427
-
428
- const commonFilePath = match[1];
429
- const resolvedCommonPath = resolve(__dirname, commonFilePath);
430
-
431
- // Read the common file content
432
- if (!existsSync(resolvedCommonPath)) {
433
- console.error(`❌ Error: Resolved common file does not exist: ${resolvedCommonPath}`);
434
- process.exit(1);
435
- }
436
-
437
- const commonFileContent = readFileSync(resolvedCommonPath, 'utf-8');
438
-
439
- // Check for the _storeid export line
440
- const storeIdPattern = /export\s+let\s+_storeid\s*=\s*import\.meta\.env\.VITE_STORE_ID\s*\|\|\s*1\s*;/;
441
- if (!storeIdPattern.test(commonFileContent)) {
442
- console.error(`❌ Error: _storeid value is wrong in ${commonFilePath}`);
443
- process.exit(1);
444
- }
445
-
446
- console.log(commonFilePath,'Success - No problem found');
447
- } catch (error) {
448
- console.error('❌ Error:', error);
449
- process.exit(1);
450
- }
451
-
452
- }
453
-
454
- const checkIsTestingInAdmob=()=>{
455
-
456
- if (admobConfig.config && admobConfig.config.isTesting === true) {
457
- console.error(`❌ Problem found while generating the AAB file. Please change "isTesting: true" to "isTesting: false" in the "admob-ad-configuration-nextgen.json" file.`);
458
- process.exit(1); // Exit with an error code to halt the process
459
- } else {
460
- console.log('✅ No problem found. "isTesting" is either already false or not defined.');
461
- }
462
- }
463
-
464
- const checkIsAdsDisableByReturnStatement=()=>{
465
-
466
-
467
- const adsFolder = join('src', 'js', 'Ads');
468
- const filePattern = /^admob-emi-nextgen-(\d+\.)+\d+\.js$/;
469
-
470
- // Step 1: Find the admob file
471
- const files = readdirSync(adsFolder);
472
- const admobFile = files.find(f => filePattern.test(f));
473
-
474
- if (!admobFile) {
475
- console.log('❌ No Admob nextgen file found.');
476
- process.exit(1);
477
- }
478
-
479
- const filePath = join(adsFolder, admobFile);
480
- const content = readFileSync(filePath, 'utf-8');
481
-
482
- // Step 2: Extract the adsOnDeviceReady function body
483
- const functionRegex = /async\s+function\s+adsOnDeviceReady\s*\([^)]*\)\s*{([\s\S]*?)^}/m;
484
- const match = content.match(functionRegex);
485
-
486
- if (!match) {
487
- console.log(`❌ Function 'adsOnDeviceReady' not found in file: ${admobFile}`);
488
- process.exit(1);
489
- }
490
-
491
- const body = match[1];
492
- const lines = body.split('\n').map(line => line.trim());
493
-
494
- // Step 3: Skip blank lines and comments, get the first real code line
495
- let firstCodeLine = '';
496
- for (const line of lines) {
497
- if (line === '' || line.startsWith('//')) continue;
498
- firstCodeLine = line;
499
- break;
500
- }
501
-
502
- // Step 4: Block if it's any of the unwanted returns
503
- const badReturnPattern = /^return\s*(true|false)?\s*;?$/;
504
-
505
- if (badReturnPattern.test(firstCodeLine)) {
506
- console.log(`❌ BLOCKED in file '${admobFile}': First active line in 'adsOnDeviceReady' is '${firstCodeLine}'`);
507
- process.exit(2);
508
- } else {
509
- console.log(`✅ Safe: No early return (true/false) found in 'adsOnDeviceReady' of file '${admobFile}'.`);
510
- }
511
- }
512
-
513
-
514
-
515
- const addPermission_AD_ID=async()=>{
516
-
517
- if (isAdmobFound) {
518
- if (existsSync(androidManifestPath)) {
519
- let manifestContent = readFileSync(androidManifestPath, 'utf8');
520
- let modified = false;
521
-
522
- // --- Step 1: Ensure AD_ID permission exists ---
523
- const adIdPermission = '<uses-permission android:name="com.google.android.gms.permission.AD_ID" />';
524
- if (!manifestContent.includes(adIdPermission)) {
525
- console.log("📄 AD_ID permission not found. Adding to AndroidManifest.xml.");
526
- manifestContent = manifestContent.replace('</manifest>', ` ${adIdPermission}\n</manifest>`);
527
- console.log("✅ AD_ID permission added successfully.");
528
- modified = true;
529
- } else {
530
- console.log("ℹ️ AD_ID permission already exists in AndroidManifest.xml.");
531
- }
532
-
533
- // --- Step 2: Ensure OPTIMIZE_AD_LOADING meta-data exists ---
534
- const optimizeAdMeta = `<meta-data android:name="com.google.android.gms.ads.flag.OPTIMIZE_AD_LOADING" android:value="true" />`;
535
-
536
- if (!manifestContent.includes(optimizeAdMeta)) {
537
- console.log("📄 OPTIMIZE_AD_LOADING meta-data not found. Adding to AndroidManifest.xml.");
538
-
539
- const appTagPattern = /<application[^>]*>/;
540
- if (appTagPattern.test(manifestContent)) {
541
- manifestContent = manifestContent.replace(appTagPattern, match => `${match}\n ${optimizeAdMeta}`);
542
- console.log("✅ OPTIMIZE_AD_LOADING meta-data added successfully.");
543
- modified = true;
544
- } else {
545
- console.error("❌ <application> tag not found in AndroidManifest.xml.");
546
- }
547
- } else {
548
- console.log("ℹ️ OPTIMIZE_AD_LOADING meta-data already exists in AndroidManifest.xml.");
549
- }
550
-
551
- // --- Step 3: Write only if modified ---
552
- if (modified) {
553
- writeFileSync(androidManifestPath, manifestContent, 'utf8');
554
- console.log("💾 AndroidManifest.xml updated successfully.");
555
- } else {
556
- console.log("✅ No changes needed. AndroidManifest.xml is up to date.");
557
- }
558
-
559
- } else {
560
- console.error("❌ AndroidManifest.xml not found at the specified path.");
561
- }
562
- } else {
563
- console.log("\x1b[33m%s\x1b[0m", "⚠️ No AdMob found, so AD_ID permission and meta-data were not added");
564
- }
565
-
566
-
567
-
568
-
569
-
570
-
571
- }
572
-
573
-
574
-
575
-
576
-
577
-
578
-
579
-
580
-
581
-
582
-
583
- checkCommonFileStoreId();
584
-
585
-
586
-
587
- if (_isADMOB_ENABLED)
588
- {
589
- checkIsTestingInAdmob();
590
- checkIsAdsDisableByReturnStatement()
591
-
592
- await addPermission_AD_ID()
593
- }
594
-
595
-
596
-
597
- let originalReleaseType, originalSigningType;
598
-
599
- function readCapacitorConfig() {
600
- return JSON.parse(fs.readFileSync(capacitorConfigPath, 'utf8'));
601
- }
602
-
603
- function writeCapacitorConfig(config) {
604
- fs.writeFileSync(capacitorConfigPath, JSON.stringify(config, null, 2), 'utf8');
605
- }
606
-
607
- /* function updateCapacitorConfig(releaseType, signingType) {
608
- const config = readCapacitorConfig();
609
-
610
- // Save original values once
611
- if (originalReleaseType === undefined) originalReleaseType = config.android?.buildOptions?.releaseType || '';
612
- if (originalSigningType === undefined) originalSigningType = config.android?.buildOptions?.signingType || '';
613
-
614
- // Update values
615
- config.android = config.android || {};
616
- config.android.buildOptions = config.android.buildOptions || {};
617
- config.android.buildOptions.releaseType = releaseType;
618
- config.android.buildOptions.signingType = signingType;
619
-
620
- writeCapacitorConfig(config);
621
- console.log(`ℹ️ capacitor.config.json updated: releaseType=${releaseType}, signingType=${signingType}`);
622
- } */
623
-
624
- /* function restoreCapacitorConfig() {
625
- const config = readCapacitorConfig();
626
- if (originalReleaseType !== undefined) config.android.buildOptions.releaseType = originalReleaseType;
627
- if (originalSigningType !== undefined) config.android.buildOptions.signingType = originalSigningType;
628
- writeCapacitorConfig(config);
629
- console.log(`✅ capacitor.config.json restored to original values.`);
630
- }
631
-
632
- process.on('SIGINT', () => {
633
- console.log('\n⚠️ Detected Ctrl+C, restoring capacitor.config.json...');
634
- restoreCapacitorConfig();
635
- process.exit(0);
636
- });
637
-
638
- process.on('exit', () => {
639
- restoreCapacitorConfig();
640
- }); */
641
-
642
-
643
-
644
- const { playstore, samsung, amazon } = (_isADMOB_ENABLED && admobConfig.IAP) ? admobConfig.IAP : { playstore: false, samsung: false, amazon: false };
645
- console.log(`ℹ️ IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
646
-
647
-
648
-
649
-
650
-
651
-
652
- // Get the store ID from the command line arguments
653
- /* const storeIdArg = ["2","3"]//process.argv[2]; // Get the store ID from the command line
654
- const storeIds = storeIdArg ? storeIdArg : Object.keys(storeNames);//["1", "2", "7"]; // If a specific ID is provided, use it; otherwise, use all store IDs
655
-
656
- debugger; */
657
-
658
- let storeIdArg = process.argv[2]; // command-line argument
659
- let storeIds;
660
-
661
- if (storeIdArg) {
662
- try {
663
- // Try parsing as JSON array first
664
- const parsed = JSON.parse(storeIdArg);
665
- if (Array.isArray(parsed)) {
666
- storeIds = parsed.map(String); // ensure strings
667
- } else {
668
- storeIds = [parsed.toString()];
669
- }
670
- } catch (e) {
671
- // Not JSON, assume comma-separated string
672
- storeIds = storeIdArg.split(",").map(s => s.trim());
673
- }
674
- } else {
675
- // No argument, use all store IDs
676
- storeIds = Object.keys(storeNames);
677
- }
678
-
679
-
680
- // 🔥 If only one APK mode, override APK storeIds
681
- /* if (isOnlyOneAPK) {
682
- console.log("⚡ isOnlyOneAPK enabled → Only MiStore (3) will be used for APK build");
683
- storeIds = ["3"]; // Only MiStore
684
- } */
685
-
686
- // Store the original minSdkVersion globally
687
- let originalMinSdkVersion;
688
-
689
- // Remove any existing AAB files before starting the build process
690
- const aabDirectory = join("android", "app", "build", "outputs", "bundle", "release");
691
- if (existsSync(aabDirectory)) {
692
- const files = readdirSync(aabDirectory).filter(file => file.endsWith('.aab'));
693
- files.forEach(file => {
694
- const filePath = join(aabDirectory, file);
695
- unlinkSync(filePath);
696
- console.log(`ℹ️ Deleted existing AAB file: ${file}`);
697
- });
698
- }
699
-
700
- const aabOutputDir = join("AAB");
701
- if (!existsSync(aabOutputDir)) {
702
- mkdirSync(aabOutputDir);
703
- console.log(`Created directory: ${aabOutputDir}`);
704
- }
705
-
706
- if (existsSync(aabOutputDir)) {
707
- const files = readdirSync(aabOutputDir).filter(
708
- file => file.endsWith('.aab') || file.endsWith('.apk')
709
- );
710
-
711
- files.forEach(file => {
712
- const filePath = join(aabOutputDir, file);
713
- unlinkSync(filePath);
714
- console.log(`Deleted existing build file: ${file}`);
715
- });
716
- }
717
-
718
-
719
- // Extract version code and version name from build.gradle
720
- const gradleFilePath = join("android", "app", "build.gradle");
721
- const gradleContent = readFileSync(gradleFilePath, 'utf8');
722
-
723
- // Return the character range of a Gradle block, allowing nested blocks inside it.
724
- function findGradleBlock(content, headerPattern) {
725
- const headerMatch = content.match(headerPattern);
726
- if (!headerMatch) return null;
727
- const openingBrace = content.indexOf('{', headerMatch.index + headerMatch[0].length);
728
- if (openingBrace === -1) return null;
729
- let depth = 0;
730
- let quote = null;
731
- for (let index = openingBrace; index < content.length; index += 1) {
732
- const character = content[index];
733
- const previous = content[index - 1];
734
- if (quote) {
735
- if (character === quote && previous !== '\\') quote = null;
736
- continue;
737
- }
738
- if (character === '\"' || character === "'") quote = character;
739
- else if (character === '{') depth += 1;
740
- else if (character === '}' && --depth === 0) return { start: openingBrace + 1, end: index };
741
- }
742
- return null;
743
- }
744
-
745
- function ensureReleaseCodeOptimization() {
746
- const currentContent = readFileSync(gradleFilePath, 'utf8');
747
- const releaseBlock = findGradleBlock(currentContent, /buildTypes\s*\{[\s\S]*?\brelease\s*/);
748
- if (!releaseBlock) throw new Error('Release build configuration was not found.');
749
-
750
- const releaseContent = currentContent.slice(releaseBlock.start, releaseBlock.end);
751
- let optimizedContent = releaseContent.replace(
752
- /getDefaultProguardFile\(\s*(['"])proguard-android\.txt\1\s*\)/g,
753
- "getDefaultProguardFile('proguard-android-optimize.txt')"
754
- );
755
- if (!/getDefaultProguardFile\(\s*(['"])proguard-android-optimize\.txt\1\s*\)/.test(optimizedContent)) {
756
- throw new Error('Release build must use the optimisation-enabled default ProGuard rules.');
757
- }
758
- const newline = currentContent.includes('\r\n') ? '\r\n' : '\n';
759
- // Preserve commented settings and explicit false values as app-specific opt-outs.
760
- const comments = optimizedContent.match(/\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g) || [];
761
- if (!comments.some(comment => /\bshrinkResources\b/.test(comment))) {
762
- const activeContent = optimizedContent.replace(/\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g, '');
763
- const shrinkResources = /^[ \t]*minifyEnabled\s*(?:=\s*)?true\b/m.test(activeContent);
764
- const shrinkPattern = /^([ \t]*shrinkResources\s*(?:=\s*)?)(true|false)\b/m;
765
- if (shrinkPattern.test(optimizedContent)) {
766
- if (!shrinkResources) optimizedContent = optimizedContent.replace(shrinkPattern, '$1false');
767
- } else {
768
- optimizedContent = `${newline} shrinkResources ${shrinkResources}${optimizedContent}`;
769
- }
770
- }
771
- if (optimizedContent !== releaseContent) {
772
- writeFileSync(gradleFilePath, currentContent.slice(0, releaseBlock.start)
773
- + optimizedContent + currentContent.slice(releaseBlock.end), 'utf8');
774
- }
775
-
776
- const propertiesPath = join(__dirname, 'android', 'gradle.properties');
777
- const properties = readFileSync(propertiesPath, 'utf8');
778
- const propertyPattern = /^[ \t]*[#!]?[ \t]*android\.r8\.optimizedResourceShrinking(?:[ \t]*[=:]|[ \t]+|[ \t]*$)/m;
779
- const property = 'android.r8.optimizedResourceShrinking=true';
780
- const nextProperties = propertyPattern.test(properties)
781
- ? properties
782
- : `${properties.trimEnd()}${newline}${property}${newline}`;
783
- if (nextProperties !== properties) writeFileSync(propertiesPath, nextProperties, 'utf8');
784
- }
785
-
786
- function signReleaseBundleWithSha256() {
787
- const buildOptions = readCapacitorConfig().android?.buildOptions;
788
- if (!buildOptions?.keystorePath || !buildOptions.keystorePassword
789
- || !buildOptions.keystoreAlias || !buildOptions.keystoreAliasPassword) {
790
- throw new Error('Android AAB signing requires the existing keystore path, alias and passwords.');
791
- }
792
-
793
- const keystorePath = resolve(__dirname, 'android', buildOptions.keystorePath);
794
- const bundleDirectory = join(__dirname, 'android', 'app', 'build', 'outputs', 'bundle', 'release');
795
- const unsignedBundle = join(bundleDirectory, 'app-release.aab');
796
- const signedBundle = join(bundleDirectory, 'app-release-signed.aab');
797
- if (!existsSync(keystorePath) || !existsSync(unsignedBundle)) {
798
- throw new Error('The configured upload keystore or release AAB was not found.');
799
- }
800
-
801
- const jarsigner = process.env.JAVA_HOME
802
- ? join(process.env.JAVA_HOME, 'bin', process.platform === 'win32' ? 'jarsigner.exe' : 'jarsigner')
803
- : 'jarsigner';
804
- try {
805
- // Keep passwords out of command arguments and error output.
806
- execFileSync(jarsigner, [
807
- '-sigalg', 'SHA256withRSA', '-digestalg', 'SHA-256',
808
- '-keystore', keystorePath,
809
- '-storepass:env', 'CODEPLAY_AAB_STORE_PASSWORD',
810
- '-keypass:env', 'CODEPLAY_AAB_KEY_PASSWORD',
811
- '-signedjar', signedBundle, unsignedBundle, buildOptions.keystoreAlias,
812
- ], {
813
- stdio: 'pipe',
814
- env: {
815
- ...process.env,
816
- CODEPLAY_AAB_STORE_PASSWORD: buildOptions.keystorePassword,
817
- CODEPLAY_AAB_KEY_PASSWORD: buildOptions.keystoreAliasPassword,
818
- },
819
- });
820
- const verification = execFileSync(jarsigner, [
821
- '-J-Duser.language=en', '-J-Duser.country=US', '-verify', signedBundle,
822
- ], { encoding: 'utf8', stdio: 'pipe' });
823
- if (!verification.includes('jar verified.') || verification.includes('treated as unsigned')) {
824
- throw new Error('Signature verification failed.');
825
- }
826
- } catch {
827
- throw new Error('SHA-256 AAB signing or verification failed. Check the configured upload key and JDK; release stopped.');
828
- }
829
- console.log('✅ Release AAB signed with SHA-256 using the existing upload key and signature verified.');
830
- }
831
-
832
- const amazonWindowExtensionsDependency = 'implementation "androidx.window.extensions.core:core:1.0.0"';
833
- const amazonWindowExtensionsDependencyPattern = /^[ \t]*implementation\s+["']androidx\.window\.extensions\.core:core:[^"']+["'][ \t]*(?:\r?\n)?/gm;
834
-
835
- function setAmazonWindowExtensionsDependency(enabled, { cleanup = false } = {}) {
836
- const currentGradleContent = readFileSync(gradleFilePath, 'utf8');
837
- let nextGradleContent = currentGradleContent.replace(amazonWindowExtensionsDependencyPattern, '');
838
-
839
- if (enabled) {
840
- const dependenciesBlock = findGradleBlock(nextGradleContent, /^\s*dependencies\s*/m);
841
- if (!dependenciesBlock) {
842
- throw new Error(`The dependencies block was not found in ${gradleFilePath}.`);
843
- }
844
-
845
- const newline = nextGradleContent.includes('\r\n') ? '\r\n' : '\n';
846
- const contentBeforeClosingBrace = nextGradleContent.slice(0, dependenciesBlock.end);
847
- const linePrefix = contentBeforeClosingBrace.endsWith('\n') ? '' : newline;
848
- nextGradleContent = contentBeforeClosingBrace
849
- + linePrefix
850
- + ` ${amazonWindowExtensionsDependency}${newline}`
851
- + nextGradleContent.slice(dependenciesBlock.end);
852
- }
853
-
854
- if (nextGradleContent !== currentGradleContent) {
855
- writeFileSync(gradleFilePath, nextGradleContent, 'utf8');
856
- }
857
-
858
- console.log(enabled
859
- ? '✅ Added Amazon Fire WebView compatibility dependency for Store ID 7.'
860
- : cleanup
861
- ? 'ℹ️ Removed temporary Amazon Fire WebView compatibility dependency after build cleanup.'
862
- : 'ℹ️ Amazon Fire WebView compatibility dependency is not included for this build.');
863
- }
864
-
865
- const versionCodeMatch = gradleContent.match(/versionCode\s+(\d+)/);
866
- const versionNameMatch = gradleContent.match(/versionName\s+"([^"]+)"/);
867
-
868
- const versionCode = versionCodeMatch ? versionCodeMatch[1] : '';
869
- const versionName = versionNameMatch ? versionNameMatch[1] : '';
870
-
871
- // Display the current versionCode and versionName
872
- console.log(`Current versionCode: ${versionCode}`);
873
- console.log(`Current versionName: ${versionName}`);
874
-
875
- // Create an interface for user input
876
- async function checkBaselineProfileBeforeRelease() {
877
- const profilePaths = [
878
- join(__dirname, 'baselineProfiles', 'baseline-prof.txt'),
879
- join(__dirname, 'android', 'app', 'src', 'main', 'generated', 'baselineProfiles', 'baseline-prof.txt'),
880
- join(__dirname, 'android', 'app', 'src', 'main', 'baseline-prof.txt'),
881
- join(__dirname, 'android', 'app', 'src', 'main', 'baselineProfiles', 'baseline-prof.txt'),
882
- ];
883
- const hasProfile = () => profilePaths.some(profilePath =>
884
- existsSync(profilePath) && readFileSync(profilePath, 'utf8').trim().length > 0);
885
- if (hasProfile()) return;
886
-
887
- console.log('⚠️ baseline-prof.txt is missing or empty.');
888
- console.log('Generation command: npm run baseline-profile:generate');
889
- console.log('Generation requires an ADB-connected Android device or a configured emulator.');
890
- const answer = await new Promise(resolveAnswer => {
891
- rl.question('Generate AAB/APK without a Baseline Profile? [Enter/Y = continue, n = generate profile first]: ', resolveAnswer);
892
- });
893
- if (answer.trim().toLowerCase() !== 'n') return;
894
-
895
- rl.pause();
896
- try {
897
- execSync('npm run baseline-profile:generate', { cwd: __dirname, stdio: 'inherit' });
898
- if (!hasProfile()) {
899
- throw new Error('Baseline Profile generation did not produce a non-empty baseline-prof.txt; release stopped.');
900
- }
901
- // Reuse setup to back up and synchronise the generated profile before packaging.
902
- execFileSync(process.execPath, [join(__dirname, 'scripts', 'setup-baseline-profile.js')], {
903
- cwd: __dirname,
904
- stdio: 'inherit',
905
- });
906
- } finally {
907
- rl.resume();
908
- }
909
- }
910
-
911
- const rl = createInterface({
912
- input: process.stdin,
913
- output: process.stdout
914
- });
915
-
916
- // Ask for new versionCode
917
- rl.question('Enter new versionCode (press enter to keep current): ', (newVersionCode) => {
918
- const finalVersionCode = newVersionCode || versionCode; // Use existing if no input
919
-
920
- // Ask for new versionName
921
- rl.question('Enter new versionName (press enter to keep current): ', async (newVersionName) => {
922
- const finalVersionName = newVersionName || versionName; // Use existing if no input
923
-
924
- // Log the final version details
925
- console.log(`📦 Final versionCode: ${finalVersionCode}`);
926
- console.log(`📝 Final versionName: ${finalVersionName}`);
927
-
928
-
929
- updateIOSVersion(finalVersionCode, finalVersionName);
930
-
931
- // Update build.gradle with the new version details
932
- let updatedGradleContent = gradleContent
933
- .replace(/versionCode\s+\d+/, `versionCode ${finalVersionCode}`)
934
- .replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"`);
935
-
936
- // Check if resConfigs "en" already exists
937
- const resConfigsLine = ' resConfigs "en"';
938
- if (!updatedGradleContent.includes(resConfigsLine)) {
939
- // Add resConfigs "en" below versionName
940
- updatedGradleContent = updatedGradleContent.replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"\n${resConfigsLine}`);
941
- } else {
942
- console.log('ℹ️ resConfigs "en" already exists in build.gradle.');
943
- }
944
-
945
-
946
-
947
- // List of package IDs for which minify should be false
948
-
949
-
950
- // Determine desired minify value
951
- const desiredMinify = !_isffmpegUsed;
952
-
953
- // Limit minification changes to release; debug may have its own test settings.
954
- const minificationBlock = findGradleBlock(updatedGradleContent, /buildTypes\s*\{[\s\S]*?\brelease\s*/);
955
- if (!minificationBlock) {
956
- throw new Error('Release build configuration was not found.');
957
- }
958
- let minificationContent = updatedGradleContent.slice(minificationBlock.start, minificationBlock.end);
959
- if (/\bminifyEnabled\s*(?:=\s*)?(true|false)\b/.test(minificationContent)) {
960
- // Replace existing value with desired
961
- minificationContent = minificationContent.replace(/\bminifyEnabled\s*(?:=\s*)?(true|false)\b/, `minifyEnabled ${desiredMinify}`);
962
- console.log(`Replaced minifyEnabled with ${desiredMinify}.`);
963
- } else {
964
- // Insert minifyEnabled if not present
965
- minificationContent = `\n minifyEnabled ${desiredMinify}${minificationContent}`;
966
- console.log(`✅ Inserted minifyEnabled ${desiredMinify} into release block.`);
967
- }
968
- updatedGradleContent = updatedGradleContent.slice(0, minificationBlock.start)
969
- + minificationContent + updatedGradleContent.slice(minificationBlock.end);
970
-
971
- // Add native debug symbols for release AABs, but leave any existing setting untouched.
972
- const releaseBlock = findGradleBlock(updatedGradleContent, /buildTypes\s*\{[\s\S]*?\brelease\s*/);
973
- if (releaseBlock) {
974
- const releaseContent = updatedGradleContent.slice(releaseBlock.start, releaseBlock.end);
975
- if (/\bdebugSymbolLevel\b/.test(releaseContent)) {
976
- console.log('ℹ️ debugSymbolLevel already exists in buildTypes.release; leaving it unchanged.');
977
- } else {
978
- const ndkBlock = `\n ndk {\n debugSymbolLevel 'FULL'\n }`;
979
- updatedGradleContent = updatedGradleContent.slice(0, releaseBlock.end)
980
- + ndkBlock
981
- + updatedGradleContent.slice(releaseBlock.end);
982
- console.log("✅ Added debugSymbolLevel 'FULL' to buildTypes.release.");
983
- }
984
- } else {
985
- console.log('⚠️ Warning: buildTypes.release block not found. debugSymbolLevel was not added.');
986
- }
987
-
988
-
989
-
990
-
991
-
992
-
993
- // Write the updated gradle content back to build.gradle
994
- writeFileSync(gradleFilePath, updatedGradleContent, 'utf8');
995
- console.log(`✅ Updated build.gradle with versionCode: ${finalVersionCode}, versionName: ${finalVersionName}, resConfigs "en" and "minifyEnabled true"`);
996
-
997
- let baselineProfileChecked = false;
998
- for (const id of storeIds) {
999
- console.log(`ℹ️ Building for Store ID ${id}`);
1000
-
1001
- // Set the environment variable for store ID
1002
- process.env.VITE_STORE_ID = id;
1003
-
1004
- // Conditionally set the new file name
1005
- let newFileName;
1006
- let storeName = storeNames[id];
1007
-
1008
-
1009
- if (
1010
- isOnlyOneAPK &&
1011
- ["OppoStore", "VivoStore"].includes(storeName)
1012
- ) {
1013
- console.log(`⏭ Skipping ${storeName} because isOnlyOneAPK is enabled`);
1014
- continue; // skip this iteration only
1015
- }
1016
-
1017
-
1018
- managePackages(storeName);
1019
-
1020
- // 🔥 Only change filename logic — nothing else touched
1021
- if (isOnlyOneAPK && ["MiStore","OppoStore","VivoStore"].includes(storeName)) {
1022
-
1023
- newFileName =
1024
- `${_appUniqueId}_${_appName.replaceAll(" ","_")}-VI_MI_OPPO-b${finalVersionCode}-v${finalVersionName.replace(/\./g,'_')}.aab`;
1025
-
1026
- }
1027
- else if (storeName === "SamsungStore") {
1028
-
1029
- newFileName =
1030
- `${_appUniqueId}_${_appName.replaceAll(" ","_")}-${(storeName.toUpperCase()).replace("STORE","")}-b${finalVersionCode}-v${finalVersionName.replace(/\./g,'_')}.aab`;
1031
-
1032
- }
1033
- else {
1034
-
1035
- newFileName =
1036
- `${_appUniqueId}_${_appName.replaceAll(" ","_")}-${(storeName.toUpperCase()).replace("STORE","")}-b${finalVersionCode}-v${finalVersionName}.aab`;
1037
-
1038
- }
1039
-
1040
- //storeName="amazon"
1041
- const checkFullPath = join("AAB", newFileName); // Update to point to the new AAB directory
1042
-
1043
- // Modify minSdkVersion in variables.gradle for SamsungStore
1044
- const variablesGradleFilePath = join("android", "variables.gradle");
1045
- let variablesGradleContent = readFileSync(variablesGradleFilePath, 'utf8');
1046
-
1047
- // Extract the current minSdkVersion
1048
- const minSdkVersionMatch = variablesGradleContent.match(/minSdkVersion\s*=\s*(\d+)/);
1049
- const currentMinSdkVersion = minSdkVersionMatch ? parseInt(minSdkVersionMatch[1], 10) : null;
1050
-
1051
- // Store the original minSdkVersion (only on the first iteration)
1052
- if (!originalMinSdkVersion) {
1053
- originalMinSdkVersion = currentMinSdkVersion;
1054
- }
1055
- try {
1056
- applyFlowchartStoreApi(id);
1057
- const shouldIncludeAmazonWindowExtensions = String(id) === '7' && amazon === true;
1058
- setAmazonWindowExtensionsDependency(shouldIncludeAmazonWindowExtensions);
1059
- // Modify the minSdkVersion based on the store
1060
-
1061
-
1062
- if(currentMinSdkVersion==23 || currentMinSdkVersion==24)
1063
- {
1064
- if (storeName === "SamsungStore" || storeName === "PlayStore" ||
1065
- //_appPackageId=="vfx.green.editor" || _appPackageId=="audio.music.sound.editor" || _appPackageId=="video.to.gif.maker"
1066
-
1067
- //ffmpegUsedPackages.includes(_appPackageId)
1068
- _isffmpegUsed
1069
- ) {
1070
- if (currentMinSdkVersion !== 24) {
1071
- variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, 'minSdkVersion = 24');
1072
- console.log('minSdkVersion updated to 24 for SamsungStore & PlayStore');
1073
- writeFileSync(variablesGradleFilePath, variablesGradleContent);
1074
- }
1075
- } else {
1076
- // For PlayStore and AmazonStore, ensure minSdkVersion is originalMinSdkVersion
1077
- //if (currentMinSdkVersion !== originalMinSdkVersion) {
1078
- variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, `minSdkVersion = ${amazonMinSdkVersion}`);
1079
- console.log(`minSdkVersion reverted to ${amazonMinSdkVersion} for ${storeName}`);
1080
- writeFileSync(variablesGradleFilePath, variablesGradleContent);
1081
- //}
1082
- }
1083
- }
1084
-
1085
-
1086
- // Run the Node.js script to modify plugin.xml
1087
- if (isAdmobFound) {
1088
- const modifyPluginXmlPath = join('buildCodeplay', 'modify-plugin-xml.js');
1089
- if (existsSync(modifyPluginXmlPath)) {
1090
- execSync(`node ${modifyPluginXmlPath}`, { stdio: 'inherit' });
1091
- } else {
1092
- console.log("\x1b[33m%s\x1b[0m", "⚠️ modify-plugin-xml.js not found. Skipping old AdMob plugin.xml modification.");
1093
- }
1094
- } else {
1095
- console.log("\x1b[33m%s\x1b[0m", "Seems to Pro Version [No ads found]");
1096
- }
1097
-
1098
- // Run the Vite build
1099
- execSync(`npm run build:storeid${id}`, { stdio: 'inherit' });
1100
-
1101
-
1102
-
1103
-
1104
-
1105
-
1106
- // Copy the built files to the appropriate folder
1107
- const src = join("www");
1108
- const dest = join("android", "app", "src", "main", "assets", "public");
1109
-
1110
- // Copy the web build with Node so releases work on every platform.
1111
- fs.cpSync(src, dest, { recursive: true, force: true });
1112
-
1113
- // Build Android AAB file
1114
- //child_process.execSync('cd android && ./gradlew bundleRelease', { stdio: 'inherit' });
1115
-
1116
-
1117
- // Build Android AAB or APK file based on store
1118
- console.log(`🏗️ Building release for ${storeName}...`);
1119
-
1120
- /* let buildType = "AAB";
1121
- if (["VivoStore", "OppoStore", "MiStore"].includes(storeName)) {
1122
- buildType = "APK";
1123
- } */
1124
-
1125
-
1126
- // Determine build type and signing type per store
1127
- let buildType = ["VivoStore","OppoStore","MiStore"].includes(storeName) ? "APK" : "AAB";
1128
- let signingType = buildType === "APK" ? "apksigner" : "jarsigner";
1129
-
1130
- // Update capacitor.config.json for this store - This is not needed
1131
- //updateCapacitorConfig(buildType, signingType);
1132
-
1133
-
1134
-
1135
- /* execSync('npx cap sync android', { stdio: 'inherit' });
1136
- execSync(`npx cap build android --androidreleasetype=${buildType}`, { stdio: 'inherit' }); */
1137
-
1138
-
1139
- execSync('npx cap sync android', { stdio: 'inherit' });
1140
-
1141
- if (!baselineProfileChecked) {
1142
- await checkBaselineProfileBeforeRelease();
1143
- baselineProfileChecked = true;
1144
- }
1145
- ensureReleaseCodeOptimization();
1146
-
1147
- if (buildType === "APK") {
1148
- console.log("📦 Using custom Node signing script for APK build...");
1149
- execSync('node buildCodeplay/apk-store-builder.js', { stdio: 'inherit' });
1150
- } else {
1151
- execSync(`npx cap build android --androidreleasetype=${buildType}`, { stdio: 'inherit' });
1152
- signReleaseBundleWithSha256();
1153
- }
1154
-
1155
-
1156
-
1157
- // Determine output paths
1158
- let oldFilePath;
1159
- let newExt = buildType === "APK" ? "apk" : "aab";
1160
-
1161
- if (buildType === "APK") {
1162
- //oldFilePath = join("android", "app", "build", "outputs", "apk", "release", "app-release-signed.apk");
1163
- oldFilePath = join("android", "app", "build", "outputs", "apk", "release", "app-release.apk");
1164
- } else {
1165
- oldFilePath = join("android", "app", "build", "outputs", "bundle", "release", "app-release-signed.aab");
1166
- }
1167
-
1168
- const checkFullPath = join("AAB", newFileName.replace(/\.aab$/, `.${newExt}`));
1169
-
1170
- // Rename the output file
1171
- if (existsSync(oldFilePath)) {
1172
- renameSync(oldFilePath, checkFullPath);
1173
- console.log(`✅ Renamed output ${newExt.toUpperCase()} file to: ${path.basename(checkFullPath)}`);
1174
- syncReleaseToCodeplay(storeName, finalVersionName, finalVersionCode, new Date().toISOString().slice(0, 10));
1175
- } else {
1176
- console.error(`❌ ${newExt.toUpperCase()} file not found after build.`);
1177
- }
1178
-
1179
- } catch (error) {
1180
- console.error(`❌ Error during build for Store ID ${id}:`, error);
1181
- restoreFlowchartStoreApi();
1182
- setAmazonWindowExtensionsDependency(false, {
1183
- cleanup: String(id) === '7' && amazon === true,
1184
- });
1185
- process.exit(1);
1186
- } finally {
1187
- restoreFlowchartStoreApi();
1188
- setAmazonWindowExtensionsDependency(false, {
1189
- cleanup: String(id) === '7' && amazon === true,
1190
- });
1191
- }
1192
- }
1193
-
1194
- rl.close(); // Close the readline interface after all operations
1195
- });
1196
- });
1197
-
1198
-
1199
-
1200
-
1201
-
1202
- function managePackages(store) {
1203
- console.log(`IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
1204
-
1205
- let install = "";
1206
- let uninstall = "";
1207
-
1208
-
1209
-
1210
- let manifestContent = readFileSync(androidManifestPath, 'utf-8');
1211
-
1212
- const permissionsToRemove = [
1213
- 'com.android.vending.BILLING',
1214
- 'com.samsung.android.iap.permission.BILLING'
1215
- ];
1216
-
1217
-
1218
- permissionsToRemove.forEach(permission => {
1219
- const permissionRegex = new RegExp(`^\\s*<uses-permission\\s+android:name="${permission}"\\s*/?>\\s*[\r\n]?`, 'm');
1220
- if (permissionRegex.test(manifestContent)) {
1221
- manifestContent = manifestContent.replace(permissionRegex, '');
1222
- console.log(`✅ Removed <uses-permission android:name="${permission}" /> from AndroidManifest.xml`);
1223
- }
1224
- });
1225
-
1226
- // Write the updated content back to the file
1227
- writeFileSync(androidManifestPath, manifestContent, 'utf-8');
1228
-
1229
-
1230
-
1231
- if ((playstore && store === "PlayStore") || (amazon && store === "AmazonStore")) {
1232
- install = '@revenuecat/purchases-capacitor';
1233
- uninstall = 'cordova-plugin-samsungiap';
1234
-
1235
- // Update AndroidManifest.xml for PlayStore
1236
- if (playstore && store === "PlayStore")
1237
- updateAndroidManifest(store,
1238
- '<uses-permission android:name="com.android.vending.BILLING" />');
1239
-
1240
- } else if (samsung && store === "SamsungStore") {
1241
- install = 'cordova-plugin-samsungiap';
1242
- uninstall = '@revenuecat/purchases-capacitor';
1243
-
1244
- // Update AndroidManifest.xml for SamsungStore
1245
- updateAndroidManifest(store,
1246
- '<uses-permission android:name="com.samsung.android.iap.permission.BILLING" />');
1247
-
1248
- } else {
1249
- console.log("No valid store specified or no configurations found. Both plugins will be uninstalled.");
1250
- try {
1251
- execSync(`npm uninstall cordova-plugin-samsungiap`, { stdio: 'inherit' });
1252
- execSync(`npm uninstall @revenuecat/purchases-capacitor`, { stdio: 'inherit' });
1253
- console.log(`✅ Both plugins uninstalled successfully.`);
1254
- } catch (err) {
1255
- console.error("❌ Error uninstalling plugins:", err);
1256
- }
1257
- return;
1258
- }
1259
-
1260
- console.log(`⚠️ Installing ${install} and uninstalling ${uninstall} for ${store}...`);
1261
- try {
1262
- if (install) {
1263
- execSync(`npm install ${install}`, { stdio: 'inherit' });
1264
- }
1265
- if (uninstall) {
1266
- execSync(`npm uninstall ${uninstall}`, { stdio: 'inherit' });
1267
- }
1268
- console.log(`✅ ${install} installed and ${uninstall} uninstalled successfully.`);
1269
- } catch (err) {
1270
- console.error(`❌ Error managing packages for ${store}:`, err);
1271
- }
1272
- }
1273
-
1274
-
1275
-
1276
- function updateAndroidManifest(store, addPermission) {
1277
- try {
1278
- if (!existsSync(androidManifestPath)) {
1279
- console.error("❌ AndroidManifest.xml file not found!");
1280
- return;
1281
- }
1282
-
1283
- // Read the content of the AndroidManifest.xml
1284
- let manifestContent = readFileSync(androidManifestPath, 'utf-8');
1285
-
1286
- // Normalize line endings to `\n` for consistent processing
1287
- manifestContent = manifestContent.replace(/\r\n/g, '\n');
1288
-
1289
- // Check if the permission is already present
1290
- if (manifestContent.includes(addPermission.trim())) {
1291
- console.log(`${addPermission} is already in the AndroidManifest.xml. Skipping addition.`);
1292
- return; // Skip if the permission is already present
1293
- }
1294
-
1295
- // Insert the permission before the closing </manifest> tag
1296
- const closingTag = '</manifest>';
1297
- const formattedPermission = ` ${addPermission.trim()}\n`;
1298
- if (manifestContent.includes(closingTag)) {
1299
- manifestContent = manifestContent.replace(
1300
- closingTag,
1301
- `${formattedPermission}${closingTag}`
1302
- );
1303
- console.log(`✅ Added ${addPermission} before </manifest> tag.`);
1304
- } else {
1305
- console.warn(`⚠️ </manifest> tag not found. Adding ${addPermission} at the end of the file.`);
1306
- manifestContent += `\n${formattedPermission}`;
1307
- }
1308
-
1309
- // Normalize line endings back to `\r\n` and write the updated content
1310
- manifestContent = manifestContent.replace(/\n/g, '\r\n');
1311
- writeFileSync(androidManifestPath, manifestContent, 'utf-8');
1312
- console.log(`✅ AndroidManifest.xml updated successfully for ${store}`);
1313
- } catch (err) {
1314
- console.error(`❌ Error updating AndroidManifest.xml for ${store}:`, err);
1315
- }
1316
- }
1317
-
1318
-
1319
-
1320
- /* restoreCapacitorConfig();
1321
- console.log("🏁 All builds completed, capacitor.config.json restored."); */
1322
-
1323
-
1324
- /* function updateAndroidManifest1(store, addPermission) {
1325
- try {
1326
- if (!fs.existsSync(androidManifestPath)) {
1327
- console.error("AndroidManifest.xml file not found!");
1328
- return;
1329
- }
1330
-
1331
- let manifestContent = fs.readFileSync(androidManifestPath, 'utf-8');
1332
-
1333
-
1334
-
1335
- // Add the required permission if not already present
1336
- if (!manifestContent.includes(addPermission)) {
1337
- const manifestLines = manifestContent.split('\n');
1338
- const insertIndex = manifestLines.findIndex(line => line.trim().startsWith('<application'));
1339
- if (insertIndex > -1) {
1340
- manifestLines.splice(insertIndex, 0, ` ${addPermission}`);
1341
- manifestContent = manifestLines.join('\n');
1342
- console.log(`Added ${addPermission} to AndroidManifest.xml`);
1343
- }
1344
- }
1345
-
1346
- // Write the updated content back to the file
1347
- fs.writeFileSync(androidManifestPath, manifestContent, 'utf-8');
1348
- console.log(`AndroidManifest.xml updated successfully for ${store}`);
1349
- } catch (err) {
1350
- console.error(`Error updating AndroidManifest.xml for ${store}:`, err);
1351
- }
1352
- } */
1353
-
1354
-
1355
-
1356
-
1357
-
1358
-
1359
-
1360
-
1
+ /*
2
+ Can be run like
3
+ node finalrelease
4
+ node finalrelease 1
5
+ node finalrelease "1,2,7"
6
+ */
7
+
8
+ import { existsSync, readFileSync, readdirSync, promises, constants, writeFileSync, unlinkSync, mkdirSync, renameSync } from 'fs';
9
+ import { join, resolve } from 'path';
10
+ import { execSync, execFileSync } from 'child_process';
11
+ import { createInterface } from 'readline';
12
+
13
+ import { fileURLToPath } from 'url';
14
+ import { dirname } from 'path';
15
+
16
+ /* const path = require('path');
17
+ const fs = require('fs'); */
18
+
19
+ import fs from 'fs';
20
+ import path from 'path';
21
+
22
+ const __filename = fileURLToPath(import.meta.url);
23
+ const __dirname = process.cwd();
24
+
25
+ function stripJavaScriptComments(content) {
26
+ let result = '';
27
+ let state = 'code';
28
+
29
+ for (let index = 0; index < content.length; index++) {
30
+ const character = content[index];
31
+ const nextCharacter = content[index + 1];
32
+
33
+ if (state === 'lineComment') {
34
+ if (character === '\n') {
35
+ result += character;
36
+ state = 'code';
37
+ } else {
38
+ result += ' ';
39
+ }
40
+ continue;
41
+ }
42
+
43
+ if (state === 'blockComment') {
44
+ if (character === '*' && nextCharacter === '/') {
45
+ result += ' ';
46
+ index++;
47
+ state = 'code';
48
+ } else {
49
+ result += character === '\n' ? '\n' : ' ';
50
+ }
51
+ continue;
52
+ }
53
+
54
+ if (state !== 'code') {
55
+ result += character;
56
+
57
+ if (character === '\\') {
58
+ if (nextCharacter !== undefined) {
59
+ result += nextCharacter;
60
+ index++;
61
+ }
62
+ } else if (
63
+ (state === 'singleQuote' && character === "'") ||
64
+ (state === 'doubleQuote' && character === '"') ||
65
+ (state === 'templateLiteral' && character === '`')
66
+ ) {
67
+ state = 'code';
68
+ }
69
+ continue;
70
+ }
71
+
72
+ if (character === '/' && nextCharacter === '/') {
73
+ result += ' ';
74
+ index++;
75
+ state = 'lineComment';
76
+ } else if (character === '/' && nextCharacter === '*') {
77
+ result += ' ';
78
+ index++;
79
+ state = 'blockComment';
80
+ } else {
81
+ result += character;
82
+
83
+ if (character === "'") state = 'singleQuote';
84
+ else if (character === '"') state = 'doubleQuote';
85
+ else if (character === '`') state = 'templateLiteral';
86
+ }
87
+ }
88
+
89
+ return result;
90
+ }
91
+
92
+ function checkProductionAdmobAlias() {
93
+ const possibleConfigFiles = ['vite.config.mjs', 'vite.config.js'];
94
+ const viteConfigPath = possibleConfigFiles
95
+ .map(configFile => resolve(__dirname, configFile))
96
+ .find(filePath => existsSync(filePath));
97
+
98
+ if (!viteConfigPath) {
99
+ console.error('❌ FINAL RELEASE BLOCKED: No vite.config.mjs or vite.config.js file found.');
100
+ process.exit(1);
101
+ }
102
+
103
+ const viteConfigContent = stripJavaScriptComments(readFileSync(viteConfigPath, 'utf8'));
104
+ const aliasPattern = /(['"])@admob\1\s*:\s*path\.resolve\(\s*__dirname\s*,\s*(['"])([^'"\r\n]+)\2\s*\)/g;
105
+ const activeAliases = [...viteConfigContent.matchAll(aliasPattern)].map(match => match[3]);
106
+ const productionAliasPattern = /^\.\/src\/js\/Ads\/(?:admob-nextgen-\d+(?:\.\d+)+\/admob-emi-nextgen|admob-emi-nextgen-\d+(?:\.\d+)+)\.js$/;
107
+
108
+ if (activeAliases.length === 0) {
109
+ console.error('❌ FINAL RELEASE BLOCKED: The production @admob alias is commented out or missing in the Vite config.');
110
+ console.error(" Enable: '@admob': path.resolve(__dirname, './src/js/Ads/admob-nextgen-x.x/admob-emi-nextgen.js')");
111
+ process.exit(1);
112
+ }
113
+
114
+ if (activeAliases.length > 1) {
115
+ console.error('❌ FINAL RELEASE BLOCKED: Multiple active @admob aliases were found in the Vite config.');
116
+ console.error(' Keep exactly one active production @admob alias.');
117
+ process.exit(1);
118
+ }
119
+
120
+ const activeAlias = activeAliases[0];
121
+ if (!productionAliasPattern.test(activeAlias)) {
122
+ console.error(`❌ FINAL RELEASE BLOCKED: @admob currently points to '${activeAlias}'.`);
123
+ console.error(" It must point to './src/js/Ads/admob-nextgen-x.x/admob-emi-nextgen.js', not a test AdMob file.");
124
+ process.exit(1);
125
+ }
126
+
127
+ const productionAdmobPath = resolve(__dirname, activeAlias);
128
+ if (!existsSync(productionAdmobPath)) {
129
+ console.error(`❌ FINAL RELEASE BLOCKED: The production @admob file does not exist: ${productionAdmobPath}`);
130
+ process.exit(1);
131
+ }
132
+
133
+ console.log(`✅ Production @admob alias verified: ${activeAlias}`);
134
+ }
135
+
136
+ // This must be the first release validation so test/no-ad builds cannot proceed.
137
+ checkProductionAdmobAlias();
138
+
139
+ // Define a mapping between store IDs and store names
140
+ /* const storeNames = {
141
+ "1": "PlayStore",
142
+ "2": "SamsungStore",
143
+ "7": "AmazonStore"
144
+ }; */
145
+
146
+
147
+ const isOnlyOneAPK = false; // 🔥 change to false for normal behavior
148
+
149
+ const storeNames = {
150
+ "1": "PlayStore",
151
+ "2": "SamsungStore",
152
+ "7": "AmazonStore",
153
+
154
+ "3": "MiStore",
155
+ "4": "HuaweiStore",
156
+ "5": "OppoStore",
157
+ //"6": "iOSStore",
158
+ "8": "VivoStore"
159
+ };
160
+
161
+
162
+ //1=> PlayStore 2=> SamsungStore 3=>MiStore 4=>HuaweiStore 5=>OppoStore 6=>iOSStore 7=> AmazonStore 8=> VivoStore
163
+
164
+
165
+
166
+
167
+
168
+
169
+
170
+ let isAdmobFound = false;
171
+
172
+ const amazonMinSdkVersion=24;
173
+
174
+ const androidManifestPath = join("android", "app", "src", "main", "AndroidManifest.xml");
175
+
176
+
177
+ const configPath = path.join(process.cwd(), 'capacitor.config.json');
178
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
179
+
180
+ const _appUniqueId = config.android?.APP_UNIQUE_ID;
181
+ const _appName=config.appName;
182
+ const _appPackageId=config.appId;
183
+
184
+ const appReleaseSyncConfigPath = join(process.cwd(), 'buildCodeplay', 'release-sync.config.json');
185
+ const releaseSyncConfigPath = appReleaseSyncConfigPath;
186
+ let releaseSyncConfig = {};
187
+ if (existsSync(releaseSyncConfigPath)) {
188
+ try {
189
+ releaseSyncConfig = JSON.parse(readFileSync(releaseSyncConfigPath, 'utf8'));
190
+ } catch (error) {
191
+ console.warn(`⚠️ Could not read ${releaseSyncConfigPath}: ${error.message}`);
192
+ }
193
+ }
194
+ const RELEASE_SYNC_URL = process.env.CODEPLAY_RELEASE_SYNC_URL || releaseSyncConfig.url || 'https://htmlcodeplay.com/codeplay/api/v1/release/sync';
195
+ const RELEASE_SYNC_TOKEN = process.env.CODEPLAY_RELEASE_SYNC_TOKEN || releaseSyncConfig.token || '';
196
+ const RELEASE_PLATFORM_IDS = { PlayStore: 1, SamsungStore: 13, AmazonStore: 17, MiStore: 15, HuaweiStore: 12, OppoStore: 14, VivoStore: 16 };
197
+
198
+ function syncReleaseToCodeplay(storeName, finalVersionName, finalVersionCode, releasedDate) {
199
+ if (!RELEASE_SYNC_TOKEN) {
200
+ console.warn(`⚠️ Codeplay release sync skipped: add a token to ${releaseSyncConfigPath}.`);
201
+ return;
202
+ }
203
+ const payload = JSON.stringify({
204
+ app_name: _appName,
205
+ package_id: _appPackageId,
206
+ version_name: String(finalVersionName),
207
+ version_code: String(finalVersionCode),
208
+ released_date: releasedDate,
209
+ language_id: 0,
210
+ language_name: 'Capacitor+ Framework 7',
211
+ notes: 'Automated release update',
212
+ status: 1,
213
+ folder_name: path.basename(process.cwd()),
214
+ app_unique_id: String(_appUniqueId || ''),
215
+ platform_id: RELEASE_PLATFORM_IDS[storeName],
216
+ });
217
+ try {
218
+ const response = execFileSync('curl.exe', ['-sS', '--fail-with-body', '-X', 'POST', RELEASE_SYNC_URL,
219
+ '-H', 'Content-Type: application/json', '-H', `X-Release-Token: ${RELEASE_SYNC_TOKEN}`, '--data-binary', payload],
220
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
221
+ console.log(`✅ Codeplay sync (${storeName}): ${response.trim()}`);
222
+ } catch (error) {
223
+ console.warn(`⚠️ Codeplay sync failed for ${storeName}; continuing release builds: ${error.message}`);
224
+ }
225
+ }
226
+
227
+ const FLOWCHART_API_APP_ID = 228;
228
+ const FLOWCHART_SHARED_PATH = join('public', 'src', 'shared.js');
229
+ const FLOWCHART_PLAY_API_BASE = 'https://htmlcodeplay.com/appfiles/128FlowChart';
230
+ const FLOWCHART_OTHER_STORE_API_BASE = 'https://htmlcodeplay.com/appfiles/128FlowChart/otherapi';
231
+ const FLOWCHART_OTHER_STORE_API_HASH = 'd1a3774529b74206ae2117f9c25f258e485a1f7348620e769db19c2796aa1fdf';
232
+ const flowchartSharedOriginal = existsSync(FLOWCHART_SHARED_PATH)
233
+ ? readFileSync(FLOWCHART_SHARED_PATH, 'utf8')
234
+ : null;
235
+
236
+ function applyFlowchartStoreApi(storeId) {
237
+ if (String(_appUniqueId) !== String(FLOWCHART_API_APP_ID) || !flowchartSharedOriginal) return false;
238
+ const apiBase = String(storeId) === '1' ? FLOWCHART_PLAY_API_BASE : FLOWCHART_OTHER_STORE_API_BASE;
239
+ const accessHash = String(storeId) === '1' ? '' : FLOWCHART_OTHER_STORE_API_HASH;
240
+ const apiBaseMarker = /const FLOWCHART_API_BASE = "[^"]*";/;
241
+ const accessHashMarker = /const FLOWCHART_API_ACCESS_HASH = "[^"]*";/;
242
+
243
+ if (!apiBaseMarker.test(flowchartSharedOriginal) || !accessHashMarker.test(flowchartSharedOriginal)) {
244
+ throw new Error(`Flowchart API configuration markers were not found in ${FLOWCHART_SHARED_PATH}.`);
245
+ }
246
+
247
+ const updated = flowchartSharedOriginal
248
+ .replace(apiBaseMarker, `const FLOWCHART_API_BASE = "${apiBase}";`)
249
+ .replace(accessHashMarker, `const FLOWCHART_API_ACCESS_HASH = "${accessHash}";`);
250
+ writeFileSync(FLOWCHART_SHARED_PATH, updated, 'utf8');
251
+ console.log(`✅ App 228 API endpoint configured for Store ID ${storeId}.`);
252
+ return true;
253
+ }
254
+
255
+ function restoreFlowchartStoreApi() {
256
+ if (String(_appUniqueId) === String(FLOWCHART_API_APP_ID) && flowchartSharedOriginal) {
257
+ writeFileSync(FLOWCHART_SHARED_PATH, flowchartSharedOriginal, 'utf8');
258
+ }
259
+ }
260
+
261
+
262
+
263
+ function fileExists(filePath) {
264
+ return existsSync(filePath);
265
+ }
266
+
267
+
268
+ const ffmpegPluginXmlPath = path.join(__dirname, 'node_modules', 'codeplay-fmpg', 'plugin.xml');
269
+ const capacitorConfigPath = join(process.cwd(), 'capacitor.config.json');
270
+
271
+
272
+
273
+ function isFfmpegUsed() {
274
+ try {
275
+ const xmlContent = fs.readFileSync(ffmpegPluginXmlPath, 'utf8');
276
+ // Simple check: if plugin.xml exists and contains <plugin> tag (or any FFmpeg-specific tag)
277
+ return /<plugin\b/.test(xmlContent);
278
+ } catch (err) {
279
+ console.log('⚠️ FFmpeg plugin not found:', err.message);
280
+ return false;
281
+ }
282
+ }
283
+
284
+ const _isffmpegUsed = isFfmpegUsed();
285
+
286
+ function getAdMobConfig() {
287
+ if (!fileExists(capacitorConfigPath)) {
288
+ throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
289
+ }
290
+
291
+ const config = JSON.parse(readFileSync(capacitorConfigPath, 'utf8'));
292
+ const admobConfig = config.plugins?.AdMob;
293
+
294
+ //_appPackageId=config.appId;
295
+
296
+ if (!admobConfig) {
297
+ throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
298
+ }
299
+
300
+ // Default to true if ADMOB_ENABLED is not specified
301
+ const isEnabled = admobConfig.ADMOB_ENABLED !== false;
302
+
303
+ if (!isEnabled) {
304
+ return { ADMOB_ENABLED: false }; // Skip further validation
305
+ }
306
+
307
+ if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
308
+ throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
309
+ }
310
+
311
+ return {
312
+ ADMOB_ENABLED: true,
313
+ APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
314
+ APP_ID_IOS: admobConfig.APP_ID_IOS,
315
+ USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
316
+ };
317
+ }
318
+
319
+
320
+
321
+ const _capacitorConfig = getAdMobConfig();
322
+
323
+ const _isADMOB_ENABLED=_capacitorConfig.ADMOB_ENABLED;
324
+ isAdmobFound = _isADMOB_ENABLED;
325
+
326
+ // Proceed only if ADMOB_ENABLED is true
327
+ //if (_capacitorConfig.ADMOB_ENABLED)
328
+
329
+
330
+ const admobConfigPath = join('src', 'js','Ads', 'admob-ad-configuration-nextgen.json');
331
+ let admobConfig;
332
+
333
+ if (_isADMOB_ENABLED)
334
+ {
335
+ try
336
+ {
337
+ admobConfig = JSON.parse(readFileSync(admobConfigPath, 'utf8'));
338
+ }
339
+ catch (err)
340
+ {
341
+ console.error("❌ Failed to read admob-ad-configuration.json", err);
342
+ process.exit(1);
343
+ }
344
+ }
345
+
346
+
347
+
348
+
349
+
350
+ function updateIOSVersion(versionCode, versionName) {
351
+
352
+ const pbxprojPath = join("ios", "App", "App.xcodeproj", "project.pbxproj");
353
+
354
+ // 🔥 Single check only
355
+ if (!existsSync(pbxprojPath)) {
356
+ console.warn("⚠️ iOS project not found, skipping version update");
357
+ return;
358
+ }
359
+
360
+
361
+ let content = readFileSync(pbxprojPath, 'utf8');
362
+
363
+ // Update MARKETING_VERSION
364
+ content = content.replace(
365
+ /MARKETING_VERSION = .*?;/g,
366
+ `MARKETING_VERSION = ${versionName};`
367
+ );
368
+
369
+ // Update CURRENT_PROJECT_VERSION
370
+ /* content = content.replace(
371
+ /CURRENT_PROJECT_VERSION = .*?;/g,
372
+ `CURRENT_PROJECT_VERSION = ${versionCode};`
373
+ ); */
374
+
375
+ writeFileSync(pbxprojPath, content, 'utf8');
376
+
377
+ console.log(`🍏 iOS updated via Xcode settings → version: ${versionName}, build: ${versionCode}`);
378
+ }
379
+
380
+
381
+
382
+
383
+
384
+
385
+
386
+
387
+
388
+
389
+
390
+
391
+
392
+
393
+
394
+
395
+
396
+
397
+
398
+
399
+
400
+ const checkCommonFileStoreId=()=>{
401
+ const possibleConfigFiles = ['vite.config.mjs', 'vite.config.js'];
402
+ let viteConfigPath;
403
+ for (const configFile of possibleConfigFiles) {
404
+ const fullPath = resolve( configFile);
405
+ if (existsSync(fullPath)) {
406
+ viteConfigPath = fullPath;
407
+ break;
408
+ }
409
+ }
410
+
411
+ if (!viteConfigPath) {
412
+ console.error('❌ Error: No vite.config.mjs or vite.config.js file found.');
413
+ process.exit(1);
414
+ }
415
+
416
+ try {
417
+ // Read vite config file
418
+ const viteConfigContent = readFileSync(viteConfigPath, 'utf-8');
419
+
420
+ // Extract @common alias path
421
+ const aliasPattern = /'@common':\s*path\.resolve\(__dirname,\s*'(.+?)'\)/;
422
+ const match = viteConfigContent.match(aliasPattern);
423
+
424
+ if (!match) {
425
+ console.error(`❌ Error: @common alias not found in ${viteConfigPath}`);
426
+ process.exit(1);
427
+ }
428
+
429
+ const commonFilePath = match[1];
430
+ const resolvedCommonPath = resolve(__dirname, commonFilePath);
431
+
432
+ // Read the common file content
433
+ if (!existsSync(resolvedCommonPath)) {
434
+ console.error(`❌ Error: Resolved common file does not exist: ${resolvedCommonPath}`);
435
+ process.exit(1);
436
+ }
437
+
438
+ const commonFileContent = readFileSync(resolvedCommonPath, 'utf-8');
439
+
440
+ // Check for the _storeid export line
441
+ const storeIdPattern = /export\s+let\s+_storeid\s*=\s*import\.meta\.env\.VITE_STORE_ID\s*\|\|\s*1\s*;/;
442
+ if (!storeIdPattern.test(commonFileContent)) {
443
+ console.error(`❌ Error: _storeid value is wrong in ${commonFilePath}`);
444
+ process.exit(1);
445
+ }
446
+
447
+ console.log(commonFilePath,'Success - No problem found');
448
+ } catch (error) {
449
+ console.error('❌ Error:', error);
450
+ process.exit(1);
451
+ }
452
+
453
+ }
454
+
455
+ const checkIsTestingInAdmob=()=>{
456
+
457
+ if (admobConfig.config && admobConfig.config.isTesting === true) {
458
+ console.error(`❌ Problem found while generating the AAB file. Please change "isTesting: true" to "isTesting: false" in the "admob-ad-configuration-nextgen.json" file.`);
459
+ process.exit(1); // Exit with an error code to halt the process
460
+ } else {
461
+ console.log('✅ No problem found. "isTesting" is either already false or not defined.');
462
+ }
463
+ }
464
+
465
+ const checkIsAdsDisableByReturnStatement=()=>{
466
+
467
+
468
+ // Inspect the controller selected by the validated production alias.
469
+ const viteFile = ['vite.config.mjs', 'vite.config.js']
470
+ .map(file => resolve(__dirname, file)).find(file => existsSync(file));
471
+ const config = stripJavaScriptComments(readFileSync(viteFile, 'utf8'));
472
+ const alias = config.match(/(['"])@admob\1\s*:\s*path\.resolve\(\s*__dirname\s*,\s*(['"])([^'"\r\n]+)\2\s*\)/);
473
+ const filePath = resolve(__dirname, alias[3]);
474
+ const admobFile = alias[3];
475
+ const content = readFileSync(filePath, 'utf-8');
476
+
477
+ // Step 2: Extract the adsOnDeviceReady function body
478
+ const functionRegex = /async\s+function\s+adsOnDeviceReady\s*\([^)]*\)\s*{([\s\S]*?)^}/m;
479
+ const match = content.match(functionRegex);
480
+
481
+ if (!match) {
482
+ console.log(`❌ Function 'adsOnDeviceReady' not found in file: ${admobFile}`);
483
+ process.exit(1);
484
+ }
485
+
486
+ const body = match[1];
487
+ const lines = body.split('\n').map(line => line.trim());
488
+
489
+ // Step 3: Skip blank lines and comments, get the first real code line
490
+ let firstCodeLine = '';
491
+ for (const line of lines) {
492
+ if (line === '' || line.startsWith('//')) continue;
493
+ firstCodeLine = line;
494
+ break;
495
+ }
496
+
497
+ // Step 4: Block if it's any of the unwanted returns
498
+ const badReturnPattern = /^return\s*(true|false)?\s*;?$/;
499
+
500
+ if (badReturnPattern.test(firstCodeLine)) {
501
+ console.log(`❌ BLOCKED in file '${admobFile}': First active line in 'adsOnDeviceReady' is '${firstCodeLine}'`);
502
+ process.exit(2);
503
+ } else {
504
+ console.log(`✅ Safe: No early return (true/false) found in 'adsOnDeviceReady' of file '${admobFile}'.`);
505
+ }
506
+ }
507
+
508
+
509
+
510
+ const addPermission_AD_ID=async()=>{
511
+
512
+ if (isAdmobFound) {
513
+ if (existsSync(androidManifestPath)) {
514
+ let manifestContent = readFileSync(androidManifestPath, 'utf8');
515
+ let modified = false;
516
+
517
+ // --- Step 1: Ensure AD_ID permission exists ---
518
+ const adIdPermission = '<uses-permission android:name="com.google.android.gms.permission.AD_ID" />';
519
+ if (!manifestContent.includes(adIdPermission)) {
520
+ console.log("📄 AD_ID permission not found. Adding to AndroidManifest.xml.");
521
+ manifestContent = manifestContent.replace('</manifest>', ` ${adIdPermission}\n</manifest>`);
522
+ console.log("✅ AD_ID permission added successfully.");
523
+ modified = true;
524
+ } else {
525
+ console.log("ℹ️ AD_ID permission already exists in AndroidManifest.xml.");
526
+ }
527
+
528
+ // --- Step 2: Ensure OPTIMIZE_AD_LOADING meta-data exists ---
529
+ const optimizeAdMeta = `<meta-data android:name="com.google.android.gms.ads.flag.OPTIMIZE_AD_LOADING" android:value="true" />`;
530
+
531
+ if (!manifestContent.includes(optimizeAdMeta)) {
532
+ console.log("📄 OPTIMIZE_AD_LOADING meta-data not found. Adding to AndroidManifest.xml.");
533
+
534
+ const appTagPattern = /<application[^>]*>/;
535
+ if (appTagPattern.test(manifestContent)) {
536
+ manifestContent = manifestContent.replace(appTagPattern, match => `${match}\n ${optimizeAdMeta}`);
537
+ console.log("✅ OPTIMIZE_AD_LOADING meta-data added successfully.");
538
+ modified = true;
539
+ } else {
540
+ console.error("❌ <application> tag not found in AndroidManifest.xml.");
541
+ }
542
+ } else {
543
+ console.log("ℹ️ OPTIMIZE_AD_LOADING meta-data already exists in AndroidManifest.xml.");
544
+ }
545
+
546
+ // --- Step 3: Write only if modified ---
547
+ if (modified) {
548
+ writeFileSync(androidManifestPath, manifestContent, 'utf8');
549
+ console.log("💾 AndroidManifest.xml updated successfully.");
550
+ } else {
551
+ console.log("✅ No changes needed. AndroidManifest.xml is up to date.");
552
+ }
553
+
554
+ } else {
555
+ console.error("❌ AndroidManifest.xml not found at the specified path.");
556
+ }
557
+ } else {
558
+ console.log("\x1b[33m%s\x1b[0m", "⚠️ No AdMob found, so AD_ID permission and meta-data were not added");
559
+ }
560
+
561
+
562
+
563
+
564
+
565
+
566
+ }
567
+
568
+
569
+
570
+
571
+
572
+
573
+
574
+
575
+
576
+
577
+
578
+ checkCommonFileStoreId();
579
+
580
+
581
+
582
+ if (_isADMOB_ENABLED)
583
+ {
584
+ checkIsTestingInAdmob();
585
+ checkIsAdsDisableByReturnStatement()
586
+
587
+ await addPermission_AD_ID()
588
+ }
589
+
590
+
591
+
592
+ let originalReleaseType, originalSigningType;
593
+
594
+ function readCapacitorConfig() {
595
+ return JSON.parse(fs.readFileSync(capacitorConfigPath, 'utf8'));
596
+ }
597
+
598
+ function writeCapacitorConfig(config) {
599
+ fs.writeFileSync(capacitorConfigPath, JSON.stringify(config, null, 2), 'utf8');
600
+ }
601
+
602
+ /* function updateCapacitorConfig(releaseType, signingType) {
603
+ const config = readCapacitorConfig();
604
+
605
+ // Save original values once
606
+ if (originalReleaseType === undefined) originalReleaseType = config.android?.buildOptions?.releaseType || '';
607
+ if (originalSigningType === undefined) originalSigningType = config.android?.buildOptions?.signingType || '';
608
+
609
+ // Update values
610
+ config.android = config.android || {};
611
+ config.android.buildOptions = config.android.buildOptions || {};
612
+ config.android.buildOptions.releaseType = releaseType;
613
+ config.android.buildOptions.signingType = signingType;
614
+
615
+ writeCapacitorConfig(config);
616
+ console.log(`ℹ️ capacitor.config.json updated: releaseType=${releaseType}, signingType=${signingType}`);
617
+ } */
618
+
619
+ /* function restoreCapacitorConfig() {
620
+ const config = readCapacitorConfig();
621
+ if (originalReleaseType !== undefined) config.android.buildOptions.releaseType = originalReleaseType;
622
+ if (originalSigningType !== undefined) config.android.buildOptions.signingType = originalSigningType;
623
+ writeCapacitorConfig(config);
624
+ console.log(`✅ capacitor.config.json restored to original values.`);
625
+ }
626
+
627
+ process.on('SIGINT', () => {
628
+ console.log('\n⚠️ Detected Ctrl+C, restoring capacitor.config.json...');
629
+ restoreCapacitorConfig();
630
+ process.exit(0);
631
+ });
632
+
633
+ process.on('exit', () => {
634
+ restoreCapacitorConfig();
635
+ }); */
636
+
637
+
638
+
639
+ const { playstore, samsung, amazon } = (_isADMOB_ENABLED && admobConfig.IAP) ? admobConfig.IAP : { playstore: false, samsung: false, amazon: false };
640
+ console.log(`ℹ️ IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
641
+
642
+
643
+
644
+
645
+
646
+
647
+ // Get the store ID from the command line arguments
648
+ /* const storeIdArg = ["2","3"]//process.argv[2]; // Get the store ID from the command line
649
+ const storeIds = storeIdArg ? storeIdArg : Object.keys(storeNames);//["1", "2", "7"]; // If a specific ID is provided, use it; otherwise, use all store IDs
650
+
651
+ debugger; */
652
+
653
+ let storeIdArg = process.argv[2]; // command-line argument
654
+ let storeIds;
655
+
656
+ if (storeIdArg) {
657
+ try {
658
+ // Try parsing as JSON array first
659
+ const parsed = JSON.parse(storeIdArg);
660
+ if (Array.isArray(parsed)) {
661
+ storeIds = parsed.map(String); // ensure strings
662
+ } else {
663
+ storeIds = [parsed.toString()];
664
+ }
665
+ } catch (e) {
666
+ // Not JSON, assume comma-separated string
667
+ storeIds = storeIdArg.split(",").map(s => s.trim());
668
+ }
669
+ } else {
670
+ // No argument, use all store IDs
671
+ storeIds = Object.keys(storeNames);
672
+ }
673
+
674
+
675
+ // 🔥 If only one APK mode, override APK storeIds
676
+ /* if (isOnlyOneAPK) {
677
+ console.log("⚡ isOnlyOneAPK enabled → Only MiStore (3) will be used for APK build");
678
+ storeIds = ["3"]; // Only MiStore
679
+ } */
680
+
681
+ // Store the original minSdkVersion globally
682
+ let originalMinSdkVersion;
683
+
684
+ // Remove any existing AAB files before starting the build process
685
+ const aabDirectory = join("android", "app", "build", "outputs", "bundle", "release");
686
+ if (existsSync(aabDirectory)) {
687
+ const files = readdirSync(aabDirectory).filter(file => file.endsWith('.aab'));
688
+ files.forEach(file => {
689
+ const filePath = join(aabDirectory, file);
690
+ unlinkSync(filePath);
691
+ console.log(`ℹ️ Deleted existing AAB file: ${file}`);
692
+ });
693
+ }
694
+
695
+ const aabOutputDir = join("AAB");
696
+ if (!existsSync(aabOutputDir)) {
697
+ mkdirSync(aabOutputDir);
698
+ console.log(`Created directory: ${aabOutputDir}`);
699
+ }
700
+
701
+ if (existsSync(aabOutputDir)) {
702
+ const files = readdirSync(aabOutputDir).filter(
703
+ file => file.endsWith('.aab') || file.endsWith('.apk')
704
+ );
705
+
706
+ files.forEach(file => {
707
+ const filePath = join(aabOutputDir, file);
708
+ unlinkSync(filePath);
709
+ console.log(`Deleted existing build file: ${file}`);
710
+ });
711
+ }
712
+
713
+
714
+ // Extract version code and version name from build.gradle
715
+ const gradleFilePath = join("android", "app", "build.gradle");
716
+ const gradleContent = readFileSync(gradleFilePath, 'utf8');
717
+
718
+ // Return the character range of a Gradle block, allowing nested blocks inside it.
719
+ function findGradleBlock(content, headerPattern) {
720
+ const headerMatch = content.match(headerPattern);
721
+ if (!headerMatch) return null;
722
+ const openingBrace = content.indexOf('{', headerMatch.index + headerMatch[0].length);
723
+ if (openingBrace === -1) return null;
724
+ let depth = 0;
725
+ let quote = null;
726
+ for (let index = openingBrace; index < content.length; index += 1) {
727
+ const character = content[index];
728
+ const previous = content[index - 1];
729
+ if (quote) {
730
+ if (character === quote && previous !== '\\') quote = null;
731
+ continue;
732
+ }
733
+ if (character === '\"' || character === "'") quote = character;
734
+ else if (character === '{') depth += 1;
735
+ else if (character === '}' && --depth === 0) return { start: openingBrace + 1, end: index };
736
+ }
737
+ return null;
738
+ }
739
+
740
+ function ensureReleaseCodeOptimization() {
741
+ const currentContent = readFileSync(gradleFilePath, 'utf8');
742
+ const releaseBlock = findGradleBlock(currentContent, /buildTypes\s*\{[\s\S]*?\brelease\s*/);
743
+ if (!releaseBlock) throw new Error('Release build configuration was not found.');
744
+
745
+ const releaseContent = currentContent.slice(releaseBlock.start, releaseBlock.end);
746
+ let optimizedContent = releaseContent.replace(
747
+ /getDefaultProguardFile\(\s*(['"])proguard-android\.txt\1\s*\)/g,
748
+ "getDefaultProguardFile('proguard-android-optimize.txt')"
749
+ );
750
+ if (!/getDefaultProguardFile\(\s*(['"])proguard-android-optimize\.txt\1\s*\)/.test(optimizedContent)) {
751
+ throw new Error('Release build must use the optimisation-enabled default ProGuard rules.');
752
+ }
753
+ const newline = currentContent.includes('\r\n') ? '\r\n' : '\n';
754
+ // Preserve commented settings and explicit false values as app-specific opt-outs.
755
+ const comments = optimizedContent.match(/\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g) || [];
756
+ if (!comments.some(comment => /\bshrinkResources\b/.test(comment))) {
757
+ const activeContent = optimizedContent.replace(/\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g, '');
758
+ const shrinkResources = /^[ \t]*minifyEnabled\s*(?:=\s*)?true\b/m.test(activeContent);
759
+ const shrinkPattern = /^([ \t]*shrinkResources\s*(?:=\s*)?)(true|false)\b/m;
760
+ if (shrinkPattern.test(optimizedContent)) {
761
+ if (!shrinkResources) optimizedContent = optimizedContent.replace(shrinkPattern, '$1false');
762
+ } else {
763
+ optimizedContent = `${newline} shrinkResources ${shrinkResources}${optimizedContent}`;
764
+ }
765
+ }
766
+ if (optimizedContent !== releaseContent) {
767
+ writeFileSync(gradleFilePath, currentContent.slice(0, releaseBlock.start)
768
+ + optimizedContent + currentContent.slice(releaseBlock.end), 'utf8');
769
+ }
770
+
771
+ const propertiesPath = join(__dirname, 'android', 'gradle.properties');
772
+ const properties = readFileSync(propertiesPath, 'utf8');
773
+ const propertyPattern = /^[ \t]*[#!]?[ \t]*android\.r8\.optimizedResourceShrinking(?:[ \t]*[=:]|[ \t]+|[ \t]*$)/m;
774
+ const property = 'android.r8.optimizedResourceShrinking=true';
775
+ const nextProperties = propertyPattern.test(properties)
776
+ ? properties
777
+ : `${properties.trimEnd()}${newline}${property}${newline}`;
778
+ if (nextProperties !== properties) writeFileSync(propertiesPath, nextProperties, 'utf8');
779
+ }
780
+
781
+ function signReleaseBundleWithSha256() {
782
+ const buildOptions = readCapacitorConfig().android?.buildOptions;
783
+ if (!buildOptions?.keystorePath || !buildOptions.keystorePassword
784
+ || !buildOptions.keystoreAlias || !buildOptions.keystoreAliasPassword) {
785
+ throw new Error('Android AAB signing requires the existing keystore path, alias and passwords.');
786
+ }
787
+
788
+ const keystorePath = resolve(__dirname, 'android', buildOptions.keystorePath);
789
+ const bundleDirectory = join(__dirname, 'android', 'app', 'build', 'outputs', 'bundle', 'release');
790
+ const unsignedBundle = join(bundleDirectory, 'app-release.aab');
791
+ const signedBundle = join(bundleDirectory, 'app-release-signed.aab');
792
+ if (!existsSync(keystorePath) || !existsSync(unsignedBundle)) {
793
+ throw new Error('The configured upload keystore or release AAB was not found.');
794
+ }
795
+
796
+ const jarsigner = process.env.JAVA_HOME
797
+ ? join(process.env.JAVA_HOME, 'bin', process.platform === 'win32' ? 'jarsigner.exe' : 'jarsigner')
798
+ : 'jarsigner';
799
+ try {
800
+ // Keep passwords out of command arguments and error output.
801
+ execFileSync(jarsigner, [
802
+ '-sigalg', 'SHA256withRSA', '-digestalg', 'SHA-256',
803
+ '-keystore', keystorePath,
804
+ '-storepass:env', 'CODEPLAY_AAB_STORE_PASSWORD',
805
+ '-keypass:env', 'CODEPLAY_AAB_KEY_PASSWORD',
806
+ '-signedjar', signedBundle, unsignedBundle, buildOptions.keystoreAlias,
807
+ ], {
808
+ stdio: 'pipe',
809
+ env: {
810
+ ...process.env,
811
+ CODEPLAY_AAB_STORE_PASSWORD: buildOptions.keystorePassword,
812
+ CODEPLAY_AAB_KEY_PASSWORD: buildOptions.keystoreAliasPassword,
813
+ },
814
+ });
815
+ const verification = execFileSync(jarsigner, [
816
+ '-J-Duser.language=en', '-J-Duser.country=US', '-verify', signedBundle,
817
+ ], { encoding: 'utf8', stdio: 'pipe' });
818
+ if (!verification.includes('jar verified.') || verification.includes('treated as unsigned')) {
819
+ throw new Error('Signature verification failed.');
820
+ }
821
+ } catch {
822
+ throw new Error('SHA-256 AAB signing or verification failed. Check the configured upload key and JDK; release stopped.');
823
+ }
824
+ console.log('✅ Release AAB signed with SHA-256 using the existing upload key and signature verified.');
825
+ }
826
+
827
+ const amazonWindowExtensionsDependency = 'implementation "androidx.window.extensions.core:core:1.0.0"';
828
+ const amazonWindowExtensionsDependencyPattern = /^[ \t]*implementation\s+["']androidx\.window\.extensions\.core:core:[^"']+["'][ \t]*(?:\r?\n)?/gm;
829
+
830
+ function setAmazonWindowExtensionsDependency(enabled, { cleanup = false } = {}) {
831
+ const currentGradleContent = readFileSync(gradleFilePath, 'utf8');
832
+ let nextGradleContent = currentGradleContent.replace(amazonWindowExtensionsDependencyPattern, '');
833
+
834
+ if (enabled) {
835
+ const dependenciesBlock = findGradleBlock(nextGradleContent, /^\s*dependencies\s*/m);
836
+ if (!dependenciesBlock) {
837
+ throw new Error(`The dependencies block was not found in ${gradleFilePath}.`);
838
+ }
839
+
840
+ const newline = nextGradleContent.includes('\r\n') ? '\r\n' : '\n';
841
+ const contentBeforeClosingBrace = nextGradleContent.slice(0, dependenciesBlock.end);
842
+ const linePrefix = contentBeforeClosingBrace.endsWith('\n') ? '' : newline;
843
+ nextGradleContent = contentBeforeClosingBrace
844
+ + linePrefix
845
+ + ` ${amazonWindowExtensionsDependency}${newline}`
846
+ + nextGradleContent.slice(dependenciesBlock.end);
847
+ }
848
+
849
+ if (nextGradleContent !== currentGradleContent) {
850
+ writeFileSync(gradleFilePath, nextGradleContent, 'utf8');
851
+ }
852
+
853
+ console.log(enabled
854
+ ? '✅ Added Amazon Fire WebView compatibility dependency for Store ID 7.'
855
+ : cleanup
856
+ ? 'ℹ️ Removed temporary Amazon Fire WebView compatibility dependency after build cleanup.'
857
+ : 'ℹ️ Amazon Fire WebView compatibility dependency is not included for this build.');
858
+ }
859
+
860
+ const versionCodeMatch = gradleContent.match(/versionCode\s+(\d+)/);
861
+ const versionNameMatch = gradleContent.match(/versionName\s+"([^"]+)"/);
862
+
863
+ const versionCode = versionCodeMatch ? versionCodeMatch[1] : '';
864
+ const versionName = versionNameMatch ? versionNameMatch[1] : '';
865
+
866
+ // Display the current versionCode and versionName
867
+ console.log(`Current versionCode: ${versionCode}`);
868
+ console.log(`Current versionName: ${versionName}`);
869
+
870
+ // Create an interface for user input
871
+ async function checkBaselineProfileBeforeRelease() {
872
+ const profilePaths = [
873
+ join(__dirname, 'baselineProfiles', 'baseline-prof.txt'),
874
+ join(__dirname, 'android', 'app', 'src', 'main', 'generated', 'baselineProfiles', 'baseline-prof.txt'),
875
+ join(__dirname, 'android', 'app', 'src', 'main', 'baseline-prof.txt'),
876
+ join(__dirname, 'android', 'app', 'src', 'main', 'baselineProfiles', 'baseline-prof.txt'),
877
+ ];
878
+ const hasProfile = () => profilePaths.some(profilePath =>
879
+ existsSync(profilePath) && readFileSync(profilePath, 'utf8').trim().length > 0);
880
+ if (hasProfile()) return;
881
+
882
+ console.log('⚠️ baseline-prof.txt is missing or empty.');
883
+ console.log('Generation command: npm run baseline-profile:generate');
884
+ console.log('Generation requires an ADB-connected Android device or a configured emulator.');
885
+ const answer = await new Promise(resolveAnswer => {
886
+ rl.question('Generate AAB/APK without a Baseline Profile? [Enter/Y = continue, n = generate profile first]: ', resolveAnswer);
887
+ });
888
+ if (answer.trim().toLowerCase() !== 'n') return;
889
+
890
+ rl.pause();
891
+ try {
892
+ execSync('npm run baseline-profile:generate', { cwd: __dirname, stdio: 'inherit' });
893
+ if (!hasProfile()) {
894
+ throw new Error('Baseline Profile generation did not produce a non-empty baseline-prof.txt; release stopped.');
895
+ }
896
+ // Reuse setup to back up and synchronise the generated profile before packaging.
897
+ execFileSync(process.execPath, [join(__dirname, 'scripts-common', 'setup-baseline-profile.js')], {
898
+ cwd: __dirname,
899
+ stdio: 'inherit',
900
+ });
901
+ } finally {
902
+ rl.resume();
903
+ }
904
+ }
905
+
906
+ const rl = createInterface({
907
+ input: process.stdin,
908
+ output: process.stdout
909
+ });
910
+
911
+ // Ask for new versionCode
912
+ rl.question('Enter new versionCode (press enter to keep current): ', (newVersionCode) => {
913
+ const finalVersionCode = newVersionCode || versionCode; // Use existing if no input
914
+
915
+ // Ask for new versionName
916
+ rl.question('Enter new versionName (press enter to keep current): ', async (newVersionName) => {
917
+ const finalVersionName = newVersionName || versionName; // Use existing if no input
918
+
919
+ // Log the final version details
920
+ console.log(`📦 Final versionCode: ${finalVersionCode}`);
921
+ console.log(`📝 Final versionName: ${finalVersionName}`);
922
+
923
+
924
+ updateIOSVersion(finalVersionCode, finalVersionName);
925
+
926
+ // Update build.gradle with the new version details
927
+ let updatedGradleContent = gradleContent
928
+ .replace(/versionCode\s+\d+/, `versionCode ${finalVersionCode}`)
929
+ .replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"`);
930
+
931
+ // Check if resConfigs "en" already exists
932
+ const resConfigsLine = ' resConfigs "en"';
933
+ if (!updatedGradleContent.includes(resConfigsLine)) {
934
+ // Add resConfigs "en" below versionName
935
+ updatedGradleContent = updatedGradleContent.replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"\n${resConfigsLine}`);
936
+ } else {
937
+ console.log('ℹ️ resConfigs "en" already exists in build.gradle.');
938
+ }
939
+
940
+
941
+
942
+ // List of package IDs for which minify should be false
943
+
944
+
945
+ // Determine desired minify value
946
+ const desiredMinify = !_isffmpegUsed;
947
+
948
+ // Limit minification changes to release; debug may have its own test settings.
949
+ const minificationBlock = findGradleBlock(updatedGradleContent, /buildTypes\s*\{[\s\S]*?\brelease\s*/);
950
+ if (!minificationBlock) {
951
+ throw new Error('Release build configuration was not found.');
952
+ }
953
+ let minificationContent = updatedGradleContent.slice(minificationBlock.start, minificationBlock.end);
954
+ if (/\bminifyEnabled\s*(?:=\s*)?(true|false)\b/.test(minificationContent)) {
955
+ // Replace existing value with desired
956
+ minificationContent = minificationContent.replace(/\bminifyEnabled\s*(?:=\s*)?(true|false)\b/, `minifyEnabled ${desiredMinify}`);
957
+ console.log(`Replaced minifyEnabled with ${desiredMinify}.`);
958
+ } else {
959
+ // Insert minifyEnabled if not present
960
+ minificationContent = `\n minifyEnabled ${desiredMinify}${minificationContent}`;
961
+ console.log(`✅ Inserted minifyEnabled ${desiredMinify} into release block.`);
962
+ }
963
+ updatedGradleContent = updatedGradleContent.slice(0, minificationBlock.start)
964
+ + minificationContent + updatedGradleContent.slice(minificationBlock.end);
965
+
966
+ // Add native debug symbols for release AABs, but leave any existing setting untouched.
967
+ const releaseBlock = findGradleBlock(updatedGradleContent, /buildTypes\s*\{[\s\S]*?\brelease\s*/);
968
+ if (releaseBlock) {
969
+ const releaseContent = updatedGradleContent.slice(releaseBlock.start, releaseBlock.end);
970
+ if (/\bdebugSymbolLevel\b/.test(releaseContent)) {
971
+ console.log('ℹ️ debugSymbolLevel already exists in buildTypes.release; leaving it unchanged.');
972
+ } else {
973
+ const ndkBlock = `\n ndk {\n debugSymbolLevel 'FULL'\n }`;
974
+ updatedGradleContent = updatedGradleContent.slice(0, releaseBlock.end)
975
+ + ndkBlock
976
+ + updatedGradleContent.slice(releaseBlock.end);
977
+ console.log("✅ Added debugSymbolLevel 'FULL' to buildTypes.release.");
978
+ }
979
+ } else {
980
+ console.log('⚠️ Warning: buildTypes.release block not found. debugSymbolLevel was not added.');
981
+ }
982
+
983
+
984
+
985
+
986
+
987
+
988
+ // Write the updated gradle content back to build.gradle
989
+ writeFileSync(gradleFilePath, updatedGradleContent, 'utf8');
990
+ console.log(`✅ Updated build.gradle with versionCode: ${finalVersionCode}, versionName: ${finalVersionName}, resConfigs "en" and "minifyEnabled true"`);
991
+
992
+ let baselineProfileChecked = false;
993
+ for (const id of storeIds) {
994
+ console.log(`ℹ️ Building for Store ID ${id}`);
995
+
996
+ // Set the environment variable for store ID
997
+ process.env.VITE_STORE_ID = id;
998
+
999
+ // Conditionally set the new file name
1000
+ let newFileName;
1001
+ let storeName = storeNames[id];
1002
+
1003
+
1004
+ if (
1005
+ isOnlyOneAPK &&
1006
+ ["OppoStore", "VivoStore"].includes(storeName)
1007
+ ) {
1008
+ console.log(`⏭ Skipping ${storeName} because isOnlyOneAPK is enabled`);
1009
+ continue; // skip this iteration only
1010
+ }
1011
+
1012
+
1013
+ // build:storeid runs the shared before-build package/permission preparation.
1014
+
1015
+ // 🔥 Only change filename logic — nothing else touched
1016
+ if (isOnlyOneAPK && ["MiStore","OppoStore","VivoStore"].includes(storeName)) {
1017
+
1018
+ newFileName =
1019
+ `${_appUniqueId}_${_appName.replaceAll(" ","_")}-VI_MI_OPPO-b${finalVersionCode}-v${finalVersionName.replace(/\./g,'_')}.aab`;
1020
+
1021
+ }
1022
+ else if (storeName === "SamsungStore") {
1023
+
1024
+ newFileName =
1025
+ `${_appUniqueId}_${_appName.replaceAll(" ","_")}-${(storeName.toUpperCase()).replace("STORE","")}-b${finalVersionCode}-v${finalVersionName.replace(/\./g,'_')}.aab`;
1026
+
1027
+ }
1028
+ else {
1029
+
1030
+ newFileName =
1031
+ `${_appUniqueId}_${_appName.replaceAll(" ","_")}-${(storeName.toUpperCase()).replace("STORE","")}-b${finalVersionCode}-v${finalVersionName}.aab`;
1032
+
1033
+ }
1034
+
1035
+ //storeName="amazon"
1036
+ const checkFullPath = join("AAB", newFileName); // Update to point to the new AAB directory
1037
+
1038
+ // Modify minSdkVersion in variables.gradle for SamsungStore
1039
+ const variablesGradleFilePath = join("android", "variables.gradle");
1040
+ let variablesGradleContent = readFileSync(variablesGradleFilePath, 'utf8');
1041
+
1042
+ // Extract the current minSdkVersion
1043
+ const minSdkVersionMatch = variablesGradleContent.match(/minSdkVersion\s*=\s*(\d+)/);
1044
+ const currentMinSdkVersion = minSdkVersionMatch ? parseInt(minSdkVersionMatch[1], 10) : null;
1045
+
1046
+ // Store the original minSdkVersion (only on the first iteration)
1047
+ if (!originalMinSdkVersion) {
1048
+ originalMinSdkVersion = currentMinSdkVersion;
1049
+ }
1050
+ try {
1051
+ applyFlowchartStoreApi(id);
1052
+ const shouldIncludeAmazonWindowExtensions = String(id) === '7' && amazon === true;
1053
+ setAmazonWindowExtensionsDependency(shouldIncludeAmazonWindowExtensions);
1054
+ // Modify the minSdkVersion based on the store
1055
+
1056
+
1057
+ if(currentMinSdkVersion==23 || currentMinSdkVersion==24)
1058
+ {
1059
+ if (storeName === "SamsungStore" || storeName === "PlayStore" ||
1060
+ //_appPackageId=="vfx.green.editor" || _appPackageId=="audio.music.sound.editor" || _appPackageId=="video.to.gif.maker"
1061
+
1062
+ //ffmpegUsedPackages.includes(_appPackageId)
1063
+ _isffmpegUsed
1064
+ ) {
1065
+ if (currentMinSdkVersion !== 24) {
1066
+ variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, 'minSdkVersion = 24');
1067
+ console.log('minSdkVersion updated to 24 for SamsungStore & PlayStore');
1068
+ writeFileSync(variablesGradleFilePath, variablesGradleContent);
1069
+ }
1070
+ } else {
1071
+ // For PlayStore and AmazonStore, ensure minSdkVersion is originalMinSdkVersion
1072
+ //if (currentMinSdkVersion !== originalMinSdkVersion) {
1073
+ variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, `minSdkVersion = ${amazonMinSdkVersion}`);
1074
+ console.log(`minSdkVersion reverted to ${amazonMinSdkVersion} for ${storeName}`);
1075
+ writeFileSync(variablesGradleFilePath, variablesGradleContent);
1076
+ //}
1077
+ }
1078
+ }
1079
+
1080
+
1081
+ // Run the Node.js script to modify plugin.xml
1082
+ if (isAdmobFound) {
1083
+ const modifyPluginXmlPath = join('buildCodeplay', 'modify-plugin-xml.js');
1084
+ if (existsSync(modifyPluginXmlPath)) {
1085
+ execSync(`node ${modifyPluginXmlPath}`, { stdio: 'inherit' });
1086
+ } else {
1087
+ console.log("\x1b[33m%s\x1b[0m", "⚠️ modify-plugin-xml.js not found. Skipping old AdMob plugin.xml modification.");
1088
+ }
1089
+ } else {
1090
+ console.log("\x1b[33m%s\x1b[0m", "Seems to Pro Version [No ads found]");
1091
+ }
1092
+
1093
+ // Run the Vite build
1094
+ execSync(`npm run build:storeid${id}`, { stdio: 'inherit' });
1095
+
1096
+
1097
+
1098
+
1099
+
1100
+
1101
+ // Copy the built files to the appropriate folder
1102
+ const src = join("www");
1103
+ const dest = join("android", "app", "src", "main", "assets", "public");
1104
+
1105
+ // Copy the web build with Node so releases work on every platform.
1106
+ fs.cpSync(src, dest, { recursive: true, force: true });
1107
+
1108
+ // Build Android AAB file
1109
+ //child_process.execSync('cd android && ./gradlew bundleRelease', { stdio: 'inherit' });
1110
+
1111
+
1112
+ // Build Android AAB or APK file based on store
1113
+ console.log(`🏗️ Building release for ${storeName}...`);
1114
+
1115
+ /* let buildType = "AAB";
1116
+ if (["VivoStore", "OppoStore", "MiStore"].includes(storeName)) {
1117
+ buildType = "APK";
1118
+ } */
1119
+
1120
+
1121
+ // Determine build type and signing type per store
1122
+ let buildType = ["VivoStore","OppoStore","MiStore"].includes(storeName) ? "APK" : "AAB";
1123
+ let signingType = buildType === "APK" ? "apksigner" : "jarsigner";
1124
+
1125
+ // Update capacitor.config.json for this store - This is not needed
1126
+ //updateCapacitorConfig(buildType, signingType);
1127
+
1128
+
1129
+
1130
+ /* execSync('npx cap sync android', { stdio: 'inherit' });
1131
+ execSync(`npx cap build android --androidreleasetype=${buildType}`, { stdio: 'inherit' }); */
1132
+
1133
+
1134
+ execSync('npx cap sync android', { stdio: 'inherit' });
1135
+
1136
+ if (!baselineProfileChecked) {
1137
+ await checkBaselineProfileBeforeRelease();
1138
+ baselineProfileChecked = true;
1139
+ }
1140
+ ensureReleaseCodeOptimization();
1141
+
1142
+ if (buildType === "APK") {
1143
+ console.log("📦 Using custom Node signing script for APK build...");
1144
+ execFileSync(process.execPath, [join(process.cwd(), 'buildCodeplay', 'apk-store-builder.js')], { stdio: 'inherit' });
1145
+ } else {
1146
+ execSync(`npx cap build android --androidreleasetype=${buildType}`, { stdio: 'inherit' });
1147
+ signReleaseBundleWithSha256();
1148
+ }
1149
+
1150
+
1151
+
1152
+ // Determine output paths
1153
+ let oldFilePath;
1154
+ let newExt = buildType === "APK" ? "apk" : "aab";
1155
+
1156
+ if (buildType === "APK") {
1157
+ //oldFilePath = join("android", "app", "build", "outputs", "apk", "release", "app-release-signed.apk");
1158
+ oldFilePath = join("android", "app", "build", "outputs", "apk", "release", "app-release.apk");
1159
+ } else {
1160
+ oldFilePath = join("android", "app", "build", "outputs", "bundle", "release", "app-release-signed.aab");
1161
+ }
1162
+
1163
+ const checkFullPath = join("AAB", newFileName.replace(/\.aab$/, `.${newExt}`));
1164
+
1165
+ // Rename the output file
1166
+ if (existsSync(oldFilePath)) {
1167
+ renameSync(oldFilePath, checkFullPath);
1168
+ console.log(`✅ Renamed output ${newExt.toUpperCase()} file to: ${path.basename(checkFullPath)}`);
1169
+ syncReleaseToCodeplay(storeName, finalVersionName, finalVersionCode, new Date().toISOString().slice(0, 10));
1170
+ } else {
1171
+ console.error(`❌ ${newExt.toUpperCase()} file not found after build.`);
1172
+ }
1173
+
1174
+ } catch (error) {
1175
+ console.error(`❌ Error during build for Store ID ${id}:`, error);
1176
+ restoreFlowchartStoreApi();
1177
+ setAmazonWindowExtensionsDependency(false, {
1178
+ cleanup: String(id) === '7' && amazon === true,
1179
+ });
1180
+ process.exit(1);
1181
+ } finally {
1182
+ restoreFlowchartStoreApi();
1183
+ setAmazonWindowExtensionsDependency(false, {
1184
+ cleanup: String(id) === '7' && amazon === true,
1185
+ });
1186
+ }
1187
+ }
1188
+
1189
+ rl.close(); // Close the readline interface after all operations
1190
+ });
1191
+ });
1192
+
1193
+
1194
+
1195
+
1196
+
1197
+ /* function updateAndroidManifest1(store, addPermission) {
1198
+ try {
1199
+ if (!fs.existsSync(androidManifestPath)) {
1200
+ console.error("AndroidManifest.xml file not found!");
1201
+ return;
1202
+ }
1203
+
1204
+ let manifestContent = fs.readFileSync(androidManifestPath, 'utf-8');
1205
+
1206
+
1207
+
1208
+ // Add the required permission if not already present
1209
+ if (!manifestContent.includes(addPermission)) {
1210
+ const manifestLines = manifestContent.split('\n');
1211
+ const insertIndex = manifestLines.findIndex(line => line.trim().startsWith('<application'));
1212
+ if (insertIndex > -1) {
1213
+ manifestLines.splice(insertIndex, 0, ` ${addPermission}`);
1214
+ manifestContent = manifestLines.join('\n');
1215
+ console.log(`Added ${addPermission} to AndroidManifest.xml`);
1216
+ }
1217
+ }
1218
+
1219
+ // Write the updated content back to the file
1220
+ fs.writeFileSync(androidManifestPath, manifestContent, 'utf-8');
1221
+ console.log(`AndroidManifest.xml updated successfully for ${store}`);
1222
+ } catch (err) {
1223
+ console.error(`Error updating AndroidManifest.xml for ${store}:`, err);
1224
+ }
1225
+ } */
1226
+
1227
+
1228
+
1229
+
1230
+
1231
+
1232
+
1233
+