codeplay-common 2.1.5 → 2.1.7

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,1182 +1,1182 @@
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
- { pattern: /backbutton-(\d+\.\d+)\.js$/, minVersion: '1.6', required: true },
14
- { pattern: /common-(\d+\.\d+)\.js$/, minVersion: '4.9', required: true },
15
- { pattern: /localization_settings-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true },
16
- { pattern: /localization-(\d+\.\d+)\.js$/, minVersion: '1.3', required: true },
17
- { pattern: /localNotification-(\d+\.\d+)\.js$/, minVersion: '2.2', required: true },
18
- { pattern: /localNotification_AppSettings-(\d+\.\d+)\.js$/, minVersion: '1.0', required: true },
19
- { pattern: /onesignal-(\d+\.\d+)\.js$/, minVersion: '2.2', required: true },
20
- { pattern: /saveToGalleryAndSaveAnyFile-(\d+\.\d+)(-ios)?\.js$/, minVersion: '2.9', required: true },
21
- { pattern: /Ads[\/\\]IAP-(\d+\.\d+)$/, minVersion: '2.5', isFolder: true , required: true },
22
- { pattern: /Ads[\/\\]admob-emi-(\d+\.\d+)\.js$/, minVersion: '3.2', required: true },
23
-
24
- // New added plugins
25
- { pattern: /video-player-(\d+\.\d+)\.js$/, minVersion: '1.5', required: true },
26
- { pattern: /image-cropper-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true },
27
-
28
- // New folders
29
- { pattern: /editor-(\d+\.\d+)$/, minVersion: '1.8', isFolder: true, required: true },
30
- { pattern: /ffmpeg-(\d+\.\d+)$/, minVersion: '1.3', isFolder: true, required: true }
31
- ];
32
-
33
-
34
-
35
-
36
-
37
-
38
- //Check codeplay-common latest version installed or not Start
39
- const { execSync } = require('child_process');
40
-
41
- function getInstalledVersion(packageName) {
42
- try {
43
- const packageJsonPath = path.join(process.cwd(), 'node_modules', packageName, 'package.json');
44
- if (fs.existsSync(packageJsonPath)) {
45
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
46
- return packageJson.version;
47
- }
48
- } catch (error) {
49
- return null;
50
- }
51
- return null;
52
- }
53
-
54
- function getLatestVersion(packageName) {
55
- try {
56
- return execSync(`npm view ${packageName} version`).toString().trim();
57
- } catch (error) {
58
- console.error(`Failed to fetch latest version for ${packageName}`);
59
- return null;
60
- }
61
- }
62
-
63
- function checkPackageVersion() {
64
- const packageName = 'codeplay-common';
65
- const installedVersion = getInstalledVersion(packageName);
66
- const latestVersion = getLatestVersion(packageName);
67
-
68
- if (!installedVersion) {
69
- console.error(`${packageName} is not installed. Please install it using "npm install ${packageName}".`);
70
- process.exit(1);
71
- }
72
-
73
- if (installedVersion !== latestVersion) {
74
- 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`);
75
- process.exit(1);
76
- }
77
-
78
- console.log(`${packageName} is up to date (version ${installedVersion}).`);
79
- }
80
-
81
- // Run package version check before executing the main script
82
- try {
83
- checkPackageVersion();
84
- } catch (error) {
85
- console.error(error.message);
86
- process.exit(1);
87
- }
88
-
89
- //Check codeplay-common latest version installed or not END
90
-
91
-
92
-
93
-
94
-
95
-
96
- const checkAppUniqueId=()=>{
97
-
98
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
99
-
100
- const appUniqueId = config.android?.APP_UNIQUE_ID;
101
- const RESIZEABLE_ACTIVITY = config.android?.RESIZEABLE_ACTIVITY;
102
- const orientation = config.android?.ORIENTATION;
103
-
104
-
105
- let logErrorMessage="";
106
-
107
- // 1️⃣ Check if it’s missing
108
- if (RESIZEABLE_ACTIVITY === undefined) {
109
- logErrorMessage+='❌ Missing android.RESIZEABLE_ACTIVITY option in capacitor.config.json.\n';
110
- }
111
-
112
- // 2️⃣ Check if it’s not boolean (true/false only)
113
- else if (typeof RESIZEABLE_ACTIVITY !== 'boolean') {
114
- logErrorMessage+='❌ Invalid android.RESIZEABLE_ACTIVITY value. Please use only true or false (without quotes).\n';
115
- }
116
-
117
-
118
-
119
- if (!orientation) {
120
- logErrorMessage+='❌ Missing android.ORIENTATION option in capacitor.config.json.\n';
121
- }
122
-
123
- else if(orientation!="portrait" && orientation!="landscape" && orientation!="auto")
124
- {
125
- logErrorMessage+='❌ Spelling mistake in android.ORIENTATION option in capacitor.config.json. Please use only ["portrait" "landscape" "auto"]\n';
126
- }
127
-
128
-
129
- if (!appUniqueId) {
130
- logErrorMessage+='❌ APP_UNIQUE_ID is missing in capacitor.config.json.';
131
- }
132
-
133
- else if (!Number.isInteger(appUniqueId)) {
134
- logErrorMessage+='❌ APP_UNIQUE_ID must be an integer. Example: 1, 2, 3, etc.';
135
- }
136
-
137
-
138
-
139
- if(logErrorMessage!="")
140
- {
141
- console.error(logErrorMessage);
142
- process.exit(1)
143
- }
144
-
145
-
146
- console.log(`✅ APP_UNIQUE_ID is valid: ${appUniqueId}`);
147
-
148
- }
149
-
150
- checkAppUniqueId();
151
-
152
-
153
-
154
-
155
-
156
-
157
-
158
- //@Codemirror check and install/uninstall the packages START
159
- //const fs = require("fs");
160
- //const path = require("path");
161
- //const { execSync } = require("child_process");
162
-
163
- const baseDir = path.join(__dirname, "..", "src", "js");
164
-
165
- // Step 1: Find highest versioned folder like `editor-1.6`
166
- const editorDirs = fs.readdirSync(baseDir)
167
- .filter(name => /^editor-\d+\.\d+$/.test(name))
168
- .sort((a, b) => {
169
- const getVersion = str => str.match(/(\d+)\.(\d+)/).slice(1).map(Number);
170
- const [aMajor, aMinor] = getVersion(a);
171
- const [bMajor, bMinor] = getVersion(b);
172
- return bMajor - aMajor || bMinor - aMinor;
173
- });
174
-
175
- if (editorDirs.length === 0) {
176
-
177
- console.log("@Codemirror used editor(s) are not found")
178
- //console.error("❌ No editor-x.x folders found in src/js.");
179
- //process.exit(1);
180
- }
181
- else
182
- {
183
-
184
- const latestEditorDir = editorDirs.sort((a, b) => {
185
- const versionA = parseFloat(a.split('-')[1]);
186
- const versionB = parseFloat(b.split('-')[1]);
187
- return versionB - versionA;
188
- })[0];
189
-
190
- //const latestEditorDir = editorDirs[editorDirs.length - 1];
191
- const runJsPath = path.join(baseDir, latestEditorDir, "run.js");
192
-
193
- if (!fs.existsSync(runJsPath)) {
194
- console.error(`❌ run.js not found in ${latestEditorDir}`);
195
- process.exit(1);
196
- }
197
-
198
- // Step 2: Execute the run.js file
199
- console.log(`🚀 Executing ${runJsPath}...`);
200
- execSync(`node "${runJsPath}"`, { stdio: "inherit" });
201
- }
202
-
203
- //@Codemirror check and install/uninstall the packages END
204
-
205
-
206
-
207
-
208
-
209
-
210
-
211
-
212
-
213
-
214
-
215
-
216
- // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists START
217
-
218
- const os = require('os');
219
-
220
- const saveToGalleryAndSaveFileCheck_iOS = () => {
221
-
222
- // List of paths to scan
223
- const SCAN_PATHS = [
224
- path.resolve(__dirname, '../src/certificate'),
225
- path.resolve(__dirname, '../src/pages'),
226
- path.resolve(__dirname, '../src/js'),
227
- path.resolve(__dirname, '../src/app.f7')
228
- ];
229
-
230
- // Directory to exclude
231
- const EXCLUDED_DIR = path.resolve(__dirname, '../src/js/Ads');
232
-
233
- const ANDROID_MANIFEST_PATH = path.resolve(__dirname, '../android/app/src/main/AndroidManifest.xml');
234
-
235
-
236
- // Match iOS-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5-ios.js) not in comments
237
- const IOS_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*-ios\.js['"]/m;
238
-
239
- // Match Android-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5.js) not in comments
240
- const ANDROID_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*\.js['"]/m;
241
-
242
-
243
-
244
-
245
-
246
- const ALLOWED_EXTENSIONS = ['.js', '.f7'];
247
- const isMac = os.platform() === 'darwin';
248
-
249
- let iosImportFound = false;
250
- let androidImportFound = false;
251
-
252
- function scanDirectory(dir) {
253
-
254
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
255
- const appUniqueId = config.android?.APP_UNIQUE_ID;
256
- if(appUniqueId=="206")
257
- return;
258
-
259
- const stat = fs.statSync(dir);
260
-
261
- if (stat.isFile()) {
262
- // Only scan allowed file extensions
263
- if (ALLOWED_EXTENSIONS.some(ext => dir.endsWith(ext))) {
264
- process.stdout.write(`\r🔍 Scanning: ${dir} `);
265
-
266
- const content = fs.readFileSync(dir, 'utf8');
267
-
268
- if (IOS_FILE_REGEX.test(content)) {
269
- iosImportFound = true;
270
- if (!isMac) {
271
- console.error(`\n❌ ERROR: iOS-specific import detected in: ${dir}`);
272
- console.error(`🚫 STOPPED: This file should not be imported in Android/Windows/Linux builds.\n`);
273
- process.exit(1);
274
- }
275
- } else if (ANDROID_FILE_REGEX.test(content) && !content.includes('-ios.js')) {
276
- androidImportFound = true;
277
- }
278
- }
279
- }
280
- else if (stat.isDirectory()) {
281
- if (dir === EXCLUDED_DIR || path.basename(dir) === 'node_modules') return;
282
-
283
- const entries = fs.readdirSync(dir, { withFileTypes: true });
284
- for (let entry of entries) {
285
- scanDirectory(path.join(dir, entry.name));
286
- }
287
- }
288
- }
289
-
290
- // Run scan on all specified paths
291
- for (let scanPath of SCAN_PATHS) {
292
- if (fs.existsSync(scanPath)) {
293
- scanDirectory(scanPath);
294
- }
295
- }
296
-
297
-
298
-
299
- /* // Check src folder
300
- if (!fs.existsSync(ROOT_DIR)) {
301
- console.warn(`⚠️ Warning: 'src' directory not found at: ${ROOT_DIR}`);
302
- return;
303
- } */
304
-
305
- //scanDirectory(ROOT_DIR);
306
-
307
- // iOS Checks
308
- if (isMac && !iosImportFound) {
309
- console.warn(`⚠️ WARNING: You're on macOS but no iOS version (saveToGalleryAndSaveAnyFile-x.x-ios.js) found.`);
310
- process.exit(1);
311
- } else if (isMac && iosImportFound) {
312
- console.log('✅ iOS version detected for macOS build.');
313
- } else if (!iosImportFound) {
314
- console.log('✅ No iOS-specific imports detected for non-macOS.');
315
- }
316
-
317
- // Android Checks
318
- if (androidImportFound) {
319
- console.log("📱 Android version of saveToGalleryAndSaveAnyFile detected. Checking AndroidManifest.xml...");
320
-
321
- if (!fs.existsSync(ANDROID_MANIFEST_PATH)) {
322
- console.error("❌ AndroidManifest.xml not found. Cannot add requestLegacyExternalStorage attribute.");
323
- return;
324
- }
325
-
326
- let manifestContent = fs.readFileSync(ANDROID_MANIFEST_PATH, 'utf8');
327
-
328
- if (!manifestContent.includes('android:requestLegacyExternalStorage="true"')) {
329
- console.log("Adding android:requestLegacyExternalStorage=\"true\" to <application> tag...");
330
-
331
- manifestContent = manifestContent.replace(
332
- /<application([^>]*)>/,
333
- (match, attrs) => {
334
- if (attrs.includes('android:requestLegacyExternalStorage')) return match;
335
- return `<application${attrs} android:requestLegacyExternalStorage="true">`;
336
- }
337
- );
338
-
339
- fs.writeFileSync(ANDROID_MANIFEST_PATH, manifestContent, 'utf8');
340
- console.log("✅ android:requestLegacyExternalStorage=\"true\" added successfully.");
341
- } else {
342
- console.log("ℹ️ android:requestLegacyExternalStorage already exists in AndroidManifest.xml.");
343
- }
344
- } else {
345
- console.log("✅ No Android saveToGalleryAndSaveAnyFile imports detected.");
346
- }
347
- };
348
-
349
- saveToGalleryAndSaveFileCheck_iOS();
350
- // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists END
351
-
352
-
353
-
354
-
355
-
356
-
357
-
358
-
359
-
360
-
361
-
362
-
363
-
364
- /*
365
- // Clean up AppleDouble files (._*) created by macOS START
366
- if (process.platform === 'darwin') {
367
- try {
368
- console.log('🧹 Cleaning up AppleDouble files (._*)...');
369
- execSync(`find . -name '._*' -delete`);
370
- console.log('✅ AppleDouble files removed.');
371
- } catch (err) {
372
- console.warn('⚠️ Failed to remove AppleDouble files:', err.message);
373
- }
374
- } else {
375
- console.log('ℹ️ Skipping AppleDouble cleanup — not a macOS machine.');
376
- }
377
-
378
- // Clean up AppleDouble files (._*) created by macOS END
379
- */
380
-
381
-
382
-
383
-
384
-
385
-
386
- //In routes.js file check static import START
387
-
388
- const routesPath = path.join(process.cwd(), 'src', 'js', 'routes.js');
389
- const routesContent = fs.readFileSync(routesPath, 'utf-8');
390
-
391
- let inBlockComment = false;
392
- const lines = routesContent.split('\n');
393
-
394
- const allowedImport = `import HomePage from '../pages/home.f7';`;
395
- const badImportRegex = /^[ \t]*import\s+[\w{}*,\s]*\s+from\s+['"].+\.f7['"]\s*;/;
396
- const badImports = [];
397
-
398
- lines.forEach((line, index) => {
399
- const trimmed = line.trim();
400
-
401
- // Handle block comment start and end
402
- if (trimmed.startsWith('/*')) inBlockComment = true;
403
- if (inBlockComment && trimmed.endsWith('*/')) {
404
- inBlockComment = false;
405
- return;
406
- }
407
-
408
- // Skip if inside block comment or line comment
409
- if (inBlockComment || trimmed.startsWith('//')) return;
410
-
411
- // Match static .f7 import
412
- if (badImportRegex.test(trimmed) && trimmed !== allowedImport) {
413
- badImports.push({ line: trimmed, number: index + 1 });
414
- }
415
- });
416
-
417
- if (badImports.length > 0) {
418
- console.error('\n❌ ERROR: Detected disallowed static imports of .f7 files in routes.js\n');
419
- console.error(`⚠️ Only this static import is allowed:\n ${allowedImport}\n`);
420
- console.error(`🔧 Please convert other imports to async dynamic imports like this:\n`);
421
- console.error(`
422
-
423
- import HomePage from '../pages/home.f7';
424
-
425
- const routes = [
426
- {
427
- path: '/',
428
- component:HomePage,
429
- },
430
- {
431
- path: '/ProfilePage/',
432
- async async({ resolve }) {
433
- const page = await import('../pages/profile.f7');
434
- resolve({ component: page.default });
435
- },
436
- }]
437
- `);
438
-
439
- badImports.forEach(({ line, number }) => {
440
- console.error(`${number}: ${line}`);
441
- });
442
-
443
- process.exit(1);
444
- } else {
445
- console.log('✅ routes.js passed the .f7 import check.');
446
- }
447
-
448
- //In routes.js file check static import END
449
-
450
-
451
-
452
-
453
-
454
-
455
-
456
-
457
-
458
-
459
-
460
-
461
-
462
- // Check and change the "BridgeWebViewClient.java" file START
463
- /*
464
- For crash issue due to low memory problem, we need to modify the onRenderProcessGone method in BridgeWebViewClient.java.
465
- */
466
-
467
-
468
- const bridgeWebViewClientFilePath = path.join(process.cwd(), 'node_modules', '@capacitor/android/capacitor/src/main/java/com/getcapacitor', 'BridgeWebViewClient.java');
469
-
470
- // Read the file
471
- if (!fs.existsSync(bridgeWebViewClientFilePath)) {
472
- console.error('❌ Error: BridgeWebViewClient.java not found.');
473
- process.exit(1);
474
- }
475
-
476
- let fileContent = fs.readFileSync(bridgeWebViewClientFilePath, 'utf8');
477
-
478
- // Define old and new code
479
- const oldCodeStart = `@Override
480
- public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
481
- super.onRenderProcessGone(view, detail);
482
- boolean result = false;
483
-
484
- List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
485
- if (webViewListeners != null) {
486
- for (WebViewListener listener : bridge.getWebViewListeners()) {
487
- result = listener.onRenderProcessGone(view, detail) || result;
488
- }
489
- }
490
-
491
- return result;
492
- }`;
493
-
494
- const newCode = `@Override
495
- public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
496
- super.onRenderProcessGone(view, detail);
497
-
498
- boolean result = false;
499
-
500
- List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
501
- if (webViewListeners != null) {
502
- for (WebViewListener listener : bridge.getWebViewListeners()) {
503
- result = listener.onRenderProcessGone(view, detail) || result;
504
- }
505
- }
506
-
507
- if (!result) {
508
- // If no one handled it, handle it ourselves!
509
-
510
- /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
511
- if (detail.didCrash()) {
512
- //Log.e("CapacitorWebView", "WebView crashed internally!");
513
- } else {
514
- //Log.w("CapacitorWebView", "WebView was killed by system (low memory) internally!");
515
- }
516
- }*/
517
-
518
- view.post(() -> {
519
- Toast.makeText(view.getContext(), "Reloading due to low memory issue", Toast.LENGTH_SHORT).show();
520
- });
521
-
522
- view.reload(); // Safely reload WebView
523
-
524
- return true; // We handled it
525
- }
526
-
527
- return result;
528
- }`;
529
-
530
- // Step 1: Update method if needed
531
- let updated = false;
532
-
533
- if (fileContent.includes(oldCodeStart)) {
534
- console.log('✅ Found old onRenderProcessGone method. Replacing it...');
535
- fileContent = fileContent.replace(oldCodeStart, newCode);
536
- updated = true;
537
- } else if (fileContent.includes(newCode)) {
538
- console.log('ℹ️ Method already updated. No changes needed in "BridgeWebViewClient.java".');
539
- } else {
540
- console.error('❌ Error: Neither old nor new code found. Unexpected content.');
541
- process.exit(1);
542
- }
543
-
544
- // Step 2: Check and add import if missing
545
- const importToast = 'import android.widget.Toast;';
546
- if (!fileContent.includes(importToast)) {
547
- console.log('✅ Adding missing import for Toast...');
548
- const importRegex = /import\s+[^;]+;/g;
549
- const matches = [...fileContent.matchAll(importRegex)];
550
-
551
- if (matches.length > 0) {
552
- const lastImport = matches[matches.length - 1];
553
- const insertPosition = lastImport.index + lastImport[0].length;
554
- fileContent = fileContent.slice(0, insertPosition) + `\n${importToast}` + fileContent.slice(insertPosition);
555
- updated = true;
556
- } else {
557
- console.error('❌ Error: No import section found in file.');
558
- process.exit(1);
559
- }
560
- } else {
561
- console.log('ℹ️ Import for Toast already exists. No changes needed.');
562
- }
563
-
564
- // Step 3: Save if updated
565
- if (updated) {
566
- fs.writeFileSync(bridgeWebViewClientFilePath, fileContent, 'utf8');
567
- console.log('✅ File updated successfully.');
568
- } else {
569
- console.log('ℹ️ No changes needed.');
570
- }
571
-
572
-
573
-
574
-
575
- // Check and change the "BridgeWebViewClient.java" file END
576
-
577
-
578
-
579
-
580
-
581
-
582
-
583
-
584
-
585
- // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file START
586
-
587
- // Build the path dynamically like you requested
588
- const gradlePath = path.join(
589
- process.cwd(),
590
- 'android',
591
- 'build.gradle'
592
- );
593
-
594
- // Read the existing build.gradle
595
- let gradleContent = fs.readFileSync(gradlePath, 'utf8');
596
-
597
- // Add `ext.kotlin_version` if it's not already there
598
- if (!gradleContent.includes('ext.kotlin_version')) {
599
- gradleContent = gradleContent.replace(
600
- /buildscript\s*{/,
601
- `buildscript {\n ext.kotlin_version = '2.1.0'`
602
- );
603
- }
604
-
605
- // Add Kotlin classpath if it's not already there
606
- if (!gradleContent.includes('org.jetbrains.kotlin:kotlin-gradle-plugin')) {
607
- gradleContent = gradleContent.replace(
608
- /dependencies\s*{([\s\S]*?)classpath 'com.android.tools.build:gradle:8.7.2'/,
609
- `dependencies {\n classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")\n$1classpath 'com.android.tools.build:gradle:8.7.2'`
610
- );
611
- }
612
-
613
- // Write back the modified content
614
- fs.writeFileSync(gradlePath, gradleContent, 'utf8');
615
-
616
- console.log('✅ Kotlin version updated in build.gradle.');
617
-
618
- // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file END
619
-
620
-
621
-
622
-
623
-
624
-
625
-
626
-
627
-
628
- let _admobConfig;
629
-
630
-
631
-
632
- const androidPlatformPath = path.join(process.cwd(), 'android');
633
- const iosPlatformPath = path.join(process.cwd(), 'ios');
634
- const pluginPath = path.join(process.cwd(), 'node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
635
- const infoPlistPath = path.join(process.cwd(), 'ios', 'App', 'App', 'Info.plist');
636
- const resourcesPath = path.join(process.cwd(), 'resources', 'res');
637
- const androidResPath = path.join(process.cwd(), 'android', 'app', 'src', 'main', 'res');
638
- const localNotificationsPluginPath = path.join(process.cwd(), 'node_modules', '@capacitor', 'local-notifications');
639
-
640
- function fileExists(filePath) {
641
- return fs.existsSync(filePath);
642
- }
643
-
644
- function copyFolderSync(source, target) {
645
- if (!fs.existsSync(target)) {
646
- fs.mkdirSync(target, { recursive: true });
647
- }
648
-
649
- fs.readdirSync(source).forEach(file => {
650
- const sourceFile = path.join(source, file);
651
- const targetFile = path.join(target, file);
652
-
653
- if (fs.lstatSync(sourceFile).isDirectory()) {
654
- copyFolderSync(sourceFile, targetFile);
655
- } else {
656
- fs.copyFileSync(sourceFile, targetFile);
657
- }
658
- });
659
- }
660
-
661
- function checkAndCopyResources() {
662
- if (fileExists(resourcesPath)) {
663
- copyFolderSync(resourcesPath, androidResPath);
664
- console.log('✅ Successfully copied resources/res to android/app/src/main/res.');
665
- } else {
666
- console.log('resources/res folder not found.');
667
-
668
- if (fileExists(localNotificationsPluginPath)) {
669
- throw new Error('❌ resources/res is required for @capacitor/local-notifications. Stopping execution.');
670
- }
671
- }
672
- }
673
-
674
-
675
-
676
-
677
-
678
-
679
-
680
-
681
- function getAdMobConfig() {
682
- if (!fileExists(configPath)) {
683
- throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
684
- }
685
-
686
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
687
- const admobConfig = config.plugins?.AdMob;
688
-
689
- if (!admobConfig) {
690
- throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
691
- }
692
-
693
- // Default to true if ADMOB_ENABLED is not specified
694
- const isEnabled = admobConfig.ADMOB_ENABLED !== false;
695
-
696
- if (!isEnabled) {
697
- return { ADMOB_ENABLED: false }; // Skip further validation
698
- }
699
-
700
- if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
701
- throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
702
- }
703
-
704
- return {
705
- ADMOB_ENABLED: true,
706
- APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
707
- APP_ID_IOS: admobConfig.APP_ID_IOS,
708
- USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
709
- };
710
- }
711
-
712
- function validateAndroidBuildOptions() {
713
-
714
-
715
- if (!fileExists(configPath)) {
716
- console.log('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
717
- process.exit(1);
718
- }
719
-
720
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
721
-
722
- const targetAppId=config.appId
723
-
724
- const buildOptions = config.android?.buildOptions;
725
-
726
- if (!buildOptions) {
727
- console.log('❌ Missing android.buildOptions in capacitor.config.json.');
728
- process.exit(1);
729
- }
730
-
731
- const requiredProps = [
732
- 'keystorePath',
733
- 'keystorePassword',
734
- 'keystoreAlias',
735
- 'keystoreAliasPassword',
736
- 'releaseType',
737
- 'signingType'
738
- ];
739
-
740
- const missing = requiredProps.filter(prop => !buildOptions[prop]);
741
-
742
- if (missing.length > 0) {
743
- console.log('❌ Missing properties android.buildOptions in capacitor.config.json.');
744
- process.exit(1);
745
- }
746
-
747
-
748
- const keystorePath=buildOptions.keystorePath
749
- const keyFileName = path.basename(keystorePath);
750
-
751
-
752
-
753
- const keystoreMap = {
754
- "gameskey.jks": [
755
- "com.cube.blaster",
756
- ],
757
- "htmleditorkeystoke.jks": [
758
- "com.HTML.AngularJS.Codeplay",
759
- "com.html.codeplay.pro",
760
- "com.bootstrap.code.play",
761
- "com.kids.learning.master",
762
- "com.Simple.Barcode.Scanner"
763
- ]
764
- };
765
-
766
- // find which keystore is required for the given targetAppId
767
- let requiredKey = "newappskey.jks"; // default
768
- for (const [keyFile, appIds] of Object.entries(keystoreMap)) {
769
- if (appIds.includes(targetAppId)) {
770
- requiredKey = keyFile;
771
- break;
772
- }
773
- }
774
-
775
- // validate
776
- if (keyFileName !== requiredKey) {
777
- console.log(`❌ The keystore path is mismatched. Expected ${requiredKey} for ${targetAppId}, but got ${keyFileName}`);
778
- process.exit(1);
779
- }
780
-
781
-
782
-
783
-
784
-
785
- // optionally return them
786
- //return buildOptions;
787
- }
788
-
789
- function updatePluginXml(admobConfig) {
790
- if (!fileExists(pluginPath)) {
791
- console.error(' ❌ plugin.xml not found. Ensure the plugin is installed.');
792
- return;
793
- }
794
-
795
- let pluginContent = fs.readFileSync(pluginPath, 'utf8');
796
-
797
- pluginContent = pluginContent
798
- .replace(/<preference name="APP_ID_ANDROID" default=".*?" \/>/, `<preference name="APP_ID_ANDROID" default="${admobConfig.APP_ID_ANDROID}" />`)
799
- .replace(/<preference name="APP_ID_IOS" default=".*?" \/>/, `<preference name="APP_ID_IOS" default="${admobConfig.APP_ID_IOS}" />`);
800
-
801
- fs.writeFileSync(pluginPath, pluginContent, 'utf8');
802
- console.log('✅ AdMob IDs successfully updated in plugin.xml');
803
- }
804
-
805
- function updateInfoPlist(admobConfig) {
806
- if (!fileExists(infoPlistPath)) {
807
- console.error(' ❌ Info.plist not found. Ensure you have built the iOS project.');
808
- return;
809
- }
810
-
811
- const plistContent = fs.readFileSync(infoPlistPath, 'utf8');
812
- const plistData = plist.parse(plistContent);
813
-
814
- plistData.GADApplicationIdentifier = admobConfig.APP_ID_IOS;
815
- plistData.NSUserTrackingUsageDescription = 'This identifier will be used to deliver personalized ads to you.';
816
- plistData.GADDelayAppMeasurementInit = true;
817
-
818
- const updatedPlistContent = plist.build(plistData);
819
- fs.writeFileSync(infoPlistPath, updatedPlistContent, 'utf8');
820
- console.log('AdMob IDs and additional configurations successfully updated in Info.plist');
821
- }
822
-
823
-
824
- try {
825
- if (!fileExists(configPath)) {
826
- throw new Error(' ❌ capacitor.config.json not found. Skipping setup.');
827
- }
828
-
829
- if (!fileExists(androidPlatformPath) && !fileExists(iosPlatformPath)) {
830
- throw new Error('Neither Android nor iOS platforms are found. Ensure platforms are added to your Capacitor project.');
831
- }
832
-
833
- checkAndCopyResources();
834
-
835
-
836
-
837
- _admobConfig = getAdMobConfig();
838
-
839
-
840
-
841
-
842
-
843
- // Proceed only if ADMOB_ENABLED is true
844
- if (_admobConfig.ADMOB_ENABLED) {
845
- if (fileExists(androidPlatformPath)) {
846
- updatePluginXml(_admobConfig);
847
- }
848
-
849
- if (fileExists(iosPlatformPath)) {
850
- updateInfoPlist(_admobConfig);
851
- }
852
- }
853
-
854
-
855
- } catch (error) {
856
- console.error(error.message);
857
- process.exit(1); // Stop execution if there's a critical error
858
- }
859
-
860
-
861
-
862
- validateAndroidBuildOptions();
863
-
864
-
865
-
866
-
867
-
868
-
869
- // Check all the codeplays plugins version START
870
-
871
-
872
- const readline = require('readline');
873
-
874
-
875
- //const srcDir = path.join(__dirname, 'src');
876
- const srcDir = path.join(process.cwd(), 'src');
877
- let outdatedPlugins = [];
878
-
879
- function parseVersion(ver) {
880
- return ver.split('.').map(n => parseInt(n, 10));
881
- }
882
-
883
- function compareVersions(v1, v2) {
884
- const [a1, b1] = parseVersion(v1);
885
- const [a2, b2] = parseVersion(v2);
886
- if (a1 !== a2) return a1 - a2;
887
- return b1 - b2;
888
- }
889
-
890
- function walkSync(dir, filelist = []) {
891
- fs.readdirSync(dir).forEach(file => {
892
- const fullPath = path.join(dir, file);
893
- const stat = fs.statSync(fullPath);
894
- if (stat.isDirectory()) {
895
- walkSync(fullPath, filelist);
896
- } else {
897
- filelist.push(fullPath);
898
- }
899
- });
900
- return filelist;
901
- }
902
-
903
- function checkPlugins() {
904
- const files = walkSync(srcDir);
905
-
906
- for (const plugin of requiredPlugins) {
907
- if (plugin.isFolder) {
908
-
909
- let baseFolder = path.join(srcDir,'js', 'Ads'); // <- use known folder name
910
-
911
- if (fs.existsSync(baseFolder)) {
912
- const subDirs = fs.readdirSync(baseFolder)
913
- .map(name => path.join(baseFolder, name))
914
- .filter(p => fs.statSync(p).isDirectory());
915
-
916
- for (const dir of subDirs) {
917
- const relativePath = path.relative(srcDir, dir).replace(/\\/g, '/'); // e.g. Ads/IAP-2.0
918
- const match = plugin.pattern.exec(relativePath);
919
- if (match) {
920
- const currentVersion = match[1];
921
- if (compareVersions(currentVersion, plugin.minVersion) < 0) {
922
- outdatedPlugins.push({
923
- name: relativePath,
924
- currentVersion,
925
- requiredVersion: plugin.minVersion
926
- });
927
- }
928
- }
929
- }
930
- }
931
- continue;
932
- }
933
-
934
- const matchedFile = files.find(file => plugin.pattern.test(file));
935
- if (matchedFile) {
936
- const match = plugin.pattern.exec(matchedFile);
937
- if (match) {
938
- const currentVersion = match[1];
939
- if (compareVersions(currentVersion, plugin.minVersion) < 0) {
940
- outdatedPlugins.push({
941
- name: path.relative(__dirname, matchedFile),
942
- currentVersion,
943
- requiredVersion: plugin.minVersion
944
- });
945
- }
946
- }
947
- }
948
- }
949
-
950
- if (outdatedPlugins.length > 0) {
951
- console.log('\n❗ The following plugins are outdated:');
952
- outdatedPlugins.forEach(p => {
953
- console.log(` ❌ - ${p.name} (Current: ${p.currentVersion}, Required: ${p.requiredVersion})`);
954
- });
955
-
956
- const rl = readline.createInterface({
957
- input: process.stdin,
958
- output: process.stdout
959
- });
960
-
961
- rl.question('\nAre you sure you want to continue without updating these plugins? (y/n): ', answer => {
962
- if (answer.toLowerCase() !== 'y') {
963
- console.log('\n❌ Build cancelled due to outdated plugins.');
964
- process.exit(1);
965
- } else {
966
- console.log('\n✅ Continuing build...');
967
- rl.close();
968
- }
969
- });
970
- } else {
971
- console.log('✅ All plugin versions are up to date.');
972
- }
973
- }
974
-
975
- // Run the validation
976
- checkPlugins();
977
-
978
-
979
-
980
-
981
- // Check all the codeplays plugins version START
982
-
983
-
984
-
985
-
986
- // ====================================================================
987
- // AUTO-ADD esbuild.drop: ['console','debugger'] to vite.config.js / mjs
988
- // ====================================================================
989
-
990
-
991
-
992
- const checkAndupdateDropInViteConfig = () => {
993
-
994
- const possibleFiles = [
995
- "vite.config.js",
996
- "vite.config.mjs"
997
- ];
998
-
999
- // Detect existing config file
1000
- const viteConfigPath = possibleFiles
1001
- .map(file => path.join(process.cwd(), file))
1002
- .find(filePath => fs.existsSync(filePath));
1003
-
1004
- if (!viteConfigPath) {
1005
- console.warn("⚠️ No vite config found. Skipping.");
1006
- return;
1007
- }
1008
-
1009
- //console.log("📄 Using:", viteConfigPath.split("/").pop());
1010
-
1011
- let viteContent = fs.readFileSync(viteConfigPath, "utf8");
1012
-
1013
- // Skip if already exists
1014
- if (/drop\s*:\s*\[.*['"]console['"].*\]/.test(viteContent)) {
1015
- console.log("ℹ️ vite.config.(m)js already Updated. Skipping...");
1016
- return;
1017
- }
1018
-
1019
- console.log("🔧 Adding esbuild.drop ...");
1020
-
1021
- // If esbuild block exists
1022
- if (/esbuild\s*:\s*{/.test(viteContent)) {
1023
- viteContent = viteContent.replace(
1024
- /esbuild\s*:\s*{([\s\S]*?)(^ {0,8})}/m,
1025
- (full, inner, indent) => {
1026
-
1027
- let lines = inner
1028
- .split("\n")
1029
- .map(l => l.trim())
1030
- .filter(Boolean);
1031
-
1032
- // Fix last comma
1033
- if (lines.length > 0) {
1034
- lines[lines.length - 1] =
1035
- lines[lines.length - 1].replace(/,+$/, "") + ",";
1036
- }
1037
-
1038
- // Re-indent
1039
- lines = lines.map(l => indent + " " + l);
1040
-
1041
- // Add drop
1042
- lines.push(`${indent} drop: ['console','debugger'],`);
1043
-
1044
- return `esbuild: {\n${lines.join("\n")}\n${indent}}`;
1045
- }
1046
- );
1047
- }
1048
-
1049
- // If esbuild missing
1050
- else {
1051
- viteContent = viteContent.replace(
1052
- /export default defineConfig\s*\(\s*{/,
1053
- m => `${m}\n esbuild: {\n drop: ['console','debugger'],\n },`
1054
- );
1055
- }
1056
-
1057
- fs.writeFileSync(viteConfigPath, viteContent, "utf8");
1058
- console.log("✅ vite.config.(m)js Updated successfully.");
1059
- };
1060
-
1061
- checkAndupdateDropInViteConfig();
1062
-
1063
-
1064
-
1065
-
1066
-
1067
-
1068
-
1069
-
1070
- const compareVersion = (v1, v2) => {
1071
- const a = v1.split(".").map(Number);
1072
- const b = v2.split(".").map(Number);
1073
-
1074
- for (let i = 0; i < Math.max(a.length, b.length); i++) {
1075
- const num1 = a[i] || 0;
1076
- const num2 = b[i] || 0;
1077
- if (num1 > num2) return 1;
1078
- if (num1 < num2) return -1;
1079
- }
1080
- return 0;
1081
- };
1082
-
1083
-
1084
-
1085
-
1086
- const admobConfigPath = path.join('src', 'js','Ads', 'admob-ad-configuration.json');
1087
-
1088
- const checkAdmobConfigurationProperty=()=>{
1089
-
1090
-
1091
- if (!_admobConfig.ADMOB_ENABLED)
1092
- {
1093
- console.log("ℹ️ Admob is not enabled so 'admob-ad-configuration.json' checking is skipping...");
1094
- return;
1095
- }
1096
-
1097
-
1098
- const REQUIRED_CONFIG_KEYS = [
1099
- "isKidsApp",
1100
- "isTesting",
1101
- "isConsoleLogEnabled",
1102
- "bannerEnabled",
1103
- "interstitialEnabled",
1104
- "appOpenEnabled",
1105
- "rewardVideoEnabled",
1106
- "rewardInterstitialEnabled",
1107
- "collapsibleEnabled",
1108
- "isLandScape",
1109
- "overlappingHeight",
1110
- "isOverlappingEnable",
1111
- "bannerTypeAndroid",
1112
- "bannerTypeiOS",
1113
- "bannerTopSpaceColor",
1114
- "interstitialLoadScreenTextColor",
1115
- "interstitialLoadScreenBackgroundColor",
1116
- "beforeBannerSpace",
1117
- "whenShow",
1118
- "minimumClick",
1119
- "interstitialTimeOut",
1120
- "interstitialFirstTimeOut",
1121
- "appOpenAdsTimeOut",
1122
- "maxRetryCount",
1123
- "retrySecondsAr",
1124
- "appOpenPerSession",
1125
- "interstitialPerSession",
1126
- "appOpenFirstTimeOut"
1127
- ];
1128
-
1129
-
1130
-
1131
-
1132
-
1133
- let admobConfigInJson;
1134
-
1135
- try {
1136
- admobConfigInJson = JSON.parse(readFileSync(admobConfigPath, "utf8"));
1137
- } catch (err) {
1138
- console.error("❌ Failed to read admob-ad-configuration.json", err);
1139
- process.exit(1);
1140
- }
1141
-
1142
- // ✅ Validate config object exists
1143
- if (!admobConfigInJson.config) {
1144
- console.error('❌ "config" object is missing in admob-ad-configuration.json');
1145
- process.exit(1);
1146
- }
1147
-
1148
-
1149
- const admobConfigMinVersion="1.4"
1150
-
1151
- if (compareVersion(admobConfigInJson.VERSION, admobConfigMinVersion) < 0) {
1152
- console.error(`❌ Please use at-least version ${admobConfigMinVersion} in "src/js/Ads/admob-ad-configuration.json"`);
1153
- process.exit(1);
1154
- }
1155
-
1156
-
1157
- const config = admobConfigInJson.config;
1158
-
1159
- // ✅ Find missing properties
1160
- const missingKeys = REQUIRED_CONFIG_KEYS.filter(
1161
- key => !(key in config)
1162
- );
1163
-
1164
-
1165
-
1166
- if (missingKeys.length > 0) {
1167
- console.error("❌ Missing required configuration keys. Please check it in 'src/js/Ads/admob-ad-configuration.json'");
1168
-
1169
- missingKeys.forEach(k => console.error(" - " + k));
1170
- process.exit(1);
1171
- }
1172
-
1173
-
1174
- console.log('✅ All keys exist. in "admob-ad-configuration.json file" Configuration looks good.');
1175
- }
1176
-
1177
-
1178
- checkAdmobConfigurationProperty()
1179
-
1180
-
1181
-
1182
-
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
+ { pattern: /backbutton-(\d+\.\d+)\.js$/, minVersion: '1.6', required: true },
14
+ { pattern: /common-(\d+\.\d+)\.js$/, minVersion: '5.0', required: true },
15
+ { pattern: /localization_settings-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true },
16
+ { pattern: /localization-(\d+\.\d+)\.js$/, minVersion: '1.3', required: true },
17
+ { pattern: /localNotification-(\d+\.\d+)\.js$/, minVersion: '2.2', required: true },
18
+ { pattern: /localNotification_AppSettings-(\d+\.\d+)\.js$/, minVersion: '1.0', required: true },
19
+ { pattern: /onesignal-(\d+\.\d+)\.js$/, minVersion: '2.2', required: true },
20
+ { pattern: /saveToGalleryAndSaveAnyFile-(\d+\.\d+)(-ios)?\.js$/, minVersion: '3.0', required: true },
21
+ { pattern: /Ads[\/\\]IAP-(\d+\.\d+)$/, minVersion: '2.5', isFolder: true , required: true },
22
+ { pattern: /Ads[\/\\]admob-emi-(\d+\.\d+)\.js$/, minVersion: '3.3', required: true },
23
+
24
+ // New added plugins
25
+ { pattern: /video-player-(\d+\.\d+)\.js$/, minVersion: '1.5', required: true },
26
+ { pattern: /image-cropper-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true },
27
+
28
+ // New folders
29
+ { pattern: /editor-(\d+\.\d+)$/, minVersion: '1.8', isFolder: true, required: true },
30
+ { pattern: /ffmpeg-(\d+\.\d+)$/, minVersion: '1.3', isFolder: true, required: true }
31
+ ];
32
+
33
+
34
+
35
+
36
+
37
+
38
+ //Check codeplay-common latest version installed or not Start
39
+ const { execSync } = require('child_process');
40
+
41
+ function getInstalledVersion(packageName) {
42
+ try {
43
+ const packageJsonPath = path.join(process.cwd(), 'node_modules', packageName, 'package.json');
44
+ if (fs.existsSync(packageJsonPath)) {
45
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
46
+ return packageJson.version;
47
+ }
48
+ } catch (error) {
49
+ return null;
50
+ }
51
+ return null;
52
+ }
53
+
54
+ function getLatestVersion(packageName) {
55
+ try {
56
+ return execSync(`npm view ${packageName} version`).toString().trim();
57
+ } catch (error) {
58
+ console.error(`Failed to fetch latest version for ${packageName}`);
59
+ return null;
60
+ }
61
+ }
62
+
63
+ function checkPackageVersion() {
64
+ const packageName = 'codeplay-common';
65
+ const installedVersion = getInstalledVersion(packageName);
66
+ const latestVersion = getLatestVersion(packageName);
67
+
68
+ if (!installedVersion) {
69
+ console.error(`${packageName} is not installed. Please install it using "npm install ${packageName}".`);
70
+ process.exit(1);
71
+ }
72
+
73
+ if (installedVersion !== latestVersion) {
74
+ 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`);
75
+ process.exit(1);
76
+ }
77
+
78
+ console.log(`${packageName} is up to date (version ${installedVersion}).`);
79
+ }
80
+
81
+ // Run package version check before executing the main script
82
+ try {
83
+ checkPackageVersion();
84
+ } catch (error) {
85
+ console.error(error.message);
86
+ process.exit(1);
87
+ }
88
+
89
+ //Check codeplay-common latest version installed or not END
90
+
91
+
92
+
93
+
94
+
95
+
96
+ const checkAppUniqueId=()=>{
97
+
98
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
99
+
100
+ const appUniqueId = config.android?.APP_UNIQUE_ID;
101
+ const RESIZEABLE_ACTIVITY = config.android?.RESIZEABLE_ACTIVITY;
102
+ const orientation = config.android?.ORIENTATION;
103
+
104
+
105
+ let logErrorMessage="";
106
+
107
+ // 1️⃣ Check if it’s missing
108
+ if (RESIZEABLE_ACTIVITY === undefined) {
109
+ logErrorMessage+='❌ Missing android.RESIZEABLE_ACTIVITY option in capacitor.config.json.\n';
110
+ }
111
+
112
+ // 2️⃣ Check if it’s not boolean (true/false only)
113
+ else if (typeof RESIZEABLE_ACTIVITY !== 'boolean') {
114
+ logErrorMessage+='❌ Invalid android.RESIZEABLE_ACTIVITY value. Please use only true or false (without quotes).\n';
115
+ }
116
+
117
+
118
+
119
+ if (!orientation) {
120
+ logErrorMessage+='❌ Missing android.ORIENTATION option in capacitor.config.json.\n';
121
+ }
122
+
123
+ else if(orientation!="portrait" && orientation!="landscape" && orientation!="auto")
124
+ {
125
+ logErrorMessage+='❌ Spelling mistake in android.ORIENTATION option in capacitor.config.json. Please use only ["portrait" "landscape" "auto"]\n';
126
+ }
127
+
128
+
129
+ if (!appUniqueId) {
130
+ logErrorMessage+='❌ APP_UNIQUE_ID is missing in capacitor.config.json.';
131
+ }
132
+
133
+ else if (!Number.isInteger(appUniqueId)) {
134
+ logErrorMessage+='❌ APP_UNIQUE_ID must be an integer. Example: 1, 2, 3, etc.';
135
+ }
136
+
137
+
138
+
139
+ if(logErrorMessage!="")
140
+ {
141
+ console.error(logErrorMessage);
142
+ process.exit(1)
143
+ }
144
+
145
+
146
+ console.log(`✅ APP_UNIQUE_ID is valid: ${appUniqueId}`);
147
+
148
+ }
149
+
150
+ checkAppUniqueId();
151
+
152
+
153
+
154
+
155
+
156
+
157
+
158
+ //@Codemirror check and install/uninstall the packages START
159
+ //const fs = require("fs");
160
+ //const path = require("path");
161
+ //const { execSync } = require("child_process");
162
+
163
+ const baseDir = path.join(__dirname, "..", "src", "js");
164
+
165
+ // Step 1: Find highest versioned folder like `editor-1.6`
166
+ const editorDirs = fs.readdirSync(baseDir)
167
+ .filter(name => /^editor-\d+\.\d+$/.test(name))
168
+ .sort((a, b) => {
169
+ const getVersion = str => str.match(/(\d+)\.(\d+)/).slice(1).map(Number);
170
+ const [aMajor, aMinor] = getVersion(a);
171
+ const [bMajor, bMinor] = getVersion(b);
172
+ return bMajor - aMajor || bMinor - aMinor;
173
+ });
174
+
175
+ if (editorDirs.length === 0) {
176
+
177
+ console.log("@Codemirror used editor(s) are not found")
178
+ //console.error("❌ No editor-x.x folders found in src/js.");
179
+ //process.exit(1);
180
+ }
181
+ else
182
+ {
183
+
184
+ const latestEditorDir = editorDirs.sort((a, b) => {
185
+ const versionA = parseFloat(a.split('-')[1]);
186
+ const versionB = parseFloat(b.split('-')[1]);
187
+ return versionB - versionA;
188
+ })[0];
189
+
190
+ //const latestEditorDir = editorDirs[editorDirs.length - 1];
191
+ const runJsPath = path.join(baseDir, latestEditorDir, "run.js");
192
+
193
+ if (!fs.existsSync(runJsPath)) {
194
+ console.error(`❌ run.js not found in ${latestEditorDir}`);
195
+ process.exit(1);
196
+ }
197
+
198
+ // Step 2: Execute the run.js file
199
+ console.log(`🚀 Executing ${runJsPath}...`);
200
+ execSync(`node "${runJsPath}"`, { stdio: "inherit" });
201
+ }
202
+
203
+ //@Codemirror check and install/uninstall the packages END
204
+
205
+
206
+
207
+
208
+
209
+
210
+
211
+
212
+
213
+
214
+
215
+
216
+ // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists START
217
+
218
+ const os = require('os');
219
+
220
+ const saveToGalleryAndSaveFileCheck_iOS = () => {
221
+
222
+ // List of paths to scan
223
+ const SCAN_PATHS = [
224
+ path.resolve(__dirname, '../src/certificate'),
225
+ path.resolve(__dirname, '../src/pages'),
226
+ path.resolve(__dirname, '../src/js'),
227
+ path.resolve(__dirname, '../src/app.f7')
228
+ ];
229
+
230
+ // Directory to exclude
231
+ const EXCLUDED_DIR = path.resolve(__dirname, '../src/js/Ads');
232
+
233
+ const ANDROID_MANIFEST_PATH = path.resolve(__dirname, '../android/app/src/main/AndroidManifest.xml');
234
+
235
+
236
+ // Match iOS-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5-ios.js) not in comments
237
+ const IOS_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*-ios\.js['"]/m;
238
+
239
+ // Match Android-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5.js) not in comments
240
+ const ANDROID_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*\.js['"]/m;
241
+
242
+
243
+
244
+
245
+
246
+ const ALLOWED_EXTENSIONS = ['.js', '.f7'];
247
+ const isMac = os.platform() === 'darwin';
248
+
249
+ let iosImportFound = false;
250
+ let androidImportFound = false;
251
+
252
+ function scanDirectory(dir) {
253
+
254
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
255
+ const appUniqueId = config.android?.APP_UNIQUE_ID;
256
+ if(appUniqueId=="206")
257
+ return;
258
+
259
+ const stat = fs.statSync(dir);
260
+
261
+ if (stat.isFile()) {
262
+ // Only scan allowed file extensions
263
+ if (ALLOWED_EXTENSIONS.some(ext => dir.endsWith(ext))) {
264
+ process.stdout.write(`\r🔍 Scanning: ${dir} `);
265
+
266
+ const content = fs.readFileSync(dir, 'utf8');
267
+
268
+ if (IOS_FILE_REGEX.test(content)) {
269
+ iosImportFound = true;
270
+ if (!isMac) {
271
+ console.error(`\n❌ ERROR: iOS-specific import detected in: ${dir}`);
272
+ console.error(`🚫 STOPPED: This file should not be imported in Android/Windows/Linux builds.\n`);
273
+ process.exit(1);
274
+ }
275
+ } else if (ANDROID_FILE_REGEX.test(content) && !content.includes('-ios.js')) {
276
+ androidImportFound = true;
277
+ }
278
+ }
279
+ }
280
+ else if (stat.isDirectory()) {
281
+ if (dir === EXCLUDED_DIR || path.basename(dir) === 'node_modules') return;
282
+
283
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
284
+ for (let entry of entries) {
285
+ scanDirectory(path.join(dir, entry.name));
286
+ }
287
+ }
288
+ }
289
+
290
+ // Run scan on all specified paths
291
+ for (let scanPath of SCAN_PATHS) {
292
+ if (fs.existsSync(scanPath)) {
293
+ scanDirectory(scanPath);
294
+ }
295
+ }
296
+
297
+
298
+
299
+ /* // Check src folder
300
+ if (!fs.existsSync(ROOT_DIR)) {
301
+ console.warn(`⚠️ Warning: 'src' directory not found at: ${ROOT_DIR}`);
302
+ return;
303
+ } */
304
+
305
+ //scanDirectory(ROOT_DIR);
306
+
307
+ // iOS Checks
308
+ if (isMac && !iosImportFound) {
309
+ console.warn(`⚠️ WARNING: You're on macOS but no iOS version (saveToGalleryAndSaveAnyFile-x.x-ios.js) found.`);
310
+ process.exit(1);
311
+ } else if (isMac && iosImportFound) {
312
+ console.log('✅ iOS version detected for macOS build.');
313
+ } else if (!iosImportFound) {
314
+ console.log('✅ No iOS-specific imports detected for non-macOS.');
315
+ }
316
+
317
+ // Android Checks
318
+ if (androidImportFound) {
319
+ console.log("📱 Android version of saveToGalleryAndSaveAnyFile detected. Checking AndroidManifest.xml...");
320
+
321
+ if (!fs.existsSync(ANDROID_MANIFEST_PATH)) {
322
+ console.error("❌ AndroidManifest.xml not found. Cannot add requestLegacyExternalStorage attribute.");
323
+ return;
324
+ }
325
+
326
+ let manifestContent = fs.readFileSync(ANDROID_MANIFEST_PATH, 'utf8');
327
+
328
+ if (!manifestContent.includes('android:requestLegacyExternalStorage="true"')) {
329
+ console.log("Adding android:requestLegacyExternalStorage=\"true\" to <application> tag...");
330
+
331
+ manifestContent = manifestContent.replace(
332
+ /<application([^>]*)>/,
333
+ (match, attrs) => {
334
+ if (attrs.includes('android:requestLegacyExternalStorage')) return match;
335
+ return `<application${attrs} android:requestLegacyExternalStorage="true">`;
336
+ }
337
+ );
338
+
339
+ fs.writeFileSync(ANDROID_MANIFEST_PATH, manifestContent, 'utf8');
340
+ console.log("✅ android:requestLegacyExternalStorage=\"true\" added successfully.");
341
+ } else {
342
+ console.log("ℹ️ android:requestLegacyExternalStorage already exists in AndroidManifest.xml.");
343
+ }
344
+ } else {
345
+ console.log("✅ No Android saveToGalleryAndSaveAnyFile imports detected.");
346
+ }
347
+ };
348
+
349
+ saveToGalleryAndSaveFileCheck_iOS();
350
+ // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists END
351
+
352
+
353
+
354
+
355
+
356
+
357
+
358
+
359
+
360
+
361
+
362
+
363
+
364
+ /*
365
+ // Clean up AppleDouble files (._*) created by macOS START
366
+ if (process.platform === 'darwin') {
367
+ try {
368
+ console.log('🧹 Cleaning up AppleDouble files (._*)...');
369
+ execSync(`find . -name '._*' -delete`);
370
+ console.log('✅ AppleDouble files removed.');
371
+ } catch (err) {
372
+ console.warn('⚠️ Failed to remove AppleDouble files:', err.message);
373
+ }
374
+ } else {
375
+ console.log('ℹ️ Skipping AppleDouble cleanup — not a macOS machine.');
376
+ }
377
+
378
+ // Clean up AppleDouble files (._*) created by macOS END
379
+ */
380
+
381
+
382
+
383
+
384
+
385
+
386
+ //In routes.js file check static import START
387
+
388
+ const routesPath = path.join(process.cwd(), 'src', 'js', 'routes.js');
389
+ const routesContent = fs.readFileSync(routesPath, 'utf-8');
390
+
391
+ let inBlockComment = false;
392
+ const lines = routesContent.split('\n');
393
+
394
+ const allowedImport = `import HomePage from '../pages/home.f7';`;
395
+ const badImportRegex = /^[ \t]*import\s+[\w{}*,\s]*\s+from\s+['"].+\.f7['"]\s*;/;
396
+ const badImports = [];
397
+
398
+ lines.forEach((line, index) => {
399
+ const trimmed = line.trim();
400
+
401
+ // Handle block comment start and end
402
+ if (trimmed.startsWith('/*')) inBlockComment = true;
403
+ if (inBlockComment && trimmed.endsWith('*/')) {
404
+ inBlockComment = false;
405
+ return;
406
+ }
407
+
408
+ // Skip if inside block comment or line comment
409
+ if (inBlockComment || trimmed.startsWith('//')) return;
410
+
411
+ // Match static .f7 import
412
+ if (badImportRegex.test(trimmed) && trimmed !== allowedImport) {
413
+ badImports.push({ line: trimmed, number: index + 1 });
414
+ }
415
+ });
416
+
417
+ if (badImports.length > 0) {
418
+ console.error('\n❌ ERROR: Detected disallowed static imports of .f7 files in routes.js\n');
419
+ console.error(`⚠️ Only this static import is allowed:\n ${allowedImport}\n`);
420
+ console.error(`🔧 Please convert other imports to async dynamic imports like this:\n`);
421
+ console.error(`
422
+
423
+ import HomePage from '../pages/home.f7';
424
+
425
+ const routes = [
426
+ {
427
+ path: '/',
428
+ component:HomePage,
429
+ },
430
+ {
431
+ path: '/ProfilePage/',
432
+ async async({ resolve }) {
433
+ const page = await import('../pages/profile.f7');
434
+ resolve({ component: page.default });
435
+ },
436
+ }]
437
+ `);
438
+
439
+ badImports.forEach(({ line, number }) => {
440
+ console.error(`${number}: ${line}`);
441
+ });
442
+
443
+ process.exit(1);
444
+ } else {
445
+ console.log('✅ routes.js passed the .f7 import check.');
446
+ }
447
+
448
+ //In routes.js file check static import END
449
+
450
+
451
+
452
+
453
+
454
+
455
+
456
+
457
+
458
+
459
+
460
+
461
+
462
+ // Check and change the "BridgeWebViewClient.java" file START
463
+ /*
464
+ For crash issue due to low memory problem, we need to modify the onRenderProcessGone method in BridgeWebViewClient.java.
465
+ */
466
+
467
+
468
+ const bridgeWebViewClientFilePath = path.join(process.cwd(), 'node_modules', '@capacitor/android/capacitor/src/main/java/com/getcapacitor', 'BridgeWebViewClient.java');
469
+
470
+ // Read the file
471
+ if (!fs.existsSync(bridgeWebViewClientFilePath)) {
472
+ console.error('❌ Error: BridgeWebViewClient.java not found.');
473
+ process.exit(1);
474
+ }
475
+
476
+ let fileContent = fs.readFileSync(bridgeWebViewClientFilePath, 'utf8');
477
+
478
+ // Define old and new code
479
+ const oldCodeStart = `@Override
480
+ public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
481
+ super.onRenderProcessGone(view, detail);
482
+ boolean result = false;
483
+
484
+ List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
485
+ if (webViewListeners != null) {
486
+ for (WebViewListener listener : bridge.getWebViewListeners()) {
487
+ result = listener.onRenderProcessGone(view, detail) || result;
488
+ }
489
+ }
490
+
491
+ return result;
492
+ }`;
493
+
494
+ const newCode = `@Override
495
+ public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
496
+ super.onRenderProcessGone(view, detail);
497
+
498
+ boolean result = false;
499
+
500
+ List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
501
+ if (webViewListeners != null) {
502
+ for (WebViewListener listener : bridge.getWebViewListeners()) {
503
+ result = listener.onRenderProcessGone(view, detail) || result;
504
+ }
505
+ }
506
+
507
+ if (!result) {
508
+ // If no one handled it, handle it ourselves!
509
+
510
+ /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
511
+ if (detail.didCrash()) {
512
+ //Log.e("CapacitorWebView", "WebView crashed internally!");
513
+ } else {
514
+ //Log.w("CapacitorWebView", "WebView was killed by system (low memory) internally!");
515
+ }
516
+ }*/
517
+
518
+ view.post(() -> {
519
+ Toast.makeText(view.getContext(), "Reloading due to low memory issue", Toast.LENGTH_SHORT).show();
520
+ });
521
+
522
+ view.reload(); // Safely reload WebView
523
+
524
+ return true; // We handled it
525
+ }
526
+
527
+ return result;
528
+ }`;
529
+
530
+ // Step 1: Update method if needed
531
+ let updated = false;
532
+
533
+ if (fileContent.includes(oldCodeStart)) {
534
+ console.log('✅ Found old onRenderProcessGone method. Replacing it...');
535
+ fileContent = fileContent.replace(oldCodeStart, newCode);
536
+ updated = true;
537
+ } else if (fileContent.includes(newCode)) {
538
+ console.log('ℹ️ Method already updated. No changes needed in "BridgeWebViewClient.java".');
539
+ } else {
540
+ console.error('❌ Error: Neither old nor new code found. Unexpected content.');
541
+ process.exit(1);
542
+ }
543
+
544
+ // Step 2: Check and add import if missing
545
+ const importToast = 'import android.widget.Toast;';
546
+ if (!fileContent.includes(importToast)) {
547
+ console.log('✅ Adding missing import for Toast...');
548
+ const importRegex = /import\s+[^;]+;/g;
549
+ const matches = [...fileContent.matchAll(importRegex)];
550
+
551
+ if (matches.length > 0) {
552
+ const lastImport = matches[matches.length - 1];
553
+ const insertPosition = lastImport.index + lastImport[0].length;
554
+ fileContent = fileContent.slice(0, insertPosition) + `\n${importToast}` + fileContent.slice(insertPosition);
555
+ updated = true;
556
+ } else {
557
+ console.error('❌ Error: No import section found in file.');
558
+ process.exit(1);
559
+ }
560
+ } else {
561
+ console.log('ℹ️ Import for Toast already exists. No changes needed.');
562
+ }
563
+
564
+ // Step 3: Save if updated
565
+ if (updated) {
566
+ fs.writeFileSync(bridgeWebViewClientFilePath, fileContent, 'utf8');
567
+ console.log('✅ File updated successfully.');
568
+ } else {
569
+ console.log('ℹ️ No changes needed.');
570
+ }
571
+
572
+
573
+
574
+
575
+ // Check and change the "BridgeWebViewClient.java" file END
576
+
577
+
578
+
579
+
580
+
581
+
582
+
583
+
584
+
585
+ // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file START
586
+
587
+ // Build the path dynamically like you requested
588
+ const gradlePath = path.join(
589
+ process.cwd(),
590
+ 'android',
591
+ 'build.gradle'
592
+ );
593
+
594
+ // Read the existing build.gradle
595
+ let gradleContent = fs.readFileSync(gradlePath, 'utf8');
596
+
597
+ // Add `ext.kotlin_version` if it's not already there
598
+ if (!gradleContent.includes('ext.kotlin_version')) {
599
+ gradleContent = gradleContent.replace(
600
+ /buildscript\s*{/,
601
+ `buildscript {\n ext.kotlin_version = '2.1.0'`
602
+ );
603
+ }
604
+
605
+ // Add Kotlin classpath if it's not already there
606
+ if (!gradleContent.includes('org.jetbrains.kotlin:kotlin-gradle-plugin')) {
607
+ gradleContent = gradleContent.replace(
608
+ /dependencies\s*{([\s\S]*?)classpath 'com.android.tools.build:gradle:8.7.2'/,
609
+ `dependencies {\n classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")\n$1classpath 'com.android.tools.build:gradle:8.7.2'`
610
+ );
611
+ }
612
+
613
+ // Write back the modified content
614
+ fs.writeFileSync(gradlePath, gradleContent, 'utf8');
615
+
616
+ console.log('✅ Kotlin version updated in build.gradle.');
617
+
618
+ // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file END
619
+
620
+
621
+
622
+
623
+
624
+
625
+
626
+
627
+
628
+ let _admobConfig;
629
+
630
+
631
+
632
+ const androidPlatformPath = path.join(process.cwd(), 'android');
633
+ const iosPlatformPath = path.join(process.cwd(), 'ios');
634
+ const pluginPath = path.join(process.cwd(), 'node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
635
+ const infoPlistPath = path.join(process.cwd(), 'ios', 'App', 'App', 'Info.plist');
636
+ const resourcesPath = path.join(process.cwd(), 'resources', 'res');
637
+ const androidResPath = path.join(process.cwd(), 'android', 'app', 'src', 'main', 'res');
638
+ const localNotificationsPluginPath = path.join(process.cwd(), 'node_modules', '@capacitor', 'local-notifications');
639
+
640
+ function fileExists(filePath) {
641
+ return fs.existsSync(filePath);
642
+ }
643
+
644
+ function copyFolderSync(source, target) {
645
+ if (!fs.existsSync(target)) {
646
+ fs.mkdirSync(target, { recursive: true });
647
+ }
648
+
649
+ fs.readdirSync(source).forEach(file => {
650
+ const sourceFile = path.join(source, file);
651
+ const targetFile = path.join(target, file);
652
+
653
+ if (fs.lstatSync(sourceFile).isDirectory()) {
654
+ copyFolderSync(sourceFile, targetFile);
655
+ } else {
656
+ fs.copyFileSync(sourceFile, targetFile);
657
+ }
658
+ });
659
+ }
660
+
661
+ function checkAndCopyResources() {
662
+ if (fileExists(resourcesPath)) {
663
+ copyFolderSync(resourcesPath, androidResPath);
664
+ console.log('✅ Successfully copied resources/res to android/app/src/main/res.');
665
+ } else {
666
+ console.log('resources/res folder not found.');
667
+
668
+ if (fileExists(localNotificationsPluginPath)) {
669
+ throw new Error('❌ resources/res is required for @capacitor/local-notifications. Stopping execution.');
670
+ }
671
+ }
672
+ }
673
+
674
+
675
+
676
+
677
+
678
+
679
+
680
+
681
+ function getAdMobConfig() {
682
+ if (!fileExists(configPath)) {
683
+ throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
684
+ }
685
+
686
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
687
+ const admobConfig = config.plugins?.AdMob;
688
+
689
+ if (!admobConfig) {
690
+ throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
691
+ }
692
+
693
+ // Default to true if ADMOB_ENABLED is not specified
694
+ const isEnabled = admobConfig.ADMOB_ENABLED !== false;
695
+
696
+ if (!isEnabled) {
697
+ return { ADMOB_ENABLED: false }; // Skip further validation
698
+ }
699
+
700
+ if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
701
+ throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
702
+ }
703
+
704
+ return {
705
+ ADMOB_ENABLED: true,
706
+ APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
707
+ APP_ID_IOS: admobConfig.APP_ID_IOS,
708
+ USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
709
+ };
710
+ }
711
+
712
+ function validateAndroidBuildOptions() {
713
+
714
+
715
+ if (!fileExists(configPath)) {
716
+ console.log('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
717
+ process.exit(1);
718
+ }
719
+
720
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
721
+
722
+ const targetAppId=config.appId
723
+
724
+ const buildOptions = config.android?.buildOptions;
725
+
726
+ if (!buildOptions) {
727
+ console.log('❌ Missing android.buildOptions in capacitor.config.json.');
728
+ process.exit(1);
729
+ }
730
+
731
+ const requiredProps = [
732
+ 'keystorePath',
733
+ 'keystorePassword',
734
+ 'keystoreAlias',
735
+ 'keystoreAliasPassword',
736
+ 'releaseType',
737
+ 'signingType'
738
+ ];
739
+
740
+ const missing = requiredProps.filter(prop => !buildOptions[prop]);
741
+
742
+ if (missing.length > 0) {
743
+ console.log('❌ Missing properties android.buildOptions in capacitor.config.json.');
744
+ process.exit(1);
745
+ }
746
+
747
+
748
+ const keystorePath=buildOptions.keystorePath
749
+ const keyFileName = path.basename(keystorePath);
750
+
751
+
752
+
753
+ const keystoreMap = {
754
+ "gameskey.jks": [
755
+ "com.cube.blaster",
756
+ ],
757
+ "htmleditorkeystoke.jks": [
758
+ "com.HTML.AngularJS.Codeplay",
759
+ "com.html.codeplay.pro",
760
+ "com.bootstrap.code.play",
761
+ "com.kids.learning.master",
762
+ "com.Simple.Barcode.Scanner"
763
+ ]
764
+ };
765
+
766
+ // find which keystore is required for the given targetAppId
767
+ let requiredKey = "newappskey.jks"; // default
768
+ for (const [keyFile, appIds] of Object.entries(keystoreMap)) {
769
+ if (appIds.includes(targetAppId)) {
770
+ requiredKey = keyFile;
771
+ break;
772
+ }
773
+ }
774
+
775
+ // validate
776
+ if (keyFileName !== requiredKey) {
777
+ console.log(`❌ The keystore path is mismatched. Expected ${requiredKey} for ${targetAppId}, but got ${keyFileName}`);
778
+ process.exit(1);
779
+ }
780
+
781
+
782
+
783
+
784
+
785
+ // optionally return them
786
+ //return buildOptions;
787
+ }
788
+
789
+ function updatePluginXml(admobConfig) {
790
+ if (!fileExists(pluginPath)) {
791
+ console.error(' ❌ plugin.xml not found. Ensure the plugin is installed.');
792
+ return;
793
+ }
794
+
795
+ let pluginContent = fs.readFileSync(pluginPath, 'utf8');
796
+
797
+ pluginContent = pluginContent
798
+ .replace(/<preference name="APP_ID_ANDROID" default=".*?" \/>/, `<preference name="APP_ID_ANDROID" default="${admobConfig.APP_ID_ANDROID}" />`)
799
+ .replace(/<preference name="APP_ID_IOS" default=".*?" \/>/, `<preference name="APP_ID_IOS" default="${admobConfig.APP_ID_IOS}" />`);
800
+
801
+ fs.writeFileSync(pluginPath, pluginContent, 'utf8');
802
+ console.log('✅ AdMob IDs successfully updated in plugin.xml');
803
+ }
804
+
805
+ function updateInfoPlist(admobConfig) {
806
+ if (!fileExists(infoPlistPath)) {
807
+ console.error(' ❌ Info.plist not found. Ensure you have built the iOS project.');
808
+ return;
809
+ }
810
+
811
+ const plistContent = fs.readFileSync(infoPlistPath, 'utf8');
812
+ const plistData = plist.parse(plistContent);
813
+
814
+ plistData.GADApplicationIdentifier = admobConfig.APP_ID_IOS;
815
+ plistData.NSUserTrackingUsageDescription = 'This identifier will be used to deliver personalized ads to you.';
816
+ plistData.GADDelayAppMeasurementInit = true;
817
+
818
+ const updatedPlistContent = plist.build(plistData);
819
+ fs.writeFileSync(infoPlistPath, updatedPlistContent, 'utf8');
820
+ console.log('AdMob IDs and additional configurations successfully updated in Info.plist');
821
+ }
822
+
823
+
824
+ try {
825
+ if (!fileExists(configPath)) {
826
+ throw new Error(' ❌ capacitor.config.json not found. Skipping setup.');
827
+ }
828
+
829
+ if (!fileExists(androidPlatformPath) && !fileExists(iosPlatformPath)) {
830
+ throw new Error('Neither Android nor iOS platforms are found. Ensure platforms are added to your Capacitor project.');
831
+ }
832
+
833
+ checkAndCopyResources();
834
+
835
+
836
+
837
+ _admobConfig = getAdMobConfig();
838
+
839
+
840
+
841
+
842
+
843
+ // Proceed only if ADMOB_ENABLED is true
844
+ if (_admobConfig.ADMOB_ENABLED) {
845
+ if (fileExists(androidPlatformPath)) {
846
+ updatePluginXml(_admobConfig);
847
+ }
848
+
849
+ if (fileExists(iosPlatformPath)) {
850
+ updateInfoPlist(_admobConfig);
851
+ }
852
+ }
853
+
854
+
855
+ } catch (error) {
856
+ console.error(error.message);
857
+ process.exit(1); // Stop execution if there's a critical error
858
+ }
859
+
860
+
861
+
862
+ validateAndroidBuildOptions();
863
+
864
+
865
+
866
+
867
+
868
+
869
+ // Check all the codeplays plugins version START
870
+
871
+
872
+ const readline = require('readline');
873
+
874
+
875
+ //const srcDir = path.join(__dirname, 'src');
876
+ const srcDir = path.join(process.cwd(), 'src');
877
+ let outdatedPlugins = [];
878
+
879
+ function parseVersion(ver) {
880
+ return ver.split('.').map(n => parseInt(n, 10));
881
+ }
882
+
883
+ function compareVersions(v1, v2) {
884
+ const [a1, b1] = parseVersion(v1);
885
+ const [a2, b2] = parseVersion(v2);
886
+ if (a1 !== a2) return a1 - a2;
887
+ return b1 - b2;
888
+ }
889
+
890
+ function walkSync(dir, filelist = []) {
891
+ fs.readdirSync(dir).forEach(file => {
892
+ const fullPath = path.join(dir, file);
893
+ const stat = fs.statSync(fullPath);
894
+ if (stat.isDirectory()) {
895
+ walkSync(fullPath, filelist);
896
+ } else {
897
+ filelist.push(fullPath);
898
+ }
899
+ });
900
+ return filelist;
901
+ }
902
+
903
+ function checkPlugins() {
904
+ const files = walkSync(srcDir);
905
+
906
+ for (const plugin of requiredPlugins) {
907
+ if (plugin.isFolder) {
908
+
909
+ let baseFolder = path.join(srcDir,'js', 'Ads'); // <- use known folder name
910
+
911
+ if (fs.existsSync(baseFolder)) {
912
+ const subDirs = fs.readdirSync(baseFolder)
913
+ .map(name => path.join(baseFolder, name))
914
+ .filter(p => fs.statSync(p).isDirectory());
915
+
916
+ for (const dir of subDirs) {
917
+ const relativePath = path.relative(srcDir, dir).replace(/\\/g, '/'); // e.g. Ads/IAP-2.0
918
+ const match = plugin.pattern.exec(relativePath);
919
+ if (match) {
920
+ const currentVersion = match[1];
921
+ if (compareVersions(currentVersion, plugin.minVersion) < 0) {
922
+ outdatedPlugins.push({
923
+ name: relativePath,
924
+ currentVersion,
925
+ requiredVersion: plugin.minVersion
926
+ });
927
+ }
928
+ }
929
+ }
930
+ }
931
+ continue;
932
+ }
933
+
934
+ const matchedFile = files.find(file => plugin.pattern.test(file));
935
+ if (matchedFile) {
936
+ const match = plugin.pattern.exec(matchedFile);
937
+ if (match) {
938
+ const currentVersion = match[1];
939
+ if (compareVersions(currentVersion, plugin.minVersion) < 0) {
940
+ outdatedPlugins.push({
941
+ name: path.relative(__dirname, matchedFile),
942
+ currentVersion,
943
+ requiredVersion: plugin.minVersion
944
+ });
945
+ }
946
+ }
947
+ }
948
+ }
949
+
950
+ if (outdatedPlugins.length > 0) {
951
+ console.log('\n❗ The following plugins are outdated:');
952
+ outdatedPlugins.forEach(p => {
953
+ console.log(` ❌ - ${p.name} (Current: ${p.currentVersion}, Required: ${p.requiredVersion})`);
954
+ });
955
+
956
+ const rl = readline.createInterface({
957
+ input: process.stdin,
958
+ output: process.stdout
959
+ });
960
+
961
+ rl.question('\nAre you sure you want to continue without updating these plugins? (y/n): ', answer => {
962
+ if (answer.toLowerCase() !== 'y') {
963
+ console.log('\n❌ Build cancelled due to outdated plugins.');
964
+ process.exit(1);
965
+ } else {
966
+ console.log('\n✅ Continuing build...');
967
+ rl.close();
968
+ }
969
+ });
970
+ } else {
971
+ console.log('✅ All plugin versions are up to date.');
972
+ }
973
+ }
974
+
975
+ // Run the validation
976
+ checkPlugins();
977
+
978
+
979
+
980
+
981
+ // Check all the codeplays plugins version START
982
+
983
+
984
+
985
+
986
+ // ====================================================================
987
+ // AUTO-ADD esbuild.drop: ['console','debugger'] to vite.config.js / mjs
988
+ // ====================================================================
989
+
990
+
991
+
992
+ const checkAndupdateDropInViteConfig = () => {
993
+
994
+ const possibleFiles = [
995
+ "vite.config.js",
996
+ "vite.config.mjs"
997
+ ];
998
+
999
+ // Detect existing config file
1000
+ const viteConfigPath = possibleFiles
1001
+ .map(file => path.join(process.cwd(), file))
1002
+ .find(filePath => fs.existsSync(filePath));
1003
+
1004
+ if (!viteConfigPath) {
1005
+ console.warn("⚠️ No vite config found. Skipping.");
1006
+ return;
1007
+ }
1008
+
1009
+ //console.log("📄 Using:", viteConfigPath.split("/").pop());
1010
+
1011
+ let viteContent = fs.readFileSync(viteConfigPath, "utf8");
1012
+
1013
+ // Skip if already exists
1014
+ if (/drop\s*:\s*\[.*['"]console['"].*\]/.test(viteContent)) {
1015
+ console.log("ℹ️ vite.config.(m)js already Updated. Skipping...");
1016
+ return;
1017
+ }
1018
+
1019
+ console.log("🔧 Adding esbuild.drop ...");
1020
+
1021
+ // If esbuild block exists
1022
+ if (/esbuild\s*:\s*{/.test(viteContent)) {
1023
+ viteContent = viteContent.replace(
1024
+ /esbuild\s*:\s*{([\s\S]*?)(^ {0,8})}/m,
1025
+ (full, inner, indent) => {
1026
+
1027
+ let lines = inner
1028
+ .split("\n")
1029
+ .map(l => l.trim())
1030
+ .filter(Boolean);
1031
+
1032
+ // Fix last comma
1033
+ if (lines.length > 0) {
1034
+ lines[lines.length - 1] =
1035
+ lines[lines.length - 1].replace(/,+$/, "") + ",";
1036
+ }
1037
+
1038
+ // Re-indent
1039
+ lines = lines.map(l => indent + " " + l);
1040
+
1041
+ // Add drop
1042
+ lines.push(`${indent} drop: ['console','debugger'],`);
1043
+
1044
+ return `esbuild: {\n${lines.join("\n")}\n${indent}}`;
1045
+ }
1046
+ );
1047
+ }
1048
+
1049
+ // If esbuild missing
1050
+ else {
1051
+ viteContent = viteContent.replace(
1052
+ /export default defineConfig\s*\(\s*{/,
1053
+ m => `${m}\n esbuild: {\n drop: ['console','debugger'],\n },`
1054
+ );
1055
+ }
1056
+
1057
+ fs.writeFileSync(viteConfigPath, viteContent, "utf8");
1058
+ console.log("✅ vite.config.(m)js Updated successfully.");
1059
+ };
1060
+
1061
+ checkAndupdateDropInViteConfig();
1062
+
1063
+
1064
+
1065
+
1066
+
1067
+
1068
+
1069
+
1070
+ const compareVersion = (v1, v2) => {
1071
+ const a = v1.split(".").map(Number);
1072
+ const b = v2.split(".").map(Number);
1073
+
1074
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
1075
+ const num1 = a[i] || 0;
1076
+ const num2 = b[i] || 0;
1077
+ if (num1 > num2) return 1;
1078
+ if (num1 < num2) return -1;
1079
+ }
1080
+ return 0;
1081
+ };
1082
+
1083
+
1084
+
1085
+
1086
+ const admobConfigPath = path.join('src', 'js','Ads', 'admob-ad-configuration.json');
1087
+
1088
+ const checkAdmobConfigurationProperty=()=>{
1089
+
1090
+
1091
+ if (!_admobConfig.ADMOB_ENABLED)
1092
+ {
1093
+ console.log("ℹ️ Admob is not enabled so 'admob-ad-configuration.json' checking is skipping...");
1094
+ return;
1095
+ }
1096
+
1097
+
1098
+ const REQUIRED_CONFIG_KEYS = [
1099
+ "isKidsApp",
1100
+ "isTesting",
1101
+ "isConsoleLogEnabled",
1102
+ "bannerEnabled",
1103
+ "interstitialEnabled",
1104
+ "appOpenEnabled",
1105
+ "rewardVideoEnabled",
1106
+ "rewardInterstitialEnabled",
1107
+ "collapsibleEnabled",
1108
+ "isLandScape",
1109
+ "overlappingHeight",
1110
+ "isOverlappingEnable",
1111
+ "bannerTypeAndroid",
1112
+ "bannerTypeiOS",
1113
+ "bannerTopSpaceColor",
1114
+ "interstitialLoadScreenTextColor",
1115
+ "interstitialLoadScreenBackgroundColor",
1116
+ "beforeBannerSpace",
1117
+ "whenShow",
1118
+ "minimumClick",
1119
+ "interstitialTimeOut",
1120
+ "interstitialFirstTimeOut",
1121
+ "appOpenAdsTimeOut",
1122
+ "maxRetryCount",
1123
+ "retrySecondsAr",
1124
+ "appOpenPerSession",
1125
+ "interstitialPerSession",
1126
+ "appOpenFirstTimeOut"
1127
+ ];
1128
+
1129
+
1130
+
1131
+
1132
+
1133
+ let admobConfigInJson;
1134
+
1135
+ try {
1136
+ admobConfigInJson = JSON.parse(readFileSync(admobConfigPath, "utf8"));
1137
+ } catch (err) {
1138
+ console.error("❌ Failed to read admob-ad-configuration.json", err);
1139
+ process.exit(1);
1140
+ }
1141
+
1142
+ // ✅ Validate config object exists
1143
+ if (!admobConfigInJson.config) {
1144
+ console.error('❌ "config" object is missing in admob-ad-configuration.json');
1145
+ process.exit(1);
1146
+ }
1147
+
1148
+
1149
+ const admobConfigMinVersion="1.4"
1150
+
1151
+ if (compareVersion(admobConfigInJson.VERSION, admobConfigMinVersion) < 0) {
1152
+ console.error(`❌ Please use at-least version ${admobConfigMinVersion} in "src/js/Ads/admob-ad-configuration.json"`);
1153
+ process.exit(1);
1154
+ }
1155
+
1156
+
1157
+ const config = admobConfigInJson.config;
1158
+
1159
+ // ✅ Find missing properties
1160
+ const missingKeys = REQUIRED_CONFIG_KEYS.filter(
1161
+ key => !(key in config)
1162
+ );
1163
+
1164
+
1165
+
1166
+ if (missingKeys.length > 0) {
1167
+ console.error("❌ Missing required configuration keys. Please check it in 'src/js/Ads/admob-ad-configuration.json'");
1168
+
1169
+ missingKeys.forEach(k => console.error(" - " + k));
1170
+ process.exit(1);
1171
+ }
1172
+
1173
+
1174
+ console.log('✅ All keys exist. in "admob-ad-configuration.json file" Configuration looks good.');
1175
+ }
1176
+
1177
+
1178
+ checkAdmobConfigurationProperty()
1179
+
1180
+
1181
+
1182
+