codeplay-common 2.1.51 → 3.0.1

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,1403 +1,1730 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const plist = require('plist');
4
-
5
- const { readFileSync } = require("fs");
6
-
7
-
8
-
9
- const configPath = path.join(process.cwd(), 'capacitor.config.json');
10
-
11
- // Expected plugin list with minimum versions
12
- const requiredPlugins = [
13
-
14
- { pattern: /backbutton-(\d+\.\d+)\.js$/, minVersion: '1.8', required: true, baseDir: 'js',mandatoryUpdate: true},
15
-
16
- /*/common-(\d+\.\d+)\.js$/*/
17
- { pattern: /common-(\d+\.\d+)(?:-beta-(\d+))?\.js$/, minVersion: '5.8', required: true, baseDir: 'js',mandatoryUpdate: true },
18
-
19
- { pattern: /localization_settings-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true, baseDir: 'js',mandatoryUpdate: false },
20
- { pattern: /localization-(\d+\.\d+)\.js$/, minVersion: '1.5', required: true, baseDir: 'js',mandatoryUpdate: true },
21
- { pattern: /localNotification-(\d+\.\d+)\.js$/, minVersion: '2.2', required: true, baseDir: 'js',mandatoryUpdate: false },
22
- { pattern: /localNotification_AppSettings-(\d+\.\d+)\.js$/, minVersion: '1.0', required: true, baseDir: 'js',mandatoryUpdate: false },
23
- { pattern: /onesignal-(\d+\.\d+)\.js$/, minVersion: '2.3', required: true, baseDir: 'js',mandatoryUpdate: false },
24
- { pattern: /saveToGalleryAndSaveAnyFile-(\d+\.\d+)(-ios)?\.js$/, minVersion: '3.1', required: true, baseDir: 'js',mandatoryUpdate: true },
25
- { pattern: /Ads[\/\\]admob-emi-(\d+\.\d+)\.js$/, minVersion: '3.6', required: true, baseDir: 'js',mandatoryUpdate: true },
26
-
27
- // New added plugins
28
- { pattern: /video-player-(\d+\.\d+)\.js$/, minVersion: '1.5', required: true, baseDir: 'js',mandatoryUpdate: false },
29
- { pattern: /image-cropper-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true, baseDir: 'js',mandatoryUpdate: false },
30
- { pattern: /common-(\d+\.\d+)\.less$/, minVersion: '1.6', required: true, baseDir: 'assets/css',mandatoryUpdate: false },
31
-
32
-
33
- // New folders
34
- { pattern: /IAP-(\d+\.\d+)$/, minVersion: '2.8', isFolder: true , required: true, baseDir: 'js/Ads',mandatoryUpdate: true },
35
- { pattern: /editor-(\d+\.\d+)$/, minVersion: '1.9', isFolder: true, required: true, baseDir: 'js',mandatoryUpdate: true },
36
- { pattern: /ffmpeg-(\d+\.\d+)$/, minVersion: '1.3', isFolder: true, required: true, baseDir: 'js',mandatoryUpdate: false },
37
- { pattern: /theme-(\d+\.\d+)$/, minVersion: '3.1', isFolder: true , required: true, baseDir: 'theme',mandatoryUpdate: true },
38
-
39
-
40
- { pattern: /certificatejs-(\d+\.\d+)$/, minVersion: '1.6', isFolder: true , required: true, baseDir: 'certificate',mandatoryUpdate: true }
41
-
42
- ];
43
-
44
-
45
-
46
-
47
-
48
-
49
- //Check codeplay-common latest version installed or not Start
50
- const { execSync } = require('child_process');
51
-
52
- function getInstalledVersion(packageName) {
53
- try {
54
- const packageJsonPath = path.join(process.cwd(), 'node_modules', packageName, 'package.json');
55
- if (fs.existsSync(packageJsonPath)) {
56
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
57
- return packageJson.version;
58
- }
59
- } catch (error) {
60
- return null;
61
- }
62
- return null;
63
- }
64
-
65
- function getLatestVersion(packageName) {
66
- try {
67
- return execSync(`npm view ${packageName} version`).toString().trim();
68
- } catch (error) {
69
- console.error(`Failed to fetch latest version for ${packageName}`);
70
- return null;
71
- }
72
- }
73
-
74
- function checkPackageVersion() {
75
- const packageName = 'codeplay-common';
76
- const installedVersion = getInstalledVersion(packageName);
77
- const latestVersion = getLatestVersion(packageName);
78
-
79
- if (!installedVersion) {
80
- console.error(`${packageName} is not installed. Please install it using "npm install ${packageName}".`);
81
- process.exit(1);
82
- }
83
-
84
- if (installedVersion !== latestVersion) {
85
- console.error(`\x1b[31m${packageName} is outdated (installed: ${installedVersion}, latest: ${latestVersion}). Please update it.\x1b[0m\n\x1b[33mUse 'npm uninstall codeplay-common ; npm i codeplay-common'\x1b[0m`);
86
- process.exit(1);
87
- }
88
-
89
- console.log(`${packageName} is up to date (version ${installedVersion}).`);
90
- }
91
-
92
- // Run package version check before executing the main script
93
- try {
94
- checkPackageVersion();
95
- } catch (error) {
96
- console.error(error.message);
97
- process.exit(1);
98
- }
99
-
100
- //Check codeplay-common latest version installed or not END
101
-
102
-
103
-
104
- function compareWithBeta(installedVersion, minVersion, isBeta) {
105
- const baseCompare = compareVersions(installedVersion, minVersion);
106
-
107
- if (!isBeta) {
108
- // Stable version → normal compare
109
- return baseCompare;
110
- }
111
-
112
- // Beta version logic
113
- if (baseCompare > 0) return 1; // 5.3-beta > 5.2
114
- if (baseCompare < 0) return -1; // 5.1-beta < 5.2
115
-
116
- // Same version but beta → LOWER than stable
117
- return -1; // 5.2-beta < 5.2
118
- }
119
-
120
-
121
-
122
-
123
- const checkAppUniqueId=()=>{
124
-
125
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
126
-
127
- const appUniqueId = config.android?.APP_UNIQUE_ID;
128
- const RESIZEABLE_ACTIVITY = config.android?.RESIZEABLE_ACTIVITY;
129
- const orientation = config.android?.ORIENTATION;
130
-
131
-
132
- let logErrorMessage="";
133
-
134
- // 1️⃣ Check if it’s missing
135
- if (RESIZEABLE_ACTIVITY === undefined) {
136
- logErrorMessage+='❌ Missing android.RESIZEABLE_ACTIVITY option in capacitor.config.json.\n';
137
- }
138
-
139
- // 2️⃣ Check if it’s not boolean (true/false only)
140
- else if (typeof RESIZEABLE_ACTIVITY !== 'boolean') {
141
- logErrorMessage+='❌ Invalid android.RESIZEABLE_ACTIVITY value. Please use only true or false (without quotes).\n';
142
- }
143
-
144
-
145
-
146
- if (!orientation) {
147
- logErrorMessage+='❌ Missing android.ORIENTATION option in capacitor.config.json.\n';
148
- }
149
-
150
- else if(orientation!="portrait" && orientation!="landscape" && orientation!="auto")
151
- {
152
- logErrorMessage+='❌ Spelling mistake in android.ORIENTATION option in capacitor.config.json. Please use only ["portrait" "landscape" "auto"]\n';
153
- }
154
-
155
-
156
- if (!appUniqueId) {
157
- logErrorMessage+='❌ APP_UNIQUE_ID is missing in capacitor.config.json.';
158
- }
159
-
160
- else if (!Number.isInteger(appUniqueId)) {
161
- logErrorMessage+='❌ APP_UNIQUE_ID must be an integer. Example: 1, 2, 3, etc.';
162
- }
163
-
164
-
165
-
166
- if(logErrorMessage!="")
167
- {
168
- console.error(logErrorMessage);
169
- process.exit(1)
170
- }
171
-
172
-
173
- console.log(`✅ APP_UNIQUE_ID is valid: ${appUniqueId}`);
174
-
175
- }
176
-
177
- checkAppUniqueId();
178
-
179
-
180
-
181
-
182
-
183
-
184
-
185
- //@Codemirror check and install/uninstall the packages START
186
- //const fs = require("fs");
187
- //const path = require("path");
188
- //const { execSync } = require("child_process");
189
-
190
- const baseDir = path.join(__dirname, "..", "src", "js");
191
-
192
- // Step 1: Find highest versioned folder like `editor-1.6`
193
- const editorDirs = fs.readdirSync(baseDir)
194
- .filter(name => /^editor-\d+\.\d+$/.test(name))
195
- .sort((a, b) => {
196
- const getVersion = str => str.match(/(\d+)\.(\d+)/).slice(1).map(Number);
197
- const [aMajor, aMinor] = getVersion(a);
198
- const [bMajor, bMinor] = getVersion(b);
199
- return bMajor - aMajor || bMinor - aMinor;
200
- });
201
-
202
- if (editorDirs.length === 0) {
203
-
204
- console.log("@Codemirror used editor(s) are not found")
205
- //console.error("❌ No editor-x.x folders found in src/js.");
206
- //process.exit(1);
207
- }
208
- else
209
- {
210
-
211
- const latestEditorDir = editorDirs.sort((a, b) => {
212
- const versionA = parseFloat(a.split('-')[1]);
213
- const versionB = parseFloat(b.split('-')[1]);
214
- return versionB - versionA;
215
- })[0];
216
-
217
- //const latestEditorDir = editorDirs[editorDirs.length - 1];
218
- const runJsPath = path.join(baseDir, latestEditorDir, "run.js");
219
-
220
- if (!fs.existsSync(runJsPath)) {
221
- console.error(`❌ run.js not found in ${latestEditorDir}`);
222
- process.exit(1);
223
- }
224
-
225
- // Step 2: Execute the run.js file
226
- console.log(`🚀 Executing ${runJsPath}...`);
227
- execSync(`node "${runJsPath}"`, { stdio: "inherit" });
228
- }
229
-
230
- //@Codemirror check and install/uninstall the packages END
231
-
232
-
233
-
234
-
235
-
236
-
237
-
238
-
239
-
240
-
241
-
242
-
243
- // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists START
244
-
245
- const os = require('os');
246
-
247
- const saveToGalleryAndSaveFileCheck_iOS = () => {
248
-
249
- // List of paths to scan
250
- const SCAN_PATHS = [
251
- path.resolve(__dirname, '../src/certificate'),
252
- path.resolve(__dirname, '../src/pages'),
253
- path.resolve(__dirname, '../src/js'),
254
- path.resolve(__dirname, '../src/app.f7')
255
- ];
256
-
257
- // Directory to exclude
258
- const EXCLUDED_DIR = path.resolve(__dirname, '../src/js/Ads');
259
-
260
- const ANDROID_MANIFEST_PATH = path.resolve(__dirname, '../android/app/src/main/AndroidManifest.xml');
261
-
262
-
263
- // Match iOS-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5-ios.js) not in comments
264
- const IOS_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*-ios\.js['"]/m;
265
-
266
- // Match Android-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5.js) not in comments
267
- const ANDROID_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*\.js['"]/m;
268
-
269
-
270
-
271
-
272
-
273
- const ALLOWED_EXTENSIONS = ['.js', '.f7'];
274
- const isMac = os.platform() === 'darwin';
275
-
276
- let iosImportFound = false;
277
- let androidImportFound = false;
278
-
279
- // Files to skip completely (full or partial match)
280
- const SKIP_FILES = [
281
- 'pdf-3.11.174.min.js',
282
- 'pdf.worker-3.11.174.min.js'
283
- ,'index.browser.js'
284
- ];
285
-
286
-
287
- function scanDirectory(dir) {
288
-
289
- /*
290
- //######################### DO NOT DELETE THIS - START [Appid base validation] #####################################
291
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
292
- const appUniqueId = config.android?.APP_UNIQUE_ID;
293
- if (appUniqueId == "206") return;
294
- //######################### DO NOT DELETE THIS - END [Appid base validation] #####################################
295
- */
296
-
297
- const stat = fs.statSync(dir);
298
-
299
- if (stat.isFile()) {
300
-
301
- // 🔥 Skip files in SKIP_FILES array
302
- const baseName = path.basename(dir);
303
- if (SKIP_FILES.includes(baseName)) {
304
- // Just skip silently
305
- return;
306
- }
307
-
308
- // Only scan allowed file extensions
309
- if (ALLOWED_EXTENSIONS.some(ext => dir.endsWith(ext))) {
310
- process.stdout.write(`\r🔍 Scanning: ${dir} `);
311
-
312
- const content = fs.readFileSync(dir, 'utf8');
313
-
314
- if (IOS_FILE_REGEX.test(content)) {
315
- iosImportFound = true;
316
- if (!isMac) {
317
- console.error(`\n❌ ERROR: iOS-specific import detected in: ${dir}`);
318
- console.error(`🚫 STOPPED: This file should not be imported in Android/Windows/Linux builds.\n`);
319
- process.exit(1);
320
- }
321
- }
322
- else if (ANDROID_FILE_REGEX.test(content) && !content.includes('-ios.js')) {
323
- androidImportFound = true;
324
- }
325
- }
326
- }
327
- else if (stat.isDirectory()) {
328
- if (dir === EXCLUDED_DIR || path.basename(dir) === 'node_modules') return;
329
-
330
- const entries = fs.readdirSync(dir, { withFileTypes: true });
331
- for (let entry of entries) {
332
- scanDirectory(path.join(dir, entry.name));
333
- }
334
- }
335
- }
336
-
337
-
338
- // Run scan on all specified paths
339
- for (let scanPath of SCAN_PATHS) {
340
- if (fs.existsSync(scanPath)) {
341
- scanDirectory(scanPath);
342
- }
343
- }
344
-
345
-
346
-
347
- /* // Check src folder
348
- if (!fs.existsSync(ROOT_DIR)) {
349
- console.warn(`⚠️ Warning: 'src' directory not found at: ${ROOT_DIR}`);
350
- return;
351
- } */
352
-
353
- //scanDirectory(ROOT_DIR);
354
-
355
- // iOS Checks
356
- if (isMac && !iosImportFound) {
357
- console.warn(`⚠️ WARNING: You're on macOS but no iOS version (saveToGalleryAndSaveAnyFile-x.x-ios.js) found.`);
358
- process.exit(1);
359
- } else if (isMac && iosImportFound) {
360
- console.log('✅ iOS version detected for macOS build.');
361
- } else if (!iosImportFound) {
362
- console.log('✅ No iOS-specific imports detected for non-macOS.');
363
- }
364
-
365
- // Android Checks
366
- if (androidImportFound) {
367
- console.log("📱 Android version of saveToGalleryAndSaveAnyFile detected. Checking AndroidManifest.xml...");
368
-
369
- if (!fs.existsSync(ANDROID_MANIFEST_PATH)) {
370
- console.error("❌ AndroidManifest.xml not found. Cannot add requestLegacyExternalStorage attribute.");
371
- return;
372
- }
373
-
374
- let manifestContent = fs.readFileSync(ANDROID_MANIFEST_PATH, 'utf8');
375
-
376
- if (!manifestContent.includes('android:requestLegacyExternalStorage="true"')) {
377
- console.log("Adding android:requestLegacyExternalStorage=\"true\" to <application> tag...");
378
-
379
- manifestContent = manifestContent.replace(
380
- /<application([^>]*)>/,
381
- (match, attrs) => {
382
- if (attrs.includes('android:requestLegacyExternalStorage')) return match;
383
- return `<application${attrs} android:requestLegacyExternalStorage="true">`;
384
- }
385
- );
386
-
387
- fs.writeFileSync(ANDROID_MANIFEST_PATH, manifestContent, 'utf8');
388
- console.log("✅ android:requestLegacyExternalStorage=\"true\" added successfully.");
389
- } else {
390
- console.log("ℹ️ android:requestLegacyExternalStorage already exists in AndroidManifest.xml.");
391
- }
392
- } else {
393
- console.log("✅ No Android saveToGalleryAndSaveAnyFile imports detected.");
394
- }
395
- };
396
-
397
- saveToGalleryAndSaveFileCheck_iOS();
398
- // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists END
399
-
400
-
401
-
402
-
403
-
404
-
405
-
406
-
407
-
408
-
409
-
410
-
411
-
412
- /*
413
- // Clean up AppleDouble files (._*) created by macOS START
414
- if (process.platform === 'darwin') {
415
- try {
416
- console.log('🧹 Cleaning up AppleDouble files (._*)...');
417
- execSync(`find . -name '._*' -delete`);
418
- console.log('✅ AppleDouble files removed.');
419
- } catch (err) {
420
- console.warn('⚠️ Failed to remove AppleDouble files:', err.message);
421
- }
422
- } else {
423
- console.log('ℹ️ Skipping AppleDouble cleanup — not a macOS machine.');
424
- }
425
-
426
- // Clean up AppleDouble files (._*) created by macOS END
427
- */
428
-
429
-
430
-
431
-
432
-
433
-
434
- //In routes.js file check static import START
435
-
436
- const routesPath = path.join(process.cwd(), 'src', 'js', 'routes.js');
437
- const routesContent = fs.readFileSync(routesPath, 'utf-8');
438
-
439
- let inBlockComment = false;
440
- const lines = routesContent.split('\n');
441
-
442
- const allowedImport = `import HomePage from '../pages/home.f7';`;
443
- const badImportRegex = /^[ \t]*import\s+[\w{}*,\s]*\s+from\s+['"].+\.f7['"]\s*;/;
444
- const badImports = [];
445
-
446
- lines.forEach((line, index) => {
447
- const trimmed = line.trim();
448
-
449
- // Handle block comment start and end
450
- if (trimmed.startsWith('/*')) inBlockComment = true;
451
- if (inBlockComment && trimmed.endsWith('*/')) {
452
- inBlockComment = false;
453
- return;
454
- }
455
-
456
- // Skip if inside block comment or line comment
457
- if (inBlockComment || trimmed.startsWith('//')) return;
458
-
459
- // Match static .f7 import
460
- if (badImportRegex.test(trimmed) && trimmed !== allowedImport) {
461
- badImports.push({ line: trimmed, number: index + 1 });
462
- }
463
- });
464
-
465
- if (badImports.length > 0) {
466
- console.error('\n❌ ERROR: Detected disallowed static imports of .f7 files in routes.js\n');
467
- console.error(`⚠️ Only this static import is allowed:\n ${allowedImport}\n`);
468
- console.error(`🔧 Please convert other imports to async dynamic imports like this:\n`);
469
- console.error(`
470
-
471
- import HomePage from '../pages/home.f7';
472
-
473
- const routes = [
474
- {
475
- path: '/',
476
- component:HomePage,
477
- },
478
- {
479
- path: '/ProfilePage/',
480
- async async({ resolve }) {
481
- const page = await import('../pages/profile.f7');
482
- resolve({ component: page.default });
483
- },
484
- }]
485
- `);
486
-
487
- badImports.forEach(({ line, number }) => {
488
- console.error(`${number}: ${line}`);
489
- });
490
-
491
- process.exit(1);
492
- } else {
493
- console.log('✅ routes.js passed the .f7 import check.');
494
- }
495
-
496
- //In routes.js file check static import END
497
-
498
-
499
-
500
-
501
-
502
-
503
-
504
-
505
-
506
-
507
-
508
-
509
-
510
- // Check and change the "BridgeWebViewClient.java" file START
511
- /*
512
- For crash issue due to low memory problem, we need to modify the onRenderProcessGone method in BridgeWebViewClient.java.
513
- */
514
-
515
-
516
- const bridgeWebViewClientFilePath = path.join(process.cwd(), 'node_modules', '@capacitor/android/capacitor/src/main/java/com/getcapacitor', 'BridgeWebViewClient.java');
517
-
518
- // Read the file
519
- if (!fs.existsSync(bridgeWebViewClientFilePath)) {
520
- console.error('❌ Error: BridgeWebViewClient.java not found.');
521
- process.exit(1);
522
- }
523
-
524
- let fileContent = fs.readFileSync(bridgeWebViewClientFilePath, 'utf8');
525
-
526
- // Define old and new code
527
- const oldCodeStart = `@Override
528
- public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
529
- super.onRenderProcessGone(view, detail);
530
- boolean result = false;
531
-
532
- List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
533
- if (webViewListeners != null) {
534
- for (WebViewListener listener : bridge.getWebViewListeners()) {
535
- result = listener.onRenderProcessGone(view, detail) || result;
536
- }
537
- }
538
-
539
- return result;
540
- }`;
541
-
542
- const newCode = `@Override
543
- public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
544
- super.onRenderProcessGone(view, detail);
545
-
546
- boolean result = false;
547
-
548
- List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
549
- if (webViewListeners != null) {
550
- for (WebViewListener listener : bridge.getWebViewListeners()) {
551
- result = listener.onRenderProcessGone(view, detail) || result;
552
- }
553
- }
554
-
555
- if (!result) {
556
- // If no one handled it, handle it ourselves!
557
-
558
- /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
559
- if (detail.didCrash()) {
560
- //Log.e("CapacitorWebView", "WebView crashed internally!");
561
- } else {
562
- //Log.w("CapacitorWebView", "WebView was killed by system (low memory) internally!");
563
- }
564
- }*/
565
-
566
- view.post(() -> {
567
- Toast.makeText(view.getContext(), "Reloading due to low memory issue", Toast.LENGTH_SHORT).show();
568
- });
569
-
570
- view.reload(); // Safely reload WebView
571
-
572
- return true; // We handled it
573
- }
574
-
575
- return result;
576
- }`;
577
-
578
- // Step 1: Update method if needed
579
- let updated = false;
580
-
581
- if (fileContent.includes(oldCodeStart)) {
582
- console.log('✅ Found old onRenderProcessGone method. Replacing it...');
583
- fileContent = fileContent.replace(oldCodeStart, newCode);
584
- updated = true;
585
- } else if (fileContent.includes(newCode)) {
586
- console.log('ℹ️ Method already updated. No changes needed in "BridgeWebViewClient.java".');
587
- } else {
588
- console.error('❌ Error: Neither old nor new code found. Unexpected content.');
589
- process.exit(1);
590
- }
591
-
592
- // Step 2: Check and add import if missing
593
- const importToast = 'import android.widget.Toast;';
594
- if (!fileContent.includes(importToast)) {
595
- console.log('✅ Adding missing import for Toast...');
596
- const importRegex = /import\s+[^;]+;/g;
597
- const matches = [...fileContent.matchAll(importRegex)];
598
-
599
- if (matches.length > 0) {
600
- const lastImport = matches[matches.length - 1];
601
- const insertPosition = lastImport.index + lastImport[0].length;
602
- fileContent = fileContent.slice(0, insertPosition) + `\n${importToast}` + fileContent.slice(insertPosition);
603
- updated = true;
604
- } else {
605
- console.error('❌ Error: No import section found in file.');
606
- process.exit(1);
607
- }
608
- } else {
609
- console.log('ℹ️ Import for Toast already exists. No changes needed.');
610
- }
611
-
612
- // Step 3: Save if updated
613
- if (updated) {
614
- fs.writeFileSync(bridgeWebViewClientFilePath, fileContent, 'utf8');
615
- console.log('✅ File updated successfully.');
616
- } else {
617
- console.log('ℹ️ No changes needed.');
618
- }
619
-
620
-
621
-
622
-
623
- // Check and change the "BridgeWebViewClient.java" file END
624
-
625
-
626
-
627
-
628
-
629
-
630
-
631
-
632
- /*
633
- // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file START
634
-
635
- // Build the path dynamically like you requested
636
- const gradlePath = path.join(
637
- process.cwd(),
638
- 'android',
639
- 'build.gradle'
640
- );
641
-
642
- // Read the existing build.gradle
643
- let gradleContent = fs.readFileSync(gradlePath, 'utf8');
644
-
645
- // Add `ext.kotlin_version` if it's not already there
646
- if (!gradleContent.includes('ext.kotlin_version')) {
647
- gradleContent = gradleContent.replace(
648
- /buildscript\s*{/,
649
- `buildscript {\n ext.kotlin_version = '2.1.0'`
650
- );
651
- }
652
-
653
- // Add Kotlin classpath if it's not already there
654
- if (!gradleContent.includes('org.jetbrains.kotlin:kotlin-gradle-plugin')) {
655
- gradleContent = gradleContent.replace(
656
- /dependencies\s*{([\s\S]*?)classpath 'com.android.tools.build:gradle:8.7.2'/,
657
- `dependencies {\n classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")\n$1classpath 'com.android.tools.build:gradle:8.7.2'`
658
- );
659
- }
660
-
661
- // Write back the modified content
662
- fs.writeFileSync(gradlePath, gradleContent, 'utf8');
663
-
664
- console.log('✅ Kotlin version updated in build.gradle.');
665
-
666
- // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file END
667
- */
668
-
669
-
670
-
671
-
672
-
673
-
674
-
675
-
676
- let _admobConfig;
677
-
678
-
679
-
680
- const androidPlatformPath = path.join(process.cwd(), 'android');
681
- const iosPlatformPath = path.join(process.cwd(), 'ios');
682
- const pluginPath = path.join(process.cwd(), 'node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
683
- const infoPlistPath = path.join(process.cwd(), 'ios', 'App', 'App', 'Info.plist');
684
- const resourcesPath = path.join(process.cwd(), 'resources', 'res');
685
- const androidResPath = path.join(process.cwd(), 'android', 'app', 'src', 'main', 'res');
686
- const localNotificationsPluginPath = path.join(process.cwd(), 'node_modules', '@capacitor', 'local-notifications');
687
-
688
- function fileExists(filePath) {
689
- return fs.existsSync(filePath);
690
- }
691
-
692
- function copyFolderSync(source, target) {
693
- if (!fs.existsSync(target)) {
694
- fs.mkdirSync(target, { recursive: true });
695
- }
696
-
697
- fs.readdirSync(source).forEach(file => {
698
- const sourceFile = path.join(source, file);
699
- const targetFile = path.join(target, file);
700
-
701
- if (fs.lstatSync(sourceFile).isDirectory()) {
702
- copyFolderSync(sourceFile, targetFile);
703
- } else {
704
- fs.copyFileSync(sourceFile, targetFile);
705
- }
706
- });
707
- }
708
-
709
- function checkAndCopyResources() {
710
- if (fileExists(resourcesPath)) {
711
- copyFolderSync(resourcesPath, androidResPath);
712
- console.log('✅ Successfully copied resources/res to android/app/src/main/res.');
713
- } else {
714
- console.log('resources/res folder not found.');
715
-
716
- if (fileExists(localNotificationsPluginPath)) {
717
- throw new Error('❌ resources/res is required for @capacitor/local-notifications. Stopping execution.');
718
- }
719
- }
720
- }
721
-
722
-
723
-
724
-
725
-
726
-
727
-
728
-
729
- function getAdMobConfig() {
730
- if (!fileExists(configPath)) {
731
- throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
732
- }
733
-
734
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
735
- const admobConfig = config.plugins?.AdMob;
736
-
737
- if (!admobConfig) {
738
- throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
739
- }
740
-
741
- // Default to true if ADMOB_ENABLED is not specified
742
- const isEnabled = admobConfig.ADMOB_ENABLED !== false;
743
-
744
- if (!isEnabled) {
745
- return { ADMOB_ENABLED: false }; // Skip further validation
746
- }
747
-
748
- if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
749
- throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
750
- }
751
-
752
- return {
753
- ADMOB_ENABLED: true,
754
- APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
755
- APP_ID_IOS: admobConfig.APP_ID_IOS,
756
- USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
757
- };
758
- }
759
-
760
- function validateAndroidBuildOptions() {
761
-
762
-
763
- if (!fileExists(configPath)) {
764
- console.log('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
765
- process.exit(1);
766
- }
767
-
768
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
769
-
770
- const targetAppId=config.appId
771
-
772
- const buildOptions = config.android?.buildOptions;
773
-
774
- if (!buildOptions) {
775
- console.log('❌ Missing android.buildOptions in capacitor.config.json.');
776
- process.exit(1);
777
- }
778
-
779
- const requiredProps = [
780
- 'keystorePath',
781
- 'keystorePassword',
782
- 'keystoreAlias',
783
- 'keystoreAliasPassword',
784
- 'releaseType',
785
- 'signingType'
786
- ];
787
-
788
- const missing = requiredProps.filter(prop => !buildOptions[prop]);
789
-
790
- if (missing.length > 0) {
791
- console.log('❌ Missing properties android.buildOptions in capacitor.config.json.');
792
- process.exit(1);
793
- }
794
-
795
-
796
- const keystorePath=buildOptions.keystorePath
797
- const keyFileName = path.basename(keystorePath);
798
-
799
-
800
-
801
- const keystoreMap = {
802
- "gameskey.jks": [
803
- "com.cube.blaster",
804
- ],
805
- "htmleditorkeystoke.jks": [
806
- "com.HTML.AngularJS.Codeplay",
807
- "com.html.codeplay.pro",
808
- "com.bootstrap.code.play",
809
- "com.kids.learning.master",
810
- "com.Simple.Barcode.Scanner"
811
- ]
812
- };
813
-
814
- // find which keystore is required for the given targetAppId
815
- let requiredKey = "newappskey.jks"; // default
816
- for (const [keyFile, appIds] of Object.entries(keystoreMap)) {
817
- if (appIds.includes(targetAppId)) {
818
- requiredKey = keyFile;
819
- break;
820
- }
821
- }
822
-
823
- // validate
824
- if (keyFileName !== requiredKey) {
825
- console.log(`❌ The keystore path is mismatched. Expected ${requiredKey} for ${targetAppId}, but got ${keyFileName}`);
826
- process.exit(1);
827
- }
828
-
829
-
830
-
831
-
832
-
833
- // optionally return them
834
- //return buildOptions;
835
- }
836
-
837
- function updatePluginXml(admobConfig) {
838
- if (!fileExists(pluginPath)) {
839
- console.error(' ❌ plugin.xml not found. Ensure the plugin is installed.');
840
- return;
841
- }
842
-
843
- let pluginContent = fs.readFileSync(pluginPath, 'utf8');
844
-
845
- pluginContent = pluginContent
846
- .replace(/<preference name="APP_ID_ANDROID" default=".*?" \/>/, `<preference name="APP_ID_ANDROID" default="${admobConfig.APP_ID_ANDROID}" />`)
847
- .replace(/<preference name="APP_ID_IOS" default=".*?" \/>/, `<preference name="APP_ID_IOS" default="${admobConfig.APP_ID_IOS}" />`);
848
-
849
- fs.writeFileSync(pluginPath, pluginContent, 'utf8');
850
- console.log('✅ AdMob IDs successfully updated in plugin.xml');
851
- }
852
-
853
- function updateInfoPlist(admobConfig) {
854
- if (!fileExists(infoPlistPath)) {
855
- console.error(' ❌ Info.plist not found. Ensure you have built the iOS project.');
856
- return;
857
- }
858
-
859
- const plistContent = fs.readFileSync(infoPlistPath, 'utf8');
860
- const plistData = plist.parse(plistContent);
861
-
862
- plistData.GADApplicationIdentifier = admobConfig.APP_ID_IOS;
863
- plistData.NSUserTrackingUsageDescription = 'This identifier will be used to deliver personalized ads to you.';
864
- plistData.GADDelayAppMeasurementInit = true;
865
-
866
- const updatedPlistContent = plist.build(plistData);
867
- fs.writeFileSync(infoPlistPath, updatedPlistContent, 'utf8');
868
- console.log('AdMob IDs and additional configurations successfully updated in Info.plist');
869
- }
870
-
871
-
872
- try {
873
- if (!fileExists(configPath)) {
874
- throw new Error(' ❌ capacitor.config.json not found. Skipping setup.');
875
- }
876
-
877
- if (!fileExists(androidPlatformPath) && !fileExists(iosPlatformPath)) {
878
- throw new Error('Neither Android nor iOS platforms are found. Ensure platforms are added to your Capacitor project.');
879
- }
880
-
881
- checkAndCopyResources();
882
-
883
-
884
-
885
- _admobConfig = getAdMobConfig();
886
-
887
-
888
-
889
-
890
-
891
- // Proceed only if ADMOB_ENABLED is true
892
- if (_admobConfig.ADMOB_ENABLED) {
893
- if (fileExists(androidPlatformPath)) {
894
- updatePluginXml(_admobConfig);
895
- }
896
-
897
- if (fileExists(iosPlatformPath)) {
898
- updateInfoPlist(_admobConfig);
899
- }
900
- }
901
-
902
-
903
- } catch (error) {
904
- console.error(error.message);
905
- process.exit(1); // Stop execution if there's a critical error
906
- }
907
-
908
-
909
-
910
- validateAndroidBuildOptions();
911
-
912
-
913
-
914
-
915
-
916
-
917
- // Check all the codeplays plugins version START
918
-
919
-
920
- const readline = require('readline');
921
-
922
-
923
- //const srcDir = path.join(__dirname, 'src');
924
- const srcDir = path.join(process.cwd(), 'src');
925
- let outdatedPlugins = [];
926
-
927
- function parseVersion(ver) {
928
- return ver.split('.').map(n => parseInt(n, 10));
929
- }
930
-
931
- function compareVersions(v1, v2) {
932
- const [a1, b1] = parseVersion(v1);
933
- const [a2, b2] = parseVersion(v2);
934
- if (a1 !== a2) return a1 - a2;
935
- return b1 - b2;
936
- }
937
-
938
- function walkSync(dir, filelist = []) {
939
- fs.readdirSync(dir).forEach(file => {
940
- const fullPath = path.join(dir, file);
941
- const stat = fs.statSync(fullPath);
942
- if (stat.isDirectory()) {
943
- walkSync(fullPath, filelist);
944
- } else {
945
- filelist.push(fullPath);
946
- }
947
- });
948
- return filelist;
949
- }
950
-
951
-
952
-
953
- function getSearchRoot(plugin) {
954
- return path.join(srcDir, plugin.baseDir || 'js');
955
- }
956
-
957
- let hasMandatoryUpdate = false;
958
- function checkPlugins() {
959
- return new Promise((resolve, reject) => {
960
- const files = walkSync(srcDir);
961
- const outdatedPlugins = [];
962
- let hasMandatoryUpdate = false;
963
-
964
- for (const plugin of requiredPlugins) {
965
- const searchRoot = getSearchRoot(plugin);
966
-
967
- // ---------- Folder plugins ----------
968
- if (plugin.isFolder) {
969
- if (!fs.existsSync(searchRoot)) continue;
970
-
971
- const subDirs = fs.readdirSync(searchRoot)
972
- .map(name => path.join(searchRoot, name))
973
- .filter(p => fs.statSync(p).isDirectory());
974
-
975
- for (const dir of subDirs) {
976
- const relativePath = path.relative(searchRoot, dir).replace(/\\/g, '/');
977
- const match = plugin.pattern.exec(relativePath);
978
-
979
- if (match) {
980
- const currentVersion = match[1];
981
-
982
- if (compareVersions(currentVersion, plugin.minVersion) < 0) {
983
- outdatedPlugins.push({
984
- name: relativePath,
985
- currentVersion,
986
- requiredVersion: plugin.minVersion,
987
- mandatoryUpdate: plugin.mandatoryUpdate === true
988
- });
989
-
990
- if (plugin.mandatoryUpdate) {
991
- hasMandatoryUpdate = true;
992
- }
993
- }
994
- }
995
- }
996
- continue;
997
- }
998
-
999
- // ---------- File plugins ----------
1000
- const matchedFile = files.find(file =>
1001
- file.startsWith(searchRoot) && plugin.pattern.test(file)
1002
- );
1003
-
1004
- if (matchedFile) {
1005
- const match = plugin.pattern.exec(matchedFile);
1006
- if (match) {
1007
- const currentVersion = match[1];
1008
- const isBeta = !!match[2];
1009
-
1010
- const cmp = plugin.pattern.source.includes('beta')
1011
- ? compareWithBeta(currentVersion, plugin.minVersion, isBeta)
1012
- : compareVersions(currentVersion, plugin.minVersion);
1013
-
1014
- if (cmp < 0) {
1015
- outdatedPlugins.push({
1016
- name: path.relative(srcDir, matchedFile),
1017
- currentVersion: isBeta ? `${currentVersion}-beta` : currentVersion,
1018
- requiredVersion: plugin.minVersion,
1019
- mandatoryUpdate: plugin.mandatoryUpdate === true
1020
- });
1021
-
1022
- if (plugin.mandatoryUpdate) {
1023
- hasMandatoryUpdate = true;
1024
- }
1025
- }
1026
- }
1027
- }
1028
- }
1029
-
1030
- // ---------- Result handling ----------
1031
- if (outdatedPlugins.length > 0) {
1032
- console.log('\n❗ The following plugins are outdated:\n');
1033
-
1034
- outdatedPlugins.forEach(p => {
1035
- const tag = p.mandatoryUpdate ? '🔥 MANDATORY' : '';
1036
- console.log(
1037
- ` ❌ - ${p.name} (Current: ${p.currentVersion}, Required: ${p.requiredVersion}) ${tag}`
1038
- );
1039
- });
1040
-
1041
- // 🚨 Mandatory update → stop build
1042
- if (hasMandatoryUpdate) {
1043
- console.log('\n🚫 One or more plugins require a mandatory update.');
1044
- console.log('❌ Build cancelled. Please update mandatory plugins and try again.');
1045
- process.exit(1);
1046
- }
1047
-
1048
- // Optional updates → ask user
1049
- const rl = readline.createInterface({
1050
- input: process.stdin,
1051
- output: process.stdout
1052
- });
1053
-
1054
- rl.question(
1055
- '\nAre you sure you want to continue without updating these plugins? (y/n): ',
1056
- answer => {
1057
- rl.close();
1058
-
1059
- if (answer.toLowerCase() !== 'y') {
1060
- console.log('\n❌ Build cancelled due to outdated plugins.');
1061
- process.exit(1);
1062
- } else {
1063
- console.log('\n✅ Continuing build...');
1064
- resolve();
1065
- }
1066
- }
1067
- );
1068
- } else {
1069
- console.log('✅ All plugin versions are up to date.');
1070
- resolve();
1071
- }
1072
- });
1073
- }
1074
-
1075
-
1076
-
1077
-
1078
-
1079
-
1080
-
1081
-
1082
- // Check all the codeplays plugins version START
1083
-
1084
-
1085
-
1086
-
1087
- // ====================================================================
1088
- // AUTO-ADD esbuild.drop: ['console','debugger'] to vite.config.js / mjs
1089
- // ====================================================================
1090
-
1091
-
1092
-
1093
- const checkAndupdateDropInViteConfig = () => {
1094
-
1095
- const possibleFiles = [
1096
- "vite.config.js",
1097
- "vite.config.mjs"
1098
- ];
1099
-
1100
- // Detect existing config file
1101
- const viteConfigPath = possibleFiles
1102
- .map(file => path.join(process.cwd(), file))
1103
- .find(filePath => fs.existsSync(filePath));
1104
-
1105
- if (!viteConfigPath) {
1106
- console.warn("⚠️ No vite config found. Skipping.");
1107
- return;
1108
- }
1109
-
1110
- //console.log("📄 Using:", viteConfigPath.split("/").pop());
1111
-
1112
- let viteContent = fs.readFileSync(viteConfigPath, "utf8");
1113
-
1114
- // Skip if already exists
1115
- if (/drop\s*:\s*\[.*['"]console['"].*\]/.test(viteContent)) {
1116
- console.log("ℹ️ vite.config.(m)js already Updated. Skipping...");
1117
- return;
1118
- }
1119
-
1120
- console.log("🔧 Adding esbuild.drop ...");
1121
-
1122
- // If esbuild block exists
1123
- if (/esbuild\s*:\s*{/.test(viteContent)) {
1124
- viteContent = viteContent.replace(
1125
- /esbuild\s*:\s*{([\s\S]*?)(^ {0,8})}/m,
1126
- (full, inner, indent) => {
1127
-
1128
- let lines = inner
1129
- .split("\n")
1130
- .map(l => l.trim())
1131
- .filter(Boolean);
1132
-
1133
- // Fix last comma
1134
- if (lines.length > 0) {
1135
- lines[lines.length - 1] =
1136
- lines[lines.length - 1].replace(/,+$/, "") + ",";
1137
- }
1138
-
1139
- // Re-indent
1140
- lines = lines.map(l => indent + " " + l);
1141
-
1142
- // Add drop
1143
- lines.push(`${indent} drop: ['console','debugger'],`);
1144
-
1145
- return `esbuild: {\n${lines.join("\n")}\n${indent}}`;
1146
- }
1147
- );
1148
- }
1149
-
1150
- // If esbuild missing
1151
- else {
1152
- viteContent = viteContent.replace(
1153
- /export default defineConfig\s*\(\s*{/,
1154
- m => `${m}\n esbuild: {\n drop: ['console','debugger'],\n },`
1155
- );
1156
- }
1157
-
1158
- fs.writeFileSync(viteConfigPath, viteContent, "utf8");
1159
- console.log("✅ vite.config.(m)js Updated successfully.");
1160
- };
1161
-
1162
-
1163
-
1164
-
1165
-
1166
-
1167
-
1168
-
1169
-
1170
-
1171
- const compareVersion = (v1, v2) => {
1172
- const a = v1.split(".").map(Number);
1173
- const b = v2.split(".").map(Number);
1174
-
1175
- for (let i = 0; i < Math.max(a.length, b.length); i++) {
1176
- const num1 = a[i] || 0;
1177
- const num2 = b[i] || 0;
1178
- if (num1 > num2) return 1;
1179
- if (num1 < num2) return -1;
1180
- }
1181
- return 0;
1182
- };
1183
-
1184
-
1185
-
1186
-
1187
- const admobConfigPath = path.join('src', 'js','Ads', 'admob-ad-configuration.json');
1188
-
1189
- const checkAdmobConfigurationProperty=()=>{
1190
-
1191
-
1192
- if (!_admobConfig.ADMOB_ENABLED)
1193
- {
1194
- console.log("ℹ️ Admob is not enabled so 'admob-ad-configuration.json' checking is skipping...");
1195
- return;
1196
- }
1197
-
1198
-
1199
- const REQUIRED_CONFIG_KEYS = [
1200
- "isKidsApp",
1201
- "isTesting",
1202
- "isConsoleLogEnabled",
1203
- "bannerEnabled",
1204
- "interstitialEnabled",
1205
- "appOpenEnabled",
1206
- "rewardVideoEnabled",
1207
- "rewardInterstitialEnabled",
1208
- "collapsibleEnabled",
1209
- "isLandScape",
1210
- "isOverlappingEnable",
1211
- "bannerTypeAndroid",
1212
- "bannerTypeiOS",
1213
- "bannerTopSpaceColor",
1214
- "interstitialLoadScreenTextColor",
1215
- "interstitialLoadScreenBackgroundColor",
1216
- "beforeBannerSpace",
1217
- "whenShow",
1218
- "minimumClick",
1219
- "interstitialTimeOut",
1220
- "interstitialFirstTimeOut",
1221
- "appOpenAdsTimeOut",
1222
- "maxRetryCount",
1223
- "retrySecondsAr",
1224
- "appOpenPerSession",
1225
- "interstitialPerSession",
1226
- "appOpenFirstTimeOut"
1227
- ];
1228
-
1229
-
1230
-
1231
-
1232
-
1233
- let admobConfigInJson;
1234
-
1235
- try {
1236
- admobConfigInJson = JSON.parse(readFileSync(admobConfigPath, "utf8"));
1237
- } catch (err) {
1238
- console.error("❌ Failed to read admob-ad-configuration.json", err);
1239
- process.exit(1);
1240
- }
1241
-
1242
- // Validate config object exists
1243
- if (!admobConfigInJson.config) {
1244
- console.error('❌ "config" object is missing in admob-ad-configuration.json');
1245
- process.exit(1);
1246
- }
1247
-
1248
-
1249
- const admobConfigMinVersion="1.5"
1250
-
1251
- if (compareVersion(admobConfigInJson.VERSION, admobConfigMinVersion) < 0) {
1252
- console.error(`❌ Please use at-least version ${admobConfigMinVersion} in "src/js/Ads/admob-ad-configuration.json"`);
1253
- process.exit(1);
1254
- }
1255
-
1256
-
1257
- const config = admobConfigInJson.config;
1258
-
1259
- // Find missing properties
1260
- const missingKeys = REQUIRED_CONFIG_KEYS.filter(
1261
- key => !(key in config)
1262
- );
1263
-
1264
-
1265
-
1266
- if (missingKeys.length > 0) {
1267
- console.error("❌ Missing required configuration keys. Please check it in 'src/js/Ads/admob-ad-configuration.json'");
1268
-
1269
- missingKeys.forEach(k => console.error(" - " + k));
1270
- process.exit(1);
1271
- }
1272
-
1273
-
1274
- console.log('✅ All keys exist. in "admob-ad-configuration.json file" Configuration looks good.');
1275
- }
1276
-
1277
-
1278
-
1279
- function ensureGitignoreEntry(entry) {
1280
- const gitignorePath = path.join(process.cwd(), '.gitignore');
1281
-
1282
- // If .gitignore doesn't exist, create it
1283
- if (!fs.existsSync(gitignorePath)) {
1284
- fs.writeFileSync(gitignorePath, `${entry}\n`, 'utf8');
1285
- console.log(`✅ .gitignore created and added: ${entry}`);
1286
- return;
1287
- }
1288
-
1289
- const content = fs.readFileSync(gitignorePath, 'utf8');
1290
-
1291
- // Normalize lines (trim + remove trailing slashes for comparison)
1292
- const lines = content
1293
- .split(/\r?\n/)
1294
- .map(l => l.trim());
1295
-
1296
- const normalizedEntry = entry.replace(/\/$/, '');
1297
-
1298
- const exists = lines.some(
1299
- line => line.replace(/\/$/, '') === normalizedEntry
1300
- );
1301
-
1302
- if (exists) {
1303
- console.log(`ℹ️ .gitignore already contains: ${entry}`);
1304
- return;
1305
- }
1306
-
1307
- // Ensure file ends with newline
1308
- const separator = content.endsWith('\n') ? '' : '\n';
1309
-
1310
- fs.appendFileSync(gitignorePath, `${separator}${entry}\n`, 'utf8');
1311
- console.log(`✅ Added to .gitignore: ${entry}`);
1312
- }
1313
-
1314
-
1315
- ensureGitignoreEntry('buildCodeplay/');
1316
-
1317
-
1318
- // Run the validation
1319
- (async () => {
1320
- await checkPlugins();
1321
- checkAndupdateDropInViteConfig();
1322
- checkAdmobConfigurationProperty()
1323
- })();
1324
-
1325
-
1326
- // ======================================================
1327
- // Validate theme folder location (src/js/theme is NOT allowed)
1328
- // ======================================================
1329
-
1330
- function validateThemeFolderLocation() {
1331
- const oldThemePath = path.join(process.cwd(), 'src', 'js', 'theme');
1332
- const newThemePath = path.join(process.cwd(), 'src', 'theme');
1333
-
1334
- // ❌ Block old structure
1335
- if (fs.existsSync(oldThemePath)) {
1336
- console.error(
1337
- '\n❌ INVALID PROJECT STRUCTURE DETECTED\n' +
1338
- '--------------------------------------------------\n' +
1339
- 'The "theme" folder must NOT be inside:\n' +
1340
- ' src/js/theme\n\n' +
1341
- '✅ Correct location is:\n' +
1342
- ' src/theme\n\n' +
1343
- '🛑 Please move the folder and re-run the build.\n'
1344
- );
1345
- process.exit(1);
1346
- }
1347
-
1348
- // ⚠️ Optional warning if new theme folder is missing
1349
- if (!fs.existsSync(newThemePath)) {
1350
- console.warn(
1351
- '\n⚠️ WARNING: "src/theme" folder not found.\n' +
1352
- 'If your app uses themes, please ensure it exists.\n'
1353
- );
1354
- } else {
1355
- console.log('✅ Theme folder structure validated (src/theme).');
1356
- }
1357
- }
1358
- validateThemeFolderLocation()
1359
-
1360
-
1361
-
1362
- const validateAndRestoreSignDetails=()=>{
1363
-
1364
- // Read config file
1365
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
1366
-
1367
- // Ensure android and buildOptions exist
1368
- if (!config.android) config.android = {};
1369
- if (!config.android.buildOptions) config.android.buildOptions = {};
1370
-
1371
- // Update only if changed
1372
- let updated = false;
1373
-
1374
- if (config.android.buildOptions.releaseType !== 'AAB') {
1375
- config.android.buildOptions.releaseType = 'AAB';
1376
- updated = true;
1377
- }
1378
-
1379
- if (config.android.buildOptions.signingType !== 'jarsigner') {
1380
- config.android.buildOptions.signingType = 'jarsigner';
1381
- updated = true;
1382
- }
1383
-
1384
- // Write back only if modified
1385
- if (updated) {
1386
- fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
1387
- console.log('capacitor.config.json updated successfully.');
1388
- } else {
1389
- console.log('No changes needed.');
1390
- }
1391
-
1392
- }
1393
-
1394
- validateAndRestoreSignDetails()
1395
-
1396
-
1397
- /*
1398
- Release Notes
1399
-
1400
- 5.1
1401
- Kotlin version update is commented. Previously admob is not worked if not update the kotlin version to higher version
1402
-
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const plist = require('plist');
4
+
5
+ const { readFileSync } = require("fs");
6
+
7
+ const ENABLE_AUTO_UPDATE = true;
8
+
9
+ const configPath = path.join(process.cwd(), 'capacitor.config.json');
10
+
11
+ // Expected plugin list with minimum versions
12
+ const requiredPlugins = [
13
+
14
+ { pattern: /backbutton-(\d+\.\d+)\.js$/, minVersion: '1.8', required: true, baseDir: 'js',mandatoryUpdate: true},
15
+
16
+ /*/common-(\d+\.\d+)\.js$/*/
17
+ { pattern: /common-(\d+\.\d+)(?:-beta-(\d+))?\.js$/, minVersion: '5.8', required: true, baseDir: 'js',mandatoryUpdate: true },
18
+
19
+ { pattern: /localization_settings-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true, baseDir: 'js',mandatoryUpdate: false },
20
+ { pattern: /localization-(\d+\.\d+)\.js$/, minVersion: '1.5', required: true, baseDir: 'js',mandatoryUpdate: true },
21
+ { pattern: /localNotification-(\d+\.\d+)\.js$/, minVersion: '2.2', required: true, baseDir: 'js',mandatoryUpdate: false },
22
+ { pattern: /localNotification_AppSettings-(\d+\.\d+)\.js$/, minVersion: '1.0', required: true, baseDir: 'js',mandatoryUpdate: false },
23
+ { pattern: /onesignal-(\d+\.\d+)\.js$/, minVersion: '2.3', required: true, baseDir: 'js',mandatoryUpdate: false },
24
+ { pattern: /saveToGalleryAndSaveAnyFile-(\d+\.\d+)(-ios)?\.js$/, minVersion: '3.1', required: true, baseDir: 'js',mandatoryUpdate: true },
25
+ { pattern: /Ads[\/\\]admob-emi-(\d+\.\d+)\.js$/, minVersion: '3.6', required: true, baseDir: 'js',mandatoryUpdate: true },
26
+
27
+ // New added plugins
28
+ { pattern: /video-player-(\d+\.\d+)\.js$/, minVersion: '1.5', required: true, baseDir: 'js',mandatoryUpdate: false },
29
+ { pattern: /image-cropper-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true, baseDir: 'js',mandatoryUpdate: false },
30
+ { pattern: /common-(\d+\.\d+)\.less$/, minVersion: '1.6', required: true, baseDir: 'assets/css',mandatoryUpdate: false },
31
+
32
+
33
+ // New folders
34
+ { pattern: /IAP-(\d+\.\d+)$/, minVersion: '2.8', isFolder: true , required: true, baseDir: 'js/Ads',mandatoryUpdate: true },
35
+ { pattern: /editor-(\d+\.\d+)$/, minVersion: '1.9', isFolder: true, required: true, baseDir: 'js',mandatoryUpdate: true },
36
+ { pattern: /ffmpeg-(\d+\.\d+)$/, minVersion: '1.5', isFolder: true, required: true, baseDir: 'js',mandatoryUpdate: false },
37
+ { pattern: /theme-(\d+\.\d+)$/, minVersion: '3.1', isFolder: true , required: true, baseDir: 'theme',mandatoryUpdate: true },
38
+
39
+
40
+ { pattern: /certificatejs-(\d+\.\d+)$/, minVersion: '1.6', isFolder: true , required: true, baseDir: 'certificate',mandatoryUpdate: true }
41
+
42
+ ];
43
+
44
+
45
+
46
+
47
+
48
+
49
+ //Check codeplay-common latest version installed or not Start
50
+ const { execSync } = require('child_process');
51
+
52
+ function getInstalledVersion(packageName) {
53
+ try {
54
+ const packageJsonPath = path.join(process.cwd(), 'node_modules', packageName, 'package.json');
55
+ if (fs.existsSync(packageJsonPath)) {
56
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
57
+ return packageJson.version;
58
+ }
59
+ } catch (error) {
60
+ return null;
61
+ }
62
+ return null;
63
+ }
64
+
65
+ function getLatestVersion(packageName) {
66
+ try {
67
+ return execSync(`npm view ${packageName} version`).toString().trim();
68
+ } catch (error) {
69
+ console.error(`Failed to fetch latest version for ${packageName}`);
70
+ return null;
71
+ }
72
+ }
73
+
74
+ function checkPackageVersion() {
75
+ const packageName = 'codeplay-common';
76
+ const installedVersion = getInstalledVersion(packageName);
77
+ const latestVersion = getLatestVersion(packageName);
78
+
79
+ if (!installedVersion) {
80
+ console.error(`${packageName} is not installed. Please install it using "npm install ${packageName}".`);
81
+ process.exit(1);
82
+ }
83
+
84
+ if (installedVersion !== latestVersion) {
85
+ console.error(`\x1b[31m${packageName} is outdated (installed: ${installedVersion}, latest: ${latestVersion}). Please update it.\x1b[0m\n\x1b[33mUse 'npm uninstall codeplay-common ; npm i codeplay-common'\x1b[0m`);
86
+ process.exit(1);
87
+ }
88
+
89
+ console.log(`${packageName} is up to date (version ${installedVersion}).`);
90
+ }
91
+
92
+ // Run package version check before executing the main script
93
+ try {
94
+ checkPackageVersion();
95
+ } catch (error) {
96
+ console.error(error.message);
97
+ process.exit(1);
98
+ }
99
+
100
+ //Check codeplay-common latest version installed or not END
101
+
102
+
103
+
104
+ function compareWithBeta(installedVersion, minVersion, isBeta) {
105
+ const baseCompare = compareVersions(installedVersion, minVersion);
106
+
107
+ if (!isBeta) {
108
+ // Stable version → normal compare
109
+ return baseCompare;
110
+ }
111
+
112
+ // Beta version logic
113
+ if (baseCompare > 0) return 1; // 5.3-beta > 5.2
114
+ if (baseCompare < 0) return -1; // 5.1-beta < 5.2
115
+
116
+ // Same version but beta → LOWER than stable
117
+ return -1; // 5.2-beta < 5.2
118
+ }
119
+
120
+
121
+
122
+
123
+ const checkAppUniqueId=()=>{
124
+
125
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
126
+
127
+ const appUniqueId = config.android?.APP_UNIQUE_ID;
128
+ const RESIZEABLE_ACTIVITY = config.android?.RESIZEABLE_ACTIVITY;
129
+ const orientation = config.android?.ORIENTATION;
130
+
131
+
132
+ let logErrorMessage="";
133
+
134
+ // 1️⃣ Check if it’s missing
135
+ if (RESIZEABLE_ACTIVITY === undefined) {
136
+ logErrorMessage+='❌ Missing android.RESIZEABLE_ACTIVITY option in capacitor.config.json.\n';
137
+ }
138
+
139
+ // 2️⃣ Check if it’s not boolean (true/false only)
140
+ else if (typeof RESIZEABLE_ACTIVITY !== 'boolean') {
141
+ logErrorMessage+='❌ Invalid android.RESIZEABLE_ACTIVITY value. Please use only true or false (without quotes).\n';
142
+ }
143
+
144
+
145
+
146
+ if (!orientation) {
147
+ logErrorMessage+='❌ Missing android.ORIENTATION option in capacitor.config.json.\n';
148
+ }
149
+
150
+ else if(orientation!="portrait" && orientation!="landscape" && orientation!="auto")
151
+ {
152
+ logErrorMessage+='❌ Spelling mistake in android.ORIENTATION option in capacitor.config.json. Please use only ["portrait" "landscape" "auto"]\n';
153
+ }
154
+
155
+
156
+ if (!appUniqueId) {
157
+ logErrorMessage+='❌ APP_UNIQUE_ID is missing in capacitor.config.json.';
158
+ }
159
+
160
+ else if (!Number.isInteger(appUniqueId)) {
161
+ logErrorMessage+='❌ APP_UNIQUE_ID must be an integer. Example: 1, 2, 3, etc.';
162
+ }
163
+
164
+
165
+
166
+ if(logErrorMessage!="")
167
+ {
168
+ console.error(logErrorMessage);
169
+ process.exit(1)
170
+ }
171
+
172
+
173
+ console.log(`✅ APP_UNIQUE_ID is valid: ${appUniqueId}`);
174
+
175
+ }
176
+
177
+ checkAppUniqueId();
178
+
179
+
180
+
181
+
182
+
183
+
184
+
185
+ //@Codemirror check and install/uninstall the packages START
186
+ //const fs = require("fs");
187
+ //const path = require("path");
188
+ //const { execSync } = require("child_process");
189
+
190
+ const baseDir = path.join(__dirname, "..", "src", "js");
191
+
192
+ // Step 1: Find highest versioned folder like `editor-1.6`
193
+ const editorDirs = fs.readdirSync(baseDir)
194
+ .filter(name => /^editor-\d+\.\d+$/.test(name))
195
+ .sort((a, b) => {
196
+ const getVersion = str => str.match(/(\d+)\.(\d+)/).slice(1).map(Number);
197
+ const [aMajor, aMinor] = getVersion(a);
198
+ const [bMajor, bMinor] = getVersion(b);
199
+ return bMajor - aMajor || bMinor - aMinor;
200
+ });
201
+
202
+ if (editorDirs.length === 0) {
203
+
204
+ console.log("@Codemirror used editor(s) are not found")
205
+ //console.error("❌ No editor-x.x folders found in src/js.");
206
+ //process.exit(1);
207
+ }
208
+ else
209
+ {
210
+
211
+ const latestEditorDir = editorDirs.sort((a, b) => {
212
+ const versionA = parseFloat(a.split('-')[1]);
213
+ const versionB = parseFloat(b.split('-')[1]);
214
+ return versionB - versionA;
215
+ })[0];
216
+
217
+ //const latestEditorDir = editorDirs[editorDirs.length - 1];
218
+ const runJsPath = path.join(baseDir, latestEditorDir, "run.js");
219
+
220
+ if (!fs.existsSync(runJsPath)) {
221
+ console.error(`❌ run.js not found in ${latestEditorDir}`);
222
+ process.exit(1);
223
+ }
224
+
225
+ // Step 2: Execute the run.js file
226
+ console.log(`🚀 Executing ${runJsPath}...`);
227
+ execSync(`node "${runJsPath}"`, { stdio: "inherit" });
228
+ }
229
+
230
+ //@Codemirror check and install/uninstall the packages END
231
+
232
+
233
+
234
+
235
+
236
+
237
+
238
+
239
+
240
+
241
+
242
+
243
+ // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists START
244
+
245
+ const os = require('os');
246
+
247
+ const saveToGalleryAndSaveFileCheck_iOS = () => {
248
+
249
+ // List of paths to scan
250
+ const SCAN_PATHS = [
251
+ path.resolve(__dirname, '../src/certificate'),
252
+ path.resolve(__dirname, '../src/pages'),
253
+ path.resolve(__dirname, '../src/js'),
254
+ path.resolve(__dirname, '../src/app.f7')
255
+ ];
256
+
257
+ // Directory to exclude
258
+ const EXCLUDED_DIR = path.resolve(__dirname, '../src/js/Ads');
259
+
260
+ const ANDROID_MANIFEST_PATH = path.resolve(__dirname, '../android/app/src/main/AndroidManifest.xml');
261
+
262
+
263
+ // Match iOS-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5-ios.js) not in comments
264
+ const IOS_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*-ios\.js['"]/m;
265
+
266
+ // Match Android-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5.js) not in comments
267
+ const ANDROID_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*\.js['"]/m;
268
+
269
+
270
+
271
+
272
+
273
+ const ALLOWED_EXTENSIONS = ['.js', '.f7'];
274
+ const isMac = os.platform() === 'darwin';
275
+
276
+ let iosImportFound = false;
277
+ let androidImportFound = false;
278
+
279
+ // Files to skip completely (full or partial match)
280
+ const SKIP_FILES = [
281
+ 'pdf-3.11.174.min.js',
282
+ 'pdf.worker-3.11.174.min.js'
283
+ ,'index.browser.js'
284
+ ];
285
+
286
+
287
+ function scanDirectory(dir) {
288
+
289
+ /*
290
+ //######################### DO NOT DELETE THIS - START [Appid base validation] #####################################
291
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
292
+ const appUniqueId = config.android?.APP_UNIQUE_ID;
293
+ if (appUniqueId == "206") return;
294
+ //######################### DO NOT DELETE THIS - END [Appid base validation] #####################################
295
+ */
296
+
297
+ const stat = fs.statSync(dir);
298
+
299
+ if (stat.isFile()) {
300
+
301
+ // 🔥 Skip files in SKIP_FILES array
302
+ const baseName = path.basename(dir);
303
+ if (SKIP_FILES.includes(baseName)) {
304
+ // Just skip silently
305
+ return;
306
+ }
307
+
308
+ // Only scan allowed file extensions
309
+ if (ALLOWED_EXTENSIONS.some(ext => dir.endsWith(ext))) {
310
+ process.stdout.write(`\r🔍 Scanning: ${dir} `);
311
+
312
+ const content = fs.readFileSync(dir, 'utf8');
313
+
314
+ if (IOS_FILE_REGEX.test(content)) {
315
+ iosImportFound = true;
316
+ if (!isMac) {
317
+ console.error(`\n❌ ERROR: iOS-specific import detected in: ${dir}`);
318
+ console.error(`🚫 STOPPED: This file should not be imported in Android/Windows/Linux builds.\n`);
319
+ process.exit(1);
320
+ }
321
+ }
322
+ else if (ANDROID_FILE_REGEX.test(content) && !content.includes('-ios.js')) {
323
+ androidImportFound = true;
324
+ }
325
+ }
326
+ }
327
+ else if (stat.isDirectory()) {
328
+ if (dir === EXCLUDED_DIR || path.basename(dir) === 'node_modules') return;
329
+
330
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
331
+ for (let entry of entries) {
332
+ scanDirectory(path.join(dir, entry.name));
333
+ }
334
+ }
335
+ }
336
+
337
+
338
+ // Run scan on all specified paths
339
+ for (let scanPath of SCAN_PATHS) {
340
+ if (fs.existsSync(scanPath)) {
341
+ scanDirectory(scanPath);
342
+ }
343
+ }
344
+
345
+
346
+
347
+ /* // Check src folder
348
+ if (!fs.existsSync(ROOT_DIR)) {
349
+ console.warn(`⚠️ Warning: 'src' directory not found at: ${ROOT_DIR}`);
350
+ return;
351
+ } */
352
+
353
+ //scanDirectory(ROOT_DIR);
354
+
355
+ // iOS Checks
356
+ if (isMac && !iosImportFound) {
357
+ console.warn(`⚠️ WARNING: You're on macOS but no iOS version (saveToGalleryAndSaveAnyFile-x.x-ios.js) found.`);
358
+ process.exit(1);
359
+ } else if (isMac && iosImportFound) {
360
+ console.log('✅ iOS version detected for macOS build.');
361
+ } else if (!iosImportFound) {
362
+ console.log('✅ No iOS-specific imports detected for non-macOS.');
363
+ }
364
+
365
+ // Android Checks
366
+ if (androidImportFound) {
367
+ console.log("📱 Android version of saveToGalleryAndSaveAnyFile detected. Checking AndroidManifest.xml...");
368
+
369
+ if (!fs.existsSync(ANDROID_MANIFEST_PATH)) {
370
+ console.error("❌ AndroidManifest.xml not found. Cannot add requestLegacyExternalStorage attribute.");
371
+ return;
372
+ }
373
+
374
+ let manifestContent = fs.readFileSync(ANDROID_MANIFEST_PATH, 'utf8');
375
+
376
+ if (!manifestContent.includes('android:requestLegacyExternalStorage="true"')) {
377
+ console.log("Adding android:requestLegacyExternalStorage=\"true\" to <application> tag...");
378
+
379
+ manifestContent = manifestContent.replace(
380
+ /<application([^>]*)>/,
381
+ (match, attrs) => {
382
+ if (attrs.includes('android:requestLegacyExternalStorage')) return match;
383
+ return `<application${attrs} android:requestLegacyExternalStorage="true">`;
384
+ }
385
+ );
386
+
387
+ fs.writeFileSync(ANDROID_MANIFEST_PATH, manifestContent, 'utf8');
388
+ console.log("✅ android:requestLegacyExternalStorage=\"true\" added successfully.");
389
+ } else {
390
+ console.log("ℹ️ android:requestLegacyExternalStorage already exists in AndroidManifest.xml.");
391
+ }
392
+ } else {
393
+ console.log("✅ No Android saveToGalleryAndSaveAnyFile imports detected.");
394
+ }
395
+ };
396
+
397
+ saveToGalleryAndSaveFileCheck_iOS();
398
+ // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists END
399
+
400
+
401
+
402
+
403
+
404
+
405
+
406
+
407
+
408
+
409
+
410
+
411
+
412
+ /*
413
+ // Clean up AppleDouble files (._*) created by macOS START
414
+ if (process.platform === 'darwin') {
415
+ try {
416
+ console.log('🧹 Cleaning up AppleDouble files (._*)...');
417
+ execSync(`find . -name '._*' -delete`);
418
+ console.log('✅ AppleDouble files removed.');
419
+ } catch (err) {
420
+ console.warn('⚠️ Failed to remove AppleDouble files:', err.message);
421
+ }
422
+ } else {
423
+ console.log('ℹ️ Skipping AppleDouble cleanup — not a macOS machine.');
424
+ }
425
+
426
+ // Clean up AppleDouble files (._*) created by macOS END
427
+ */
428
+
429
+
430
+
431
+
432
+
433
+
434
+ //In routes.js file check static import START
435
+
436
+ const routesPath = path.join(process.cwd(), 'src', 'js', 'routes.js');
437
+ const routesContent = fs.readFileSync(routesPath, 'utf-8');
438
+
439
+ let inBlockComment = false;
440
+ const lines = routesContent.split('\n');
441
+
442
+ const allowedImport = `import HomePage from '../pages/home.f7';`;
443
+ const badImportRegex = /^[ \t]*import\s+[\w{}*,\s]*\s+from\s+['"].+\.f7['"]\s*;/;
444
+ const badImports = [];
445
+
446
+ lines.forEach((line, index) => {
447
+ const trimmed = line.trim();
448
+
449
+ // Handle block comment start and end
450
+ if (trimmed.startsWith('/*')) inBlockComment = true;
451
+ if (inBlockComment && trimmed.endsWith('*/')) {
452
+ inBlockComment = false;
453
+ return;
454
+ }
455
+
456
+ // Skip if inside block comment or line comment
457
+ if (inBlockComment || trimmed.startsWith('//')) return;
458
+
459
+ // Match static .f7 import
460
+ if (badImportRegex.test(trimmed) && trimmed !== allowedImport) {
461
+ badImports.push({ line: trimmed, number: index + 1 });
462
+ }
463
+ });
464
+
465
+ if (badImports.length > 0) {
466
+ console.error('\n❌ ERROR: Detected disallowed static imports of .f7 files in routes.js\n');
467
+ console.error(`⚠️ Only this static import is allowed:\n ${allowedImport}\n`);
468
+ console.error(`🔧 Please convert other imports to async dynamic imports like this:\n`);
469
+ console.error(`
470
+
471
+ import HomePage from '../pages/home.f7';
472
+
473
+ const routes = [
474
+ {
475
+ path: '/',
476
+ component:HomePage,
477
+ },
478
+ {
479
+ path: '/ProfilePage/',
480
+ async async({ resolve }) {
481
+ const page = await import('../pages/profile.f7');
482
+ resolve({ component: page.default });
483
+ },
484
+ }]
485
+ `);
486
+
487
+ badImports.forEach(({ line, number }) => {
488
+ console.error(`${number}: ${line}`);
489
+ });
490
+
491
+ process.exit(1);
492
+ } else {
493
+ console.log('✅ routes.js passed the .f7 import check.');
494
+ }
495
+
496
+ //In routes.js file check static import END
497
+
498
+
499
+
500
+
501
+
502
+
503
+
504
+
505
+
506
+
507
+
508
+
509
+
510
+ // Check and change the "BridgeWebViewClient.java" file START
511
+ /*
512
+ For crash issue due to low memory problem, we need to modify the onRenderProcessGone method in BridgeWebViewClient.java.
513
+ */
514
+
515
+
516
+ const bridgeWebViewClientFilePath = path.join(process.cwd(), 'node_modules', '@capacitor/android/capacitor/src/main/java/com/getcapacitor', 'BridgeWebViewClient.java');
517
+
518
+ // Read the file
519
+ if (!fs.existsSync(bridgeWebViewClientFilePath)) {
520
+ console.error('❌ Error: BridgeWebViewClient.java not found.');
521
+ process.exit(1);
522
+ }
523
+
524
+ let fileContent = fs.readFileSync(bridgeWebViewClientFilePath, 'utf8');
525
+
526
+ // Define old and new code
527
+ const oldCodeStart = `@Override
528
+ public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
529
+ super.onRenderProcessGone(view, detail);
530
+ boolean result = false;
531
+
532
+ List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
533
+ if (webViewListeners != null) {
534
+ for (WebViewListener listener : bridge.getWebViewListeners()) {
535
+ result = listener.onRenderProcessGone(view, detail) || result;
536
+ }
537
+ }
538
+
539
+ return result;
540
+ }`;
541
+
542
+ const newCode = `@Override
543
+ public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
544
+ super.onRenderProcessGone(view, detail);
545
+
546
+ boolean result = false;
547
+
548
+ List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
549
+ if (webViewListeners != null) {
550
+ for (WebViewListener listener : bridge.getWebViewListeners()) {
551
+ result = listener.onRenderProcessGone(view, detail) || result;
552
+ }
553
+ }
554
+
555
+ if (!result) {
556
+ // If no one handled it, handle it ourselves!
557
+
558
+ /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
559
+ if (detail.didCrash()) {
560
+ //Log.e("CapacitorWebView", "WebView crashed internally!");
561
+ } else {
562
+ //Log.w("CapacitorWebView", "WebView was killed by system (low memory) internally!");
563
+ }
564
+ }*/
565
+
566
+ view.post(() -> {
567
+ Toast.makeText(view.getContext(), "Reloading due to low memory issue", Toast.LENGTH_SHORT).show();
568
+ });
569
+
570
+ view.reload(); // Safely reload WebView
571
+
572
+ return true; // We handled it
573
+ }
574
+
575
+ return result;
576
+ }`;
577
+
578
+ // Step 1: Update method if needed
579
+ let updated = false;
580
+
581
+ if (fileContent.includes(oldCodeStart)) {
582
+ console.log('✅ Found old onRenderProcessGone method. Replacing it...');
583
+ fileContent = fileContent.replace(oldCodeStart, newCode);
584
+ updated = true;
585
+ } else if (fileContent.includes(newCode)) {
586
+ console.log('ℹ️ Method already updated. No changes needed in "BridgeWebViewClient.java".');
587
+ } else {
588
+ console.error('❌ Error: Neither old nor new code found. Unexpected content.');
589
+ process.exit(1);
590
+ }
591
+
592
+ // Step 2: Check and add import if missing
593
+ const importToast = 'import android.widget.Toast;';
594
+ if (!fileContent.includes(importToast)) {
595
+ console.log('✅ Adding missing import for Toast...');
596
+ const importRegex = /import\s+[^;]+;/g;
597
+ const matches = [...fileContent.matchAll(importRegex)];
598
+
599
+ if (matches.length > 0) {
600
+ const lastImport = matches[matches.length - 1];
601
+ const insertPosition = lastImport.index + lastImport[0].length;
602
+ fileContent = fileContent.slice(0, insertPosition) + `\n${importToast}` + fileContent.slice(insertPosition);
603
+ updated = true;
604
+ } else {
605
+ console.error('❌ Error: No import section found in file.');
606
+ process.exit(1);
607
+ }
608
+ } else {
609
+ console.log('ℹ️ Import for Toast already exists. No changes needed.');
610
+ }
611
+
612
+ // Step 3: Save if updated
613
+ if (updated) {
614
+ fs.writeFileSync(bridgeWebViewClientFilePath, fileContent, 'utf8');
615
+ console.log('✅ File updated successfully.');
616
+ } else {
617
+ console.log('ℹ️ No changes needed.');
618
+ }
619
+
620
+
621
+
622
+
623
+ // Check and change the "BridgeWebViewClient.java" file END
624
+
625
+
626
+
627
+
628
+
629
+
630
+
631
+
632
+ /*
633
+ // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file START
634
+
635
+ // Build the path dynamically like you requested
636
+ const gradlePath = path.join(
637
+ process.cwd(),
638
+ 'android',
639
+ 'build.gradle'
640
+ );
641
+
642
+ // Read the existing build.gradle
643
+ let gradleContent = fs.readFileSync(gradlePath, 'utf8');
644
+
645
+ // Add `ext.kotlin_version` if it's not already there
646
+ if (!gradleContent.includes('ext.kotlin_version')) {
647
+ gradleContent = gradleContent.replace(
648
+ /buildscript\s*{/,
649
+ `buildscript {\n ext.kotlin_version = '2.1.0'`
650
+ );
651
+ }
652
+
653
+ // Add Kotlin classpath if it's not already there
654
+ if (!gradleContent.includes('org.jetbrains.kotlin:kotlin-gradle-plugin')) {
655
+ gradleContent = gradleContent.replace(
656
+ /dependencies\s*{([\s\S]*?)classpath 'com.android.tools.build:gradle:8.7.2'/,
657
+ `dependencies {\n classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")\n$1classpath 'com.android.tools.build:gradle:8.7.2'`
658
+ );
659
+ }
660
+
661
+ // Write back the modified content
662
+ fs.writeFileSync(gradlePath, gradleContent, 'utf8');
663
+
664
+ console.log('✅ Kotlin version updated in build.gradle.');
665
+
666
+ // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file END
667
+ */
668
+
669
+
670
+
671
+
672
+
673
+
674
+
675
+
676
+ let _admobConfig;
677
+
678
+
679
+
680
+ const androidPlatformPath = path.join(process.cwd(), 'android');
681
+ const iosPlatformPath = path.join(process.cwd(), 'ios');
682
+ const pluginPath = path.join(process.cwd(), 'node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
683
+ const infoPlistPath = path.join(process.cwd(), 'ios', 'App', 'App', 'Info.plist');
684
+ const resourcesPath = path.join(process.cwd(), 'resources', 'res');
685
+ const androidResPath = path.join(process.cwd(), 'android', 'app', 'src', 'main', 'res');
686
+ const localNotificationsPluginPath = path.join(process.cwd(), 'node_modules', '@capacitor', 'local-notifications');
687
+
688
+ function fileExists(filePath) {
689
+ return fs.existsSync(filePath);
690
+ }
691
+
692
+ function copyFolderSync(source, target) {
693
+ if (!fs.existsSync(target)) {
694
+ fs.mkdirSync(target, { recursive: true });
695
+ }
696
+
697
+ fs.readdirSync(source).forEach(file => {
698
+ const sourceFile = path.join(source, file);
699
+ const targetFile = path.join(target, file);
700
+
701
+ if (fs.lstatSync(sourceFile).isDirectory()) {
702
+ copyFolderSync(sourceFile, targetFile);
703
+ } else {
704
+ fs.copyFileSync(sourceFile, targetFile);
705
+ }
706
+ });
707
+ }
708
+
709
+ function checkAndCopyResources() {
710
+ if (fileExists(resourcesPath)) {
711
+ copyFolderSync(resourcesPath, androidResPath);
712
+ console.log('✅ Successfully copied resources/res to android/app/src/main/res.');
713
+ } else {
714
+ console.log('resources/res folder not found.');
715
+
716
+ if (fileExists(localNotificationsPluginPath)) {
717
+ throw new Error('❌ resources/res is required for @capacitor/local-notifications. Stopping execution.');
718
+ }
719
+ }
720
+ }
721
+
722
+
723
+
724
+
725
+
726
+
727
+
728
+
729
+ function getAdMobConfig() {
730
+ if (!fileExists(configPath)) {
731
+ throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
732
+ }
733
+
734
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
735
+ const admobConfig = config.plugins?.AdMob;
736
+
737
+ if (!admobConfig) {
738
+ throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
739
+ }
740
+
741
+ // Default to true if ADMOB_ENABLED is not specified
742
+ const isEnabled = admobConfig.ADMOB_ENABLED !== false;
743
+
744
+ if (!isEnabled) {
745
+ return { ADMOB_ENABLED: false }; // Skip further validation
746
+ }
747
+
748
+ if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
749
+ throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
750
+ }
751
+
752
+ return {
753
+ ADMOB_ENABLED: true,
754
+ APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
755
+ APP_ID_IOS: admobConfig.APP_ID_IOS,
756
+ USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
757
+ };
758
+ }
759
+
760
+ function validateAndroidBuildOptions() {
761
+
762
+
763
+ if (!fileExists(configPath)) {
764
+ console.log('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
765
+ process.exit(1);
766
+ }
767
+
768
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
769
+
770
+ const targetAppId=config.appId
771
+
772
+ const buildOptions = config.android?.buildOptions;
773
+
774
+ if (!buildOptions) {
775
+ console.log('❌ Missing android.buildOptions in capacitor.config.json.');
776
+ process.exit(1);
777
+ }
778
+
779
+ const requiredProps = [
780
+ 'keystorePath',
781
+ 'keystorePassword',
782
+ 'keystoreAlias',
783
+ 'keystoreAliasPassword',
784
+ 'releaseType',
785
+ 'signingType'
786
+ ];
787
+
788
+ const missing = requiredProps.filter(prop => !buildOptions[prop]);
789
+
790
+ if (missing.length > 0) {
791
+ console.log('❌ Missing properties android.buildOptions in capacitor.config.json.');
792
+ process.exit(1);
793
+ }
794
+
795
+
796
+ const keystorePath=buildOptions.keystorePath
797
+ const keyFileName = path.basename(keystorePath);
798
+
799
+
800
+
801
+ const keystoreMap = {
802
+ "gameskey.jks": [
803
+ "com.cube.blaster",
804
+ ],
805
+ "htmleditorkeystoke.jks": [
806
+ "com.HTML.AngularJS.Codeplay",
807
+ "com.html.codeplay.pro",
808
+ "com.bootstrap.code.play",
809
+ "com.kids.learning.master",
810
+ "com.Simple.Barcode.Scanner"
811
+ ]
812
+ };
813
+
814
+ // find which keystore is required for the given targetAppId
815
+ let requiredKey = "newappskey.jks"; // default
816
+ for (const [keyFile, appIds] of Object.entries(keystoreMap)) {
817
+ if (appIds.includes(targetAppId)) {
818
+ requiredKey = keyFile;
819
+ break;
820
+ }
821
+ }
822
+
823
+ // validate
824
+ if (keyFileName !== requiredKey) {
825
+ console.log(`❌ The keystore path is mismatched. Expected ${requiredKey} for ${targetAppId}, but got ${keyFileName}`);
826
+ process.exit(1);
827
+ }
828
+
829
+
830
+
831
+
832
+
833
+ // optionally return them
834
+ //return buildOptions;
835
+ }
836
+
837
+ function updatePluginXml(admobConfig) {
838
+ if (!fileExists(pluginPath)) {
839
+ console.error(' ❌ plugin.xml not found. Ensure the plugin is installed.');
840
+ return;
841
+ }
842
+
843
+ let pluginContent = fs.readFileSync(pluginPath, 'utf8');
844
+
845
+ pluginContent = pluginContent
846
+ .replace(/<preference name="APP_ID_ANDROID" default=".*?" \/>/, `<preference name="APP_ID_ANDROID" default="${admobConfig.APP_ID_ANDROID}" />`)
847
+ .replace(/<preference name="APP_ID_IOS" default=".*?" \/>/, `<preference name="APP_ID_IOS" default="${admobConfig.APP_ID_IOS}" />`);
848
+
849
+ fs.writeFileSync(pluginPath, pluginContent, 'utf8');
850
+ console.log('✅ AdMob IDs successfully updated in plugin.xml');
851
+ }
852
+
853
+ function updateInfoPlist(admobConfig) {
854
+ if (!fileExists(infoPlistPath)) {
855
+ console.error(' ❌ Info.plist not found. Ensure you have built the iOS project.');
856
+ return;
857
+ }
858
+
859
+ const plistContent = fs.readFileSync(infoPlistPath, 'utf8');
860
+ const plistData = plist.parse(plistContent);
861
+
862
+ plistData.GADApplicationIdentifier = admobConfig.APP_ID_IOS;
863
+ plistData.NSUserTrackingUsageDescription = 'This identifier will be used to deliver personalized ads to you.';
864
+ plistData.GADDelayAppMeasurementInit = true;
865
+
866
+ const updatedPlistContent = plist.build(plistData);
867
+ fs.writeFileSync(infoPlistPath, updatedPlistContent, 'utf8');
868
+ console.log('AdMob IDs and additional configurations successfully updated in Info.plist');
869
+ }
870
+
871
+
872
+ try {
873
+ if (!fileExists(configPath)) {
874
+ throw new Error(' ❌ capacitor.config.json not found. Skipping setup.');
875
+ }
876
+
877
+ if (!fileExists(androidPlatformPath) && !fileExists(iosPlatformPath)) {
878
+ throw new Error('Neither Android nor iOS platforms are found. Ensure platforms are added to your Capacitor project.');
879
+ }
880
+
881
+ checkAndCopyResources();
882
+
883
+
884
+
885
+ _admobConfig = getAdMobConfig();
886
+
887
+
888
+
889
+
890
+
891
+ // Proceed only if ADMOB_ENABLED is true
892
+ if (_admobConfig.ADMOB_ENABLED) {
893
+ if (fileExists(androidPlatformPath)) {
894
+ updatePluginXml(_admobConfig);
895
+ }
896
+
897
+ if (fileExists(iosPlatformPath)) {
898
+ updateInfoPlist(_admobConfig);
899
+ }
900
+ }
901
+
902
+
903
+ } catch (error) {
904
+ console.error(error.message);
905
+ process.exit(1); // Stop execution if there's a critical error
906
+ }
907
+
908
+
909
+
910
+ validateAndroidBuildOptions();
911
+
912
+
913
+
914
+
915
+
916
+
917
+ // Check all the codeplays plugins version START
918
+
919
+
920
+ const readline = require('readline');
921
+
922
+
923
+ //const srcDir = path.join(__dirname, 'src');
924
+ const srcDir = path.join(process.cwd(), 'src');
925
+ let outdatedPlugins = [];
926
+
927
+ function parseVersion(ver) {
928
+ return ver.split('.').map(n => parseInt(n, 10));
929
+ }
930
+
931
+ function compareVersions(v1, v2) {
932
+ const [a1, b1] = parseVersion(v1);
933
+ const [a2, b2] = parseVersion(v2);
934
+ if (a1 !== a2) return a1 - a2;
935
+ return b1 - b2;
936
+ }
937
+
938
+ function walkSync(dir, filelist = []) {
939
+ fs.readdirSync(dir).forEach(file => {
940
+ const fullPath = path.join(dir, file);
941
+ const stat = fs.statSync(fullPath);
942
+ if (stat.isDirectory()) {
943
+ walkSync(fullPath, filelist);
944
+ } else {
945
+ filelist.push(fullPath);
946
+ }
947
+ });
948
+ return filelist;
949
+ }
950
+
951
+
952
+
953
+ function getSearchRoot(plugin) {
954
+ return path.join(srcDir, plugin.baseDir || 'js');
955
+ }
956
+
957
+
958
+
959
+
960
+
961
+
962
+
963
+
964
+
965
+
966
+
967
+
968
+
969
+
970
+
971
+
972
+
973
+
974
+
975
+
976
+ /*############################################## AUTO DOWNLOAD FROM SERVER START #####################################*/
977
+
978
+ // ============================================================
979
+ // 🔥 AUTO PLUGIN UPDATE SYSTEM (MANDATORY UPDATES)
980
+ // ============================================================
981
+
982
+ const https = require("https");
983
+
984
+ /**
985
+ * Check if file exists on server using HEAD request
986
+ */
987
+ function urlExists(url) {
988
+ return new Promise(resolve => {
989
+ const req = https.request(url, { method: "HEAD" }, res => {
990
+ resolve(res.statusCode === 200);
991
+ });
992
+
993
+ req.on("error", () => resolve(false));
994
+ req.end();
995
+ });
996
+ }
997
+
998
+ /**
999
+ * Download file from server
1000
+ */
1001
+ function downloadFile(url, dest) {
1002
+ return new Promise((resolve, reject) => {
1003
+ const file = fs.createWriteStream(dest);
1004
+
1005
+ https.get(url, response => {
1006
+ if (response.statusCode !== 200) {
1007
+ reject("Download failed");
1008
+ return;
1009
+ }
1010
+
1011
+ response.pipe(file);
1012
+
1013
+ file.on("finish", () => {
1014
+ file.close(resolve);
1015
+ });
1016
+ }).on("error", err => {
1017
+ fs.unlink(dest, () => {});
1018
+ reject(err);
1019
+ });
1020
+ });
1021
+ }
1022
+
1023
+ /**
1024
+ * Update imports across src folder
1025
+ * Replaces old filename → new filename
1026
+ */
1027
+ /**
1028
+ * Update imports across project
1029
+ * Replaces old filename → new filename
1030
+ */
1031
+
1032
+ const VITE_ALIAS_ONLY = [
1033
+ "common",
1034
+ "admob-emi",
1035
+ "localization",
1036
+ "theme",
1037
+ "certificatejs",
1038
+ "ffmpeg"
1039
+ ];
1040
+ function updateImports(oldName, newName) {
1041
+
1042
+ const projectRoot = process.cwd();
1043
+
1044
+ const viteFiles = [
1045
+ path.join(projectRoot, "vite.config.js"),
1046
+ path.join(projectRoot, "vite.config.mjs")
1047
+ ];
1048
+
1049
+ // Detect if alias-only plugin
1050
+ const isAliasOnly = VITE_ALIAS_ONLY.some(p =>
1051
+ oldName.includes(p)
1052
+ );
1053
+
1054
+ //--------------------------------------------------
1055
+ // 1️⃣ ALWAYS update vite config
1056
+ //--------------------------------------------------
1057
+ viteFiles.forEach(file => {
1058
+ if (!fs.existsSync(file)) return;
1059
+
1060
+ let content = fs.readFileSync(file, "utf8");
1061
+
1062
+ if (content.includes(oldName)) {
1063
+ content = content.replaceAll(oldName, newName);
1064
+ fs.writeFileSync(file, content);
1065
+
1066
+ console.log(`✏️ Updated alias in ${path.basename(file)}`);
1067
+ }
1068
+ });
1069
+
1070
+ //--------------------------------------------------
1071
+ // 2️⃣ If alias-only → STOP here
1072
+ //--------------------------------------------------
1073
+ if (isAliasOnly) {
1074
+ console.log(`⚡ Alias-only plugin → skipped full scan`);
1075
+ return;
1076
+ }
1077
+
1078
+ //--------------------------------------------------
1079
+ // 3️⃣ Otherwise scan src
1080
+ //--------------------------------------------------
1081
+ const srcDir = path.join(projectRoot, "src");
1082
+
1083
+ function walk(dir) {
1084
+ fs.readdirSync(dir).forEach(file => {
1085
+
1086
+ if (["node_modules","android","ios","dist",".git"].includes(file))
1087
+ return;
1088
+
1089
+ const full = path.join(dir, file);
1090
+ const stat = fs.statSync(full);
1091
+
1092
+ if (stat.isDirectory()) {
1093
+ walk(full);
1094
+ }
1095
+ else if (
1096
+ (full.endsWith(".js") ||
1097
+ full.endsWith(".f7") ||
1098
+ full.endsWith(".mjs")) &&
1099
+ !full.endsWith(".min.js")
1100
+ ) {
1101
+ let content = fs.readFileSync(full, "utf8");
1102
+
1103
+ if (content.includes(oldName)) {
1104
+ content = content.replaceAll(oldName, newName);
1105
+ fs.writeFileSync(full, content);
1106
+
1107
+ console.log(`✏️ Updated import in ${path.relative(projectRoot, full)}`);
1108
+ }
1109
+ }
1110
+ });
1111
+ }
1112
+
1113
+ if (fs.existsSync(srcDir)) {
1114
+ walk(srcDir);
1115
+ }
1116
+ }
1117
+
1118
+
1119
+
1120
+ /**
1121
+ * Auto-update a plugin file
1122
+ * Returns TRUE if success
1123
+ * Returns FALSE if fallback to manual needed
1124
+ */
1125
+
1126
+
1127
+
1128
+ function fetchVersions() {
1129
+ return new Promise((resolve, reject) => {
1130
+ https.get(
1131
+ "https://htmlcodeplay.com/code-play-plugin/versions.json",
1132
+ res => {
1133
+ let data = "";
1134
+
1135
+ res.on("data", chunk => data += chunk);
1136
+ res.on("end", () => {
1137
+ try {
1138
+ resolve(JSON.parse(data));
1139
+ } catch {
1140
+ resolve(null);
1141
+ }
1142
+ });
1143
+ }
1144
+ ).on("error", () => resolve(null));
1145
+ });
1146
+ }
1147
+
1148
+
1149
+
1150
+ async function autoUpdatePlugin(pluginDef, pluginInfo) {
1151
+
1152
+ if (pluginDef.isFolder) return false;
1153
+
1154
+ const versions = await fetchVersions();
1155
+
1156
+ if (!versions) {
1157
+ console.log("⚠️ versions.json not reachable");
1158
+ return false;
1159
+ }
1160
+
1161
+ const oldFullPath = path.join(srcDir, pluginInfo.name);
1162
+ const oldFileName = path.basename(oldFullPath);
1163
+
1164
+ // Extract base name
1165
+ const baseName = oldFileName.replace(/-\d+\.\d+.*$/, "");
1166
+
1167
+ const latestVersion = versions[baseName];
1168
+
1169
+ if (!latestVersion) {
1170
+ console.log(`❌ No version entry for ${baseName}`);
1171
+ return false;
1172
+ }
1173
+
1174
+ const newFileName = `${baseName}-${latestVersion}.js`;
1175
+
1176
+ const url =
1177
+ `https://htmlcodeplay.com/code-play-plugin/${newFileName}`;
1178
+
1179
+ console.log(`🔍 Checking latest: ${newFileName}`);
1180
+
1181
+ if (!(await urlExists(url))) {
1182
+ console.log(`❌ File missing on server`);
1183
+ return false;
1184
+ }
1185
+
1186
+ const destPath =
1187
+ path.join(path.dirname(oldFullPath), newFileName);
1188
+
1189
+ await downloadFile(url, destPath);
1190
+
1191
+ fs.unlinkSync(oldFullPath);
1192
+
1193
+ updateImports(oldFileName, newFileName);
1194
+
1195
+ console.log(`✅ Updated → ${newFileName}`);
1196
+
1197
+ return true;
1198
+ }
1199
+
1200
+
1201
+
1202
+
1203
+ /*############################################## AUTO DOWNLOAD FROM SERVER END #####################################*/
1204
+
1205
+
1206
+
1207
+
1208
+
1209
+
1210
+
1211
+
1212
+
1213
+
1214
+
1215
+
1216
+
1217
+
1218
+
1219
+
1220
+
1221
+
1222
+
1223
+
1224
+
1225
+
1226
+ let hasMandatoryUpdate = false;
1227
+ function checkPlugins() {
1228
+ return new Promise(async (resolve, reject) => {
1229
+ const files = walkSync(srcDir);
1230
+ const outdatedPlugins = [];
1231
+ let hasMandatoryUpdate = false;
1232
+
1233
+ for (const plugin of requiredPlugins) {
1234
+ const searchRoot = getSearchRoot(plugin);
1235
+
1236
+ // ---------- Folder plugins ----------
1237
+ if (plugin.isFolder) {
1238
+ if (!fs.existsSync(searchRoot)) continue;
1239
+
1240
+ const subDirs = fs.readdirSync(searchRoot)
1241
+ .map(name => path.join(searchRoot, name))
1242
+ .filter(p => fs.statSync(p).isDirectory());
1243
+
1244
+ for (const dir of subDirs) {
1245
+ const relativePath = path.relative(searchRoot, dir).replace(/\\/g, '/');
1246
+ const match = plugin.pattern.exec(relativePath);
1247
+
1248
+ if (match) {
1249
+ const currentVersion = match[1];
1250
+
1251
+ if (compareVersions(currentVersion, plugin.minVersion) < 0) {
1252
+ outdatedPlugins.push({
1253
+ name: relativePath,
1254
+ currentVersion,
1255
+ requiredVersion: plugin.minVersion,
1256
+ mandatoryUpdate: plugin.mandatoryUpdate === true
1257
+ });
1258
+
1259
+ if (plugin.mandatoryUpdate) {
1260
+ hasMandatoryUpdate = true;
1261
+ }
1262
+ }
1263
+ }
1264
+ }
1265
+ continue;
1266
+ }
1267
+
1268
+ // ---------- File plugins ----------
1269
+ const matchedFile = files.find(file =>
1270
+ file.startsWith(searchRoot) && plugin.pattern.test(file)
1271
+ );
1272
+
1273
+ if (matchedFile) {
1274
+ const match = plugin.pattern.exec(matchedFile);
1275
+ if (match) {
1276
+ const currentVersion = match[1];
1277
+ const isBeta = !!match[2];
1278
+
1279
+ const cmp = plugin.pattern.source.includes('beta')
1280
+ ? compareWithBeta(currentVersion, plugin.minVersion, isBeta)
1281
+ : compareVersions(currentVersion, plugin.minVersion);
1282
+
1283
+ if (cmp < 0) {
1284
+ outdatedPlugins.push({
1285
+ name: path.relative(srcDir, matchedFile),
1286
+ currentVersion: isBeta ? `${currentVersion}-beta` : currentVersion,
1287
+ requiredVersion: plugin.minVersion,
1288
+ mandatoryUpdate: plugin.mandatoryUpdate === true
1289
+ });
1290
+
1291
+ if (plugin.mandatoryUpdate) {
1292
+ hasMandatoryUpdate = true;
1293
+ }
1294
+ }
1295
+ }
1296
+ }
1297
+ }
1298
+
1299
+ // ---------- Result handling ----------
1300
+ if (outdatedPlugins.length > 0) {
1301
+ console.log('\n❗ The following plugins are outdated:\n');
1302
+
1303
+ outdatedPlugins.forEach( p => {
1304
+ const tag = p.mandatoryUpdate ? '🔥 MANDATORY' : '';
1305
+ console.log(
1306
+ ` ❌ - ${p.name} (Current: ${p.currentVersion}, Required: ${p.requiredVersion}) ${tag}`
1307
+ );
1308
+ });
1309
+
1310
+ // 🚨 Mandatory update → stop build
1311
+ /* if (hasMandatoryUpdate) {
1312
+ console.log('\n🚫 One or more plugins require a mandatory update.');
1313
+ console.log('❌ Build cancelled. Please update mandatory plugins and try again.');
1314
+ process.exit(1);
1315
+ } */
1316
+
1317
+
1318
+
1319
+
1320
+
1321
+ if (hasMandatoryUpdate) {
1322
+
1323
+ //--------------------------------------------------
1324
+ // 🚫 AUTO UPDATE DISABLED
1325
+ //--------------------------------------------------
1326
+ if (!ENABLE_AUTO_UPDATE) {
1327
+ console.log("\n🚫 Auto-update disabled.");
1328
+ console.log("❌ Manual update required.");
1329
+ process.exit(1);
1330
+ }
1331
+
1332
+ //--------------------------------------------------
1333
+ // 🔥 AUTO UPDATE ENABLED
1334
+ //--------------------------------------------------
1335
+ console.log("\n🔥 Mandatory plugins outdated. Trying auto-update...\n");
1336
+
1337
+
1338
+
1339
+ let autoFailed = false;
1340
+
1341
+ for (const p of outdatedPlugins.filter(x => x.mandatoryUpdate)) {
1342
+
1343
+ const pluginDef = requiredPlugins.find(def =>
1344
+ def.pattern.test(p.name)
1345
+ );
1346
+
1347
+ if (!pluginDef) continue;
1348
+
1349
+ const success = await autoUpdatePlugin(
1350
+ pluginDef,
1351
+ p
1352
+ );
1353
+
1354
+ if (!success) {
1355
+ autoFailed = true;
1356
+ console.log(`❌ Manual update required for ${p.name}`);
1357
+ }
1358
+ }
1359
+
1360
+ // 🚨 Fallback to manual if any failed
1361
+ if (autoFailed) {
1362
+ console.log('\n🚫 One or more plugins require manual update.');
1363
+ console.log('❌ Build cancelled. Please update mandatory plugins.');
1364
+ process.exit(1);
1365
+ }
1366
+
1367
+ console.log('\n🎉 All mandatory plugins auto-updated!');
1368
+ }
1369
+
1370
+
1371
+
1372
+
1373
+
1374
+
1375
+ // Optional updates → ask user
1376
+ const rl = readline.createInterface({
1377
+ input: process.stdin,
1378
+ output: process.stdout
1379
+ });
1380
+
1381
+ rl.question(
1382
+ '\nAre you sure you want to continue without updating these plugins? (y/n): ',
1383
+ answer => {
1384
+ rl.close();
1385
+
1386
+ if (answer.toLowerCase() !== 'y') {
1387
+ console.log('\n❌ Build cancelled due to outdated plugins.');
1388
+ process.exit(1);
1389
+ } else {
1390
+ console.log('\n✅ Continuing build...');
1391
+ resolve();
1392
+ }
1393
+ }
1394
+ );
1395
+ } else {
1396
+ console.log('✅ All plugin versions are up to date.');
1397
+ resolve();
1398
+ }
1399
+ });
1400
+ }
1401
+
1402
+
1403
+
1404
+
1405
+
1406
+
1407
+
1408
+
1409
+ // Check all the codeplays plugins version START
1410
+
1411
+
1412
+
1413
+
1414
+ // ====================================================================
1415
+ // AUTO-ADD esbuild.drop: ['console','debugger'] to vite.config.js / mjs
1416
+ // ====================================================================
1417
+
1418
+
1419
+
1420
+ const checkAndupdateDropInViteConfig = () => {
1421
+
1422
+ const possibleFiles = [
1423
+ "vite.config.js",
1424
+ "vite.config.mjs"
1425
+ ];
1426
+
1427
+ // Detect existing config file
1428
+ const viteConfigPath = possibleFiles
1429
+ .map(file => path.join(process.cwd(), file))
1430
+ .find(filePath => fs.existsSync(filePath));
1431
+
1432
+ if (!viteConfigPath) {
1433
+ console.warn("⚠️ No vite config found. Skipping.");
1434
+ return;
1435
+ }
1436
+
1437
+ //console.log("📄 Using:", viteConfigPath.split("/").pop());
1438
+
1439
+ let viteContent = fs.readFileSync(viteConfigPath, "utf8");
1440
+
1441
+ // Skip if already exists
1442
+ if (/drop\s*:\s*\[.*['"]console['"].*\]/.test(viteContent)) {
1443
+ console.log("ℹ️ vite.config.(m)js already Updated. Skipping...");
1444
+ return;
1445
+ }
1446
+
1447
+ console.log("🔧 Adding esbuild.drop ...");
1448
+
1449
+ // If esbuild block exists
1450
+ if (/esbuild\s*:\s*{/.test(viteContent)) {
1451
+ viteContent = viteContent.replace(
1452
+ /esbuild\s*:\s*{([\s\S]*?)(^ {0,8})}/m,
1453
+ (full, inner, indent) => {
1454
+
1455
+ let lines = inner
1456
+ .split("\n")
1457
+ .map(l => l.trim())
1458
+ .filter(Boolean);
1459
+
1460
+ // Fix last comma
1461
+ if (lines.length > 0) {
1462
+ lines[lines.length - 1] =
1463
+ lines[lines.length - 1].replace(/,+$/, "") + ",";
1464
+ }
1465
+
1466
+ // Re-indent
1467
+ lines = lines.map(l => indent + " " + l);
1468
+
1469
+ // Add drop
1470
+ lines.push(`${indent} drop: ['console','debugger'],`);
1471
+
1472
+ return `esbuild: {\n${lines.join("\n")}\n${indent}}`;
1473
+ }
1474
+ );
1475
+ }
1476
+
1477
+ // If esbuild missing
1478
+ else {
1479
+ viteContent = viteContent.replace(
1480
+ /export default defineConfig\s*\(\s*{/,
1481
+ m => `${m}\n esbuild: {\n drop: ['console','debugger'],\n },`
1482
+ );
1483
+ }
1484
+
1485
+ fs.writeFileSync(viteConfigPath, viteContent, "utf8");
1486
+ console.log("✅ vite.config.(m)js Updated successfully.");
1487
+ };
1488
+
1489
+
1490
+
1491
+
1492
+
1493
+
1494
+
1495
+
1496
+
1497
+
1498
+ const compareVersion = (v1, v2) => {
1499
+ const a = v1.split(".").map(Number);
1500
+ const b = v2.split(".").map(Number);
1501
+
1502
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
1503
+ const num1 = a[i] || 0;
1504
+ const num2 = b[i] || 0;
1505
+ if (num1 > num2) return 1;
1506
+ if (num1 < num2) return -1;
1507
+ }
1508
+ return 0;
1509
+ };
1510
+
1511
+
1512
+
1513
+
1514
+ const admobConfigPath = path.join('src', 'js','Ads', 'admob-ad-configuration.json');
1515
+
1516
+ const checkAdmobConfigurationProperty=()=>{
1517
+
1518
+
1519
+ if (!_admobConfig.ADMOB_ENABLED)
1520
+ {
1521
+ console.log("ℹ️ Admob is not enabled so 'admob-ad-configuration.json' checking is skipping...");
1522
+ return;
1523
+ }
1524
+
1525
+
1526
+ const REQUIRED_CONFIG_KEYS = [
1527
+ "isKidsApp",
1528
+ "isTesting",
1529
+ "isConsoleLogEnabled",
1530
+ "bannerEnabled",
1531
+ "interstitialEnabled",
1532
+ "appOpenEnabled",
1533
+ "rewardVideoEnabled",
1534
+ "rewardInterstitialEnabled",
1535
+ "collapsibleEnabled",
1536
+ "isLandScape",
1537
+ "isOverlappingEnable",
1538
+ "bannerTypeAndroid",
1539
+ "bannerTypeiOS",
1540
+ "bannerTopSpaceColor",
1541
+ "interstitialLoadScreenTextColor",
1542
+ "interstitialLoadScreenBackgroundColor",
1543
+ "beforeBannerSpace",
1544
+ "whenShow",
1545
+ "minimumClick",
1546
+ "interstitialTimeOut",
1547
+ "interstitialFirstTimeOut",
1548
+ "appOpenAdsTimeOut",
1549
+ "maxRetryCount",
1550
+ "retrySecondsAr",
1551
+ "appOpenPerSession",
1552
+ "interstitialPerSession",
1553
+ "appOpenFirstTimeOut"
1554
+ ];
1555
+
1556
+
1557
+
1558
+
1559
+
1560
+ let admobConfigInJson;
1561
+
1562
+ try {
1563
+ admobConfigInJson = JSON.parse(readFileSync(admobConfigPath, "utf8"));
1564
+ } catch (err) {
1565
+ console.error("❌ Failed to read admob-ad-configuration.json", err);
1566
+ process.exit(1);
1567
+ }
1568
+
1569
+ // ✅ Validate config object exists
1570
+ if (!admobConfigInJson.config) {
1571
+ console.error('❌ "config" object is missing in admob-ad-configuration.json');
1572
+ process.exit(1);
1573
+ }
1574
+
1575
+
1576
+ const admobConfigMinVersion="1.5"
1577
+
1578
+ if (compareVersion(admobConfigInJson.VERSION, admobConfigMinVersion) < 0) {
1579
+ console.error(`❌ Please use at-least version ${admobConfigMinVersion} in "src/js/Ads/admob-ad-configuration.json"`);
1580
+ process.exit(1);
1581
+ }
1582
+
1583
+
1584
+ const config = admobConfigInJson.config;
1585
+
1586
+ // ✅ Find missing properties
1587
+ const missingKeys = REQUIRED_CONFIG_KEYS.filter(
1588
+ key => !(key in config)
1589
+ );
1590
+
1591
+
1592
+
1593
+ if (missingKeys.length > 0) {
1594
+ console.error("❌ Missing required configuration keys. Please check it in 'src/js/Ads/admob-ad-configuration.json'");
1595
+
1596
+ missingKeys.forEach(k => console.error(" - " + k));
1597
+ process.exit(1);
1598
+ }
1599
+
1600
+
1601
+ console.log('✅ All keys exist. in "admob-ad-configuration.json file" Configuration looks good.');
1602
+ }
1603
+
1604
+
1605
+
1606
+ function ensureGitignoreEntry(entry) {
1607
+ const gitignorePath = path.join(process.cwd(), '.gitignore');
1608
+
1609
+ // If .gitignore doesn't exist, create it
1610
+ if (!fs.existsSync(gitignorePath)) {
1611
+ fs.writeFileSync(gitignorePath, `${entry}\n`, 'utf8');
1612
+ console.log(`✅ .gitignore created and added: ${entry}`);
1613
+ return;
1614
+ }
1615
+
1616
+ const content = fs.readFileSync(gitignorePath, 'utf8');
1617
+
1618
+ // Normalize lines (trim + remove trailing slashes for comparison)
1619
+ const lines = content
1620
+ .split(/\r?\n/)
1621
+ .map(l => l.trim());
1622
+
1623
+ const normalizedEntry = entry.replace(/\/$/, '');
1624
+
1625
+ const exists = lines.some(
1626
+ line => line.replace(/\/$/, '') === normalizedEntry
1627
+ );
1628
+
1629
+ if (exists) {
1630
+ console.log(`ℹ️ .gitignore already contains: ${entry}`);
1631
+ return;
1632
+ }
1633
+
1634
+ // Ensure file ends with newline
1635
+ const separator = content.endsWith('\n') ? '' : '\n';
1636
+
1637
+ fs.appendFileSync(gitignorePath, `${separator}${entry}\n`, 'utf8');
1638
+ console.log(`✅ Added to .gitignore: ${entry}`);
1639
+ }
1640
+
1641
+
1642
+ ensureGitignoreEntry('buildCodeplay/');
1643
+
1644
+
1645
+ // Run the validation
1646
+ (async () => {
1647
+ await checkPlugins();
1648
+ checkAndupdateDropInViteConfig();
1649
+ checkAdmobConfigurationProperty()
1650
+ })();
1651
+
1652
+
1653
+ // ======================================================
1654
+ // Validate theme folder location (src/js/theme is NOT allowed)
1655
+ // ======================================================
1656
+
1657
+ function validateThemeFolderLocation() {
1658
+ const oldThemePath = path.join(process.cwd(), 'src', 'js', 'theme');
1659
+ const newThemePath = path.join(process.cwd(), 'src', 'theme');
1660
+
1661
+ // ❌ Block old structure
1662
+ if (fs.existsSync(oldThemePath)) {
1663
+ console.error(
1664
+ '\n❌ INVALID PROJECT STRUCTURE DETECTED\n' +
1665
+ '--------------------------------------------------\n' +
1666
+ 'The "theme" folder must NOT be inside:\n' +
1667
+ ' src/js/theme\n\n' +
1668
+ '✅ Correct location is:\n' +
1669
+ ' src/theme\n\n' +
1670
+ '🛑 Please move the folder and re-run the build.\n'
1671
+ );
1672
+ process.exit(1);
1673
+ }
1674
+
1675
+ // ⚠️ Optional warning if new theme folder is missing
1676
+ if (!fs.existsSync(newThemePath)) {
1677
+ console.warn(
1678
+ '\n⚠️ WARNING: "src/theme" folder not found.\n' +
1679
+ 'If your app uses themes, please ensure it exists.\n'
1680
+ );
1681
+ } else {
1682
+ console.log('✅ Theme folder structure validated (src/theme).');
1683
+ }
1684
+ }
1685
+ validateThemeFolderLocation()
1686
+
1687
+
1688
+
1689
+ const validateAndRestoreSignDetails=()=>{
1690
+
1691
+ // Read config file
1692
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
1693
+
1694
+ // Ensure android and buildOptions exist
1695
+ if (!config.android) config.android = {};
1696
+ if (!config.android.buildOptions) config.android.buildOptions = {};
1697
+
1698
+ // Update only if changed
1699
+ let updated = false;
1700
+
1701
+ if (config.android.buildOptions.releaseType !== 'AAB') {
1702
+ config.android.buildOptions.releaseType = 'AAB';
1703
+ updated = true;
1704
+ }
1705
+
1706
+ if (config.android.buildOptions.signingType !== 'jarsigner') {
1707
+ config.android.buildOptions.signingType = 'jarsigner';
1708
+ updated = true;
1709
+ }
1710
+
1711
+ // Write back only if modified
1712
+ if (updated) {
1713
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
1714
+ console.log('capacitor.config.json updated successfully.');
1715
+ } else {
1716
+ console.log('No changes needed.');
1717
+ }
1718
+
1719
+ }
1720
+
1721
+ validateAndRestoreSignDetails()
1722
+
1723
+
1724
+ /*
1725
+ Release Notes
1726
+
1727
+ 5.1
1728
+ Kotlin version update is commented. Previously admob is not worked if not update the kotlin version to higher version
1729
+
1403
1730
  */