codeplay-common 1.8.1 → 1.8.3

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,831 +1,831 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const plist = require('plist');
4
-
5
-
6
- // Expected plugin list with minimum versions
7
- const requiredPlugins = [
8
- { pattern: /backbutton-(\d+\.\d+)\.js$/, minVersion: '1.4', required: true },
9
- { pattern: /common-(\d+\.\d+)\.js$/, minVersion: '4.0', required: true },
10
- { pattern: /localization_settings-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true },
11
- { pattern: /localization-(\d+\.\d+)\.js$/, minVersion: '1.3', required: true },
12
- { pattern: /localNotification-(\d+\.\d+)\.js$/, minVersion: '2.2', required: true },
13
- { pattern: /localNotification_AppSettings-(\d+\.\d+)\.js$/, minVersion: '1.0', required: true },
14
- { pattern: /onesignal-(\d+\.\d+)\.js$/, minVersion: '2.1', required: true },
15
- { pattern: /saveToGalleryAndSaveAnyFile-(\d+\.\d+)(-ios)?\.js$/, minVersion: '2.5', required: true },
16
- { pattern: /Ads[\/\\]IAP-(\d+\.\d+)$/, minVersion: '2.5', isFolder: true , required: true},
17
- { pattern: /Ads[\/\\]admob-emi-(\d+\.\d+)\.js$/, minVersion: '2.8', required: true }
18
- ];
19
-
20
-
21
-
22
-
23
-
24
-
25
- //Check codeplay-common latest version installed or not Start
26
- const { execSync } = require('child_process');
27
-
28
- function getInstalledVersion(packageName) {
29
- try {
30
- const packageJsonPath = path.join(process.cwd(), 'node_modules', packageName, 'package.json');
31
- if (fs.existsSync(packageJsonPath)) {
32
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
33
- return packageJson.version;
34
- }
35
- } catch (error) {
36
- return null;
37
- }
38
- return null;
39
- }
40
-
41
- function getLatestVersion(packageName) {
42
- try {
43
- return execSync(`npm view ${packageName} version`).toString().trim();
44
- } catch (error) {
45
- console.error(`Failed to fetch latest version for ${packageName}`);
46
- return null;
47
- }
48
- }
49
-
50
- function checkPackageVersion() {
51
- const packageName = 'codeplay-common';
52
- const installedVersion = getInstalledVersion(packageName);
53
- const latestVersion = getLatestVersion(packageName);
54
-
55
- if (!installedVersion) {
56
- console.error(`${packageName} is not installed. Please install it using "npm install ${packageName}".`);
57
- process.exit(1);
58
- }
59
-
60
- if (installedVersion !== latestVersion) {
61
- 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`);
62
- process.exit(1);
63
- }
64
-
65
- console.log(`${packageName} is up to date (version ${installedVersion}).`);
66
- }
67
-
68
- // Run package version check before executing the main script
69
- try {
70
- checkPackageVersion();
71
- } catch (error) {
72
- console.error(error.message);
73
- process.exit(1);
74
- }
75
-
76
- //Check codeplay-common latest version installed or not END
77
-
78
-
79
-
80
-
81
-
82
-
83
-
84
-
85
-
86
- //@Codemirror check and install/uninstall the packages START
87
- //const fs = require("fs");
88
- //const path = require("path");
89
- //const { execSync } = require("child_process");
90
-
91
- const baseDir = path.join(__dirname, "..", "src", "js");
92
-
93
- // Step 1: Find highest versioned folder like `editor-1.6`
94
- const editorDirs = fs.readdirSync(baseDir)
95
- .filter(name => /^editor-\d+\.\d+$/.test(name))
96
- .sort((a, b) => {
97
- const getVersion = str => str.match(/(\d+)\.(\d+)/).slice(1).map(Number);
98
- const [aMajor, aMinor] = getVersion(a);
99
- const [bMajor, bMinor] = getVersion(b);
100
- return bMajor - aMajor || bMinor - aMinor;
101
- });
102
-
103
- if (editorDirs.length === 0) {
104
-
105
- console.log("@Codemirror used editor(s) are not found")
106
- //console.error("❌ No editor-x.x folders found in src/js.");
107
- //process.exit(1);
108
- }
109
- else
110
- {
111
- const latestEditorDir = editorDirs[editorDirs.length - 1];
112
- const runJsPath = path.join(baseDir, latestEditorDir, "run.js");
113
-
114
- if (!fs.existsSync(runJsPath)) {
115
- console.error(`❌ run.js not found in ${latestEditorDir}`);
116
- process.exit(1);
117
- }
118
-
119
- // Step 2: Execute the run.js file
120
- console.log(`🚀 Executing ${runJsPath}...`);
121
- execSync(`node "${runJsPath}"`, { stdio: "inherit" });
122
- }
123
-
124
- //@Codemirror check and install/uninstall the packages END
125
-
126
-
127
-
128
-
129
-
130
-
131
-
132
-
133
-
134
-
135
-
136
-
137
- // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists START
138
-
139
- const os = require('os');
140
-
141
- const saveToGalleryAndSaveFileCheck_iOS = () => {
142
- const ROOT_DIR = path.resolve(__dirname, '../src');
143
-
144
- const IOS_FILE_REGEX = /(?:import|require)?\s*\(?['"].*saveToGalleryAndSaveAnyFile-\d+(\.\d+)?-ios\.js['"]\)?/;
145
- const ALLOWED_EXTENSIONS = ['.js', '.f7'];
146
- const isMac = os.platform() === 'darwin';
147
-
148
- let iosImportFound = false;
149
-
150
- function scanDirectory(dir) {
151
- const entries = fs.readdirSync(dir, { withFileTypes: true });
152
-
153
- for (let entry of entries) {
154
- const fullPath = path.join(dir, entry.name);
155
-
156
- if (entry.isDirectory()) {
157
- if (entry.name === 'node_modules') continue;
158
- scanDirectory(fullPath);
159
- } else if (
160
- entry.isFile() &&
161
- ALLOWED_EXTENSIONS.some(ext => fullPath.endsWith(ext))
162
- ) {
163
- const content = fs.readFileSync(fullPath, 'utf8');
164
- const matches = content.match(IOS_FILE_REGEX);
165
- if (matches) {
166
- iosImportFound = true;
167
- //console.error(`\n❌❌❌ BIG ERROR: iOS-specific import detected in: ${fullPath}`);
168
- //console.error(`🔍 Matched: ${matches[0]}\n`);
169
- if (!isMac) {
170
- console.error(`\n❌❌❌ BIG ERROR: iOS-specific import detected in: ${fullPath}`);
171
- console.error(`🚫 STOPPED: This file should not be imported in Android/Windows/Linux builds.\n`);
172
- process.exit(1);
173
- }
174
- }
175
- }
176
- }
177
- }
178
-
179
- // Check if src folder exists first
180
- if (!fs.existsSync(ROOT_DIR)) {
181
- console.warn(`⚠️ Warning: 'src' directory not found at: ${ROOT_DIR}`);
182
- return;
183
- }
184
-
185
- scanDirectory(ROOT_DIR);
186
-
187
- if (isMac && !iosImportFound) {
188
- console.warn(`\x1b[31m\n⚠️⚠️⚠️ WARNING: You're on macOS but no iOS-specific file (saveToGalleryAndSaveAnyFile-x.x-ios.js) was found.\x1b[0m`);
189
- console.warn(`👉 You may want to double-check your imports for the iOS platform.\n`);
190
- process.exit(1);
191
- } else if (isMac && iosImportFound) {
192
- console.log('✅ iOS file detected as expected for macOS.');
193
- } else if (!iosImportFound) {
194
- console.log('✅ No iOS-specific file imports detected for non-macOS.');
195
- }
196
- };
197
-
198
- saveToGalleryAndSaveFileCheck_iOS();
199
- // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists END
200
-
201
-
202
-
203
-
204
-
205
-
206
-
207
-
208
-
209
-
210
-
211
-
212
-
213
- /*
214
- // Clean up AppleDouble files (._*) created by macOS START
215
- if (process.platform === 'darwin') {
216
- try {
217
- console.log('🧹 Cleaning up AppleDouble files (._*)...');
218
- execSync(`find . -name '._*' -delete`);
219
- console.log('✅ AppleDouble files removed.');
220
- } catch (err) {
221
- console.warn('⚠️ Failed to remove AppleDouble files:', err.message);
222
- }
223
- } else {
224
- console.log('ℹ️ Skipping AppleDouble cleanup — not a macOS machine.');
225
- }
226
-
227
- // Clean up AppleDouble files (._*) created by macOS END
228
- */
229
-
230
-
231
-
232
-
233
-
234
-
235
- //In routes.js file check static import START
236
-
237
- const routesPath = path.join(process.cwd(), 'src', 'js', 'routes.js');
238
- const routesContent = fs.readFileSync(routesPath, 'utf-8');
239
-
240
- let inBlockComment = false;
241
- const lines = routesContent.split('\n');
242
-
243
- const allowedImport = `import HomePage from '../pages/home.f7';`;
244
- const badImportRegex = /^[ \t]*import\s+[\w{}*,\s]*\s+from\s+['"].+\.f7['"]\s*;/;
245
- const badImports = [];
246
-
247
- lines.forEach((line, index) => {
248
- const trimmed = line.trim();
249
-
250
- // Handle block comment start and end
251
- if (trimmed.startsWith('/*')) inBlockComment = true;
252
- if (inBlockComment && trimmed.endsWith('*/')) {
253
- inBlockComment = false;
254
- return;
255
- }
256
-
257
- // Skip if inside block comment or line comment
258
- if (inBlockComment || trimmed.startsWith('//')) return;
259
-
260
- // Match static .f7 import
261
- if (badImportRegex.test(trimmed) && trimmed !== allowedImport) {
262
- badImports.push({ line: trimmed, number: index + 1 });
263
- }
264
- });
265
-
266
- if (badImports.length > 0) {
267
- console.error('\n❌ ERROR: Detected disallowed static imports of .f7 files in routes.js\n');
268
- console.error(`⚠️ Only this static import is allowed:\n ${allowedImport}\n`);
269
- console.error(`🔧 Please convert other imports to async dynamic imports like this:\n`);
270
- console.error(`
271
-
272
- import HomePage from '../pages/home.f7';
273
-
274
- const routes = [
275
- {
276
- path: '/',
277
- component:HomePage,
278
- },
279
- {
280
- path: '/ProfilePage/',
281
- async async({ resolve }) {
282
- const page = await import('../pages/profile.f7');
283
- resolve({ component: page.default });
284
- },
285
- }]
286
- `);
287
-
288
- badImports.forEach(({ line, number }) => {
289
- console.error(`${number}: ${line}`);
290
- });
291
-
292
- process.exit(1);
293
- } else {
294
- console.log('✅ routes.js passed the .f7 import check.');
295
- }
296
-
297
- //In routes.js file check static import END
298
-
299
-
300
-
301
-
302
-
303
-
304
-
305
-
306
-
307
-
308
-
309
-
310
-
311
- // Check and change the "BridgeWebViewClient.java" file START
312
- /*
313
- For crash issue due to low memory problem, we need to modify the onRenderProcessGone method in BridgeWebViewClient.java.
314
- */
315
-
316
-
317
- const bridgeWebViewClientFilePath = path.join(process.cwd(), 'node_modules', '@capacitor/android/capacitor/src/main/java/com/getcapacitor', 'BridgeWebViewClient.java');
318
-
319
- // Read the file
320
- if (!fs.existsSync(bridgeWebViewClientFilePath)) {
321
- console.error('❌ Error: BridgeWebViewClient.java not found.');
322
- process.exit(1);
323
- }
324
-
325
- let fileContent = fs.readFileSync(bridgeWebViewClientFilePath, 'utf8');
326
-
327
- // Define old and new code
328
- const oldCodeStart = `@Override
329
- public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
330
- super.onRenderProcessGone(view, detail);
331
- boolean result = false;
332
-
333
- List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
334
- if (webViewListeners != null) {
335
- for (WebViewListener listener : bridge.getWebViewListeners()) {
336
- result = listener.onRenderProcessGone(view, detail) || result;
337
- }
338
- }
339
-
340
- return result;
341
- }`;
342
-
343
- const newCode = `@Override
344
- public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
345
- super.onRenderProcessGone(view, detail);
346
-
347
- boolean result = false;
348
-
349
- List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
350
- if (webViewListeners != null) {
351
- for (WebViewListener listener : bridge.getWebViewListeners()) {
352
- result = listener.onRenderProcessGone(view, detail) || result;
353
- }
354
- }
355
-
356
- if (!result) {
357
- // If no one handled it, handle it ourselves!
358
-
359
- /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
360
- if (detail.didCrash()) {
361
- //Log.e("CapacitorWebView", "WebView crashed internally!");
362
- } else {
363
- //Log.w("CapacitorWebView", "WebView was killed by system (low memory) internally!");
364
- }
365
- }*/
366
-
367
- view.post(() -> {
368
- Toast.makeText(view.getContext(), "Reloading due to low memory issue", Toast.LENGTH_SHORT).show();
369
- });
370
-
371
- view.reload(); // Safely reload WebView
372
-
373
- return true; // We handled it
374
- }
375
-
376
- return result;
377
- }`;
378
-
379
- // Step 1: Update method if needed
380
- let updated = false;
381
-
382
- if (fileContent.includes(oldCodeStart)) {
383
- console.log('✅ Found old onRenderProcessGone method. Replacing it...');
384
- fileContent = fileContent.replace(oldCodeStart, newCode);
385
- updated = true;
386
- } else if (fileContent.includes(newCode)) {
387
- console.log('ℹ️ Method already updated. No changes needed in "BridgeWebViewClient.java".');
388
- } else {
389
- console.error('❌ Error: Neither old nor new code found. Unexpected content.');
390
- process.exit(1);
391
- }
392
-
393
- // Step 2: Check and add import if missing
394
- const importToast = 'import android.widget.Toast;';
395
- if (!fileContent.includes(importToast)) {
396
- console.log('✅ Adding missing import for Toast...');
397
- const importRegex = /import\s+[^;]+;/g;
398
- const matches = [...fileContent.matchAll(importRegex)];
399
-
400
- if (matches.length > 0) {
401
- const lastImport = matches[matches.length - 1];
402
- const insertPosition = lastImport.index + lastImport[0].length;
403
- fileContent = fileContent.slice(0, insertPosition) + `\n${importToast}` + fileContent.slice(insertPosition);
404
- updated = true;
405
- } else {
406
- console.error('❌ Error: No import section found in file.');
407
- process.exit(1);
408
- }
409
- } else {
410
- console.log('ℹ️ Import for Toast already exists. No changes needed.');
411
- }
412
-
413
- // Step 3: Save if updated
414
- if (updated) {
415
- fs.writeFileSync(bridgeWebViewClientFilePath, fileContent, 'utf8');
416
- console.log('✅ File updated successfully.');
417
- } else {
418
- console.log('ℹ️ No changes needed.');
419
- }
420
-
421
-
422
-
423
-
424
- // Check and change the "BridgeWebViewClient.java" file END
425
-
426
-
427
-
428
-
429
-
430
-
431
-
432
-
433
-
434
- // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file START
435
-
436
- // Build the path dynamically like you requested
437
- const gradlePath = path.join(
438
- process.cwd(),
439
- 'android',
440
- 'build.gradle'
441
- );
442
-
443
- // Read the existing build.gradle
444
- let gradleContent = fs.readFileSync(gradlePath, 'utf8');
445
-
446
- // Add `ext.kotlin_version` if it's not already there
447
- if (!gradleContent.includes('ext.kotlin_version')) {
448
- gradleContent = gradleContent.replace(
449
- /buildscript\s*{/,
450
- `buildscript {\n ext.kotlin_version = '2.1.0'`
451
- );
452
- }
453
-
454
- // Add Kotlin classpath if it's not already there
455
- if (!gradleContent.includes('org.jetbrains.kotlin:kotlin-gradle-plugin')) {
456
- gradleContent = gradleContent.replace(
457
- /dependencies\s*{([\s\S]*?)classpath 'com.android.tools.build:gradle:8.7.2'/,
458
- `dependencies {\n classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")\n$1classpath 'com.android.tools.build:gradle:8.7.2'`
459
- );
460
- }
461
-
462
- // Write back the modified content
463
- fs.writeFileSync(gradlePath, gradleContent, 'utf8');
464
-
465
- console.log('✅ Kotlin version updated in build.gradle.');
466
-
467
- // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file END
468
-
469
-
470
-
471
-
472
-
473
-
474
-
475
-
476
-
477
-
478
- const configPath = path.join(process.cwd(), 'capacitor.config.json');
479
- const androidPlatformPath = path.join(process.cwd(), 'android');
480
- const iosPlatformPath = path.join(process.cwd(), 'ios');
481
- const pluginPath = path.join(process.cwd(), 'node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
482
- const infoPlistPath = path.join(process.cwd(), 'ios', 'App', 'App', 'Info.plist');
483
- const resourcesPath = path.join(process.cwd(), 'resources', 'res');
484
- const androidResPath = path.join(process.cwd(), 'android', 'app', 'src', 'main', 'res');
485
- const localNotificationsPluginPath = path.join(process.cwd(), 'node_modules', '@capacitor', 'local-notifications');
486
-
487
- function fileExists(filePath) {
488
- return fs.existsSync(filePath);
489
- }
490
-
491
- function copyFolderSync(source, target) {
492
- if (!fs.existsSync(target)) {
493
- fs.mkdirSync(target, { recursive: true });
494
- }
495
-
496
- fs.readdirSync(source).forEach(file => {
497
- const sourceFile = path.join(source, file);
498
- const targetFile = path.join(target, file);
499
-
500
- if (fs.lstatSync(sourceFile).isDirectory()) {
501
- copyFolderSync(sourceFile, targetFile);
502
- } else {
503
- fs.copyFileSync(sourceFile, targetFile);
504
- }
505
- });
506
- }
507
-
508
- function checkAndCopyResources() {
509
- if (fileExists(resourcesPath)) {
510
- copyFolderSync(resourcesPath, androidResPath);
511
- console.log('✅ Successfully copied resources/res to android/app/src/main/res.');
512
- } else {
513
- console.log('resources/res folder not found.');
514
-
515
- if (fileExists(localNotificationsPluginPath)) {
516
- throw new Error('❌ resources/res is required for @capacitor/local-notifications. Stopping execution.');
517
- }
518
- }
519
- }
520
-
521
-
522
-
523
- function getAdMobConfig() {
524
- if (!fileExists(configPath)) {
525
- throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
526
- }
527
-
528
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
529
- const admobConfig = config.plugins?.AdMob;
530
-
531
- if (!admobConfig) {
532
- throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
533
- }
534
-
535
- // Default to true if ADMOB_ENABLED is not specified
536
- const isEnabled = admobConfig.ADMOB_ENABLED !== false;
537
-
538
- if (!isEnabled) {
539
- return { ADMOB_ENABLED: false }; // Skip further validation
540
- }
541
-
542
- if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
543
- throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
544
- }
545
-
546
- return {
547
- ADMOB_ENABLED: true,
548
- APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
549
- APP_ID_IOS: admobConfig.APP_ID_IOS,
550
- USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
551
- };
552
- }
553
-
554
- function validateAndroidBuildOptions() {
555
-
556
-
557
- if (!fileExists(configPath)) {
558
- console.log('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
559
- process.exit(1);
560
- }
561
-
562
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
563
-
564
- const targetAppId=config.appId
565
-
566
- const buildOptions = config.android?.buildOptions;
567
-
568
- if (!buildOptions) {
569
- console.log('❌ Missing android.buildOptions in capacitor.config.json.');
570
- process.exit(1);
571
- }
572
-
573
- const requiredProps = [
574
- 'keystorePath',
575
- 'keystorePassword',
576
- 'keystoreAlias',
577
- 'keystoreAliasPassword',
578
- 'releaseType',
579
- 'signingType'
580
- ];
581
-
582
- const missing = requiredProps.filter(prop => !buildOptions[prop]);
583
-
584
- if (missing.length > 0) {
585
- console.log('❌ Missing properties android.buildOptions in capacitor.config.json.');
586
- process.exit(1);
587
- }
588
-
589
-
590
- const keystorePath=buildOptions.keystorePath
591
- const keyFileName = path.basename(keystorePath);
592
-
593
-
594
-
595
- const keystoreMap = {
596
- "gameskey.jks": [
597
- "com.cube.blaster",
598
- ],
599
- "htmleditorkeystoke.jks": [
600
- "com.HTML.AngularJS.Codeplay",
601
- "com.html.codeplay.pro",
602
- "com.bootstrap.code.play",
603
- "com.kids.learning.master"
604
- ]
605
- };
606
-
607
- // find which keystore is required for the given targetAppId
608
- let requiredKey = "newappskey.jks"; // default
609
- for (const [keyFile, appIds] of Object.entries(keystoreMap)) {
610
- if (appIds.includes(targetAppId)) {
611
- requiredKey = keyFile;
612
- break;
613
- }
614
- }
615
-
616
- // validate
617
- if (keyFileName !== requiredKey) {
618
- console.log(`❌ The keystore path is mismatched. Expected ${requiredKey} for ${targetAppId}, but got ${keyFileName}`);
619
- process.exit(1);
620
- }
621
-
622
-
623
-
624
-
625
-
626
- // optionally return them
627
- //return buildOptions;
628
- }
629
-
630
- function updatePluginXml(admobConfig) {
631
- if (!fileExists(pluginPath)) {
632
- console.error(' ❌ plugin.xml not found. Ensure the plugin is installed.');
633
- return;
634
- }
635
-
636
- let pluginContent = fs.readFileSync(pluginPath, 'utf8');
637
-
638
- pluginContent = pluginContent
639
- .replace(/<preference name="APP_ID_ANDROID" default=".*?" \/>/, `<preference name="APP_ID_ANDROID" default="${admobConfig.APP_ID_ANDROID}" />`)
640
- .replace(/<preference name="APP_ID_IOS" default=".*?" \/>/, `<preference name="APP_ID_IOS" default="${admobConfig.APP_ID_IOS}" />`);
641
-
642
- fs.writeFileSync(pluginPath, pluginContent, 'utf8');
643
- console.log('✅ AdMob IDs successfully updated in plugin.xml');
644
- }
645
-
646
- function updateInfoPlist(admobConfig) {
647
- if (!fileExists(infoPlistPath)) {
648
- console.error(' ❌ Info.plist not found. Ensure you have built the iOS project.');
649
- return;
650
- }
651
-
652
- const plistContent = fs.readFileSync(infoPlistPath, 'utf8');
653
- const plistData = plist.parse(plistContent);
654
-
655
- plistData.GADApplicationIdentifier = admobConfig.APP_ID_IOS;
656
- plistData.NSUserTrackingUsageDescription = 'This identifier will be used to deliver personalized ads to you.';
657
- plistData.GADDelayAppMeasurementInit = true;
658
-
659
- const updatedPlistContent = plist.build(plistData);
660
- fs.writeFileSync(infoPlistPath, updatedPlistContent, 'utf8');
661
- console.log('AdMob IDs and additional configurations successfully updated in Info.plist');
662
- }
663
-
664
- try {
665
- if (!fileExists(configPath)) {
666
- throw new Error(' ❌ capacitor.config.json not found. Skipping setup.');
667
- }
668
-
669
- if (!fileExists(androidPlatformPath) && !fileExists(iosPlatformPath)) {
670
- throw new Error('Neither Android nor iOS platforms are found. Ensure platforms are added to your Capacitor project.');
671
- }
672
-
673
- checkAndCopyResources();
674
-
675
- const admobConfig = getAdMobConfig();
676
-
677
-
678
-
679
-
680
- // Proceed only if ADMOB_ENABLED is true
681
- if (admobConfig.ADMOB_ENABLED) {
682
- if (fileExists(androidPlatformPath)) {
683
- updatePluginXml(admobConfig);
684
- }
685
-
686
- if (fileExists(iosPlatformPath)) {
687
- updateInfoPlist(admobConfig);
688
- }
689
- }
690
-
691
-
692
- } catch (error) {
693
- console.error(error.message);
694
- process.exit(1); // Stop execution if there's a critical error
695
- }
696
-
697
-
698
-
699
- validateAndroidBuildOptions();
700
-
701
-
702
-
703
-
704
-
705
-
706
- // Check all the codeplays plugins version START
707
-
708
-
709
- const readline = require('readline');
710
-
711
-
712
- //const srcDir = path.join(__dirname, 'src');
713
- const srcDir = path.join(process.cwd(), 'src');
714
- let outdatedPlugins = [];
715
-
716
- function parseVersion(ver) {
717
- return ver.split('.').map(n => parseInt(n, 10));
718
- }
719
-
720
- function compareVersions(v1, v2) {
721
- const [a1, b1] = parseVersion(v1);
722
- const [a2, b2] = parseVersion(v2);
723
- if (a1 !== a2) return a1 - a2;
724
- return b1 - b2;
725
- }
726
-
727
- function walkSync(dir, filelist = []) {
728
- fs.readdirSync(dir).forEach(file => {
729
- const fullPath = path.join(dir, file);
730
- const stat = fs.statSync(fullPath);
731
- if (stat.isDirectory()) {
732
- walkSync(fullPath, filelist);
733
- } else {
734
- filelist.push(fullPath);
735
- }
736
- });
737
- return filelist;
738
- }
739
-
740
- function checkPlugins() {
741
- const files = walkSync(srcDir);
742
-
743
- for (const plugin of requiredPlugins) {
744
- if (plugin.isFolder) {
745
-
746
- let baseFolder = path.join(srcDir,'js', 'Ads'); // <- use known folder name
747
-
748
- if (fs.existsSync(baseFolder)) {
749
- const subDirs = fs.readdirSync(baseFolder)
750
- .map(name => path.join(baseFolder, name))
751
- .filter(p => fs.statSync(p).isDirectory());
752
-
753
- for (const dir of subDirs) {
754
- const relativePath = path.relative(srcDir, dir).replace(/\\/g, '/'); // e.g. Ads/IAP-2.0
755
- const match = plugin.pattern.exec(relativePath);
756
- if (match) {
757
- const currentVersion = match[1];
758
- if (compareVersions(currentVersion, plugin.minVersion) < 0) {
759
- outdatedPlugins.push({
760
- name: relativePath,
761
- currentVersion,
762
- requiredVersion: plugin.minVersion
763
- });
764
- }
765
- }
766
- }
767
- }
768
- continue;
769
- }
770
-
771
- const matchedFile = files.find(file => plugin.pattern.test(file));
772
- if (matchedFile) {
773
- const match = plugin.pattern.exec(matchedFile);
774
- if (match) {
775
- const currentVersion = match[1];
776
- if (compareVersions(currentVersion, plugin.minVersion) < 0) {
777
- outdatedPlugins.push({
778
- name: path.relative(__dirname, matchedFile),
779
- currentVersion,
780
- requiredVersion: plugin.minVersion
781
- });
782
- }
783
- }
784
- }
785
- }
786
-
787
- if (outdatedPlugins.length > 0) {
788
- console.log('\n❗ The following plugins are outdated:');
789
- outdatedPlugins.forEach(p => {
790
- console.log(` ❌ - ${p.name} (Current: ${p.currentVersion}, Required: ${p.requiredVersion})`);
791
- });
792
-
793
- const rl = readline.createInterface({
794
- input: process.stdin,
795
- output: process.stdout
796
- });
797
-
798
- rl.question('\nAre you sure you want to continue without updating these plugins? (y/n): ', answer => {
799
- if (answer.toLowerCase() !== 'y') {
800
- console.log('\n❌ Build cancelled due to outdated plugins.');
801
- process.exit(1);
802
- } else {
803
- console.log('\n✅ Continuing build...');
804
- rl.close();
805
- }
806
- });
807
- } else {
808
- console.log('✅ All plugin versions are up to date.');
809
- }
810
- }
811
-
812
- // Run the validation
813
- checkPlugins();
814
-
815
-
816
-
817
-
818
- // Check all the codeplays plugins version START
819
-
820
-
821
-
822
-
823
-
824
-
825
-
826
-
827
-
828
-
829
-
830
-
831
-
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const plist = require('plist');
4
+
5
+
6
+ // Expected plugin list with minimum versions
7
+ const requiredPlugins = [
8
+ { pattern: /backbutton-(\d+\.\d+)\.js$/, minVersion: '1.4', required: true },
9
+ { pattern: /common-(\d+\.\d+)\.js$/, minVersion: '4.0', required: true },
10
+ { pattern: /localization_settings-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true },
11
+ { pattern: /localization-(\d+\.\d+)\.js$/, minVersion: '1.3', required: true },
12
+ { pattern: /localNotification-(\d+\.\d+)\.js$/, minVersion: '2.2', required: true },
13
+ { pattern: /localNotification_AppSettings-(\d+\.\d+)\.js$/, minVersion: '1.0', required: true },
14
+ { pattern: /onesignal-(\d+\.\d+)\.js$/, minVersion: '2.1', required: true },
15
+ { pattern: /saveToGalleryAndSaveAnyFile-(\d+\.\d+)(-ios)?\.js$/, minVersion: '2.5', required: true },
16
+ { pattern: /Ads[\/\\]IAP-(\d+\.\d+)$/, minVersion: '2.5', isFolder: true , required: true},
17
+ { pattern: /Ads[\/\\]admob-emi-(\d+\.\d+)\.js$/, minVersion: '2.8', required: true }
18
+ ];
19
+
20
+
21
+
22
+
23
+
24
+
25
+ //Check codeplay-common latest version installed or not Start
26
+ const { execSync } = require('child_process');
27
+
28
+ function getInstalledVersion(packageName) {
29
+ try {
30
+ const packageJsonPath = path.join(process.cwd(), 'node_modules', packageName, 'package.json');
31
+ if (fs.existsSync(packageJsonPath)) {
32
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
33
+ return packageJson.version;
34
+ }
35
+ } catch (error) {
36
+ return null;
37
+ }
38
+ return null;
39
+ }
40
+
41
+ function getLatestVersion(packageName) {
42
+ try {
43
+ return execSync(`npm view ${packageName} version`).toString().trim();
44
+ } catch (error) {
45
+ console.error(`Failed to fetch latest version for ${packageName}`);
46
+ return null;
47
+ }
48
+ }
49
+
50
+ function checkPackageVersion() {
51
+ const packageName = 'codeplay-common';
52
+ const installedVersion = getInstalledVersion(packageName);
53
+ const latestVersion = getLatestVersion(packageName);
54
+
55
+ if (!installedVersion) {
56
+ console.error(`${packageName} is not installed. Please install it using "npm install ${packageName}".`);
57
+ process.exit(1);
58
+ }
59
+
60
+ if (installedVersion !== latestVersion) {
61
+ 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`);
62
+ process.exit(1);
63
+ }
64
+
65
+ console.log(`${packageName} is up to date (version ${installedVersion}).`);
66
+ }
67
+
68
+ // Run package version check before executing the main script
69
+ try {
70
+ checkPackageVersion();
71
+ } catch (error) {
72
+ console.error(error.message);
73
+ process.exit(1);
74
+ }
75
+
76
+ //Check codeplay-common latest version installed or not END
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+ //@Codemirror check and install/uninstall the packages START
87
+ //const fs = require("fs");
88
+ //const path = require("path");
89
+ //const { execSync } = require("child_process");
90
+
91
+ const baseDir = path.join(__dirname, "..", "src", "js");
92
+
93
+ // Step 1: Find highest versioned folder like `editor-1.6`
94
+ const editorDirs = fs.readdirSync(baseDir)
95
+ .filter(name => /^editor-\d+\.\d+$/.test(name))
96
+ .sort((a, b) => {
97
+ const getVersion = str => str.match(/(\d+)\.(\d+)/).slice(1).map(Number);
98
+ const [aMajor, aMinor] = getVersion(a);
99
+ const [bMajor, bMinor] = getVersion(b);
100
+ return bMajor - aMajor || bMinor - aMinor;
101
+ });
102
+
103
+ if (editorDirs.length === 0) {
104
+
105
+ console.log("@Codemirror used editor(s) are not found")
106
+ //console.error("❌ No editor-x.x folders found in src/js.");
107
+ //process.exit(1);
108
+ }
109
+ else
110
+ {
111
+ const latestEditorDir = editorDirs[editorDirs.length - 1];
112
+ const runJsPath = path.join(baseDir, latestEditorDir, "run.js");
113
+
114
+ if (!fs.existsSync(runJsPath)) {
115
+ console.error(`❌ run.js not found in ${latestEditorDir}`);
116
+ process.exit(1);
117
+ }
118
+
119
+ // Step 2: Execute the run.js file
120
+ console.log(`🚀 Executing ${runJsPath}...`);
121
+ execSync(`node "${runJsPath}"`, { stdio: "inherit" });
122
+ }
123
+
124
+ //@Codemirror check and install/uninstall the packages END
125
+
126
+
127
+
128
+
129
+
130
+
131
+
132
+
133
+
134
+
135
+
136
+
137
+ // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists START
138
+
139
+ const os = require('os');
140
+
141
+ const saveToGalleryAndSaveFileCheck_iOS = () => {
142
+ const ROOT_DIR = path.resolve(__dirname, '../src');
143
+
144
+ const IOS_FILE_REGEX = /(?:import|require)?\s*\(?['"].*saveToGalleryAndSaveAnyFile-\d+(\.\d+)?-ios\.js['"]\)?/;
145
+ const ALLOWED_EXTENSIONS = ['.js', '.f7'];
146
+ const isMac = os.platform() === 'darwin';
147
+
148
+ let iosImportFound = false;
149
+
150
+ function scanDirectory(dir) {
151
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
152
+
153
+ for (let entry of entries) {
154
+ const fullPath = path.join(dir, entry.name);
155
+
156
+ if (entry.isDirectory()) {
157
+ if (entry.name === 'node_modules') continue;
158
+ scanDirectory(fullPath);
159
+ } else if (
160
+ entry.isFile() &&
161
+ ALLOWED_EXTENSIONS.some(ext => fullPath.endsWith(ext))
162
+ ) {
163
+ const content = fs.readFileSync(fullPath, 'utf8');
164
+ const matches = content.match(IOS_FILE_REGEX);
165
+ if (matches) {
166
+ iosImportFound = true;
167
+ //console.error(`\n❌❌❌ BIG ERROR: iOS-specific import detected in: ${fullPath}`);
168
+ //console.error(`🔍 Matched: ${matches[0]}\n`);
169
+ if (!isMac) {
170
+ console.error(`\n❌❌❌ BIG ERROR: iOS-specific import detected in: ${fullPath}`);
171
+ console.error(`🚫 STOPPED: This file should not be imported in Android/Windows/Linux builds.\n`);
172
+ process.exit(1);
173
+ }
174
+ }
175
+ }
176
+ }
177
+ }
178
+
179
+ // Check if src folder exists first
180
+ if (!fs.existsSync(ROOT_DIR)) {
181
+ console.warn(`⚠️ Warning: 'src' directory not found at: ${ROOT_DIR}`);
182
+ return;
183
+ }
184
+
185
+ scanDirectory(ROOT_DIR);
186
+
187
+ if (isMac && !iosImportFound) {
188
+ console.warn(`\x1b[31m\n⚠️⚠️⚠️ WARNING: You're on macOS but no iOS-specific file (saveToGalleryAndSaveAnyFile-x.x-ios.js) was found.\x1b[0m`);
189
+ console.warn(`👉 You may want to double-check your imports for the iOS platform.\n`);
190
+ process.exit(1);
191
+ } else if (isMac && iosImportFound) {
192
+ console.log('✅ iOS file detected as expected for macOS.');
193
+ } else if (!iosImportFound) {
194
+ console.log('✅ No iOS-specific file imports detected for non-macOS.');
195
+ }
196
+ };
197
+
198
+ saveToGalleryAndSaveFileCheck_iOS();
199
+ // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists END
200
+
201
+
202
+
203
+
204
+
205
+
206
+
207
+
208
+
209
+
210
+
211
+
212
+
213
+ /*
214
+ // Clean up AppleDouble files (._*) created by macOS START
215
+ if (process.platform === 'darwin') {
216
+ try {
217
+ console.log('🧹 Cleaning up AppleDouble files (._*)...');
218
+ execSync(`find . -name '._*' -delete`);
219
+ console.log('✅ AppleDouble files removed.');
220
+ } catch (err) {
221
+ console.warn('⚠️ Failed to remove AppleDouble files:', err.message);
222
+ }
223
+ } else {
224
+ console.log('ℹ️ Skipping AppleDouble cleanup — not a macOS machine.');
225
+ }
226
+
227
+ // Clean up AppleDouble files (._*) created by macOS END
228
+ */
229
+
230
+
231
+
232
+
233
+
234
+
235
+ //In routes.js file check static import START
236
+
237
+ const routesPath = path.join(process.cwd(), 'src', 'js', 'routes.js');
238
+ const routesContent = fs.readFileSync(routesPath, 'utf-8');
239
+
240
+ let inBlockComment = false;
241
+ const lines = routesContent.split('\n');
242
+
243
+ const allowedImport = `import HomePage from '../pages/home.f7';`;
244
+ const badImportRegex = /^[ \t]*import\s+[\w{}*,\s]*\s+from\s+['"].+\.f7['"]\s*;/;
245
+ const badImports = [];
246
+
247
+ lines.forEach((line, index) => {
248
+ const trimmed = line.trim();
249
+
250
+ // Handle block comment start and end
251
+ if (trimmed.startsWith('/*')) inBlockComment = true;
252
+ if (inBlockComment && trimmed.endsWith('*/')) {
253
+ inBlockComment = false;
254
+ return;
255
+ }
256
+
257
+ // Skip if inside block comment or line comment
258
+ if (inBlockComment || trimmed.startsWith('//')) return;
259
+
260
+ // Match static .f7 import
261
+ if (badImportRegex.test(trimmed) && trimmed !== allowedImport) {
262
+ badImports.push({ line: trimmed, number: index + 1 });
263
+ }
264
+ });
265
+
266
+ if (badImports.length > 0) {
267
+ console.error('\n❌ ERROR: Detected disallowed static imports of .f7 files in routes.js\n');
268
+ console.error(`⚠️ Only this static import is allowed:\n ${allowedImport}\n`);
269
+ console.error(`🔧 Please convert other imports to async dynamic imports like this:\n`);
270
+ console.error(`
271
+
272
+ import HomePage from '../pages/home.f7';
273
+
274
+ const routes = [
275
+ {
276
+ path: '/',
277
+ component:HomePage,
278
+ },
279
+ {
280
+ path: '/ProfilePage/',
281
+ async async({ resolve }) {
282
+ const page = await import('../pages/profile.f7');
283
+ resolve({ component: page.default });
284
+ },
285
+ }]
286
+ `);
287
+
288
+ badImports.forEach(({ line, number }) => {
289
+ console.error(`${number}: ${line}`);
290
+ });
291
+
292
+ process.exit(1);
293
+ } else {
294
+ console.log('✅ routes.js passed the .f7 import check.');
295
+ }
296
+
297
+ //In routes.js file check static import END
298
+
299
+
300
+
301
+
302
+
303
+
304
+
305
+
306
+
307
+
308
+
309
+
310
+
311
+ // Check and change the "BridgeWebViewClient.java" file START
312
+ /*
313
+ For crash issue due to low memory problem, we need to modify the onRenderProcessGone method in BridgeWebViewClient.java.
314
+ */
315
+
316
+
317
+ const bridgeWebViewClientFilePath = path.join(process.cwd(), 'node_modules', '@capacitor/android/capacitor/src/main/java/com/getcapacitor', 'BridgeWebViewClient.java');
318
+
319
+ // Read the file
320
+ if (!fs.existsSync(bridgeWebViewClientFilePath)) {
321
+ console.error('❌ Error: BridgeWebViewClient.java not found.');
322
+ process.exit(1);
323
+ }
324
+
325
+ let fileContent = fs.readFileSync(bridgeWebViewClientFilePath, 'utf8');
326
+
327
+ // Define old and new code
328
+ const oldCodeStart = `@Override
329
+ public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
330
+ super.onRenderProcessGone(view, detail);
331
+ boolean result = false;
332
+
333
+ List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
334
+ if (webViewListeners != null) {
335
+ for (WebViewListener listener : bridge.getWebViewListeners()) {
336
+ result = listener.onRenderProcessGone(view, detail) || result;
337
+ }
338
+ }
339
+
340
+ return result;
341
+ }`;
342
+
343
+ const newCode = `@Override
344
+ public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
345
+ super.onRenderProcessGone(view, detail);
346
+
347
+ boolean result = false;
348
+
349
+ List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
350
+ if (webViewListeners != null) {
351
+ for (WebViewListener listener : bridge.getWebViewListeners()) {
352
+ result = listener.onRenderProcessGone(view, detail) || result;
353
+ }
354
+ }
355
+
356
+ if (!result) {
357
+ // If no one handled it, handle it ourselves!
358
+
359
+ /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
360
+ if (detail.didCrash()) {
361
+ //Log.e("CapacitorWebView", "WebView crashed internally!");
362
+ } else {
363
+ //Log.w("CapacitorWebView", "WebView was killed by system (low memory) internally!");
364
+ }
365
+ }*/
366
+
367
+ view.post(() -> {
368
+ Toast.makeText(view.getContext(), "Reloading due to low memory issue", Toast.LENGTH_SHORT).show();
369
+ });
370
+
371
+ view.reload(); // Safely reload WebView
372
+
373
+ return true; // We handled it
374
+ }
375
+
376
+ return result;
377
+ }`;
378
+
379
+ // Step 1: Update method if needed
380
+ let updated = false;
381
+
382
+ if (fileContent.includes(oldCodeStart)) {
383
+ console.log('✅ Found old onRenderProcessGone method. Replacing it...');
384
+ fileContent = fileContent.replace(oldCodeStart, newCode);
385
+ updated = true;
386
+ } else if (fileContent.includes(newCode)) {
387
+ console.log('ℹ️ Method already updated. No changes needed in "BridgeWebViewClient.java".');
388
+ } else {
389
+ console.error('❌ Error: Neither old nor new code found. Unexpected content.');
390
+ process.exit(1);
391
+ }
392
+
393
+ // Step 2: Check and add import if missing
394
+ const importToast = 'import android.widget.Toast;';
395
+ if (!fileContent.includes(importToast)) {
396
+ console.log('✅ Adding missing import for Toast...');
397
+ const importRegex = /import\s+[^;]+;/g;
398
+ const matches = [...fileContent.matchAll(importRegex)];
399
+
400
+ if (matches.length > 0) {
401
+ const lastImport = matches[matches.length - 1];
402
+ const insertPosition = lastImport.index + lastImport[0].length;
403
+ fileContent = fileContent.slice(0, insertPosition) + `\n${importToast}` + fileContent.slice(insertPosition);
404
+ updated = true;
405
+ } else {
406
+ console.error('❌ Error: No import section found in file.');
407
+ process.exit(1);
408
+ }
409
+ } else {
410
+ console.log('ℹ️ Import for Toast already exists. No changes needed.');
411
+ }
412
+
413
+ // Step 3: Save if updated
414
+ if (updated) {
415
+ fs.writeFileSync(bridgeWebViewClientFilePath, fileContent, 'utf8');
416
+ console.log('✅ File updated successfully.');
417
+ } else {
418
+ console.log('ℹ️ No changes needed.');
419
+ }
420
+
421
+
422
+
423
+
424
+ // Check and change the "BridgeWebViewClient.java" file END
425
+
426
+
427
+
428
+
429
+
430
+
431
+
432
+
433
+
434
+ // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file START
435
+
436
+ // Build the path dynamically like you requested
437
+ const gradlePath = path.join(
438
+ process.cwd(),
439
+ 'android',
440
+ 'build.gradle'
441
+ );
442
+
443
+ // Read the existing build.gradle
444
+ let gradleContent = fs.readFileSync(gradlePath, 'utf8');
445
+
446
+ // Add `ext.kotlin_version` if it's not already there
447
+ if (!gradleContent.includes('ext.kotlin_version')) {
448
+ gradleContent = gradleContent.replace(
449
+ /buildscript\s*{/,
450
+ `buildscript {\n ext.kotlin_version = '2.1.0'`
451
+ );
452
+ }
453
+
454
+ // Add Kotlin classpath if it's not already there
455
+ if (!gradleContent.includes('org.jetbrains.kotlin:kotlin-gradle-plugin')) {
456
+ gradleContent = gradleContent.replace(
457
+ /dependencies\s*{([\s\S]*?)classpath 'com.android.tools.build:gradle:8.7.2'/,
458
+ `dependencies {\n classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")\n$1classpath 'com.android.tools.build:gradle:8.7.2'`
459
+ );
460
+ }
461
+
462
+ // Write back the modified content
463
+ fs.writeFileSync(gradlePath, gradleContent, 'utf8');
464
+
465
+ console.log('✅ Kotlin version updated in build.gradle.');
466
+
467
+ // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file END
468
+
469
+
470
+
471
+
472
+
473
+
474
+
475
+
476
+
477
+
478
+ const configPath = path.join(process.cwd(), 'capacitor.config.json');
479
+ const androidPlatformPath = path.join(process.cwd(), 'android');
480
+ const iosPlatformPath = path.join(process.cwd(), 'ios');
481
+ const pluginPath = path.join(process.cwd(), 'node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
482
+ const infoPlistPath = path.join(process.cwd(), 'ios', 'App', 'App', 'Info.plist');
483
+ const resourcesPath = path.join(process.cwd(), 'resources', 'res');
484
+ const androidResPath = path.join(process.cwd(), 'android', 'app', 'src', 'main', 'res');
485
+ const localNotificationsPluginPath = path.join(process.cwd(), 'node_modules', '@capacitor', 'local-notifications');
486
+
487
+ function fileExists(filePath) {
488
+ return fs.existsSync(filePath);
489
+ }
490
+
491
+ function copyFolderSync(source, target) {
492
+ if (!fs.existsSync(target)) {
493
+ fs.mkdirSync(target, { recursive: true });
494
+ }
495
+
496
+ fs.readdirSync(source).forEach(file => {
497
+ const sourceFile = path.join(source, file);
498
+ const targetFile = path.join(target, file);
499
+
500
+ if (fs.lstatSync(sourceFile).isDirectory()) {
501
+ copyFolderSync(sourceFile, targetFile);
502
+ } else {
503
+ fs.copyFileSync(sourceFile, targetFile);
504
+ }
505
+ });
506
+ }
507
+
508
+ function checkAndCopyResources() {
509
+ if (fileExists(resourcesPath)) {
510
+ copyFolderSync(resourcesPath, androidResPath);
511
+ console.log('✅ Successfully copied resources/res to android/app/src/main/res.');
512
+ } else {
513
+ console.log('resources/res folder not found.');
514
+
515
+ if (fileExists(localNotificationsPluginPath)) {
516
+ throw new Error('❌ resources/res is required for @capacitor/local-notifications. Stopping execution.');
517
+ }
518
+ }
519
+ }
520
+
521
+
522
+
523
+ function getAdMobConfig() {
524
+ if (!fileExists(configPath)) {
525
+ throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
526
+ }
527
+
528
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
529
+ const admobConfig = config.plugins?.AdMob;
530
+
531
+ if (!admobConfig) {
532
+ throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
533
+ }
534
+
535
+ // Default to true if ADMOB_ENABLED is not specified
536
+ const isEnabled = admobConfig.ADMOB_ENABLED !== false;
537
+
538
+ if (!isEnabled) {
539
+ return { ADMOB_ENABLED: false }; // Skip further validation
540
+ }
541
+
542
+ if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
543
+ throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
544
+ }
545
+
546
+ return {
547
+ ADMOB_ENABLED: true,
548
+ APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
549
+ APP_ID_IOS: admobConfig.APP_ID_IOS,
550
+ USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
551
+ };
552
+ }
553
+
554
+ function validateAndroidBuildOptions() {
555
+
556
+
557
+ if (!fileExists(configPath)) {
558
+ console.log('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
559
+ process.exit(1);
560
+ }
561
+
562
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
563
+
564
+ const targetAppId=config.appId
565
+
566
+ const buildOptions = config.android?.buildOptions;
567
+
568
+ if (!buildOptions) {
569
+ console.log('❌ Missing android.buildOptions in capacitor.config.json.');
570
+ process.exit(1);
571
+ }
572
+
573
+ const requiredProps = [
574
+ 'keystorePath',
575
+ 'keystorePassword',
576
+ 'keystoreAlias',
577
+ 'keystoreAliasPassword',
578
+ 'releaseType',
579
+ 'signingType'
580
+ ];
581
+
582
+ const missing = requiredProps.filter(prop => !buildOptions[prop]);
583
+
584
+ if (missing.length > 0) {
585
+ console.log('❌ Missing properties android.buildOptions in capacitor.config.json.');
586
+ process.exit(1);
587
+ }
588
+
589
+
590
+ const keystorePath=buildOptions.keystorePath
591
+ const keyFileName = path.basename(keystorePath);
592
+
593
+
594
+
595
+ const keystoreMap = {
596
+ "gameskey.jks": [
597
+ "com.cube.blaster",
598
+ ],
599
+ "htmleditorkeystoke.jks": [
600
+ "com.HTML.AngularJS.Codeplay",
601
+ "com.html.codeplay.pro",
602
+ "com.bootstrap.code.play",
603
+ "com.kids.learning.master"
604
+ ]
605
+ };
606
+
607
+ // find which keystore is required for the given targetAppId
608
+ let requiredKey = "newappskey.jks"; // default
609
+ for (const [keyFile, appIds] of Object.entries(keystoreMap)) {
610
+ if (appIds.includes(targetAppId)) {
611
+ requiredKey = keyFile;
612
+ break;
613
+ }
614
+ }
615
+
616
+ // validate
617
+ if (keyFileName !== requiredKey) {
618
+ console.log(`❌ The keystore path is mismatched. Expected ${requiredKey} for ${targetAppId}, but got ${keyFileName}`);
619
+ process.exit(1);
620
+ }
621
+
622
+
623
+
624
+
625
+
626
+ // optionally return them
627
+ //return buildOptions;
628
+ }
629
+
630
+ function updatePluginXml(admobConfig) {
631
+ if (!fileExists(pluginPath)) {
632
+ console.error(' ❌ plugin.xml not found. Ensure the plugin is installed.');
633
+ return;
634
+ }
635
+
636
+ let pluginContent = fs.readFileSync(pluginPath, 'utf8');
637
+
638
+ pluginContent = pluginContent
639
+ .replace(/<preference name="APP_ID_ANDROID" default=".*?" \/>/, `<preference name="APP_ID_ANDROID" default="${admobConfig.APP_ID_ANDROID}" />`)
640
+ .replace(/<preference name="APP_ID_IOS" default=".*?" \/>/, `<preference name="APP_ID_IOS" default="${admobConfig.APP_ID_IOS}" />`);
641
+
642
+ fs.writeFileSync(pluginPath, pluginContent, 'utf8');
643
+ console.log('✅ AdMob IDs successfully updated in plugin.xml');
644
+ }
645
+
646
+ function updateInfoPlist(admobConfig) {
647
+ if (!fileExists(infoPlistPath)) {
648
+ console.error(' ❌ Info.plist not found. Ensure you have built the iOS project.');
649
+ return;
650
+ }
651
+
652
+ const plistContent = fs.readFileSync(infoPlistPath, 'utf8');
653
+ const plistData = plist.parse(plistContent);
654
+
655
+ plistData.GADApplicationIdentifier = admobConfig.APP_ID_IOS;
656
+ plistData.NSUserTrackingUsageDescription = 'This identifier will be used to deliver personalized ads to you.';
657
+ plistData.GADDelayAppMeasurementInit = true;
658
+
659
+ const updatedPlistContent = plist.build(plistData);
660
+ fs.writeFileSync(infoPlistPath, updatedPlistContent, 'utf8');
661
+ console.log('AdMob IDs and additional configurations successfully updated in Info.plist');
662
+ }
663
+
664
+ try {
665
+ if (!fileExists(configPath)) {
666
+ throw new Error(' ❌ capacitor.config.json not found. Skipping setup.');
667
+ }
668
+
669
+ if (!fileExists(androidPlatformPath) && !fileExists(iosPlatformPath)) {
670
+ throw new Error('Neither Android nor iOS platforms are found. Ensure platforms are added to your Capacitor project.');
671
+ }
672
+
673
+ checkAndCopyResources();
674
+
675
+ const admobConfig = getAdMobConfig();
676
+
677
+
678
+
679
+
680
+ // Proceed only if ADMOB_ENABLED is true
681
+ if (admobConfig.ADMOB_ENABLED) {
682
+ if (fileExists(androidPlatformPath)) {
683
+ updatePluginXml(admobConfig);
684
+ }
685
+
686
+ if (fileExists(iosPlatformPath)) {
687
+ updateInfoPlist(admobConfig);
688
+ }
689
+ }
690
+
691
+
692
+ } catch (error) {
693
+ console.error(error.message);
694
+ process.exit(1); // Stop execution if there's a critical error
695
+ }
696
+
697
+
698
+
699
+ validateAndroidBuildOptions();
700
+
701
+
702
+
703
+
704
+
705
+
706
+ // Check all the codeplays plugins version START
707
+
708
+
709
+ const readline = require('readline');
710
+
711
+
712
+ //const srcDir = path.join(__dirname, 'src');
713
+ const srcDir = path.join(process.cwd(), 'src');
714
+ let outdatedPlugins = [];
715
+
716
+ function parseVersion(ver) {
717
+ return ver.split('.').map(n => parseInt(n, 10));
718
+ }
719
+
720
+ function compareVersions(v1, v2) {
721
+ const [a1, b1] = parseVersion(v1);
722
+ const [a2, b2] = parseVersion(v2);
723
+ if (a1 !== a2) return a1 - a2;
724
+ return b1 - b2;
725
+ }
726
+
727
+ function walkSync(dir, filelist = []) {
728
+ fs.readdirSync(dir).forEach(file => {
729
+ const fullPath = path.join(dir, file);
730
+ const stat = fs.statSync(fullPath);
731
+ if (stat.isDirectory()) {
732
+ walkSync(fullPath, filelist);
733
+ } else {
734
+ filelist.push(fullPath);
735
+ }
736
+ });
737
+ return filelist;
738
+ }
739
+
740
+ function checkPlugins() {
741
+ const files = walkSync(srcDir);
742
+
743
+ for (const plugin of requiredPlugins) {
744
+ if (plugin.isFolder) {
745
+
746
+ let baseFolder = path.join(srcDir,'js', 'Ads'); // <- use known folder name
747
+
748
+ if (fs.existsSync(baseFolder)) {
749
+ const subDirs = fs.readdirSync(baseFolder)
750
+ .map(name => path.join(baseFolder, name))
751
+ .filter(p => fs.statSync(p).isDirectory());
752
+
753
+ for (const dir of subDirs) {
754
+ const relativePath = path.relative(srcDir, dir).replace(/\\/g, '/'); // e.g. Ads/IAP-2.0
755
+ const match = plugin.pattern.exec(relativePath);
756
+ if (match) {
757
+ const currentVersion = match[1];
758
+ if (compareVersions(currentVersion, plugin.minVersion) < 0) {
759
+ outdatedPlugins.push({
760
+ name: relativePath,
761
+ currentVersion,
762
+ requiredVersion: plugin.minVersion
763
+ });
764
+ }
765
+ }
766
+ }
767
+ }
768
+ continue;
769
+ }
770
+
771
+ const matchedFile = files.find(file => plugin.pattern.test(file));
772
+ if (matchedFile) {
773
+ const match = plugin.pattern.exec(matchedFile);
774
+ if (match) {
775
+ const currentVersion = match[1];
776
+ if (compareVersions(currentVersion, plugin.minVersion) < 0) {
777
+ outdatedPlugins.push({
778
+ name: path.relative(__dirname, matchedFile),
779
+ currentVersion,
780
+ requiredVersion: plugin.minVersion
781
+ });
782
+ }
783
+ }
784
+ }
785
+ }
786
+
787
+ if (outdatedPlugins.length > 0) {
788
+ console.log('\n❗ The following plugins are outdated:');
789
+ outdatedPlugins.forEach(p => {
790
+ console.log(` ❌ - ${p.name} (Current: ${p.currentVersion}, Required: ${p.requiredVersion})`);
791
+ });
792
+
793
+ const rl = readline.createInterface({
794
+ input: process.stdin,
795
+ output: process.stdout
796
+ });
797
+
798
+ rl.question('\nAre you sure you want to continue without updating these plugins? (y/n): ', answer => {
799
+ if (answer.toLowerCase() !== 'y') {
800
+ console.log('\n❌ Build cancelled due to outdated plugins.');
801
+ process.exit(1);
802
+ } else {
803
+ console.log('\n✅ Continuing build...');
804
+ rl.close();
805
+ }
806
+ });
807
+ } else {
808
+ console.log('✅ All plugin versions are up to date.');
809
+ }
810
+ }
811
+
812
+ // Run the validation
813
+ checkPlugins();
814
+
815
+
816
+
817
+
818
+ // Check all the codeplays plugins version START
819
+
820
+
821
+
822
+
823
+
824
+
825
+
826
+
827
+
828
+
829
+
830
+
831
+