codeplay-common 3.2.4 → 3.2.6

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,2602 +1,2602 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const plist = require('plist');
4
-
5
-
6
-
7
- const { execSync } = require("child_process");
8
-
9
-
10
-
11
-
12
- const { readFileSync } = require("fs");
13
-
14
- const ENABLE_AUTO_UPDATE = true;
15
- const USE_LIVE_SERVER_VERSION = true;
16
-
17
- const configPath = path.join(process.cwd(), 'capacitor.config.json');
18
- const updateLogFile = path.join(process.cwd(), "", "plugin-update-log.txt");
19
-
20
- // Expected plugin list with minimum versions
21
- /* const requiredPlugins = [
22
-
23
- { pattern: /backbutton-(\d+\.\d+)\.js$/, minVersion: '2.0', required: true, baseDir: 'js',mandatoryUpdate: true},
24
-
25
-
26
- { pattern: /common-(\d+\.\d+)(?:-beta-(\d+))?\.js$/, minVersion: '6.0', required: true, baseDir: 'js',mandatoryUpdate: true },
27
-
28
- { pattern: /localization_settings-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true, baseDir: 'js',mandatoryUpdate: false },
29
- { pattern: /localization-(\d+\.\d+)\.js$/, minVersion: '1.5', required: true, baseDir: 'js',mandatoryUpdate: true },
30
- { pattern: /localNotification-(\d+\.\d+)\.js$/, minVersion: '2.2', required: true, baseDir: 'js',mandatoryUpdate: false },
31
- { pattern: /localNotification_AppSettings-(\d+\.\d+)\.js$/, minVersion: '1.0', required: true, baseDir: 'js',mandatoryUpdate: false },
32
- { pattern: /onesignal-(\d+\.\d+)\.js$/, minVersion: '2.3', required: true, baseDir: 'js',mandatoryUpdate: false },
33
- { pattern: /saveToGalleryAndSaveAnyFile-(\d+\.\d+)(-ios)?\.js$/, minVersion: '3.1', required: true, baseDir: 'js',mandatoryUpdate: true },
34
- { pattern: /Ads[\/\\]admob-emi-(\d+\.\d+)\.js$/, minVersion: '3.7', required: true, baseDir: 'js',mandatoryUpdate: true },
35
-
36
- // New added plugins
37
- { pattern: /video-player-(\d+\.\d+)\.js$/, minVersion: '1.5', required: true, baseDir: 'js',mandatoryUpdate: false },
38
- { pattern: /image-cropper-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true, baseDir: 'js',mandatoryUpdate: false },
39
- { pattern: /common-(\d+\.\d+)\.less$/, minVersion: '1.6', required: true, baseDir: 'assets/css',mandatoryUpdate: false },
40
-
41
-
42
- // New folders
43
- { pattern: /IAP-(\d+\.\d+)$/, minVersion: '2.8', isFolder: true , required: true, baseDir: 'js/Ads',mandatoryUpdate: true },
44
- { pattern: /editor-(\d+\.\d+)$/, minVersion: '1.9', isFolder: true, required: true, baseDir: 'js',mandatoryUpdate: true },
45
- { pattern: /ffmpeg-(\d+\.\d+)$/, minVersion: '1.6', isFolder: true, required: true, baseDir: 'js',mandatoryUpdate: true },
46
- { pattern: /theme-(\d+\.\d+)$/, minVersion: '3.3', isFolder: true , required: true, baseDir: 'theme',mandatoryUpdate: true },
47
-
48
-
49
- { pattern: /certificatejs-(\d+\.\d+)$/, minVersion: '1.6', isFolder: true , required: true, baseDir: 'certificate',mandatoryUpdate: true }
50
-
51
- ]; */
52
-
53
-
54
- const ROOT_DIR = path.join(__dirname, "..", "src");
55
-
56
- function requireOrInstall(packageName) {
57
- try {
58
- return require(packageName);
59
- } catch (err) {
60
-
61
- console.log(`📦 "${packageName}" not found. Installing automatically...`);
62
-
63
- try {
64
- execSync(`npm install ${packageName}`, { stdio: "inherit" });
65
- console.log(`✅ "${packageName}" installed successfully.`);
66
- } catch (installErr) {
67
- console.error(`❌ Failed to install "${packageName}".`);
68
- process.exit(1);
69
- }
70
-
71
- // Try loading again
72
- return require(packageName);
73
- }
74
- }
75
-
76
- const AdmZip = requireOrInstall("adm-zip");
77
-
78
-
79
-
80
- const pkg = require(path.join(process.cwd(), 'node_modules', 'codeplay-common', 'package.json'));
81
-
82
- const pluginName = pkg.name;
83
- const pluginVersion = pkg.version;
84
-
85
- let updateLogs = [];
86
-
87
- function writeUpdateLine(message) {
88
- updateLogs.push(message);
89
- }
90
-
91
- const MAX_LOG_BLOCKS = 50;
92
-
93
- function saveUpdateLogs() {
94
-
95
- if (updateLogs.length === 0) return;
96
-
97
- const logDir = path.dirname(updateLogFile);
98
-
99
- if (!fs.existsSync(logDir)) {
100
- fs.mkdirSync(logDir, { recursive: true });
101
- }
102
-
103
- const now = new Date();
104
-
105
- const formattedTime = now.toLocaleString('en-GB', {
106
- day: '2-digit',
107
- month: '2-digit',
108
- year: 'numeric',
109
- hour: '2-digit',
110
- minute: '2-digit',
111
- hour12: true
112
- }).replace(',', '').replace(/\//g, '-');
113
-
114
- let newBlock = `${pluginName}: ${pluginVersion}\n[${formattedTime}]\n`;
115
-
116
- updateLogs.forEach(line => {
117
- newBlock += `${line}\n`;
118
- });
119
-
120
- newBlock += "\n";
121
-
122
- let existingLog = "";
123
-
124
- if (fs.existsSync(updateLogFile)) {
125
- existingLog = fs.readFileSync(updateLogFile, "utf8");
126
- }
127
-
128
- let combinedLog = newBlock + existingLog;
129
-
130
- // Split blocks by plugin header
131
- const blocks = combinedLog.split(/\n(?=codeplay-common:)/);
132
-
133
- // Keep only latest 50
134
- const trimmed = blocks.slice(0, MAX_LOG_BLOCKS).join("\n");
135
-
136
- fs.writeFileSync(updateLogFile, trimmed);
137
-
138
- }
139
-
140
-
141
-
142
-
143
-
144
- const versionsFile = path.join(__dirname, "versions.json");
145
-
146
- function loadRequiredPlugins() {
147
-
148
- if (!fs.existsSync(versionsFile)) {
149
- console.error("❌ versions.json not found");
150
- process.exit(1);
151
- }
152
-
153
- const json = JSON.parse(fs.readFileSync(versionsFile, "utf8"));
154
-
155
- return json.plugins.map(p => ({
156
- ...p,
157
- pattern: new RegExp(p.pattern)
158
- }));
159
-
160
- }
161
-
162
- let requiredPlugins = loadRequiredPlugins();
163
-
164
-
165
-
166
-
167
-
168
-
169
- async function downloadAndExtractZip(url, destFolder) {
170
-
171
- const zipPath = destFolder + ".zip";
172
-
173
- await downloadFile(url, zipPath);
174
-
175
- const zip = new AdmZip(zipPath);
176
- zip.extractAllTo(destFolder, true);
177
-
178
- fs.unlinkSync(zipPath);
179
-
180
- }
181
-
182
-
183
-
184
-
185
-
186
-
187
-
188
- //Check codeplay-common latest version installed or not Start
189
- //const { execSync } = require('child_process');
190
-
191
-
192
- function getInstalledVersion(packageName) {
193
- try {
194
- const packageJsonPath = path.join(process.cwd(), 'node_modules', packageName, 'package.json');
195
- if (fs.existsSync(packageJsonPath)) {
196
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
197
- return packageJson.version;
198
- }
199
- } catch (error) {
200
- return null;
201
- }
202
- return null;
203
- }
204
-
205
- function getLatestVersion(packageName) {
206
- try {
207
- return execSync(`npm view ${packageName} version`).toString().trim();
208
- } catch (error) {
209
- console.error(`Failed to fetch latest version for ${packageName}`);
210
- return null;
211
- }
212
- }
213
-
214
- function checkPackageVersion() {
215
- const packageName = 'codeplay-common';
216
- const installedVersion = getInstalledVersion(packageName);
217
- const latestVersion = getLatestVersion(packageName);
218
-
219
- if (!installedVersion) {
220
- console.error(`${packageName} is not installed. Please install it using "npm install ${packageName}".`);
221
- process.exit(1);
222
- }
223
-
224
- if (installedVersion !== latestVersion) {
225
- 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`);
226
- process.exit(1);
227
- }
228
-
229
- console.log(`${packageName} is up to date (version ${installedVersion}).`);
230
- }
231
-
232
- // Run package version check before executing the main script
233
- try {
234
- checkPackageVersion();
235
- } catch (error) {
236
- console.error(error.message);
237
- process.exit(1);
238
- }
239
-
240
- //Check codeplay-common latest version installed or not END
241
-
242
-
243
-
244
- function compareWithBeta(installedVersion, minVersion, isBeta) {
245
- const baseCompare = compareVersions(installedVersion, minVersion);
246
-
247
- if (!isBeta) {
248
- // Stable version → normal compare
249
- return baseCompare;
250
- }
251
-
252
- // Beta version logic
253
- if (baseCompare > 0) return 1; // 5.3-beta > 5.2
254
- if (baseCompare < 0) return -1; // 5.1-beta < 5.2
255
-
256
- // Same version but beta → LOWER than stable
257
- return -1; // 5.2-beta < 5.2
258
- }
259
-
260
-
261
-
262
-
263
- const checkAppUniqueId=()=>{
264
-
265
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
266
-
267
- const appUniqueId = config.android?.APP_UNIQUE_ID;
268
- const RESIZEABLE_ACTIVITY = config.android?.RESIZEABLE_ACTIVITY;
269
- const orientation = config.android?.ORIENTATION;
270
-
271
-
272
- let logErrorMessage="";
273
-
274
- // 1️⃣ Check if it’s missing
275
- if (RESIZEABLE_ACTIVITY === undefined) {
276
- logErrorMessage+='❌ Missing android.RESIZEABLE_ACTIVITY option in capacitor.config.json.\n';
277
- }
278
-
279
- // 2️⃣ Check if it’s not boolean (true/false only)
280
- else if (typeof RESIZEABLE_ACTIVITY !== 'boolean') {
281
- logErrorMessage+='❌ Invalid android.RESIZEABLE_ACTIVITY value. Please use only true or false (without quotes).\n';
282
- }
283
-
284
-
285
-
286
- if (!orientation) {
287
- logErrorMessage+='❌ Missing android.ORIENTATION option in capacitor.config.json.\n';
288
- }
289
-
290
- else if(orientation!="portrait" && orientation!="landscape" && orientation!="auto")
291
- {
292
- logErrorMessage+='❌ Spelling mistake in android.ORIENTATION option in capacitor.config.json. Please use only ["portrait" "landscape" "auto"]\n';
293
- }
294
-
295
-
296
- if (!appUniqueId) {
297
- logErrorMessage+='❌ APP_UNIQUE_ID is missing in capacitor.config.json.';
298
- }
299
-
300
- else if (!Number.isInteger(appUniqueId)) {
301
- logErrorMessage+='❌ APP_UNIQUE_ID must be an integer. Example: 1, 2, 3, etc.';
302
- }
303
-
304
-
305
-
306
- if(logErrorMessage!="")
307
- {
308
- console.error(logErrorMessage);
309
- process.exit(1)
310
- }
311
-
312
-
313
- console.log(`✅ APP_UNIQUE_ID is valid: ${appUniqueId}`);
314
-
315
- }
316
-
317
- checkAppUniqueId();
318
-
319
-
320
-
321
-
322
-
323
-
324
- // ======================================================
325
- // 🚫 BLOCK STATIC IMPORT OF showSubscribePopup (ANY VERSION)
326
- // ======================================================
327
-
328
- const STATIC_SUBSCRIBE_REGEX = /import\s*{\s*showSubscribePopup\s*}\s*from\s*['"].*\/js\/Ads\/IAP-\d+(\.\d+)*\/IAP-check-And-LoadAd\.js['"]/;
329
-
330
- // ✅ Detect dynamic import (valid)
331
- const DYNAMIC_SUBSCRIBE_REGEX = /await\s+import\s*\(\s*['"].*\/js\/Ads\/IAP-\d+(\.\d+)*\/IAP-check-And-LoadAd\.js['"]\s*\)/;
332
-
333
- let subscribeImportError = false;
334
-
335
- function scanSubscribeImport(dir) {
336
- const files = fs.readdirSync(dir);
337
-
338
- for (const file of files) {
339
- const fullPath = path.join(dir, file);
340
- const stat = fs.statSync(fullPath);
341
-
342
- if (stat.isDirectory()) {
343
- scanSubscribeImport(fullPath);
344
- }
345
- else if (file.endsWith(".js") || file.endsWith(".ts") || file.endsWith(".f7")) {
346
-
347
- const content = fs.readFileSync(fullPath, "utf-8");
348
- const lines = content.split("\n");
349
-
350
- lines.forEach((line, index) => {
351
-
352
- // ❌ STATIC import → ERROR
353
- if (STATIC_SUBSCRIBE_REGEX.test(line)) {
354
- console.error(`
355
- ❌ Forbidden static import detected!
356
-
357
- File: ${fullPath}
358
- Line: ${index + 1}
359
- Code: ${line.trim()}
360
-
361
- 🚫 DO NOT use static import for showSubscribePopup
362
-
363
- 👉 Remove:
364
- import { showSubscribePopup } from './../js/Ads/IAP-x.x/IAP-check-And-LoadAd.js'
365
-
366
-
367
- ✅ Use dynamic import (ANY version allowed):
368
-
369
- let IAPModule = null;
370
- const loadIAP = async () => {
371
- if (!IAPModule) {
372
- IAPModule = await import('./../js/Ads/IAP-3.1/IAP-check-And-LoadAd.js');
373
- IAPModule.initIAP?.();
374
- }
375
-
376
- return IAPModule;
377
- };
378
-
379
- $on('pageAfterIn', async () => {
380
- await loadIAP();
381
- });
382
-
383
- const subscribeOrProLink = async () => {
384
-
385
- //This is only allowed if samsung have pro version
386
- if(_storeid==2)
387
- buyProMethod()
388
- else{
389
- const module = await loadIAP();
390
- module.showSubscribePopup();
391
- }
392
- };
393
- `);
394
- subscribeImportError = true;
395
- }
396
-
397
- // ❌ Optional: detect wrong dynamic usage (no await)
398
- if (
399
- line.includes("import(") &&
400
- line.includes("IAP-") &&
401
- !line.includes("await")
402
- ) {
403
- console.warn(`
404
- ⚠️ Warning: Dynamic import without await
405
-
406
- File: ${fullPath}
407
- Line: ${index + 1}
408
- Code: ${line.trim()}
409
-
410
- 👉 Always use:
411
- const { showSubscribePopup } = await import(...)
412
- `);
413
- }
414
-
415
- });
416
- }
417
- }
418
- }
419
-
420
-
421
- // Run scan
422
- scanSubscribeImport(ROOT_DIR);
423
-
424
- // Stop build
425
- if (subscribeImportError) {
426
- console.error("🚫 Build failed due to forbidden showSubscribePopup static import.");
427
- process.exit(1);
428
- } else {
429
- console.log("✅ showSubscribePopup import usage is valid.");
430
- }
431
-
432
-
433
-
434
-
435
- // ======================================================
436
- // 🚫 BLOCK STATIC IMPORT OF showSubscribePopup (ANY VERSION) END
437
- // ======================================================
438
-
439
-
440
-
441
-
442
-
443
-
444
-
445
-
446
-
447
-
448
-
449
- //@Codemirror check and install/uninstall the packages START
450
- //const fs = require("fs");
451
- //const path = require("path");
452
- //const { execSync } = require("child_process");
453
-
454
- const jsDir = path.join(__dirname, "..", "src", "js");
455
-
456
- // 🔍 Detect OLD structure
457
- const oldEditorDirs = fs.readdirSync(jsDir)
458
- .filter(name => /^editor-\d+\.\d+$/.test(name));
459
-
460
- // 📁 New structure path (optional, not mandatory)
461
- const newEditorBaseDir = path.join(jsDir, "editor");
462
-
463
- // ======================================================
464
- // ❌ CASE 1: OLD STRUCTURE FOUND → STOP
465
- // ======================================================
466
- if (oldEditorDirs.length > 0) {
467
-
468
- console.error(`
469
- ❌ OLD EDITOR STRUCTURE DETECTED
470
-
471
- You are using outdated folder structure:
472
- src/js/editor-x.x/
473
-
474
- 🚨 This is no longer supported.
475
-
476
- 📦 Found folders:
477
- ${oldEditorDirs.map(d => " - " + d).join("\n")}
478
-
479
- 👉 Please move them manually:
480
-
481
- src/js/editor-1.6
482
-
483
- src/js/editor/editor-1.6
484
-
485
- ⚠️ Also ensure:
486
- src/js/editor/configuration.json exists
487
-
488
- ❌ Build stopped.
489
- `);
490
-
491
- process.exit(1);
492
- }
493
-
494
- // ======================================================
495
- // ✅ CASE 2: NEW STRUCTURE EXISTS → VALIDATE
496
- // ======================================================
497
- if (fs.existsSync(newEditorBaseDir)) {
498
-
499
- // 🔍 Find editor-x.x inside new folder
500
- const editorDirs = fs.readdirSync(newEditorBaseDir)
501
- .filter(name => /^editor-\d+\.\d+$/.test(name));
502
-
503
- // 👉 If editor folder exists but no versions → skip safely
504
- if (editorDirs.length === 0) {
505
- console.log("ℹ️ No editor-x.x folders found inside src/js/editor/");
506
- return;
507
- }
508
-
509
- // ======================================================
510
- // ✅ Validate configuration.json (NEW RULE)
511
- // ======================================================
512
-
513
- const editorConfigPath = path.join(newEditorBaseDir, "configuration.json");
514
-
515
- // ❌ Missing config
516
- if (!fs.existsSync(editorConfigPath)) {
517
- console.error(`
518
- ❌ MISSING EDITOR CONFIGURATION FILE
519
-
520
- Required:
521
- src/js/editor/configuration.json
522
-
523
- ❌ Build stopped.
524
- `);
525
- process.exit(1);
526
- }
527
-
528
- // ❌ Check wrong placement
529
- const invalidConfigs = [];
530
-
531
- editorDirs.forEach(dir => {
532
- const wrongPath = path.join(newEditorBaseDir, dir, "configuration.json");
533
- if (fs.existsSync(wrongPath)) {
534
- invalidConfigs.push(`src/js/editor/${dir}/configuration.json`);
535
- }
536
- });
537
-
538
- if (invalidConfigs.length > 0) {
539
- console.error(`
540
- ❌ INVALID CONFIGURATION LOCATION
541
-
542
- 🚫 configuration.json must NOT be inside version folders.
543
-
544
- Found:
545
- ${invalidConfigs.map(p => " - " + p).join("\n")}
546
-
547
- ✅ Correct:
548
- src/js/editor/configuration.json
549
-
550
- ❌ Build stopped.
551
- `);
552
- process.exit(1);
553
- }
554
-
555
- console.log("✅ Editor structure validated.");
556
-
557
- // ======================================================
558
- // 🚀 Continue execution (run.js)
559
- // ======================================================
560
-
561
- const latestEditorDir = editorDirs.sort((a, b) => {
562
- const vA = parseFloat(a.split('-')[1]);
563
- const vB = parseFloat(b.split('-')[1]);
564
- return vB - vA;
565
- })[0];
566
-
567
- const runJsPath = path.join(newEditorBaseDir, latestEditorDir, "run.js");
568
-
569
- if (!fs.existsSync(runJsPath)) {
570
- console.error(`❌ run.js not found in ${latestEditorDir}`);
571
- process.exit(1);
572
- }
573
-
574
- console.log(`🚀 Executing ${runJsPath}...`);
575
- execSync(`node "${runJsPath}"`, { stdio: "inherit" });
576
- }
577
-
578
- // ======================================================
579
- // ✅ CASE 3: NOTHING EXISTS → DO NOTHING
580
- // ======================================================
581
- else {
582
- console.log("ℹ️ Editor not used in this project. Skipping...");
583
- }
584
-
585
- //@Codemirror check and install/uninstall the packages END
586
-
587
-
588
-
589
-
590
-
591
-
592
-
593
-
594
-
595
- // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists START
596
-
597
- const os = require('os');
598
-
599
- const saveToGalleryAndSaveFileCheck_iOS = () => {
600
-
601
- // List of paths to scan
602
- const SCAN_PATHS = [
603
- path.resolve(__dirname, '../src/certificate'),
604
- path.resolve(__dirname, '../src/pages'),
605
- path.resolve(__dirname, '../src/js'),
606
- path.resolve(__dirname, '../src/app.f7')
607
- ];
608
-
609
- // Directory to exclude
610
- const EXCLUDED_DIR = path.resolve(__dirname, '../src/js/Ads');
611
-
612
- const ANDROID_MANIFEST_PATH = path.resolve(__dirname, '../android/app/src/main/AndroidManifest.xml');
613
-
614
-
615
- // Match iOS-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5-ios.js) not in comments
616
- const IOS_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*-ios\.js['"]/m;
617
-
618
- // Match Android-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5.js) not in comments
619
- const ANDROID_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*\.js['"]/m;
620
-
621
-
622
-
623
-
624
-
625
- const ALLOWED_EXTENSIONS = ['.js', '.f7'];
626
- const isMac = os.platform() === 'darwin';
627
-
628
- let iosImportFound = false;
629
- let androidImportFound = false;
630
-
631
- // Files to skip completely (full or partial match)
632
- const SKIP_FILES = [
633
- 'pdf-3.11.174.min.js',
634
- 'pdf.worker-3.11.174.min.js'
635
- ,'index.browser.js'
636
- ];
637
-
638
-
639
- function scanDirectory(dir) {
640
-
641
- /*
642
- //######################### DO NOT DELETE THIS - START [Appid base validation] #####################################
643
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
644
- const appUniqueId = config.android?.APP_UNIQUE_ID;
645
- if (appUniqueId == "206") return;
646
- //######################### DO NOT DELETE THIS - END [Appid base validation] #####################################
647
- */
648
-
649
- const stat = fs.statSync(dir);
650
-
651
- if (stat.isFile()) {
652
-
653
- // 🔥 Skip files in SKIP_FILES array
654
- const baseName = path.basename(dir);
655
- if (SKIP_FILES.includes(baseName)) {
656
- // Just skip silently
657
- return;
658
- }
659
-
660
- // Only scan allowed file extensions
661
- if (ALLOWED_EXTENSIONS.some(ext => dir.endsWith(ext))) {
662
- process.stdout.write(`\r🔍 Scanning: ${dir} `);
663
-
664
- const content = fs.readFileSync(dir, 'utf8');
665
-
666
- if (IOS_FILE_REGEX.test(content)) {
667
- iosImportFound = true;
668
- if (!isMac) {
669
- console.error(`\n❌ ERROR: iOS-specific import detected in: ${dir}`);
670
- console.error(`🚫 STOPPED: This file should not be imported in Android/Windows/Linux builds.\n`);
671
- process.exit(1);
672
- }
673
- }
674
- else if (ANDROID_FILE_REGEX.test(content) && !content.includes('-ios.js')) {
675
- androidImportFound = true;
676
- }
677
- }
678
- }
679
- else if (stat.isDirectory()) {
680
- if (dir === EXCLUDED_DIR || path.basename(dir) === 'node_modules') return;
681
-
682
- const entries = fs.readdirSync(dir, { withFileTypes: true });
683
- for (let entry of entries) {
684
- scanDirectory(path.join(dir, entry.name));
685
- }
686
- }
687
- }
688
-
689
-
690
- // Run scan on all specified paths
691
- for (let scanPath of SCAN_PATHS) {
692
- if (fs.existsSync(scanPath)) {
693
- scanDirectory(scanPath);
694
- }
695
- }
696
-
697
-
698
-
699
- /* // Check src folder
700
- if (!fs.existsSync(ROOT_DIR)) {
701
- console.warn(`⚠️ Warning: 'src' directory not found at: ${ROOT_DIR}`);
702
- return;
703
- } */
704
-
705
- //scanDirectory(ROOT_DIR);
706
-
707
- // iOS Checks
708
- if (isMac && !iosImportFound) {
709
- console.warn(`⚠️ WARNING: You're on macOS but no iOS version (saveToGalleryAndSaveAnyFile-x.x-ios.js) found.`);
710
- process.exit(1);
711
- } else if (isMac && iosImportFound) {
712
- console.log('✅ iOS version detected for macOS build.');
713
- } else if (!iosImportFound) {
714
- console.log('✅ No iOS-specific imports detected for non-macOS.');
715
- }
716
-
717
- // Android Checks
718
- if (androidImportFound) {
719
- console.log("📱 Android version of saveToGalleryAndSaveAnyFile detected. Checking AndroidManifest.xml...");
720
-
721
- if (!fs.existsSync(ANDROID_MANIFEST_PATH)) {
722
- console.error("❌ AndroidManifest.xml not found. Cannot add requestLegacyExternalStorage attribute.");
723
- return;
724
- }
725
-
726
- let manifestContent = fs.readFileSync(ANDROID_MANIFEST_PATH, 'utf8');
727
-
728
- if (!manifestContent.includes('android:requestLegacyExternalStorage="true"')) {
729
- console.log("Adding android:requestLegacyExternalStorage=\"true\" to <application> tag...");
730
-
731
- manifestContent = manifestContent.replace(
732
- /<application([^>]*)>/,
733
- (match, attrs) => {
734
- if (attrs.includes('android:requestLegacyExternalStorage')) return match;
735
- return `<application${attrs} android:requestLegacyExternalStorage="true">`;
736
- }
737
- );
738
-
739
- fs.writeFileSync(ANDROID_MANIFEST_PATH, manifestContent, 'utf8');
740
- console.log("✅ android:requestLegacyExternalStorage=\"true\" added successfully.");
741
- } else {
742
- console.log("ℹ️ android:requestLegacyExternalStorage already exists in AndroidManifest.xml.");
743
- }
744
- } else {
745
- console.log("✅ No Android saveToGalleryAndSaveAnyFile imports detected.");
746
- }
747
- };
748
-
749
- saveToGalleryAndSaveFileCheck_iOS();
750
- // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists END
751
-
752
-
753
-
754
-
755
-
756
-
757
-
758
-
759
-
760
-
761
-
762
-
763
-
764
- /*
765
- // Clean up AppleDouble files (._*) created by macOS START
766
- if (process.platform === 'darwin') {
767
- try {
768
- console.log('🧹 Cleaning up AppleDouble files (._*)...');
769
- execSync(`find . -name '._*' -delete`);
770
- console.log('✅ AppleDouble files removed.');
771
- } catch (err) {
772
- console.warn('⚠️ Failed to remove AppleDouble files:', err.message);
773
- }
774
- } else {
775
- console.log('ℹ️ Skipping AppleDouble cleanup — not a macOS machine.');
776
- }
777
-
778
- // Clean up AppleDouble files (._*) created by macOS END
779
- */
780
-
781
-
782
-
783
-
784
-
785
-
786
- //In routes.js file check static import START
787
-
788
- const routesPath = path.join(process.cwd(), 'src', 'js', 'routes.js');
789
- const routesContent = fs.readFileSync(routesPath, 'utf-8');
790
-
791
- let inBlockComment = false;
792
- const lines = routesContent.split('\n');
793
-
794
- const allowedImport = `import HomePage from '../pages/home.f7';`;
795
- const badImportRegex = /^[ \t]*import\s+[\w{}*,\s]*\s+from\s+['"].+\.f7['"]\s*;/;
796
- const badImports = [];
797
-
798
- lines.forEach((line, index) => {
799
- const trimmed = line.trim();
800
-
801
- // Handle block comment start and end
802
- if (trimmed.startsWith('/*')) inBlockComment = true;
803
- if (inBlockComment && trimmed.endsWith('*/')) {
804
- inBlockComment = false;
805
- return;
806
- }
807
-
808
- // Skip if inside block comment or line comment
809
- if (inBlockComment || trimmed.startsWith('//')) return;
810
-
811
- // Match static .f7 import
812
- if (badImportRegex.test(trimmed) && trimmed !== allowedImport) {
813
- badImports.push({ line: trimmed, number: index + 1 });
814
- }
815
- });
816
-
817
- if (badImports.length > 0) {
818
- console.error('\n❌ ERROR: Detected disallowed static imports of .f7 files in routes.js\n');
819
- console.error(`⚠️ Only this static import is allowed:\n ${allowedImport}\n`);
820
- console.error(`🔧 Please convert other imports to async dynamic imports like this:\n`);
821
- console.error(`
822
-
823
- import HomePage from '../pages/home.f7';
824
-
825
- const routes = [
826
- {
827
- path: '/',
828
- component:HomePage,
829
- },
830
- {
831
- path: '/ProfilePage/',
832
- async async({ resolve }) {
833
- const page = await import('../pages/profile.f7');
834
- resolve({ component: page.default });
835
- },
836
- }]
837
- `);
838
-
839
- badImports.forEach(({ line, number }) => {
840
- console.error(`${number}: ${line}`);
841
- });
842
-
843
- process.exit(1);
844
- } else {
845
- console.log('✅ routes.js passed the .f7 import check.');
846
- }
847
-
848
- //In routes.js file check static import END
849
-
850
-
851
-
852
-
853
-
854
-
855
-
856
-
857
-
858
-
859
-
860
-
861
-
862
- // Check and change the "BridgeWebViewClient.java" file START
863
- /*
864
- For crash issue due to low memory problem, we need to modify the onRenderProcessGone method in BridgeWebViewClient.java.
865
- */
866
-
867
-
868
- const bridgeWebViewClientFilePath = path.join(process.cwd(), 'node_modules', '@capacitor/android/capacitor/src/main/java/com/getcapacitor', 'BridgeWebViewClient.java');
869
-
870
- // Read the file
871
- if (!fs.existsSync(bridgeWebViewClientFilePath)) {
872
- console.error('❌ Error: BridgeWebViewClient.java not found.');
873
- process.exit(1);
874
- }
875
-
876
- let fileContent = fs.readFileSync(bridgeWebViewClientFilePath, 'utf8');
877
-
878
- // Define old and new code
879
- const oldCodeStart = `@Override
880
- public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
881
- super.onRenderProcessGone(view, detail);
882
- boolean result = false;
883
-
884
- List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
885
- if (webViewListeners != null) {
886
- for (WebViewListener listener : bridge.getWebViewListeners()) {
887
- result = listener.onRenderProcessGone(view, detail) || result;
888
- }
889
- }
890
-
891
- return result;
892
- }`;
893
-
894
- const newCode = `@Override
895
- public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
896
- super.onRenderProcessGone(view, detail);
897
-
898
- boolean result = false;
899
-
900
- List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
901
- if (webViewListeners != null) {
902
- for (WebViewListener listener : bridge.getWebViewListeners()) {
903
- result = listener.onRenderProcessGone(view, detail) || result;
904
- }
905
- }
906
-
907
- if (!result) {
908
- // If no one handled it, handle it ourselves!
909
-
910
- /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
911
- if (detail.didCrash()) {
912
- //Log.e("CapacitorWebView", "WebView crashed internally!");
913
- } else {
914
- //Log.w("CapacitorWebView", "WebView was killed by system (low memory) internally!");
915
- }
916
- }*/
917
-
918
- view.post(() -> {
919
- Toast.makeText(view.getContext(), "Reloading due to low memory issue", Toast.LENGTH_SHORT).show();
920
- });
921
-
922
- view.reload(); // Safely reload WebView
923
-
924
- return true; // We handled it
925
- }
926
-
927
- return result;
928
- }`;
929
-
930
- // Step 1: Update method if needed
931
- let updated = false;
932
-
933
- if (fileContent.includes(oldCodeStart)) {
934
- console.log('✅ Found old onRenderProcessGone method. Replacing it...');
935
- fileContent = fileContent.replace(oldCodeStart, newCode);
936
- updated = true;
937
- } else if (fileContent.includes(newCode)) {
938
- console.log('ℹ️ Method already updated. No changes needed in "BridgeWebViewClient.java".');
939
- } else {
940
- console.error('❌ Error: Neither old nor new code found. Unexpected content.');
941
- process.exit(1);
942
- }
943
-
944
- // Step 2: Check and add import if missing
945
- const importToast = 'import android.widget.Toast;';
946
- if (!fileContent.includes(importToast)) {
947
- console.log('✅ Adding missing import for Toast...');
948
- const importRegex = /import\s+[^;]+;/g;
949
- const matches = [...fileContent.matchAll(importRegex)];
950
-
951
- if (matches.length > 0) {
952
- const lastImport = matches[matches.length - 1];
953
- const insertPosition = lastImport.index + lastImport[0].length;
954
- fileContent = fileContent.slice(0, insertPosition) + `\n${importToast}` + fileContent.slice(insertPosition);
955
- updated = true;
956
- } else {
957
- console.error('❌ Error: No import section found in file.');
958
- process.exit(1);
959
- }
960
- } else {
961
- console.log('ℹ️ Import for Toast already exists. No changes needed.');
962
- }
963
-
964
- // Step 3: Save if updated
965
- if (updated) {
966
- fs.writeFileSync(bridgeWebViewClientFilePath, fileContent, 'utf8');
967
- console.log('✅ File updated successfully.');
968
- } else {
969
- console.log('ℹ️ No changes needed.');
970
- }
971
-
972
-
973
-
974
-
975
- // Check and change the "BridgeWebViewClient.java" file END
976
-
977
-
978
-
979
-
980
-
981
-
982
-
983
-
984
- /*
985
- // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file START
986
-
987
- // Build the path dynamically like you requested
988
- const gradlePath = path.join(
989
- process.cwd(),
990
- 'android',
991
- 'build.gradle'
992
- );
993
-
994
- // Read the existing build.gradle
995
- let gradleContent = fs.readFileSync(gradlePath, 'utf8');
996
-
997
- // Add `ext.kotlin_version` if it's not already there
998
- if (!gradleContent.includes('ext.kotlin_version')) {
999
- gradleContent = gradleContent.replace(
1000
- /buildscript\s*{/,
1001
- `buildscript {\n ext.kotlin_version = '2.1.0'`
1002
- );
1003
- }
1004
-
1005
- // Add Kotlin classpath if it's not already there
1006
- if (!gradleContent.includes('org.jetbrains.kotlin:kotlin-gradle-plugin')) {
1007
- gradleContent = gradleContent.replace(
1008
- /dependencies\s*{([\s\S]*?)classpath 'com.android.tools.build:gradle:8.7.2'/,
1009
- `dependencies {\n classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")\n$1classpath 'com.android.tools.build:gradle:8.7.2'`
1010
- );
1011
- }
1012
-
1013
- // Write back the modified content
1014
- fs.writeFileSync(gradlePath, gradleContent, 'utf8');
1015
-
1016
- console.log('✅ Kotlin version updated in build.gradle.');
1017
-
1018
- // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file END
1019
- */
1020
-
1021
-
1022
-
1023
-
1024
-
1025
-
1026
-
1027
-
1028
- let _admobConfig;
1029
-
1030
-
1031
-
1032
- const androidPlatformPath = path.join(process.cwd(), 'android');
1033
- const iosPlatformPath = path.join(process.cwd(), 'ios');
1034
- const pluginPath = path.join(process.cwd(), 'node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
1035
- const infoPlistPath = path.join(process.cwd(), 'ios', 'App', 'App', 'Info.plist');
1036
- const resourcesPath = path.join(process.cwd(), 'resources', 'res');
1037
- const androidResPath = path.join(process.cwd(), 'android', 'app', 'src', 'main', 'res');
1038
- const localNotificationsPluginPath = path.join(process.cwd(), 'node_modules', '@capacitor', 'local-notifications');
1039
-
1040
- function fileExists(filePath) {
1041
- return fs.existsSync(filePath);
1042
- }
1043
-
1044
- function copyFolderSync(source, target) {
1045
- if (!fs.existsSync(target)) {
1046
- fs.mkdirSync(target, { recursive: true });
1047
- }
1048
-
1049
- fs.readdirSync(source).forEach(file => {
1050
- const sourceFile = path.join(source, file);
1051
- const targetFile = path.join(target, file);
1052
-
1053
- if (fs.lstatSync(sourceFile).isDirectory()) {
1054
- copyFolderSync(sourceFile, targetFile);
1055
- } else {
1056
- fs.copyFileSync(sourceFile, targetFile);
1057
- }
1058
- });
1059
- }
1060
-
1061
- function checkAndCopyResources() {
1062
- if (fileExists(resourcesPath)) {
1063
- copyFolderSync(resourcesPath, androidResPath);
1064
- console.log('✅ Successfully copied resources/res to android/app/src/main/res.');
1065
- } else {
1066
- console.log('resources/res folder not found.');
1067
-
1068
- if (fileExists(localNotificationsPluginPath)) {
1069
- throw new Error('❌ resources/res is required for @capacitor/local-notifications. Stopping execution.');
1070
- }
1071
- }
1072
- }
1073
-
1074
-
1075
-
1076
-
1077
-
1078
-
1079
-
1080
-
1081
- function getAdMobConfig() {
1082
- if (!fileExists(configPath)) {
1083
- throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
1084
- }
1085
-
1086
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
1087
- const admobConfig = config.plugins?.AdMob;
1088
-
1089
- if (!admobConfig) {
1090
- throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
1091
- }
1092
-
1093
- // Default to true if ADMOB_ENABLED is not specified
1094
- const isEnabled = admobConfig.ADMOB_ENABLED !== false;
1095
-
1096
- if (!isEnabled) {
1097
- return { ADMOB_ENABLED: false }; // Skip further validation
1098
- }
1099
-
1100
- if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
1101
- throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
1102
- }
1103
-
1104
- return {
1105
- ADMOB_ENABLED: true,
1106
- APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
1107
- APP_ID_IOS: admobConfig.APP_ID_IOS,
1108
- USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
1109
- };
1110
- }
1111
-
1112
- function validateAndroidBuildOptions() {
1113
-
1114
-
1115
- if (!fileExists(configPath)) {
1116
- console.log('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
1117
- process.exit(1);
1118
- }
1119
-
1120
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
1121
-
1122
- const targetAppId=config.appId
1123
-
1124
- const buildOptions = config.android?.buildOptions;
1125
-
1126
- if (!buildOptions) {
1127
- console.log('❌ Missing android.buildOptions in capacitor.config.json.');
1128
- process.exit(1);
1129
- }
1130
-
1131
- const requiredProps = [
1132
- 'keystorePath',
1133
- 'keystorePassword',
1134
- 'keystoreAlias',
1135
- 'keystoreAliasPassword',
1136
- 'releaseType',
1137
- 'signingType'
1138
- ];
1139
-
1140
- const missing = requiredProps.filter(prop => !buildOptions[prop]);
1141
-
1142
- if (missing.length > 0) {
1143
- console.log('❌ Missing properties android.buildOptions in capacitor.config.json.');
1144
- process.exit(1);
1145
- }
1146
-
1147
-
1148
- const keystorePath=buildOptions.keystorePath
1149
- const keyFileName = path.basename(keystorePath);
1150
-
1151
-
1152
-
1153
- const keystoreMap = {
1154
- "gameskey.jks": [
1155
- "com.cube.blaster",
1156
- ],
1157
- "htmleditorkeystoke.jks": [
1158
- "com.HTML.AngularJS.Codeplay",
1159
- "com.html.codeplay.pro",
1160
- "com.bootstrap.code.play",
1161
- "com.kids.learning.master",
1162
- "com.Simple.Barcode.Scanner",
1163
- "com.FAShtmlcssjs.editor"
1164
- ]
1165
- };
1166
-
1167
- // find which keystore is required for the given targetAppId
1168
- let requiredKey = "newappskey.jks"; // default
1169
- for (const [keyFile, appIds] of Object.entries(keystoreMap)) {
1170
- if (appIds.includes(targetAppId)) {
1171
- requiredKey = keyFile;
1172
- break;
1173
- }
1174
- }
1175
-
1176
- // validate
1177
- if (keyFileName !== requiredKey) {
1178
- console.log(`❌ The keystore path is mismatched. Expected ${requiredKey} for ${targetAppId}, but got ${keyFileName}`);
1179
- process.exit(1);
1180
- }
1181
-
1182
-
1183
-
1184
-
1185
-
1186
- // optionally return them
1187
- //return buildOptions;
1188
- }
1189
-
1190
- function updatePluginXml(admobConfig) {
1191
- if (!fileExists(pluginPath)) {
1192
- console.error(' ❌ plugin.xml not found. Ensure the plugin is installed.');
1193
- return;
1194
- }
1195
-
1196
- let pluginContent = fs.readFileSync(pluginPath, 'utf8');
1197
-
1198
- pluginContent = pluginContent
1199
- .replace(/<preference name="APP_ID_ANDROID" default=".*?" \/>/, `<preference name="APP_ID_ANDROID" default="${admobConfig.APP_ID_ANDROID}" />`)
1200
- .replace(/<preference name="APP_ID_IOS" default=".*?" \/>/, `<preference name="APP_ID_IOS" default="${admobConfig.APP_ID_IOS}" />`);
1201
-
1202
- fs.writeFileSync(pluginPath, pluginContent, 'utf8');
1203
- console.log('✅ AdMob IDs successfully updated in plugin.xml');
1204
- }
1205
-
1206
- function updateInfoPlist(admobConfig) {
1207
- if (!fileExists(infoPlistPath)) {
1208
- console.error(' ❌ Info.plist not found. Ensure you have built the iOS project.');
1209
- return;
1210
- }
1211
-
1212
- const plistContent = fs.readFileSync(infoPlistPath, 'utf8');
1213
- const plistData = plist.parse(plistContent);
1214
-
1215
- plistData.GADApplicationIdentifier = admobConfig.APP_ID_IOS;
1216
- plistData.NSUserTrackingUsageDescription = 'This identifier will be used to deliver personalized ads to you.';
1217
- plistData.GADDelayAppMeasurementInit = true;
1218
-
1219
- const updatedPlistContent = plist.build(plistData);
1220
- fs.writeFileSync(infoPlistPath, updatedPlistContent, 'utf8');
1221
- console.log('AdMob IDs and additional configurations successfully updated in Info.plist');
1222
- }
1223
-
1224
-
1225
- try {
1226
- if (!fileExists(configPath)) {
1227
- throw new Error(' ❌ capacitor.config.json not found. Skipping setup.');
1228
- }
1229
-
1230
- if (!fileExists(androidPlatformPath) && !fileExists(iosPlatformPath)) {
1231
- throw new Error('Neither Android nor iOS platforms are found. Ensure platforms are added to your Capacitor project.');
1232
- }
1233
-
1234
- checkAndCopyResources();
1235
-
1236
-
1237
-
1238
- _admobConfig = getAdMobConfig();
1239
-
1240
-
1241
-
1242
-
1243
-
1244
- // Proceed only if ADMOB_ENABLED is true
1245
- if (_admobConfig.ADMOB_ENABLED) {
1246
- if (fileExists(androidPlatformPath)) {
1247
- updatePluginXml(_admobConfig);
1248
- }
1249
-
1250
- if (fileExists(iosPlatformPath)) {
1251
- updateInfoPlist(_admobConfig);
1252
- }
1253
- }
1254
-
1255
-
1256
- } catch (error) {
1257
- console.error(error.message);
1258
- process.exit(1); // Stop execution if there's a critical error
1259
- }
1260
-
1261
-
1262
-
1263
- validateAndroidBuildOptions();
1264
-
1265
-
1266
-
1267
-
1268
-
1269
-
1270
- // Check all the codeplays plugins version START
1271
-
1272
-
1273
- const readline = require('readline');
1274
-
1275
-
1276
- //const srcDir = path.join(__dirname, 'src');
1277
- const srcDir = path.join(process.cwd(), 'src');
1278
- let outdatedPlugins = [];
1279
-
1280
- function parseVersion(ver) {
1281
- return ver.split('.').map(n => parseInt(n, 10));
1282
- }
1283
-
1284
- function compareVersions(v1, v2) {
1285
- const [a1, b1] = parseVersion(v1);
1286
- const [a2, b2] = parseVersion(v2);
1287
- if (a1 !== a2) return a1 - a2;
1288
- return b1 - b2;
1289
- }
1290
-
1291
- function walkSync(dir, filelist = []) {
1292
- fs.readdirSync(dir).forEach(file => {
1293
- const fullPath = path.join(dir, file);
1294
- const stat = fs.statSync(fullPath);
1295
- if (stat.isDirectory()) {
1296
- walkSync(fullPath, filelist);
1297
- } else {
1298
- filelist.push(fullPath);
1299
- }
1300
- });
1301
- return filelist;
1302
- }
1303
-
1304
-
1305
-
1306
- function getSearchRoot(plugin) {
1307
- return path.join(srcDir, plugin.baseDir || 'js');
1308
- }
1309
-
1310
-
1311
-
1312
-
1313
-
1314
-
1315
-
1316
-
1317
-
1318
-
1319
-
1320
-
1321
-
1322
-
1323
-
1324
-
1325
-
1326
-
1327
-
1328
-
1329
- /*############################################## AUTO DOWNLOAD FROM SERVER START #####################################*/
1330
-
1331
- // ============================================================
1332
- // 🔥 AUTO PLUGIN UPDATE SYSTEM (MANDATORY UPDATES)
1333
- // ============================================================
1334
-
1335
- const https = require("https");
1336
-
1337
- /**
1338
- * Check if file exists on server using HEAD request
1339
- */
1340
- function urlExists(url) {
1341
- return new Promise(resolve => {
1342
- const req = https.request(url, { method: "HEAD" }, res => {
1343
- resolve(res.statusCode === 200);
1344
- });
1345
-
1346
- req.on("error", () => resolve(false));
1347
- req.end();
1348
- });
1349
- }
1350
-
1351
- /**
1352
- * Download file from server
1353
- */
1354
- function downloadFile(url, dest) {
1355
- return new Promise((resolve, reject) => {
1356
- const file = fs.createWriteStream(dest);
1357
-
1358
- https.get(url, response => {
1359
- if (response.statusCode !== 200) {
1360
- reject("Download failed");
1361
- return;
1362
- }
1363
-
1364
- response.pipe(file);
1365
-
1366
- file.on("finish", () => {
1367
- file.close(resolve);
1368
- });
1369
- }).on("error", err => {
1370
- fs.unlink(dest, () => {});
1371
- reject(err);
1372
- });
1373
- });
1374
- }
1375
-
1376
- /**
1377
- * Update imports across src folder
1378
- * Replaces old filename → new filename
1379
- */
1380
- /**
1381
- * Update imports across project
1382
- * Replaces old filename → new filename
1383
- */
1384
-
1385
- const VITE_ALIAS_ONLY = [
1386
- "common",
1387
- "admob-emi",
1388
- "localization",
1389
- "theme",
1390
- "certificatejs",
1391
- "ffmpeg"
1392
- ];
1393
-
1394
- function updateImports(oldName, newName) {
1395
-
1396
- const projectRoot = process.cwd();
1397
-
1398
- const filesToScan = [
1399
- path.join(projectRoot, "vite.config.js"),
1400
- path.join(projectRoot, "vite.config.mjs")
1401
- ];
1402
-
1403
- const srcDir = path.join(projectRoot, "src");
1404
-
1405
- // scan vite config
1406
- filesToScan.forEach(file => {
1407
-
1408
- if (!fs.existsSync(file)) return;
1409
-
1410
- let content = fs.readFileSync(file, "utf8");
1411
-
1412
- if (content.includes(oldName)) {
1413
-
1414
- content = content.split(oldName).join(newName);
1415
-
1416
- fs.writeFileSync(file, content);
1417
-
1418
- console.log(`✏️ Updated alias in ${path.basename(file)}`);
1419
- }
1420
-
1421
- });
1422
-
1423
- // scan src files
1424
- function walk(dir) {
1425
-
1426
- fs.readdirSync(dir).forEach(file => {
1427
-
1428
- if (["node_modules","android","ios","dist",".git"].includes(file))
1429
- return;
1430
-
1431
- const full = path.join(dir, file);
1432
- const stat = fs.statSync(full);
1433
-
1434
- if (stat.isDirectory()) {
1435
- walk(full);
1436
- }
1437
-
1438
- else if (
1439
- (full.endsWith(".js") ||
1440
- full.endsWith(".f7") ||
1441
- full.endsWith(".mjs")) &&
1442
- !full.endsWith(".min.js")
1443
- ) {
1444
-
1445
- let content = fs.readFileSync(full, "utf8");
1446
-
1447
- if (content.includes(oldName)) {
1448
-
1449
- content = content.split(oldName).join(newName);
1450
-
1451
- fs.writeFileSync(full, content);
1452
-
1453
- console.log(`✏️ Updated import in ${path.relative(projectRoot, full)}`);
1454
- }
1455
-
1456
- }
1457
-
1458
- });
1459
-
1460
- }
1461
-
1462
- if (fs.existsSync(srcDir)) {
1463
- walk(srcDir);
1464
- }
1465
-
1466
- }
1467
-
1468
-
1469
- /**
1470
- * Auto-update a plugin file
1471
- * Returns TRUE if success
1472
- * Returns FALSE if fallback to manual needed
1473
- */
1474
-
1475
-
1476
- let _serverVersions = null;
1477
- async function fetchVersions() {
1478
-
1479
- if (_serverVersions) return _serverVersions;
1480
-
1481
- return new Promise((resolve) => {
1482
-
1483
- https.get(
1484
- "https://htmlcodeplay.com/code-play-plugin/versions.json",
1485
- { timeout: 5000 },
1486
- res => {
1487
-
1488
- let data = "";
1489
-
1490
- res.on("data", chunk => data += chunk);
1491
-
1492
- res.on("end", () => {
1493
-
1494
- try {
1495
-
1496
- _serverVersions = JSON.parse(data);
1497
-
1498
- resolve(_serverVersions);
1499
-
1500
- } catch {
1501
-
1502
- resolve(null);
1503
-
1504
- }
1505
-
1506
- });
1507
-
1508
- }
1509
-
1510
- ).on("error", () => resolve(null));
1511
-
1512
- });
1513
-
1514
- }
1515
-
1516
-
1517
-
1518
- async function autoUpdatePlugin(pluginDef, pluginInfo) {
1519
-
1520
- const versions = await fetchVersions();
1521
-
1522
- if (!versions) {
1523
- console.log("⚠️ versions.json not reachable");
1524
- return false;
1525
- }
1526
-
1527
- const oldFullPath = path.join(srcDir, pluginInfo.name);
1528
- const oldFileName = path.basename(oldFullPath);
1529
-
1530
- //const oldFileName = path.basename(oldFullPath);
1531
- const oldVersionFile = oldFileName;
1532
-
1533
-
1534
- const ext = path.extname(oldFileName); // .js or .less
1535
- //const baseName = oldFileName.replace(/-\d+\.\d+.*$/, "");
1536
- const baseName = oldFileName.replace(/-\d+\.\d+.*$/, '').replace(/\.(js|less)$/, '');
1537
-
1538
- // version lookup key
1539
- let pluginKey = baseName;
1540
-
1541
-
1542
- // Only common plugin has js and less variants
1543
- if (baseName === "common") {
1544
- if (ext === ".js") pluginKey = "common-js";
1545
- if (ext === ".less") pluginKey = "common-less";
1546
- }
1547
-
1548
- const latestVersion = versions[pluginKey];
1549
-
1550
- if (!latestVersion) {
1551
- console.log(`❌ No version entry for ${baseName}`);
1552
- return false;
1553
- }
1554
-
1555
- // ===============================
1556
- // FOLDER PLUGIN UPDATE
1557
- // ===============================
1558
- if (pluginDef.isFolder) {
1559
-
1560
- const zipName = `${baseName}-${latestVersion}.zip`;
1561
- const url = `https://htmlcodeplay.com/code-play-plugin/${zipName}`;
1562
-
1563
- const destRoot = path.join(srcDir, pluginDef.destDir || pluginDef.baseDir || '');
1564
- const oldPath = path.join(destRoot, pluginInfo.name);
1565
- const newPath = path.join(destRoot, `${baseName}-${latestVersion}`);
1566
-
1567
- if (!(await urlExists(url))) return false;
1568
-
1569
- fs.rmSync(oldPath, { recursive: true, force: true });
1570
-
1571
- await downloadAndExtractZip(url, newPath);
1572
-
1573
- updateImports(pluginInfo.name, `${baseName}-${latestVersion}`);
1574
-
1575
- // ✅ ADD THIS
1576
- writeUpdateLine(`${pluginInfo.name} -> ${baseName}-${latestVersion}`);
1577
-
1578
- console.log(`✅ Folder updated → ${baseName}-${latestVersion}`);
1579
-
1580
- return true;
1581
- }
1582
- // ===============================
1583
- // FILE PLUGIN UPDATE
1584
- // ===============================
1585
-
1586
- const pluginDir = path.dirname(oldFullPath);
1587
-
1588
- // Only this plugin has ios variant
1589
- const IOS_VARIANT_PLUGINS = [
1590
- "saveToGalleryAndSaveAnyFile"
1591
- ];
1592
-
1593
- /* let variants = [
1594
- `${baseName}-${latestVersion}.js`
1595
- ]; */
1596
-
1597
- //const ext = path.extname(oldFileName);
1598
- const variants = [`${baseName.replace(ext,'')}-${latestVersion}${ext}`];
1599
-
1600
-
1601
- if (IOS_VARIANT_PLUGINS.includes(baseName)) {
1602
- variants.push(`${baseName}-${latestVersion}-ios.js`);
1603
- }
1604
-
1605
- let downloaded = [];
1606
-
1607
- // Download files
1608
- for (const fileName of variants) {
1609
-
1610
- const url = `https://htmlcodeplay.com/code-play-plugin/${fileName}`;
1611
-
1612
- console.log(`🔍 Checking latest: ${fileName}`);
1613
-
1614
- if (await urlExists(url)) {
1615
-
1616
- const destPath = path.join(pluginDir, fileName);
1617
-
1618
- await downloadFile(url, destPath);
1619
-
1620
- downloaded.push(fileName);
1621
-
1622
- console.log(`⬇ Downloaded → ${fileName}`);
1623
-
1624
- //writeUpdateLine(`Downloaded: ${fileName}`);
1625
-
1626
- }
1627
- }
1628
-
1629
- if (downloaded.length === 0) {
1630
- console.log(`❌ No files downloaded for ${baseName}`);
1631
- return false;
1632
- }
1633
-
1634
- // Remove ONLY versioned files (safe)
1635
- //const versionPattern = new RegExp(`^${baseName}-\\d+\\.\\d+(-ios)?\\.js$`);
1636
- const versionPattern = new RegExp(`^${baseName}-\\d+\\.\\d+(-ios)?\\${ext}$`);
1637
-
1638
- const existingFiles = fs.readdirSync(pluginDir);
1639
-
1640
- existingFiles.forEach(file => {
1641
-
1642
- if (
1643
- versionPattern.test(file) &&
1644
- !downloaded.includes(file)
1645
- ) {
1646
-
1647
- const oldPath = path.join(pluginDir, file);
1648
-
1649
- fs.unlinkSync(oldPath);
1650
-
1651
- console.log(`🗑 Removed old file → ${file}`);
1652
- //writeUpdateLine(`Removed old file: ${file}`);
1653
- }
1654
-
1655
- });
1656
-
1657
- //const newFileName = `${baseName}-${latestVersion}.js`;
1658
- const newFileName = `${baseName}-${latestVersion}${ext}`;
1659
-
1660
- writeUpdateLine(`${oldVersionFile} -> ${newFileName}`);
1661
-
1662
- updateImports(oldFileName, newFileName);
1663
- //updateImports(baseName, `${baseName}-${latestVersion}.js`);
1664
- //updateImports(pluginInfo.name, `${baseName}-${latestVersion}`);
1665
-
1666
- //console.log(`✅ Updated → ${newFileName}`);
1667
- //console.log(`✅ Updated → ${baseName}-${latestVersion}`);
1668
-
1669
- return true;
1670
- }
1671
-
1672
-
1673
-
1674
-
1675
- /*############################################## AUTO DOWNLOAD FROM SERVER END #####################################*/
1676
-
1677
-
1678
-
1679
-
1680
-
1681
-
1682
-
1683
-
1684
-
1685
-
1686
-
1687
-
1688
-
1689
-
1690
-
1691
-
1692
-
1693
-
1694
- async function loadPluginVersions() {
1695
-
1696
- if (!USE_LIVE_SERVER_VERSION) {
1697
- console.log("ℹ️ Using local plugin versions (offline mode).");
1698
- return;
1699
- }
1700
-
1701
- console.log("🌐 Fetching plugin versions from server...");
1702
-
1703
- const versions = await fetchVersions();
1704
-
1705
- if (!versions || typeof versions !== "object") {
1706
- console.log("⚠️ Server unavailable or invalid versions.json. Falling back to local versions.");
1707
- return;
1708
- }
1709
-
1710
- requiredPlugins.forEach(plugin => {
1711
-
1712
- if (!plugin.name) return;
1713
-
1714
- if (versions[plugin.name]) {
1715
- plugin.minVersion = versions[plugin.name];
1716
- }
1717
-
1718
- });
1719
-
1720
- console.log("✅ Plugin versions loaded from server.");
1721
-
1722
- }
1723
-
1724
-
1725
-
1726
- let hasMandatoryUpdate = false;
1727
- function checkPlugins() {
1728
- return new Promise(async (resolve, reject) => {
1729
- const files = walkSync(srcDir);
1730
- const outdatedPlugins = [];
1731
- let hasMandatoryUpdate = false;
1732
-
1733
- for (const plugin of requiredPlugins) {
1734
- const searchRoot = getSearchRoot(plugin);
1735
-
1736
- // ---------- Folder plugins ----------
1737
- if (plugin.isFolder) {
1738
- if (!fs.existsSync(searchRoot)) continue;
1739
-
1740
- const subDirs = fs.readdirSync(searchRoot)
1741
- .map(name => path.join(searchRoot, name))
1742
- .filter(p => fs.statSync(p).isDirectory());
1743
-
1744
- for (const dir of subDirs) {
1745
- const relativePath = path.relative(searchRoot, dir).replace(/\\/g, '/');
1746
- const match = plugin.pattern.exec(relativePath);
1747
-
1748
- if (match) {
1749
- const currentVersion = match[1];
1750
-
1751
- if (compareVersions(currentVersion, plugin.minVersion) < 0) {
1752
- outdatedPlugins.push({
1753
- name: relativePath,
1754
- currentVersion,
1755
- requiredVersion: plugin.minVersion,
1756
- mandatoryUpdate: plugin.mandatoryUpdate === true
1757
- });
1758
-
1759
- if (plugin.mandatoryUpdate) {
1760
- hasMandatoryUpdate = true;
1761
- }
1762
- }
1763
- }
1764
- }
1765
- continue;
1766
- }
1767
-
1768
- // ---------- File plugins ----------
1769
- const matchedFile = files.find(file =>
1770
- file.startsWith(searchRoot) && plugin.pattern.test(file)
1771
- );
1772
-
1773
- if (matchedFile) {
1774
- const match = plugin.pattern.exec(matchedFile);
1775
- if (match) {
1776
- const currentVersion = match[1];
1777
- const isBeta = !!match[2];
1778
-
1779
- const cmp = plugin.pattern.source.includes('beta')
1780
- ? compareWithBeta(currentVersion, plugin.minVersion, isBeta)
1781
- : compareVersions(currentVersion, plugin.minVersion);
1782
-
1783
- if (cmp < 0) {
1784
- outdatedPlugins.push({
1785
- name: path.relative(srcDir, matchedFile),
1786
- currentVersion: isBeta ? `${currentVersion}-beta` : currentVersion,
1787
- requiredVersion: plugin.minVersion,
1788
- mandatoryUpdate: plugin.mandatoryUpdate === true
1789
- });
1790
-
1791
- if (plugin.mandatoryUpdate) {
1792
- hasMandatoryUpdate = true;
1793
- }
1794
- }
1795
- }
1796
- }
1797
- }
1798
-
1799
- // ---------- Result handling ----------
1800
- if (outdatedPlugins.length > 0) {
1801
- console.log('\n❗ The following plugins are outdated:\n');
1802
-
1803
- outdatedPlugins.forEach( p => {
1804
- const tag = p.mandatoryUpdate ? '🔥 MANDATORY' : '';
1805
- console.log(
1806
- ` ⚠️ - ${p.name} (Current: ${p.currentVersion}, Required: ${p.requiredVersion}) ${tag}`
1807
- );
1808
- });
1809
-
1810
- // 🚨 Mandatory update → stop build
1811
- /* if (hasMandatoryUpdate) {
1812
- console.log('\n🚫 One or more plugins require a mandatory update.');
1813
- console.log('❌ Build cancelled. Please update mandatory plugins and try again.');
1814
- process.exit(1);
1815
- } */
1816
-
1817
-
1818
-
1819
-
1820
-
1821
- if (hasMandatoryUpdate) {
1822
-
1823
- //--------------------------------------------------
1824
- // 🚫 AUTO UPDATE DISABLED
1825
- //--------------------------------------------------
1826
- if (!ENABLE_AUTO_UPDATE) {
1827
- console.log("\n🚫 Auto-update disabled.");
1828
- console.log("❌ Manual update required.");
1829
- process.exit(1);
1830
- }
1831
-
1832
- //--------------------------------------------------
1833
- // 🔥 AUTO UPDATE ENABLED
1834
- //--------------------------------------------------
1835
- console.log("\n🔥 Mandatory plugins outdated. Trying auto-update...\n");
1836
-
1837
-
1838
-
1839
- let autoFailed = false;
1840
-
1841
- for (const p of outdatedPlugins.filter(x => x.mandatoryUpdate)) {
1842
-
1843
- const pluginDef = requiredPlugins.find(def =>
1844
- def.pattern.test(p.name)
1845
- );
1846
-
1847
- if (!pluginDef) continue;
1848
-
1849
- const success = await autoUpdatePlugin(
1850
- pluginDef,
1851
- p
1852
- );
1853
-
1854
- if (!success) {
1855
- autoFailed = true;
1856
-
1857
- const pluginDef = requiredPlugins.find(def =>
1858
- def.pattern.test(p.name)
1859
- );
1860
-
1861
- console.log(`❌ Manual update required for ${p.name}`);
1862
-
1863
- if (pluginDef) {
1864
- console.log(`👉 Required minimum version: ${pluginDef.minVersion}`);
1865
- }
1866
- }
1867
- }
1868
-
1869
- // 🚨 Fallback to manual if any failed
1870
- if (autoFailed) {
1871
- console.log('\n🚫 One or more plugins require manual update.');
1872
- console.log('❌ Build cancelled. Please update mandatory plugins.');
1873
- process.exit(1);
1874
- }
1875
-
1876
- console.log('\n🎉 All mandatory plugins auto-updated! Rechecking plugins...\n');
1877
-
1878
- // Re-run plugin check so outdated list becomes empty
1879
- await checkPlugins();
1880
- return;
1881
- }
1882
-
1883
-
1884
-
1885
-
1886
-
1887
-
1888
- // Optional updates → ask user
1889
- const rl = readline.createInterface({
1890
- input: process.stdin,
1891
- output: process.stdout
1892
- });
1893
-
1894
- rl.question(
1895
- '\nAre you sure you want to continue without updating these plugins? (y/n): ',
1896
- answer => {
1897
- rl.close();
1898
-
1899
- if (answer.toLowerCase() !== 'y') {
1900
- console.log('\n❌ Build cancelled due to outdated plugins.');
1901
- process.exit(1);
1902
- } else {
1903
- console.log('\n✅ Continuing build...');
1904
- resolve();
1905
- }
1906
- }
1907
- );
1908
- } else {
1909
- console.log('✅ All plugin versions are up to date.');
1910
- saveUpdateLogs();
1911
- resolve();
1912
- }
1913
- });
1914
- }
1915
-
1916
-
1917
-
1918
-
1919
-
1920
-
1921
-
1922
-
1923
-
1924
-
1925
- const localizationBaseDir = path.join(__dirname, "..", "src", "js", "localization");
1926
-
1927
- // ======================================================
1928
- // 🌐 LOCALIZATION CHECK (FULLY DYNAMIC)
1929
- // ======================================================
1930
-
1931
-
1932
- const jsRootDir = path.join(__dirname, "..", "src", "js");
1933
-
1934
- // 🔍 Detect OLD localization files in root js/
1935
- const oldLocalizationFiles = fs.readdirSync(jsRootDir)
1936
- .filter(name =>
1937
- /^localization-\d+(\.\d+)*\.js$/.test(name) ||
1938
- /^localization_settings-\d+(\.\d+)*\.js$/.test(name)
1939
- );
1940
-
1941
- // ❌ If old structure found → STOP
1942
- if (oldLocalizationFiles.length > 0) {
1943
-
1944
- console.error(`
1945
- ❌ OLD LOCALIZATION STRUCTURE DETECTED
1946
-
1947
- You are using outdated file structure:
1948
- src/js/localization-x.x.js
1949
- src/js/localization_settings-x.x.js
1950
-
1951
- 🚨 This is no longer supported.
1952
-
1953
- 📦 Found files:
1954
- ${oldLocalizationFiles.map(f => " - " + f).join("\n")}
1955
-
1956
- 👉 Please move them to new structure:
1957
-
1958
- src/js/localization/localization_settings-x.x.js
1959
- src/js/localization/localization-x.x/
1960
-
1961
- ⚠️ Example:
1962
-
1963
- OLD:
1964
- src/js/localization-x.x.js
1965
- src/js/localization_settings-x.x.js
1966
-
1967
- NEW:
1968
- src/js/localization/localization_settings-1.1.js
1969
- src/js/localization/localization-x.x/localization-x.x.js
1970
-
1971
- ❌ Build stopped.
1972
- `);
1973
-
1974
- process.exit(1);
1975
- }
1976
-
1977
-
1978
-
1979
-
1980
- if (fs.existsSync(localizationBaseDir)) {
1981
-
1982
- // ❌ Block wrong files
1983
- const invalidFiles = fs.readdirSync(localizationBaseDir)
1984
- .filter(name => /^localization-\d+(\.\d+)*\.js$/.test(name));
1985
-
1986
- if (invalidFiles.length > 0) {
1987
- console.error(`
1988
- ❌ INVALID LOCALIZATION FILE LOCATION
1989
-
1990
- 🚫 localization-x.x.js must NOT be directly inside:
1991
- src/js/localization/
1992
-
1993
- 📦 Found:
1994
- ${invalidFiles.map(f => " - " + f).join("\n")}
1995
-
1996
- ❌ Build stopped.
1997
- `);
1998
- process.exit(1);
1999
- }
2000
-
2001
- // 🔍 Find localization-x.x folders
2002
- const localizationVersions = fs.readdirSync(localizationBaseDir)
2003
- .filter(name => /^localization-\d+(\.\d+)+$/.test(name));
2004
-
2005
- if (localizationVersions.length === 0) {
2006
- console.log("ℹ️ No localization-x.x folder found. Skipping...");
2007
- } else {
2008
-
2009
- // ✅ Get latest version (same logic as editor)
2010
- const latestLocalizationDir = localizationVersions.sort((a, b) => {
2011
- const vA = parseFloat(a.split('-')[1]);
2012
- const vB = parseFloat(b.split('-')[1]);
2013
- return vB - vA;
2014
- })[0];
2015
-
2016
- const localizationPath = path.join(localizationBaseDir, latestLocalizationDir);
2017
-
2018
- // ======================================================
2019
- // ✅ CHECK localization-x.x.js exists
2020
- // ======================================================
2021
-
2022
- const version = latestLocalizationDir.split('-')[1];
2023
- const expectedFile = `localization-${version}.js`;
2024
- const localizationFilePath = path.join(localizationPath, expectedFile);
2025
-
2026
- if (!fs.existsSync(localizationFilePath)) {
2027
- console.error(`
2028
- ❌ localization file missing
2029
-
2030
- Expected:
2031
- ${localizationFilePath}
2032
-
2033
- ❌ Build stopped.
2034
- `);
2035
- process.exit(1);
2036
- }
2037
-
2038
- // ======================================================
2039
- // ✅ CHECK run.js exists
2040
- // ======================================================
2041
-
2042
- const runJsPath = path.join(localizationPath, "run.js");
2043
-
2044
- if (!fs.existsSync(runJsPath)) {
2045
- console.error(`❌ run.js not found in ${latestLocalizationDir}`);
2046
- process.exit(1);
2047
- }
2048
-
2049
- // ======================================================
2050
- // 🚀 EXECUTE run.js
2051
- // ======================================================
2052
-
2053
- console.log(`🌐 Localization detected: ${latestLocalizationDir}`);
2054
- console.log(`🚀 Executing ${runJsPath}...`);
2055
-
2056
- execSync(`node "${runJsPath}"`, { stdio: "inherit" });
2057
- }
2058
-
2059
- } else {
2060
- console.log("ℹ️ Localization not used in this project. Skipping...");
2061
- }
2062
-
2063
-
2064
-
2065
-
2066
-
2067
-
2068
-
2069
-
2070
-
2071
-
2072
-
2073
-
2074
-
2075
-
2076
-
2077
-
2078
-
2079
-
2080
-
2081
- //editor-x.x import old style check and stop execution START
2082
-
2083
-
2084
-
2085
- // Match: editor/editor-2.3, editor/editor-2.3.1, etc.
2086
- const FORBIDDEN_REGEX = /editor\/editor-\d+(\.\d+)+/;
2087
-
2088
- let hasError = false;
2089
-
2090
- const ERROR_MESSAGE = `const ERROR_MESSAGE = ❌ Invalid import detected!
2091
-
2092
- You are using a direct version-based path like: editor/editor-x.x/editor.js
2093
-
2094
- 🚫 This is NOT allowed.
2095
-
2096
- 👉 Please use the proper alias or updated import method.
2097
- Example: import { ... } from '@editor'
2098
-
2099
- ⚠️ Do not use version-based paths in imports.
2100
- 👉 Please add this manually in vite.config.js:
2101
-
2102
- alias: {
2103
- '@editor': path.resolve(__dirname, './src/js/editor/editor-x.x')
2104
- }`
2105
-
2106
- function scanDir(dir) {
2107
- const files = fs.readdirSync(dir);
2108
-
2109
- for (const file of files) {
2110
- const fullPath = path.join(dir, file);
2111
- const stat = fs.statSync(fullPath);
2112
-
2113
- if (stat.isDirectory()) {
2114
- scanDir(fullPath);
2115
- } else if (file.endsWith(".js") || file.endsWith(".ts") || file.endsWith(".f7")) {
2116
- const content = fs.readFileSync(fullPath, "utf-8");
2117
-
2118
- const lines = content.split("\n");
2119
-
2120
- lines.forEach((line, index) => {
2121
- if (FORBIDDEN_REGEX.test(line)) {
2122
- console.error(
2123
- `❌ Forbidden import found:\nFile: ${fullPath}\nLine: ${index + 1}\nCode: ${line.trim()}\n`,
2124
- ERROR_MESSAGE
2125
- );
2126
- hasError = true;
2127
- }
2128
- });
2129
- }
2130
- }
2131
- }
2132
-
2133
- // Run scan
2134
- scanDir(ROOT_DIR);
2135
-
2136
- // Throw error (exit process)
2137
- if (hasError) {
2138
- console.error("🚫 Build failed due to forbidden editor imports.");
2139
- process.exit(1);
2140
- } else {
2141
- console.log("✅ No forbidden imports found.");
2142
- }
2143
-
2144
-
2145
-
2146
-
2147
-
2148
-
2149
- //editor-x.x import old style check and stop execution START
2150
-
2151
-
2152
-
2153
-
2154
-
2155
-
2156
-
2157
-
2158
-
2159
-
2160
- // Check all the codeplays plugins version START
2161
-
2162
-
2163
-
2164
-
2165
- // ====================================================================
2166
- // AUTO-ADD esbuild.drop: ['console','debugger'] to vite.config.js / mjs
2167
- // ====================================================================
2168
-
2169
-
2170
-
2171
- const checkAndupdateDropInViteConfig = () => {
2172
-
2173
- const possibleFiles = [
2174
- "vite.config.js",
2175
- "vite.config.mjs"
2176
- ];
2177
-
2178
- // Detect existing config file
2179
- const viteConfigPath = possibleFiles
2180
- .map(file => path.join(process.cwd(), file))
2181
- .find(filePath => fs.existsSync(filePath));
2182
-
2183
- if (!viteConfigPath) {
2184
- console.warn("⚠️ No vite config found. Skipping.");
2185
- return;
2186
- }
2187
-
2188
- //console.log("📄 Using:", viteConfigPath.split("/").pop());
2189
-
2190
- let viteContent = fs.readFileSync(viteConfigPath, "utf8");
2191
-
2192
- // Skip if already exists
2193
- if (/drop\s*:\s*\[.*['"]console['"].*\]/.test(viteContent)) {
2194
- console.log("ℹ️ vite.config.(m)js already Updated. Skipping...");
2195
- return;
2196
- }
2197
-
2198
- console.log("🔧 Adding esbuild.drop ...");
2199
-
2200
- // If esbuild block exists
2201
- if (/esbuild\s*:\s*{/.test(viteContent)) {
2202
- viteContent = viteContent.replace(
2203
- /esbuild\s*:\s*{([\s\S]*?)(^ {0,8})}/m,
2204
- (full, inner, indent) => {
2205
-
2206
- let lines = inner
2207
- .split("\n")
2208
- .map(l => l.trim())
2209
- .filter(Boolean);
2210
-
2211
- // Fix last comma
2212
- if (lines.length > 0) {
2213
- lines[lines.length - 1] =
2214
- lines[lines.length - 1].replace(/,+$/, "") + ",";
2215
- }
2216
-
2217
- // Re-indent
2218
- lines = lines.map(l => indent + " " + l);
2219
-
2220
- // Add drop
2221
- lines.push(`${indent} drop: ['console','debugger'],`);
2222
-
2223
- return `esbuild: {\n${lines.join("\n")}\n${indent}}`;
2224
- }
2225
- );
2226
- }
2227
-
2228
- // If esbuild missing
2229
- else {
2230
- viteContent = viteContent.replace(
2231
- /export default defineConfig\s*\(\s*{/,
2232
- m => `${m}\n esbuild: {\n drop: ['console','debugger'],\n },`
2233
- );
2234
- }
2235
-
2236
- fs.writeFileSync(viteConfigPath, viteContent, "utf8");
2237
- console.log("✅ vite.config.(m)js Updated successfully.");
2238
- };
2239
-
2240
-
2241
-
2242
-
2243
-
2244
-
2245
-
2246
-
2247
-
2248
-
2249
- const compareVersion = (v1, v2) => {
2250
- const a = v1.split(".").map(Number);
2251
- const b = v2.split(".").map(Number);
2252
-
2253
- for (let i = 0; i < Math.max(a.length, b.length); i++) {
2254
- const num1 = a[i] || 0;
2255
- const num2 = b[i] || 0;
2256
- if (num1 > num2) return 1;
2257
- if (num1 < num2) return -1;
2258
- }
2259
- return 0;
2260
- };
2261
-
2262
-
2263
-
2264
-
2265
-
2266
-
2267
-
2268
-
2269
-
2270
-
2271
- const admobConfigPath = path.join('src', 'js','Ads', 'admob-ad-configuration.json');
2272
-
2273
- const checkAdmobConfigurationProperty=()=>{
2274
-
2275
-
2276
- if (!_admobConfig.ADMOB_ENABLED)
2277
- {
2278
- console.log("ℹ️ Admob is not enabled so 'admob-ad-configuration.json' checking is skipping...");
2279
- return;
2280
- }
2281
-
2282
-
2283
- const REQUIRED_CONFIG_KEYS = [
2284
- "isKidsApp",
2285
- "isTesting",
2286
- "isConsoleLogEnabled",
2287
- "bannerEnabled",
2288
- "interstitialEnabled",
2289
- "appOpenEnabled",
2290
- "rewardVideoEnabled",
2291
- "rewardInterstitialEnabled",
2292
- "collapsibleEnabled",
2293
- "isLandScape",
2294
- "isOverlappingEnable",
2295
- "bannerTypeAndroid",
2296
- "bannerTypeiOS",
2297
- "bannerTopSpaceColor",
2298
- "interstitialLoadScreenTextColor",
2299
- "interstitialLoadScreenBackgroundColor",
2300
- "beforeBannerSpace",
2301
- "whenShow",
2302
- "minimumClick",
2303
- "interstitialTimeOut",
2304
- "interstitialFirstTimeOut",
2305
- "appOpenAdsTimeOut",
2306
- "maxRetryCount",
2307
- "retrySecondsAr",
2308
- "appOpenPerSession",
2309
- "interstitialPerSession",
2310
- "appOpenFirstTimeOut"
2311
- ];
2312
-
2313
-
2314
-
2315
-
2316
-
2317
- let admobConfigInJson;
2318
-
2319
- try {
2320
- admobConfigInJson = JSON.parse(readFileSync(admobConfigPath, "utf8"));
2321
- } catch (err) {
2322
- console.error("❌ Failed to read admob-ad-configuration.json", err);
2323
- process.exit(1);
2324
- }
2325
-
2326
- // ✅ Validate config object exists
2327
- if (!admobConfigInJson.config) {
2328
- console.error('❌ "config" object is missing in admob-ad-configuration.json');
2329
- process.exit(1);
2330
- }
2331
-
2332
-
2333
- const admobConfigMinVersion="1.5"
2334
-
2335
- if (compareVersion(admobConfigInJson.VERSION, admobConfigMinVersion) < 0) {
2336
- console.error(`❌ Please use at-least version ${admobConfigMinVersion} in "src/js/Ads/admob-ad-configuration.json"`);
2337
- process.exit(1);
2338
- }
2339
-
2340
-
2341
- const config = admobConfigInJson.config;
2342
-
2343
- // ✅ Find missing properties
2344
- const missingKeys = REQUIRED_CONFIG_KEYS.filter(
2345
- key => !(key in config)
2346
- );
2347
-
2348
-
2349
-
2350
- if (missingKeys.length > 0) {
2351
- console.error("❌ Missing required configuration keys. Please check it in 'src/js/Ads/admob-ad-configuration.json'");
2352
-
2353
- missingKeys.forEach(k => console.error(" - " + k));
2354
- process.exit(1);
2355
- }
2356
-
2357
-
2358
- console.log('✅ All keys exist. in "admob-ad-configuration.json file" Configuration looks good.');
2359
- }
2360
-
2361
-
2362
-
2363
- function ensureGitignoreEntry(entry) {
2364
- const gitignorePath = path.join(process.cwd(), '.gitignore');
2365
-
2366
- // If .gitignore doesn't exist, create it
2367
- if (!fs.existsSync(gitignorePath)) {
2368
- fs.writeFileSync(gitignorePath, `${entry}\n`, 'utf8');
2369
- console.log(`✅ .gitignore created and added: ${entry}`);
2370
- return;
2371
- }
2372
-
2373
- const content = fs.readFileSync(gitignorePath, 'utf8');
2374
-
2375
- // Normalize lines (trim + remove trailing slashes for comparison)
2376
- const lines = content
2377
- .split(/\r?\n/)
2378
- .map(l => l.trim());
2379
-
2380
- const normalizedEntry = entry.replace(/\/$/, '');
2381
-
2382
- const exists = lines.some(
2383
- line => line.replace(/\/$/, '') === normalizedEntry
2384
- );
2385
-
2386
- if (exists) {
2387
- console.log(`ℹ️ .gitignore already contains: ${entry}`);
2388
- return;
2389
- }
2390
-
2391
- // Ensure file ends with newline
2392
- const separator = content.endsWith('\n') ? '' : '\n';
2393
-
2394
- fs.appendFileSync(gitignorePath, `${separator}${entry}\n`, 'utf8');
2395
- console.log(`✅ Added to .gitignore: ${entry}`);
2396
- }
2397
-
2398
-
2399
- ensureGitignoreEntry('buildCodeplay/');
2400
-
2401
-
2402
- // Run the validation
2403
- (async () => {
2404
-
2405
- await loadPluginVersions(); // 🔥 NEW
2406
-
2407
- await checkPlugins();
2408
- checkAndupdateDropInViteConfig();
2409
- checkAdmobConfigurationProperty()
2410
- })();
2411
-
2412
-
2413
- // ======================================================
2414
- // Validate theme folder location (src/js/theme is NOT allowed)
2415
- // ======================================================
2416
-
2417
- function validateThemeFolderLocation() {
2418
- const oldThemePath = path.join(process.cwd(), 'src', 'js', 'theme');
2419
- const newThemePath = path.join(process.cwd(), 'src', 'theme');
2420
-
2421
- // ❌ Block old structure
2422
- if (fs.existsSync(oldThemePath)) {
2423
- console.error(
2424
- '\n❌ INVALID PROJECT STRUCTURE DETECTED\n' +
2425
- '--------------------------------------------------\n' +
2426
- 'The "theme" folder must NOT be inside:\n' +
2427
- ' src/js/theme\n\n' +
2428
- '✅ Correct location is:\n' +
2429
- ' src/theme\n\n' +
2430
- '🛑 Please move the folder and re-run the build.\n'
2431
- );
2432
- process.exit(1);
2433
- }
2434
-
2435
- // ⚠️ Optional warning if new theme folder is missing
2436
- if (!fs.existsSync(newThemePath)) {
2437
- console.warn(
2438
- '\n⚠️ WARNING: "src/theme" folder not found.\n' +
2439
- 'If your app uses themes, please ensure it exists.\n'
2440
- );
2441
- } else {
2442
- console.log('✅ Theme folder structure validated (src/theme).');
2443
- }
2444
- }
2445
- validateThemeFolderLocation()
2446
-
2447
-
2448
-
2449
- const validateAndRestoreSignDetails=()=>{
2450
-
2451
- // Read config file
2452
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
2453
-
2454
- // Ensure android and buildOptions exist
2455
- if (!config.android) config.android = {};
2456
- if (!config.android.buildOptions) config.android.buildOptions = {};
2457
-
2458
- // Update only if changed
2459
- let updated = false;
2460
-
2461
- if (config.android.buildOptions.releaseType !== 'AAB') {
2462
- config.android.buildOptions.releaseType = 'AAB';
2463
- updated = true;
2464
- }
2465
-
2466
- if (config.android.buildOptions.signingType !== 'jarsigner') {
2467
- config.android.buildOptions.signingType = 'jarsigner';
2468
- updated = true;
2469
- }
2470
-
2471
- // Write back only if modified
2472
- if (updated) {
2473
- fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
2474
- console.log('capacitor.config.json updated successfully.');
2475
- } else {
2476
- console.log('No changes needed.');
2477
- }
2478
-
2479
- }
2480
-
2481
- validateAndRestoreSignDetails()
2482
-
2483
-
2484
- execSync('node buildCodeplay/fix-onesignal-plugin.js', { stdio: 'inherit' });
2485
-
2486
-
2487
-
2488
-
2489
-
2490
-
2491
-
2492
- //################################## SystemBars.java update for "@capacitor/android": "^8.3.0" plugin START ###############################
2493
-
2494
-
2495
- const filePath = path.join(
2496
- __dirname,
2497
- "../node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/SystemBars.java"
2498
- );
2499
-
2500
- // 🔍 OLD BLOCK (anchor)
2501
- const OLD_BLOCK = `if (shouldPassthroughInsets) {
2502
- // We need to correct for a possible shown IME
2503
- v.setPadding(0, 0, 0, keyboardVisible ? imeInsets.bottom : 0);
2504
-
2505
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM && hasViewportCover && insetHandlingEnabled) {
2506
- Insets safeAreaInsets = calcSafeAreaInsets(insets);
2507
- injectSafeAreaCSS(safeAreaInsets.top, safeAreaInsets.right, safeAreaInsets.bottom, safeAreaInsets.left);
2508
- }
2509
-
2510
- return new WindowInsetsCompat.Builder(insets)
2511
- .setInsets(
2512
- WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout(),
2513
- Insets.of(
2514
- systemBarsInsets.left,
2515
- systemBarsInsets.top,
2516
- systemBarsInsets.right,
2517
- getBottomInset(systemBarsInsets, keyboardVisible)
2518
- )
2519
- )
2520
- .build();
2521
- }`;
2522
-
2523
- // ✅ NEW BLOCK
2524
- const NEW_BLOCK = `if (shouldPassthroughInsets) {
2525
- /* 🔴 ORIGINAL CODE (COMMENTED FOR SAFETY)
2526
- ${OLD_BLOCK.split("\n").map(line => " " + line).join("\n")}
2527
- */
2528
-
2529
- // ✅ NEW LOGIC (CUSTOM FIX)
2530
- v.setPadding(0, 0, 0, 0);
2531
-
2532
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM && hasViewportCover && insetHandlingEnabled) {
2533
- Insets safeAreaInsets = calcSafeAreaInsets(insets);
2534
- injectSafeAreaCSS(safeAreaInsets.top, safeAreaInsets.right, safeAreaInsets.bottom, safeAreaInsets.left);
2535
- }
2536
-
2537
- return insets; // WebView handles everything
2538
- }`;
2539
-
2540
- // 🚨 ERROR MESSAGE
2541
- const ERROR_MSG = `
2542
- ❌ Capacitor SystemBars.java structure changed!
2543
-
2544
- Plugin: @capacitor/android
2545
- Path : node_modules\@capacitor\android\capacitor\src\main\java\com\getcapacitor\plugin\SystemBars.java
2546
-
2547
- Check version of "@capacitor/android": in package.json
2548
-
2549
- 👉 Expected code block not found.
2550
-
2551
- This usually means Capacitor updated internally.
2552
-
2553
- Please:
2554
- 1. Open SystemBars.java
2555
- 2. Update patch script
2556
- 3. Re-run build
2557
-
2558
- ⛔ Build stopped.
2559
- `;
2560
-
2561
- function patchFile() {
2562
- if (!fs.existsSync(filePath)) {
2563
- console.error("❌ SystemBars.java not found!");
2564
- process.exit(1);
2565
- }
2566
-
2567
- let content = fs.readFileSync(filePath, "utf8");
2568
-
2569
- // ✅ Already patched?
2570
- if (content.includes("🔴 ORIGINAL CODE (COMMENTED FOR SAFETY)")) {
2571
- console.log("✅ Already SystemBars.java patched. Skipping...");
2572
- return;
2573
- }
2574
-
2575
- // 🔍 Check old block exists
2576
- if (!content.includes(OLD_BLOCK)) {
2577
- console.error(ERROR_MSG);
2578
- process.exit(1);
2579
- }
2580
-
2581
- // 🔁 Replace
2582
- const updated = content.replace(OLD_BLOCK, NEW_BLOCK);
2583
-
2584
- fs.writeFileSync(filePath, updated, "utf8");
2585
-
2586
- console.log("✅ SystemBars.java patched (comment + new logic)!");
2587
- }
2588
-
2589
- patchFile();
2590
-
2591
- //################################## SystemBars.java update for "@capacitor/android": "^8.3.0" plugin END ###############################
2592
-
2593
-
2594
-
2595
-
2596
- /*
2597
- Release Notes
2598
-
2599
- 5.1
2600
- Kotlin version update is commented. Previously admob is not worked if not update the kotlin version to higher version
2601
-
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const plist = require('plist');
4
+
5
+
6
+
7
+ const { execSync } = require("child_process");
8
+
9
+
10
+
11
+
12
+ const { readFileSync } = require("fs");
13
+
14
+ const ENABLE_AUTO_UPDATE = true;
15
+ const USE_LIVE_SERVER_VERSION = true;
16
+
17
+ const configPath = path.join(process.cwd(), 'capacitor.config.json');
18
+ const updateLogFile = path.join(process.cwd(), "", "plugin-update-log.txt");
19
+
20
+ // Expected plugin list with minimum versions
21
+ /* const requiredPlugins = [
22
+
23
+ { pattern: /backbutton-(\d+\.\d+)\.js$/, minVersion: '2.0', required: true, baseDir: 'js',mandatoryUpdate: true},
24
+
25
+
26
+ { pattern: /common-(\d+\.\d+)(?:-beta-(\d+))?\.js$/, minVersion: '6.0', required: true, baseDir: 'js',mandatoryUpdate: true },
27
+
28
+ { pattern: /localization_settings-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true, baseDir: 'js',mandatoryUpdate: false },
29
+ { pattern: /localization-(\d+\.\d+)\.js$/, minVersion: '1.5', required: true, baseDir: 'js',mandatoryUpdate: true },
30
+ { pattern: /localNotification-(\d+\.\d+)\.js$/, minVersion: '2.2', required: true, baseDir: 'js',mandatoryUpdate: false },
31
+ { pattern: /localNotification_AppSettings-(\d+\.\d+)\.js$/, minVersion: '1.0', required: true, baseDir: 'js',mandatoryUpdate: false },
32
+ { pattern: /onesignal-(\d+\.\d+)\.js$/, minVersion: '2.3', required: true, baseDir: 'js',mandatoryUpdate: false },
33
+ { pattern: /saveToGalleryAndSaveAnyFile-(\d+\.\d+)(-ios)?\.js$/, minVersion: '3.1', required: true, baseDir: 'js',mandatoryUpdate: true },
34
+ { pattern: /Ads[\/\\]admob-emi-(\d+\.\d+)\.js$/, minVersion: '3.7', required: true, baseDir: 'js',mandatoryUpdate: true },
35
+
36
+ // New added plugins
37
+ { pattern: /video-player-(\d+\.\d+)\.js$/, minVersion: '1.5', required: true, baseDir: 'js',mandatoryUpdate: false },
38
+ { pattern: /image-cropper-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true, baseDir: 'js',mandatoryUpdate: false },
39
+ { pattern: /common-(\d+\.\d+)\.less$/, minVersion: '1.6', required: true, baseDir: 'assets/css',mandatoryUpdate: false },
40
+
41
+
42
+ // New folders
43
+ { pattern: /IAP-(\d+\.\d+)$/, minVersion: '2.8', isFolder: true , required: true, baseDir: 'js/Ads',mandatoryUpdate: true },
44
+ { pattern: /editor-(\d+\.\d+)$/, minVersion: '1.9', isFolder: true, required: true, baseDir: 'js',mandatoryUpdate: true },
45
+ { pattern: /ffmpeg-(\d+\.\d+)$/, minVersion: '1.6', isFolder: true, required: true, baseDir: 'js',mandatoryUpdate: true },
46
+ { pattern: /theme-(\d+\.\d+)$/, minVersion: '3.3', isFolder: true , required: true, baseDir: 'theme',mandatoryUpdate: true },
47
+
48
+
49
+ { pattern: /certificatejs-(\d+\.\d+)$/, minVersion: '1.6', isFolder: true , required: true, baseDir: 'certificate',mandatoryUpdate: true }
50
+
51
+ ]; */
52
+
53
+
54
+ const ROOT_DIR = path.join(__dirname, "..", "src");
55
+
56
+ function requireOrInstall(packageName) {
57
+ try {
58
+ return require(packageName);
59
+ } catch (err) {
60
+
61
+ console.log(`📦 "${packageName}" not found. Installing automatically...`);
62
+
63
+ try {
64
+ execSync(`npm install ${packageName}`, { stdio: "inherit" });
65
+ console.log(`✅ "${packageName}" installed successfully.`);
66
+ } catch (installErr) {
67
+ console.error(`❌ Failed to install "${packageName}".`);
68
+ process.exit(1);
69
+ }
70
+
71
+ // Try loading again
72
+ return require(packageName);
73
+ }
74
+ }
75
+
76
+ const AdmZip = requireOrInstall("adm-zip");
77
+
78
+
79
+
80
+ const pkg = require(path.join(process.cwd(), 'node_modules', 'codeplay-common', 'package.json'));
81
+
82
+ const pluginName = pkg.name;
83
+ const pluginVersion = pkg.version;
84
+
85
+ let updateLogs = [];
86
+
87
+ function writeUpdateLine(message) {
88
+ updateLogs.push(message);
89
+ }
90
+
91
+ const MAX_LOG_BLOCKS = 50;
92
+
93
+ function saveUpdateLogs() {
94
+
95
+ if (updateLogs.length === 0) return;
96
+
97
+ const logDir = path.dirname(updateLogFile);
98
+
99
+ if (!fs.existsSync(logDir)) {
100
+ fs.mkdirSync(logDir, { recursive: true });
101
+ }
102
+
103
+ const now = new Date();
104
+
105
+ const formattedTime = now.toLocaleString('en-GB', {
106
+ day: '2-digit',
107
+ month: '2-digit',
108
+ year: 'numeric',
109
+ hour: '2-digit',
110
+ minute: '2-digit',
111
+ hour12: true
112
+ }).replace(',', '').replace(/\//g, '-');
113
+
114
+ let newBlock = `${pluginName}: ${pluginVersion}\n[${formattedTime}]\n`;
115
+
116
+ updateLogs.forEach(line => {
117
+ newBlock += `${line}\n`;
118
+ });
119
+
120
+ newBlock += "\n";
121
+
122
+ let existingLog = "";
123
+
124
+ if (fs.existsSync(updateLogFile)) {
125
+ existingLog = fs.readFileSync(updateLogFile, "utf8");
126
+ }
127
+
128
+ let combinedLog = newBlock + existingLog;
129
+
130
+ // Split blocks by plugin header
131
+ const blocks = combinedLog.split(/\n(?=codeplay-common:)/);
132
+
133
+ // Keep only latest 50
134
+ const trimmed = blocks.slice(0, MAX_LOG_BLOCKS).join("\n");
135
+
136
+ fs.writeFileSync(updateLogFile, trimmed);
137
+
138
+ }
139
+
140
+
141
+
142
+
143
+
144
+ const versionsFile = path.join(__dirname, "versions.json");
145
+
146
+ function loadRequiredPlugins() {
147
+
148
+ if (!fs.existsSync(versionsFile)) {
149
+ console.error("❌ versions.json not found");
150
+ process.exit(1);
151
+ }
152
+
153
+ const json = JSON.parse(fs.readFileSync(versionsFile, "utf8"));
154
+
155
+ return json.plugins.map(p => ({
156
+ ...p,
157
+ pattern: new RegExp(p.pattern)
158
+ }));
159
+
160
+ }
161
+
162
+ let requiredPlugins = loadRequiredPlugins();
163
+
164
+
165
+
166
+
167
+
168
+
169
+ async function downloadAndExtractZip(url, destFolder) {
170
+
171
+ const zipPath = destFolder + ".zip";
172
+
173
+ await downloadFile(url, zipPath);
174
+
175
+ const zip = new AdmZip(zipPath);
176
+ zip.extractAllTo(destFolder, true);
177
+
178
+ fs.unlinkSync(zipPath);
179
+
180
+ }
181
+
182
+
183
+
184
+
185
+
186
+
187
+
188
+ //Check codeplay-common latest version installed or not Start
189
+ //const { execSync } = require('child_process');
190
+
191
+
192
+ function getInstalledVersion(packageName) {
193
+ try {
194
+ const packageJsonPath = path.join(process.cwd(), 'node_modules', packageName, 'package.json');
195
+ if (fs.existsSync(packageJsonPath)) {
196
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
197
+ return packageJson.version;
198
+ }
199
+ } catch (error) {
200
+ return null;
201
+ }
202
+ return null;
203
+ }
204
+
205
+ function getLatestVersion(packageName) {
206
+ try {
207
+ return execSync(`npm view ${packageName} version`).toString().trim();
208
+ } catch (error) {
209
+ console.error(`Failed to fetch latest version for ${packageName}`);
210
+ return null;
211
+ }
212
+ }
213
+
214
+ function checkPackageVersion() {
215
+ const packageName = 'codeplay-common';
216
+ const installedVersion = getInstalledVersion(packageName);
217
+ const latestVersion = getLatestVersion(packageName);
218
+
219
+ if (!installedVersion) {
220
+ console.error(`${packageName} is not installed. Please install it using "npm install ${packageName}".`);
221
+ process.exit(1);
222
+ }
223
+
224
+ if (installedVersion !== latestVersion) {
225
+ 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`);
226
+ process.exit(1);
227
+ }
228
+
229
+ console.log(`${packageName} is up to date (version ${installedVersion}).`);
230
+ }
231
+
232
+ // Run package version check before executing the main script
233
+ try {
234
+ checkPackageVersion();
235
+ } catch (error) {
236
+ console.error(error.message);
237
+ process.exit(1);
238
+ }
239
+
240
+ //Check codeplay-common latest version installed or not END
241
+
242
+
243
+
244
+ function compareWithBeta(installedVersion, minVersion, isBeta) {
245
+ const baseCompare = compareVersions(installedVersion, minVersion);
246
+
247
+ if (!isBeta) {
248
+ // Stable version → normal compare
249
+ return baseCompare;
250
+ }
251
+
252
+ // Beta version logic
253
+ if (baseCompare > 0) return 1; // 5.3-beta > 5.2
254
+ if (baseCompare < 0) return -1; // 5.1-beta < 5.2
255
+
256
+ // Same version but beta → LOWER than stable
257
+ return -1; // 5.2-beta < 5.2
258
+ }
259
+
260
+
261
+
262
+
263
+ const checkAppUniqueId=()=>{
264
+
265
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
266
+
267
+ const appUniqueId = config.android?.APP_UNIQUE_ID;
268
+ const RESIZEABLE_ACTIVITY = config.android?.RESIZEABLE_ACTIVITY;
269
+ const orientation = config.android?.ORIENTATION;
270
+
271
+
272
+ let logErrorMessage="";
273
+
274
+ // 1️⃣ Check if it’s missing
275
+ if (RESIZEABLE_ACTIVITY === undefined) {
276
+ logErrorMessage+='❌ Missing android.RESIZEABLE_ACTIVITY option in capacitor.config.json.\n';
277
+ }
278
+
279
+ // 2️⃣ Check if it’s not boolean (true/false only)
280
+ else if (typeof RESIZEABLE_ACTIVITY !== 'boolean') {
281
+ logErrorMessage+='❌ Invalid android.RESIZEABLE_ACTIVITY value. Please use only true or false (without quotes).\n';
282
+ }
283
+
284
+
285
+
286
+ if (!orientation) {
287
+ logErrorMessage+='❌ Missing android.ORIENTATION option in capacitor.config.json.\n';
288
+ }
289
+
290
+ else if(orientation!="portrait" && orientation!="landscape" && orientation!="auto")
291
+ {
292
+ logErrorMessage+='❌ Spelling mistake in android.ORIENTATION option in capacitor.config.json. Please use only ["portrait" "landscape" "auto"]\n';
293
+ }
294
+
295
+
296
+ if (!appUniqueId) {
297
+ logErrorMessage+='❌ APP_UNIQUE_ID is missing in capacitor.config.json.';
298
+ }
299
+
300
+ else if (!Number.isInteger(appUniqueId)) {
301
+ logErrorMessage+='❌ APP_UNIQUE_ID must be an integer. Example: 1, 2, 3, etc.';
302
+ }
303
+
304
+
305
+
306
+ if(logErrorMessage!="")
307
+ {
308
+ console.error(logErrorMessage);
309
+ process.exit(1)
310
+ }
311
+
312
+
313
+ console.log(`✅ APP_UNIQUE_ID is valid: ${appUniqueId}`);
314
+
315
+ }
316
+
317
+ checkAppUniqueId();
318
+
319
+
320
+
321
+
322
+
323
+
324
+ // ======================================================
325
+ // 🚫 BLOCK STATIC IMPORT OF showSubscribePopup (ANY VERSION)
326
+ // ======================================================
327
+
328
+ const STATIC_SUBSCRIBE_REGEX = /import\s*{\s*showSubscribePopup\s*}\s*from\s*['"].*\/js\/Ads\/IAP-\d+(\.\d+)*\/IAP-check-And-LoadAd\.js['"]/;
329
+
330
+ // ✅ Detect dynamic import (valid)
331
+ const DYNAMIC_SUBSCRIBE_REGEX = /await\s+import\s*\(\s*['"].*\/js\/Ads\/IAP-\d+(\.\d+)*\/IAP-check-And-LoadAd\.js['"]\s*\)/;
332
+
333
+ let subscribeImportError = false;
334
+
335
+ function scanSubscribeImport(dir) {
336
+ const files = fs.readdirSync(dir);
337
+
338
+ for (const file of files) {
339
+ const fullPath = path.join(dir, file);
340
+ const stat = fs.statSync(fullPath);
341
+
342
+ if (stat.isDirectory()) {
343
+ scanSubscribeImport(fullPath);
344
+ }
345
+ else if (file.endsWith(".js") || file.endsWith(".ts") || file.endsWith(".f7")) {
346
+
347
+ const content = fs.readFileSync(fullPath, "utf-8");
348
+ const lines = content.split("\n");
349
+
350
+ lines.forEach((line, index) => {
351
+
352
+ // ❌ STATIC import → ERROR
353
+ if (STATIC_SUBSCRIBE_REGEX.test(line)) {
354
+ console.error(`
355
+ ❌ Forbidden static import detected!
356
+
357
+ File: ${fullPath}
358
+ Line: ${index + 1}
359
+ Code: ${line.trim()}
360
+
361
+ 🚫 DO NOT use static import for showSubscribePopup
362
+
363
+ 👉 Remove:
364
+ import { showSubscribePopup } from './../js/Ads/IAP-x.x/IAP-check-And-LoadAd.js'
365
+
366
+
367
+ ✅ Use dynamic import (ANY version allowed):
368
+
369
+ let IAPModule = null;
370
+ const loadIAP = async () => {
371
+ if (!IAPModule) {
372
+ IAPModule = await import('./../js/Ads/IAP-x.x/IAP-check-And-LoadAd.js');
373
+ IAPModule.initIAP?.();
374
+ }
375
+
376
+ return IAPModule;
377
+ };
378
+
379
+ $on('pageAfterIn', async () => {
380
+ await loadIAP();
381
+ });
382
+
383
+ const subscribeOrProLink = async () => {
384
+
385
+ //This is only allowed if samsung have pro version
386
+ if(_storeid==2)
387
+ gotoBuyPro("com.html.codeplay.pro",noAppOpenShowUntilResume)
388
+ else{
389
+ const module = await loadIAP();
390
+ module.showSubscribePopup();
391
+ }
392
+ };
393
+ `);
394
+ subscribeImportError = true;
395
+ }
396
+
397
+ // ❌ Optional: detect wrong dynamic usage (no await)
398
+ if (
399
+ line.includes("import(") &&
400
+ line.includes("IAP-") &&
401
+ !line.includes("await")
402
+ ) {
403
+ console.warn(`
404
+ ⚠️ Warning: Dynamic import without await
405
+
406
+ File: ${fullPath}
407
+ Line: ${index + 1}
408
+ Code: ${line.trim()}
409
+
410
+ 👉 Always use:
411
+ const { showSubscribePopup } = await import(...)
412
+ `);
413
+ }
414
+
415
+ });
416
+ }
417
+ }
418
+ }
419
+
420
+
421
+ // Run scan
422
+ scanSubscribeImport(ROOT_DIR);
423
+
424
+ // Stop build
425
+ if (subscribeImportError) {
426
+ console.error("🚫 Build failed due to forbidden showSubscribePopup static import.");
427
+ process.exit(1);
428
+ } else {
429
+ console.log("✅ showSubscribePopup import usage is valid.");
430
+ }
431
+
432
+
433
+
434
+
435
+ // ======================================================
436
+ // 🚫 BLOCK STATIC IMPORT OF showSubscribePopup (ANY VERSION) END
437
+ // ======================================================
438
+
439
+
440
+
441
+
442
+
443
+
444
+
445
+
446
+
447
+
448
+
449
+ //@Codemirror check and install/uninstall the packages START
450
+ //const fs = require("fs");
451
+ //const path = require("path");
452
+ //const { execSync } = require("child_process");
453
+
454
+ const jsDir = path.join(__dirname, "..", "src", "js");
455
+
456
+ // 🔍 Detect OLD structure
457
+ const oldEditorDirs = fs.readdirSync(jsDir)
458
+ .filter(name => /^editor-\d+\.\d+$/.test(name));
459
+
460
+ // 📁 New structure path (optional, not mandatory)
461
+ const newEditorBaseDir = path.join(jsDir, "editor");
462
+
463
+ // ======================================================
464
+ // ❌ CASE 1: OLD STRUCTURE FOUND → STOP
465
+ // ======================================================
466
+ if (oldEditorDirs.length > 0) {
467
+
468
+ console.error(`
469
+ ❌ OLD EDITOR STRUCTURE DETECTED
470
+
471
+ You are using outdated folder structure:
472
+ src/js/editor-x.x/
473
+
474
+ 🚨 This is no longer supported.
475
+
476
+ 📦 Found folders:
477
+ ${oldEditorDirs.map(d => " - " + d).join("\n")}
478
+
479
+ 👉 Please move them manually:
480
+
481
+ src/js/editor-1.6
482
+
483
+ src/js/editor/editor-1.6
484
+
485
+ ⚠️ Also ensure:
486
+ src/js/editor/configuration.json exists
487
+
488
+ ❌ Build stopped.
489
+ `);
490
+
491
+ process.exit(1);
492
+ }
493
+
494
+ // ======================================================
495
+ // ✅ CASE 2: NEW STRUCTURE EXISTS → VALIDATE
496
+ // ======================================================
497
+ if (fs.existsSync(newEditorBaseDir)) {
498
+
499
+ // 🔍 Find editor-x.x inside new folder
500
+ const editorDirs = fs.readdirSync(newEditorBaseDir)
501
+ .filter(name => /^editor-\d+\.\d+$/.test(name));
502
+
503
+ // 👉 If editor folder exists but no versions → skip safely
504
+ if (editorDirs.length === 0) {
505
+ console.log("ℹ️ No editor-x.x folders found inside src/js/editor/");
506
+ return;
507
+ }
508
+
509
+ // ======================================================
510
+ // ✅ Validate configuration.json (NEW RULE)
511
+ // ======================================================
512
+
513
+ const editorConfigPath = path.join(newEditorBaseDir, "configuration.json");
514
+
515
+ // ❌ Missing config
516
+ if (!fs.existsSync(editorConfigPath)) {
517
+ console.error(`
518
+ ❌ MISSING EDITOR CONFIGURATION FILE
519
+
520
+ Required:
521
+ src/js/editor/configuration.json
522
+
523
+ ❌ Build stopped.
524
+ `);
525
+ process.exit(1);
526
+ }
527
+
528
+ // ❌ Check wrong placement
529
+ const invalidConfigs = [];
530
+
531
+ editorDirs.forEach(dir => {
532
+ const wrongPath = path.join(newEditorBaseDir, dir, "configuration.json");
533
+ if (fs.existsSync(wrongPath)) {
534
+ invalidConfigs.push(`src/js/editor/${dir}/configuration.json`);
535
+ }
536
+ });
537
+
538
+ if (invalidConfigs.length > 0) {
539
+ console.error(`
540
+ ❌ INVALID CONFIGURATION LOCATION
541
+
542
+ 🚫 configuration.json must NOT be inside version folders.
543
+
544
+ Found:
545
+ ${invalidConfigs.map(p => " - " + p).join("\n")}
546
+
547
+ ✅ Correct:
548
+ src/js/editor/configuration.json
549
+
550
+ ❌ Build stopped.
551
+ `);
552
+ process.exit(1);
553
+ }
554
+
555
+ console.log("✅ Editor structure validated.");
556
+
557
+ // ======================================================
558
+ // 🚀 Continue execution (run.js)
559
+ // ======================================================
560
+
561
+ const latestEditorDir = editorDirs.sort((a, b) => {
562
+ const vA = parseFloat(a.split('-')[1]);
563
+ const vB = parseFloat(b.split('-')[1]);
564
+ return vB - vA;
565
+ })[0];
566
+
567
+ const runJsPath = path.join(newEditorBaseDir, latestEditorDir, "run.js");
568
+
569
+ if (!fs.existsSync(runJsPath)) {
570
+ console.error(`❌ run.js not found in ${latestEditorDir}`);
571
+ process.exit(1);
572
+ }
573
+
574
+ console.log(`🚀 Executing ${runJsPath}...`);
575
+ execSync(`node "${runJsPath}"`, { stdio: "inherit" });
576
+ }
577
+
578
+ // ======================================================
579
+ // ✅ CASE 3: NOTHING EXISTS → DO NOTHING
580
+ // ======================================================
581
+ else {
582
+ console.log("ℹ️ Editor not used in this project. Skipping...");
583
+ }
584
+
585
+ //@Codemirror check and install/uninstall the packages END
586
+
587
+
588
+
589
+
590
+
591
+
592
+
593
+
594
+
595
+ // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists START
596
+
597
+ const os = require('os');
598
+
599
+ const saveToGalleryAndSaveFileCheck_iOS = () => {
600
+
601
+ // List of paths to scan
602
+ const SCAN_PATHS = [
603
+ path.resolve(__dirname, '../src/certificate'),
604
+ path.resolve(__dirname, '../src/pages'),
605
+ path.resolve(__dirname, '../src/js'),
606
+ path.resolve(__dirname, '../src/app.f7')
607
+ ];
608
+
609
+ // Directory to exclude
610
+ const EXCLUDED_DIR = path.resolve(__dirname, '../src/js/Ads');
611
+
612
+ const ANDROID_MANIFEST_PATH = path.resolve(__dirname, '../android/app/src/main/AndroidManifest.xml');
613
+
614
+
615
+ // Match iOS-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5-ios.js) not in comments
616
+ const IOS_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*-ios\.js['"]/m;
617
+
618
+ // Match Android-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5.js) not in comments
619
+ const ANDROID_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*\.js['"]/m;
620
+
621
+
622
+
623
+
624
+
625
+ const ALLOWED_EXTENSIONS = ['.js', '.f7'];
626
+ const isMac = os.platform() === 'darwin';
627
+
628
+ let iosImportFound = false;
629
+ let androidImportFound = false;
630
+
631
+ // Files to skip completely (full or partial match)
632
+ const SKIP_FILES = [
633
+ 'pdf-3.11.174.min.js',
634
+ 'pdf.worker-3.11.174.min.js'
635
+ ,'index.browser.js'
636
+ ];
637
+
638
+
639
+ function scanDirectory(dir) {
640
+
641
+ /*
642
+ //######################### DO NOT DELETE THIS - START [Appid base validation] #####################################
643
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
644
+ const appUniqueId = config.android?.APP_UNIQUE_ID;
645
+ if (appUniqueId == "206") return;
646
+ //######################### DO NOT DELETE THIS - END [Appid base validation] #####################################
647
+ */
648
+
649
+ const stat = fs.statSync(dir);
650
+
651
+ if (stat.isFile()) {
652
+
653
+ // 🔥 Skip files in SKIP_FILES array
654
+ const baseName = path.basename(dir);
655
+ if (SKIP_FILES.includes(baseName)) {
656
+ // Just skip silently
657
+ return;
658
+ }
659
+
660
+ // Only scan allowed file extensions
661
+ if (ALLOWED_EXTENSIONS.some(ext => dir.endsWith(ext))) {
662
+ process.stdout.write(`\r🔍 Scanning: ${dir} `);
663
+
664
+ const content = fs.readFileSync(dir, 'utf8');
665
+
666
+ if (IOS_FILE_REGEX.test(content)) {
667
+ iosImportFound = true;
668
+ if (!isMac) {
669
+ console.error(`\n❌ ERROR: iOS-specific import detected in: ${dir}`);
670
+ console.error(`🚫 STOPPED: This file should not be imported in Android/Windows/Linux builds.\n`);
671
+ process.exit(1);
672
+ }
673
+ }
674
+ else if (ANDROID_FILE_REGEX.test(content) && !content.includes('-ios.js')) {
675
+ androidImportFound = true;
676
+ }
677
+ }
678
+ }
679
+ else if (stat.isDirectory()) {
680
+ if (dir === EXCLUDED_DIR || path.basename(dir) === 'node_modules') return;
681
+
682
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
683
+ for (let entry of entries) {
684
+ scanDirectory(path.join(dir, entry.name));
685
+ }
686
+ }
687
+ }
688
+
689
+
690
+ // Run scan on all specified paths
691
+ for (let scanPath of SCAN_PATHS) {
692
+ if (fs.existsSync(scanPath)) {
693
+ scanDirectory(scanPath);
694
+ }
695
+ }
696
+
697
+
698
+
699
+ /* // Check src folder
700
+ if (!fs.existsSync(ROOT_DIR)) {
701
+ console.warn(`⚠️ Warning: 'src' directory not found at: ${ROOT_DIR}`);
702
+ return;
703
+ } */
704
+
705
+ //scanDirectory(ROOT_DIR);
706
+
707
+ // iOS Checks
708
+ if (isMac && !iosImportFound) {
709
+ console.warn(`⚠️ WARNING: You're on macOS but no iOS version (saveToGalleryAndSaveAnyFile-x.x-ios.js) found.`);
710
+ process.exit(1);
711
+ } else if (isMac && iosImportFound) {
712
+ console.log('✅ iOS version detected for macOS build.');
713
+ } else if (!iosImportFound) {
714
+ console.log('✅ No iOS-specific imports detected for non-macOS.');
715
+ }
716
+
717
+ // Android Checks
718
+ if (androidImportFound) {
719
+ console.log("📱 Android version of saveToGalleryAndSaveAnyFile detected. Checking AndroidManifest.xml...");
720
+
721
+ if (!fs.existsSync(ANDROID_MANIFEST_PATH)) {
722
+ console.error("❌ AndroidManifest.xml not found. Cannot add requestLegacyExternalStorage attribute.");
723
+ return;
724
+ }
725
+
726
+ let manifestContent = fs.readFileSync(ANDROID_MANIFEST_PATH, 'utf8');
727
+
728
+ if (!manifestContent.includes('android:requestLegacyExternalStorage="true"')) {
729
+ console.log("Adding android:requestLegacyExternalStorage=\"true\" to <application> tag...");
730
+
731
+ manifestContent = manifestContent.replace(
732
+ /<application([^>]*)>/,
733
+ (match, attrs) => {
734
+ if (attrs.includes('android:requestLegacyExternalStorage')) return match;
735
+ return `<application${attrs} android:requestLegacyExternalStorage="true">`;
736
+ }
737
+ );
738
+
739
+ fs.writeFileSync(ANDROID_MANIFEST_PATH, manifestContent, 'utf8');
740
+ console.log("✅ android:requestLegacyExternalStorage=\"true\" added successfully.");
741
+ } else {
742
+ console.log("ℹ️ android:requestLegacyExternalStorage already exists in AndroidManifest.xml.");
743
+ }
744
+ } else {
745
+ console.log("✅ No Android saveToGalleryAndSaveAnyFile imports detected.");
746
+ }
747
+ };
748
+
749
+ saveToGalleryAndSaveFileCheck_iOS();
750
+ // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists END
751
+
752
+
753
+
754
+
755
+
756
+
757
+
758
+
759
+
760
+
761
+
762
+
763
+
764
+ /*
765
+ // Clean up AppleDouble files (._*) created by macOS START
766
+ if (process.platform === 'darwin') {
767
+ try {
768
+ console.log('🧹 Cleaning up AppleDouble files (._*)...');
769
+ execSync(`find . -name '._*' -delete`);
770
+ console.log('✅ AppleDouble files removed.');
771
+ } catch (err) {
772
+ console.warn('⚠️ Failed to remove AppleDouble files:', err.message);
773
+ }
774
+ } else {
775
+ console.log('ℹ️ Skipping AppleDouble cleanup — not a macOS machine.');
776
+ }
777
+
778
+ // Clean up AppleDouble files (._*) created by macOS END
779
+ */
780
+
781
+
782
+
783
+
784
+
785
+
786
+ //In routes.js file check static import START
787
+
788
+ const routesPath = path.join(process.cwd(), 'src', 'js', 'routes.js');
789
+ const routesContent = fs.readFileSync(routesPath, 'utf-8');
790
+
791
+ let inBlockComment = false;
792
+ const lines = routesContent.split('\n');
793
+
794
+ const allowedImport = `import HomePage from '../pages/home.f7';`;
795
+ const badImportRegex = /^[ \t]*import\s+[\w{}*,\s]*\s+from\s+['"].+\.f7['"]\s*;/;
796
+ const badImports = [];
797
+
798
+ lines.forEach((line, index) => {
799
+ const trimmed = line.trim();
800
+
801
+ // Handle block comment start and end
802
+ if (trimmed.startsWith('/*')) inBlockComment = true;
803
+ if (inBlockComment && trimmed.endsWith('*/')) {
804
+ inBlockComment = false;
805
+ return;
806
+ }
807
+
808
+ // Skip if inside block comment or line comment
809
+ if (inBlockComment || trimmed.startsWith('//')) return;
810
+
811
+ // Match static .f7 import
812
+ if (badImportRegex.test(trimmed) && trimmed !== allowedImport) {
813
+ badImports.push({ line: trimmed, number: index + 1 });
814
+ }
815
+ });
816
+
817
+ if (badImports.length > 0) {
818
+ console.error('\n❌ ERROR: Detected disallowed static imports of .f7 files in routes.js\n');
819
+ console.error(`⚠️ Only this static import is allowed:\n ${allowedImport}\n`);
820
+ console.error(`🔧 Please convert other imports to async dynamic imports like this:\n`);
821
+ console.error(`
822
+
823
+ import HomePage from '../pages/home.f7';
824
+
825
+ const routes = [
826
+ {
827
+ path: '/',
828
+ component:HomePage,
829
+ },
830
+ {
831
+ path: '/ProfilePage/',
832
+ async async({ resolve }) {
833
+ const page = await import('../pages/profile.f7');
834
+ resolve({ component: page.default });
835
+ },
836
+ }]
837
+ `);
838
+
839
+ badImports.forEach(({ line, number }) => {
840
+ console.error(`${number}: ${line}`);
841
+ });
842
+
843
+ process.exit(1);
844
+ } else {
845
+ console.log('✅ routes.js passed the .f7 import check.');
846
+ }
847
+
848
+ //In routes.js file check static import END
849
+
850
+
851
+
852
+
853
+
854
+
855
+
856
+
857
+
858
+
859
+
860
+
861
+
862
+ // Check and change the "BridgeWebViewClient.java" file START
863
+ /*
864
+ For crash issue due to low memory problem, we need to modify the onRenderProcessGone method in BridgeWebViewClient.java.
865
+ */
866
+
867
+
868
+ const bridgeWebViewClientFilePath = path.join(process.cwd(), 'node_modules', '@capacitor/android/capacitor/src/main/java/com/getcapacitor', 'BridgeWebViewClient.java');
869
+
870
+ // Read the file
871
+ if (!fs.existsSync(bridgeWebViewClientFilePath)) {
872
+ console.error('❌ Error: BridgeWebViewClient.java not found.');
873
+ process.exit(1);
874
+ }
875
+
876
+ let fileContent = fs.readFileSync(bridgeWebViewClientFilePath, 'utf8');
877
+
878
+ // Define old and new code
879
+ const oldCodeStart = `@Override
880
+ public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
881
+ super.onRenderProcessGone(view, detail);
882
+ boolean result = false;
883
+
884
+ List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
885
+ if (webViewListeners != null) {
886
+ for (WebViewListener listener : bridge.getWebViewListeners()) {
887
+ result = listener.onRenderProcessGone(view, detail) || result;
888
+ }
889
+ }
890
+
891
+ return result;
892
+ }`;
893
+
894
+ const newCode = `@Override
895
+ public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
896
+ super.onRenderProcessGone(view, detail);
897
+
898
+ boolean result = false;
899
+
900
+ List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
901
+ if (webViewListeners != null) {
902
+ for (WebViewListener listener : bridge.getWebViewListeners()) {
903
+ result = listener.onRenderProcessGone(view, detail) || result;
904
+ }
905
+ }
906
+
907
+ if (!result) {
908
+ // If no one handled it, handle it ourselves!
909
+
910
+ /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
911
+ if (detail.didCrash()) {
912
+ //Log.e("CapacitorWebView", "WebView crashed internally!");
913
+ } else {
914
+ //Log.w("CapacitorWebView", "WebView was killed by system (low memory) internally!");
915
+ }
916
+ }*/
917
+
918
+ view.post(() -> {
919
+ Toast.makeText(view.getContext(), "Reloading due to low memory issue", Toast.LENGTH_SHORT).show();
920
+ });
921
+
922
+ view.reload(); // Safely reload WebView
923
+
924
+ return true; // We handled it
925
+ }
926
+
927
+ return result;
928
+ }`;
929
+
930
+ // Step 1: Update method if needed
931
+ let updated = false;
932
+
933
+ if (fileContent.includes(oldCodeStart)) {
934
+ console.log('✅ Found old onRenderProcessGone method. Replacing it...');
935
+ fileContent = fileContent.replace(oldCodeStart, newCode);
936
+ updated = true;
937
+ } else if (fileContent.includes(newCode)) {
938
+ console.log('ℹ️ Method already updated. No changes needed in "BridgeWebViewClient.java".');
939
+ } else {
940
+ console.error('❌ Error: Neither old nor new code found. Unexpected content.');
941
+ process.exit(1);
942
+ }
943
+
944
+ // Step 2: Check and add import if missing
945
+ const importToast = 'import android.widget.Toast;';
946
+ if (!fileContent.includes(importToast)) {
947
+ console.log('✅ Adding missing import for Toast...');
948
+ const importRegex = /import\s+[^;]+;/g;
949
+ const matches = [...fileContent.matchAll(importRegex)];
950
+
951
+ if (matches.length > 0) {
952
+ const lastImport = matches[matches.length - 1];
953
+ const insertPosition = lastImport.index + lastImport[0].length;
954
+ fileContent = fileContent.slice(0, insertPosition) + `\n${importToast}` + fileContent.slice(insertPosition);
955
+ updated = true;
956
+ } else {
957
+ console.error('❌ Error: No import section found in file.');
958
+ process.exit(1);
959
+ }
960
+ } else {
961
+ console.log('ℹ️ Import for Toast already exists. No changes needed.');
962
+ }
963
+
964
+ // Step 3: Save if updated
965
+ if (updated) {
966
+ fs.writeFileSync(bridgeWebViewClientFilePath, fileContent, 'utf8');
967
+ console.log('✅ File updated successfully.');
968
+ } else {
969
+ console.log('ℹ️ No changes needed.');
970
+ }
971
+
972
+
973
+
974
+
975
+ // Check and change the "BridgeWebViewClient.java" file END
976
+
977
+
978
+
979
+
980
+
981
+
982
+
983
+
984
+ /*
985
+ // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file START
986
+
987
+ // Build the path dynamically like you requested
988
+ const gradlePath = path.join(
989
+ process.cwd(),
990
+ 'android',
991
+ 'build.gradle'
992
+ );
993
+
994
+ // Read the existing build.gradle
995
+ let gradleContent = fs.readFileSync(gradlePath, 'utf8');
996
+
997
+ // Add `ext.kotlin_version` if it's not already there
998
+ if (!gradleContent.includes('ext.kotlin_version')) {
999
+ gradleContent = gradleContent.replace(
1000
+ /buildscript\s*{/,
1001
+ `buildscript {\n ext.kotlin_version = '2.1.0'`
1002
+ );
1003
+ }
1004
+
1005
+ // Add Kotlin classpath if it's not already there
1006
+ if (!gradleContent.includes('org.jetbrains.kotlin:kotlin-gradle-plugin')) {
1007
+ gradleContent = gradleContent.replace(
1008
+ /dependencies\s*{([\s\S]*?)classpath 'com.android.tools.build:gradle:8.7.2'/,
1009
+ `dependencies {\n classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")\n$1classpath 'com.android.tools.build:gradle:8.7.2'`
1010
+ );
1011
+ }
1012
+
1013
+ // Write back the modified content
1014
+ fs.writeFileSync(gradlePath, gradleContent, 'utf8');
1015
+
1016
+ console.log('✅ Kotlin version updated in build.gradle.');
1017
+
1018
+ // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file END
1019
+ */
1020
+
1021
+
1022
+
1023
+
1024
+
1025
+
1026
+
1027
+
1028
+ let _admobConfig;
1029
+
1030
+
1031
+
1032
+ const androidPlatformPath = path.join(process.cwd(), 'android');
1033
+ const iosPlatformPath = path.join(process.cwd(), 'ios');
1034
+ const pluginPath = path.join(process.cwd(), 'node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
1035
+ const infoPlistPath = path.join(process.cwd(), 'ios', 'App', 'App', 'Info.plist');
1036
+ const resourcesPath = path.join(process.cwd(), 'resources', 'res');
1037
+ const androidResPath = path.join(process.cwd(), 'android', 'app', 'src', 'main', 'res');
1038
+ const localNotificationsPluginPath = path.join(process.cwd(), 'node_modules', '@capacitor', 'local-notifications');
1039
+
1040
+ function fileExists(filePath) {
1041
+ return fs.existsSync(filePath);
1042
+ }
1043
+
1044
+ function copyFolderSync(source, target) {
1045
+ if (!fs.existsSync(target)) {
1046
+ fs.mkdirSync(target, { recursive: true });
1047
+ }
1048
+
1049
+ fs.readdirSync(source).forEach(file => {
1050
+ const sourceFile = path.join(source, file);
1051
+ const targetFile = path.join(target, file);
1052
+
1053
+ if (fs.lstatSync(sourceFile).isDirectory()) {
1054
+ copyFolderSync(sourceFile, targetFile);
1055
+ } else {
1056
+ fs.copyFileSync(sourceFile, targetFile);
1057
+ }
1058
+ });
1059
+ }
1060
+
1061
+ function checkAndCopyResources() {
1062
+ if (fileExists(resourcesPath)) {
1063
+ copyFolderSync(resourcesPath, androidResPath);
1064
+ console.log('✅ Successfully copied resources/res to android/app/src/main/res.');
1065
+ } else {
1066
+ console.log('resources/res folder not found.');
1067
+
1068
+ if (fileExists(localNotificationsPluginPath)) {
1069
+ throw new Error('❌ resources/res is required for @capacitor/local-notifications. Stopping execution.');
1070
+ }
1071
+ }
1072
+ }
1073
+
1074
+
1075
+
1076
+
1077
+
1078
+
1079
+
1080
+
1081
+ function getAdMobConfig() {
1082
+ if (!fileExists(configPath)) {
1083
+ throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
1084
+ }
1085
+
1086
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
1087
+ const admobConfig = config.plugins?.AdMob;
1088
+
1089
+ if (!admobConfig) {
1090
+ throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
1091
+ }
1092
+
1093
+ // Default to true if ADMOB_ENABLED is not specified
1094
+ const isEnabled = admobConfig.ADMOB_ENABLED !== false;
1095
+
1096
+ if (!isEnabled) {
1097
+ return { ADMOB_ENABLED: false }; // Skip further validation
1098
+ }
1099
+
1100
+ if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
1101
+ throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
1102
+ }
1103
+
1104
+ return {
1105
+ ADMOB_ENABLED: true,
1106
+ APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
1107
+ APP_ID_IOS: admobConfig.APP_ID_IOS,
1108
+ USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
1109
+ };
1110
+ }
1111
+
1112
+ function validateAndroidBuildOptions() {
1113
+
1114
+
1115
+ if (!fileExists(configPath)) {
1116
+ console.log('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
1117
+ process.exit(1);
1118
+ }
1119
+
1120
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
1121
+
1122
+ const targetAppId=config.appId
1123
+
1124
+ const buildOptions = config.android?.buildOptions;
1125
+
1126
+ if (!buildOptions) {
1127
+ console.log('❌ Missing android.buildOptions in capacitor.config.json.');
1128
+ process.exit(1);
1129
+ }
1130
+
1131
+ const requiredProps = [
1132
+ 'keystorePath',
1133
+ 'keystorePassword',
1134
+ 'keystoreAlias',
1135
+ 'keystoreAliasPassword',
1136
+ 'releaseType',
1137
+ 'signingType'
1138
+ ];
1139
+
1140
+ const missing = requiredProps.filter(prop => !buildOptions[prop]);
1141
+
1142
+ if (missing.length > 0) {
1143
+ console.log('❌ Missing properties android.buildOptions in capacitor.config.json.');
1144
+ process.exit(1);
1145
+ }
1146
+
1147
+
1148
+ const keystorePath=buildOptions.keystorePath
1149
+ const keyFileName = path.basename(keystorePath);
1150
+
1151
+
1152
+
1153
+ const keystoreMap = {
1154
+ "gameskey.jks": [
1155
+ "com.cube.blaster",
1156
+ ],
1157
+ "htmleditorkeystoke.jks": [
1158
+ "com.HTML.AngularJS.Codeplay",
1159
+ "com.html.codeplay.pro",
1160
+ "com.bootstrap.code.play",
1161
+ "com.kids.learning.master",
1162
+ "com.Simple.Barcode.Scanner",
1163
+ "com.FAShtmlcssjs.editor"
1164
+ ]
1165
+ };
1166
+
1167
+ // find which keystore is required for the given targetAppId
1168
+ let requiredKey = "newappskey.jks"; // default
1169
+ for (const [keyFile, appIds] of Object.entries(keystoreMap)) {
1170
+ if (appIds.includes(targetAppId)) {
1171
+ requiredKey = keyFile;
1172
+ break;
1173
+ }
1174
+ }
1175
+
1176
+ // validate
1177
+ if (keyFileName !== requiredKey) {
1178
+ console.log(`❌ The keystore path is mismatched. Expected ${requiredKey} for ${targetAppId}, but got ${keyFileName}`);
1179
+ process.exit(1);
1180
+ }
1181
+
1182
+
1183
+
1184
+
1185
+
1186
+ // optionally return them
1187
+ //return buildOptions;
1188
+ }
1189
+
1190
+ function updatePluginXml(admobConfig) {
1191
+ if (!fileExists(pluginPath)) {
1192
+ console.error(' ❌ plugin.xml not found. Ensure the plugin is installed.');
1193
+ return;
1194
+ }
1195
+
1196
+ let pluginContent = fs.readFileSync(pluginPath, 'utf8');
1197
+
1198
+ pluginContent = pluginContent
1199
+ .replace(/<preference name="APP_ID_ANDROID" default=".*?" \/>/, `<preference name="APP_ID_ANDROID" default="${admobConfig.APP_ID_ANDROID}" />`)
1200
+ .replace(/<preference name="APP_ID_IOS" default=".*?" \/>/, `<preference name="APP_ID_IOS" default="${admobConfig.APP_ID_IOS}" />`);
1201
+
1202
+ fs.writeFileSync(pluginPath, pluginContent, 'utf8');
1203
+ console.log('✅ AdMob IDs successfully updated in plugin.xml');
1204
+ }
1205
+
1206
+ function updateInfoPlist(admobConfig) {
1207
+ if (!fileExists(infoPlistPath)) {
1208
+ console.error(' ❌ Info.plist not found. Ensure you have built the iOS project.');
1209
+ return;
1210
+ }
1211
+
1212
+ const plistContent = fs.readFileSync(infoPlistPath, 'utf8');
1213
+ const plistData = plist.parse(plistContent);
1214
+
1215
+ plistData.GADApplicationIdentifier = admobConfig.APP_ID_IOS;
1216
+ plistData.NSUserTrackingUsageDescription = 'This identifier will be used to deliver personalized ads to you.';
1217
+ plistData.GADDelayAppMeasurementInit = true;
1218
+
1219
+ const updatedPlistContent = plist.build(plistData);
1220
+ fs.writeFileSync(infoPlistPath, updatedPlistContent, 'utf8');
1221
+ console.log('AdMob IDs and additional configurations successfully updated in Info.plist');
1222
+ }
1223
+
1224
+
1225
+ try {
1226
+ if (!fileExists(configPath)) {
1227
+ throw new Error(' ❌ capacitor.config.json not found. Skipping setup.');
1228
+ }
1229
+
1230
+ if (!fileExists(androidPlatformPath) && !fileExists(iosPlatformPath)) {
1231
+ throw new Error('Neither Android nor iOS platforms are found. Ensure platforms are added to your Capacitor project.');
1232
+ }
1233
+
1234
+ checkAndCopyResources();
1235
+
1236
+
1237
+
1238
+ _admobConfig = getAdMobConfig();
1239
+
1240
+
1241
+
1242
+
1243
+
1244
+ // Proceed only if ADMOB_ENABLED is true
1245
+ if (_admobConfig.ADMOB_ENABLED) {
1246
+ if (fileExists(androidPlatformPath)) {
1247
+ updatePluginXml(_admobConfig);
1248
+ }
1249
+
1250
+ if (fileExists(iosPlatformPath)) {
1251
+ updateInfoPlist(_admobConfig);
1252
+ }
1253
+ }
1254
+
1255
+
1256
+ } catch (error) {
1257
+ console.error(error.message);
1258
+ process.exit(1); // Stop execution if there's a critical error
1259
+ }
1260
+
1261
+
1262
+
1263
+ validateAndroidBuildOptions();
1264
+
1265
+
1266
+
1267
+
1268
+
1269
+
1270
+ // Check all the codeplays plugins version START
1271
+
1272
+
1273
+ const readline = require('readline');
1274
+
1275
+
1276
+ //const srcDir = path.join(__dirname, 'src');
1277
+ const srcDir = path.join(process.cwd(), 'src');
1278
+ let outdatedPlugins = [];
1279
+
1280
+ function parseVersion(ver) {
1281
+ return ver.split('.').map(n => parseInt(n, 10));
1282
+ }
1283
+
1284
+ function compareVersions(v1, v2) {
1285
+ const [a1, b1] = parseVersion(v1);
1286
+ const [a2, b2] = parseVersion(v2);
1287
+ if (a1 !== a2) return a1 - a2;
1288
+ return b1 - b2;
1289
+ }
1290
+
1291
+ function walkSync(dir, filelist = []) {
1292
+ fs.readdirSync(dir).forEach(file => {
1293
+ const fullPath = path.join(dir, file);
1294
+ const stat = fs.statSync(fullPath);
1295
+ if (stat.isDirectory()) {
1296
+ walkSync(fullPath, filelist);
1297
+ } else {
1298
+ filelist.push(fullPath);
1299
+ }
1300
+ });
1301
+ return filelist;
1302
+ }
1303
+
1304
+
1305
+
1306
+ function getSearchRoot(plugin) {
1307
+ return path.join(srcDir, plugin.baseDir || 'js');
1308
+ }
1309
+
1310
+
1311
+
1312
+
1313
+
1314
+
1315
+
1316
+
1317
+
1318
+
1319
+
1320
+
1321
+
1322
+
1323
+
1324
+
1325
+
1326
+
1327
+
1328
+
1329
+ /*############################################## AUTO DOWNLOAD FROM SERVER START #####################################*/
1330
+
1331
+ // ============================================================
1332
+ // 🔥 AUTO PLUGIN UPDATE SYSTEM (MANDATORY UPDATES)
1333
+ // ============================================================
1334
+
1335
+ const https = require("https");
1336
+
1337
+ /**
1338
+ * Check if file exists on server using HEAD request
1339
+ */
1340
+ function urlExists(url) {
1341
+ return new Promise(resolve => {
1342
+ const req = https.request(url, { method: "HEAD" }, res => {
1343
+ resolve(res.statusCode === 200);
1344
+ });
1345
+
1346
+ req.on("error", () => resolve(false));
1347
+ req.end();
1348
+ });
1349
+ }
1350
+
1351
+ /**
1352
+ * Download file from server
1353
+ */
1354
+ function downloadFile(url, dest) {
1355
+ return new Promise((resolve, reject) => {
1356
+ const file = fs.createWriteStream(dest);
1357
+
1358
+ https.get(url, response => {
1359
+ if (response.statusCode !== 200) {
1360
+ reject("Download failed");
1361
+ return;
1362
+ }
1363
+
1364
+ response.pipe(file);
1365
+
1366
+ file.on("finish", () => {
1367
+ file.close(resolve);
1368
+ });
1369
+ }).on("error", err => {
1370
+ fs.unlink(dest, () => {});
1371
+ reject(err);
1372
+ });
1373
+ });
1374
+ }
1375
+
1376
+ /**
1377
+ * Update imports across src folder
1378
+ * Replaces old filename → new filename
1379
+ */
1380
+ /**
1381
+ * Update imports across project
1382
+ * Replaces old filename → new filename
1383
+ */
1384
+
1385
+ const VITE_ALIAS_ONLY = [
1386
+ "common",
1387
+ "admob-emi",
1388
+ "localization",
1389
+ "theme",
1390
+ "certificatejs",
1391
+ "ffmpeg"
1392
+ ];
1393
+
1394
+ function updateImports(oldName, newName) {
1395
+
1396
+ const projectRoot = process.cwd();
1397
+
1398
+ const filesToScan = [
1399
+ path.join(projectRoot, "vite.config.js"),
1400
+ path.join(projectRoot, "vite.config.mjs")
1401
+ ];
1402
+
1403
+ const srcDir = path.join(projectRoot, "src");
1404
+
1405
+ // scan vite config
1406
+ filesToScan.forEach(file => {
1407
+
1408
+ if (!fs.existsSync(file)) return;
1409
+
1410
+ let content = fs.readFileSync(file, "utf8");
1411
+
1412
+ if (content.includes(oldName)) {
1413
+
1414
+ content = content.split(oldName).join(newName);
1415
+
1416
+ fs.writeFileSync(file, content);
1417
+
1418
+ console.log(`✏️ Updated alias in ${path.basename(file)}`);
1419
+ }
1420
+
1421
+ });
1422
+
1423
+ // scan src files
1424
+ function walk(dir) {
1425
+
1426
+ fs.readdirSync(dir).forEach(file => {
1427
+
1428
+ if (["node_modules","android","ios","dist",".git"].includes(file))
1429
+ return;
1430
+
1431
+ const full = path.join(dir, file);
1432
+ const stat = fs.statSync(full);
1433
+
1434
+ if (stat.isDirectory()) {
1435
+ walk(full);
1436
+ }
1437
+
1438
+ else if (
1439
+ (full.endsWith(".js") ||
1440
+ full.endsWith(".f7") ||
1441
+ full.endsWith(".mjs")) &&
1442
+ !full.endsWith(".min.js")
1443
+ ) {
1444
+
1445
+ let content = fs.readFileSync(full, "utf8");
1446
+
1447
+ if (content.includes(oldName)) {
1448
+
1449
+ content = content.split(oldName).join(newName);
1450
+
1451
+ fs.writeFileSync(full, content);
1452
+
1453
+ console.log(`✏️ Updated import in ${path.relative(projectRoot, full)}`);
1454
+ }
1455
+
1456
+ }
1457
+
1458
+ });
1459
+
1460
+ }
1461
+
1462
+ if (fs.existsSync(srcDir)) {
1463
+ walk(srcDir);
1464
+ }
1465
+
1466
+ }
1467
+
1468
+
1469
+ /**
1470
+ * Auto-update a plugin file
1471
+ * Returns TRUE if success
1472
+ * Returns FALSE if fallback to manual needed
1473
+ */
1474
+
1475
+
1476
+ let _serverVersions = null;
1477
+ async function fetchVersions() {
1478
+
1479
+ if (_serverVersions) return _serverVersions;
1480
+
1481
+ return new Promise((resolve) => {
1482
+
1483
+ https.get(
1484
+ "https://htmlcodeplay.com/code-play-plugin/versions.json",
1485
+ { timeout: 5000 },
1486
+ res => {
1487
+
1488
+ let data = "";
1489
+
1490
+ res.on("data", chunk => data += chunk);
1491
+
1492
+ res.on("end", () => {
1493
+
1494
+ try {
1495
+
1496
+ _serverVersions = JSON.parse(data);
1497
+
1498
+ resolve(_serverVersions);
1499
+
1500
+ } catch {
1501
+
1502
+ resolve(null);
1503
+
1504
+ }
1505
+
1506
+ });
1507
+
1508
+ }
1509
+
1510
+ ).on("error", () => resolve(null));
1511
+
1512
+ });
1513
+
1514
+ }
1515
+
1516
+
1517
+
1518
+ async function autoUpdatePlugin(pluginDef, pluginInfo) {
1519
+
1520
+ const versions = await fetchVersions();
1521
+
1522
+ if (!versions) {
1523
+ console.log("⚠️ versions.json not reachable");
1524
+ return false;
1525
+ }
1526
+
1527
+ const oldFullPath = path.join(srcDir, pluginInfo.name);
1528
+ const oldFileName = path.basename(oldFullPath);
1529
+
1530
+ //const oldFileName = path.basename(oldFullPath);
1531
+ const oldVersionFile = oldFileName;
1532
+
1533
+
1534
+ const ext = path.extname(oldFileName); // .js or .less
1535
+ //const baseName = oldFileName.replace(/-\d+\.\d+.*$/, "");
1536
+ const baseName = oldFileName.replace(/-\d+\.\d+.*$/, '').replace(/\.(js|less)$/, '');
1537
+
1538
+ // version lookup key
1539
+ let pluginKey = baseName;
1540
+
1541
+
1542
+ // Only common plugin has js and less variants
1543
+ if (baseName === "common") {
1544
+ if (ext === ".js") pluginKey = "common-js";
1545
+ if (ext === ".less") pluginKey = "common-less";
1546
+ }
1547
+
1548
+ const latestVersion = versions[pluginKey];
1549
+
1550
+ if (!latestVersion) {
1551
+ console.log(`❌ No version entry for ${baseName}`);
1552
+ return false;
1553
+ }
1554
+
1555
+ // ===============================
1556
+ // FOLDER PLUGIN UPDATE
1557
+ // ===============================
1558
+ if (pluginDef.isFolder) {
1559
+
1560
+ const zipName = `${baseName}-${latestVersion}.zip`;
1561
+ const url = `https://htmlcodeplay.com/code-play-plugin/${zipName}`;
1562
+
1563
+ const destRoot = path.join(srcDir, pluginDef.destDir || pluginDef.baseDir || '');
1564
+ const oldPath = path.join(destRoot, pluginInfo.name);
1565
+ const newPath = path.join(destRoot, `${baseName}-${latestVersion}`);
1566
+
1567
+ if (!(await urlExists(url))) return false;
1568
+
1569
+ fs.rmSync(oldPath, { recursive: true, force: true });
1570
+
1571
+ await downloadAndExtractZip(url, newPath);
1572
+
1573
+ updateImports(pluginInfo.name, `${baseName}-${latestVersion}`);
1574
+
1575
+ // ✅ ADD THIS
1576
+ writeUpdateLine(`${pluginInfo.name} -> ${baseName}-${latestVersion}`);
1577
+
1578
+ console.log(`✅ Folder updated → ${baseName}-${latestVersion}`);
1579
+
1580
+ return true;
1581
+ }
1582
+ // ===============================
1583
+ // FILE PLUGIN UPDATE
1584
+ // ===============================
1585
+
1586
+ const pluginDir = path.dirname(oldFullPath);
1587
+
1588
+ // Only this plugin has ios variant
1589
+ const IOS_VARIANT_PLUGINS = [
1590
+ "saveToGalleryAndSaveAnyFile"
1591
+ ];
1592
+
1593
+ /* let variants = [
1594
+ `${baseName}-${latestVersion}.js`
1595
+ ]; */
1596
+
1597
+ //const ext = path.extname(oldFileName);
1598
+ const variants = [`${baseName.replace(ext,'')}-${latestVersion}${ext}`];
1599
+
1600
+
1601
+ if (IOS_VARIANT_PLUGINS.includes(baseName)) {
1602
+ variants.push(`${baseName}-${latestVersion}-ios.js`);
1603
+ }
1604
+
1605
+ let downloaded = [];
1606
+
1607
+ // Download files
1608
+ for (const fileName of variants) {
1609
+
1610
+ const url = `https://htmlcodeplay.com/code-play-plugin/${fileName}`;
1611
+
1612
+ console.log(`🔍 Checking latest: ${fileName}`);
1613
+
1614
+ if (await urlExists(url)) {
1615
+
1616
+ const destPath = path.join(pluginDir, fileName);
1617
+
1618
+ await downloadFile(url, destPath);
1619
+
1620
+ downloaded.push(fileName);
1621
+
1622
+ console.log(`⬇ Downloaded → ${fileName}`);
1623
+
1624
+ //writeUpdateLine(`Downloaded: ${fileName}`);
1625
+
1626
+ }
1627
+ }
1628
+
1629
+ if (downloaded.length === 0) {
1630
+ console.log(`❌ No files downloaded for ${baseName}`);
1631
+ return false;
1632
+ }
1633
+
1634
+ // Remove ONLY versioned files (safe)
1635
+ //const versionPattern = new RegExp(`^${baseName}-\\d+\\.\\d+(-ios)?\\.js$`);
1636
+ const versionPattern = new RegExp(`^${baseName}-\\d+\\.\\d+(-ios)?\\${ext}$`);
1637
+
1638
+ const existingFiles = fs.readdirSync(pluginDir);
1639
+
1640
+ existingFiles.forEach(file => {
1641
+
1642
+ if (
1643
+ versionPattern.test(file) &&
1644
+ !downloaded.includes(file)
1645
+ ) {
1646
+
1647
+ const oldPath = path.join(pluginDir, file);
1648
+
1649
+ fs.unlinkSync(oldPath);
1650
+
1651
+ console.log(`🗑 Removed old file → ${file}`);
1652
+ //writeUpdateLine(`Removed old file: ${file}`);
1653
+ }
1654
+
1655
+ });
1656
+
1657
+ //const newFileName = `${baseName}-${latestVersion}.js`;
1658
+ const newFileName = `${baseName}-${latestVersion}${ext}`;
1659
+
1660
+ writeUpdateLine(`${oldVersionFile} -> ${newFileName}`);
1661
+
1662
+ updateImports(oldFileName, newFileName);
1663
+ //updateImports(baseName, `${baseName}-${latestVersion}.js`);
1664
+ //updateImports(pluginInfo.name, `${baseName}-${latestVersion}`);
1665
+
1666
+ //console.log(`✅ Updated → ${newFileName}`);
1667
+ //console.log(`✅ Updated → ${baseName}-${latestVersion}`);
1668
+
1669
+ return true;
1670
+ }
1671
+
1672
+
1673
+
1674
+
1675
+ /*############################################## AUTO DOWNLOAD FROM SERVER END #####################################*/
1676
+
1677
+
1678
+
1679
+
1680
+
1681
+
1682
+
1683
+
1684
+
1685
+
1686
+
1687
+
1688
+
1689
+
1690
+
1691
+
1692
+
1693
+
1694
+ async function loadPluginVersions() {
1695
+
1696
+ if (!USE_LIVE_SERVER_VERSION) {
1697
+ console.log("ℹ️ Using local plugin versions (offline mode).");
1698
+ return;
1699
+ }
1700
+
1701
+ console.log("🌐 Fetching plugin versions from server...");
1702
+
1703
+ const versions = await fetchVersions();
1704
+
1705
+ if (!versions || typeof versions !== "object") {
1706
+ console.log("⚠️ Server unavailable or invalid versions.json. Falling back to local versions.");
1707
+ return;
1708
+ }
1709
+
1710
+ requiredPlugins.forEach(plugin => {
1711
+
1712
+ if (!plugin.name) return;
1713
+
1714
+ if (versions[plugin.name]) {
1715
+ plugin.minVersion = versions[plugin.name];
1716
+ }
1717
+
1718
+ });
1719
+
1720
+ console.log("✅ Plugin versions loaded from server.");
1721
+
1722
+ }
1723
+
1724
+
1725
+
1726
+ let hasMandatoryUpdate = false;
1727
+ function checkPlugins() {
1728
+ return new Promise(async (resolve, reject) => {
1729
+ const files = walkSync(srcDir);
1730
+ const outdatedPlugins = [];
1731
+ let hasMandatoryUpdate = false;
1732
+
1733
+ for (const plugin of requiredPlugins) {
1734
+ const searchRoot = getSearchRoot(plugin);
1735
+
1736
+ // ---------- Folder plugins ----------
1737
+ if (plugin.isFolder) {
1738
+ if (!fs.existsSync(searchRoot)) continue;
1739
+
1740
+ const subDirs = fs.readdirSync(searchRoot)
1741
+ .map(name => path.join(searchRoot, name))
1742
+ .filter(p => fs.statSync(p).isDirectory());
1743
+
1744
+ for (const dir of subDirs) {
1745
+ const relativePath = path.relative(searchRoot, dir).replace(/\\/g, '/');
1746
+ const match = plugin.pattern.exec(relativePath);
1747
+
1748
+ if (match) {
1749
+ const currentVersion = match[1];
1750
+
1751
+ if (compareVersions(currentVersion, plugin.minVersion) < 0) {
1752
+ outdatedPlugins.push({
1753
+ name: relativePath,
1754
+ currentVersion,
1755
+ requiredVersion: plugin.minVersion,
1756
+ mandatoryUpdate: plugin.mandatoryUpdate === true
1757
+ });
1758
+
1759
+ if (plugin.mandatoryUpdate) {
1760
+ hasMandatoryUpdate = true;
1761
+ }
1762
+ }
1763
+ }
1764
+ }
1765
+ continue;
1766
+ }
1767
+
1768
+ // ---------- File plugins ----------
1769
+ const matchedFile = files.find(file =>
1770
+ file.startsWith(searchRoot) && plugin.pattern.test(file)
1771
+ );
1772
+
1773
+ if (matchedFile) {
1774
+ const match = plugin.pattern.exec(matchedFile);
1775
+ if (match) {
1776
+ const currentVersion = match[1];
1777
+ const isBeta = !!match[2];
1778
+
1779
+ const cmp = plugin.pattern.source.includes('beta')
1780
+ ? compareWithBeta(currentVersion, plugin.minVersion, isBeta)
1781
+ : compareVersions(currentVersion, plugin.minVersion);
1782
+
1783
+ if (cmp < 0) {
1784
+ outdatedPlugins.push({
1785
+ name: path.relative(srcDir, matchedFile),
1786
+ currentVersion: isBeta ? `${currentVersion}-beta` : currentVersion,
1787
+ requiredVersion: plugin.minVersion,
1788
+ mandatoryUpdate: plugin.mandatoryUpdate === true
1789
+ });
1790
+
1791
+ if (plugin.mandatoryUpdate) {
1792
+ hasMandatoryUpdate = true;
1793
+ }
1794
+ }
1795
+ }
1796
+ }
1797
+ }
1798
+
1799
+ // ---------- Result handling ----------
1800
+ if (outdatedPlugins.length > 0) {
1801
+ console.log('\n❗ The following plugins are outdated:\n');
1802
+
1803
+ outdatedPlugins.forEach( p => {
1804
+ const tag = p.mandatoryUpdate ? '🔥 MANDATORY' : '';
1805
+ console.log(
1806
+ ` ⚠️ - ${p.name} (Current: ${p.currentVersion}, Required: ${p.requiredVersion}) ${tag}`
1807
+ );
1808
+ });
1809
+
1810
+ // 🚨 Mandatory update → stop build
1811
+ /* if (hasMandatoryUpdate) {
1812
+ console.log('\n🚫 One or more plugins require a mandatory update.');
1813
+ console.log('❌ Build cancelled. Please update mandatory plugins and try again.');
1814
+ process.exit(1);
1815
+ } */
1816
+
1817
+
1818
+
1819
+
1820
+
1821
+ if (hasMandatoryUpdate) {
1822
+
1823
+ //--------------------------------------------------
1824
+ // 🚫 AUTO UPDATE DISABLED
1825
+ //--------------------------------------------------
1826
+ if (!ENABLE_AUTO_UPDATE) {
1827
+ console.log("\n🚫 Auto-update disabled.");
1828
+ console.log("❌ Manual update required.");
1829
+ process.exit(1);
1830
+ }
1831
+
1832
+ //--------------------------------------------------
1833
+ // 🔥 AUTO UPDATE ENABLED
1834
+ //--------------------------------------------------
1835
+ console.log("\n🔥 Mandatory plugins outdated. Trying auto-update...\n");
1836
+
1837
+
1838
+
1839
+ let autoFailed = false;
1840
+
1841
+ for (const p of outdatedPlugins.filter(x => x.mandatoryUpdate)) {
1842
+
1843
+ const pluginDef = requiredPlugins.find(def =>
1844
+ def.pattern.test(p.name)
1845
+ );
1846
+
1847
+ if (!pluginDef) continue;
1848
+
1849
+ const success = await autoUpdatePlugin(
1850
+ pluginDef,
1851
+ p
1852
+ );
1853
+
1854
+ if (!success) {
1855
+ autoFailed = true;
1856
+
1857
+ const pluginDef = requiredPlugins.find(def =>
1858
+ def.pattern.test(p.name)
1859
+ );
1860
+
1861
+ console.log(`❌ Manual update required for ${p.name}`);
1862
+
1863
+ if (pluginDef) {
1864
+ console.log(`👉 Required minimum version: ${pluginDef.minVersion}`);
1865
+ }
1866
+ }
1867
+ }
1868
+
1869
+ // 🚨 Fallback to manual if any failed
1870
+ if (autoFailed) {
1871
+ console.log('\n🚫 One or more plugins require manual update.');
1872
+ console.log('❌ Build cancelled. Please update mandatory plugins.');
1873
+ process.exit(1);
1874
+ }
1875
+
1876
+ console.log('\n🎉 All mandatory plugins auto-updated! Rechecking plugins...\n');
1877
+
1878
+ // Re-run plugin check so outdated list becomes empty
1879
+ await checkPlugins();
1880
+ return;
1881
+ }
1882
+
1883
+
1884
+
1885
+
1886
+
1887
+
1888
+ // Optional updates → ask user
1889
+ const rl = readline.createInterface({
1890
+ input: process.stdin,
1891
+ output: process.stdout
1892
+ });
1893
+
1894
+ rl.question(
1895
+ '\nAre you sure you want to continue without updating these plugins? (y/n): ',
1896
+ answer => {
1897
+ rl.close();
1898
+
1899
+ if (answer.toLowerCase() !== 'y') {
1900
+ console.log('\n❌ Build cancelled due to outdated plugins.');
1901
+ process.exit(1);
1902
+ } else {
1903
+ console.log('\n✅ Continuing build...');
1904
+ resolve();
1905
+ }
1906
+ }
1907
+ );
1908
+ } else {
1909
+ console.log('✅ All plugin versions are up to date.');
1910
+ saveUpdateLogs();
1911
+ resolve();
1912
+ }
1913
+ });
1914
+ }
1915
+
1916
+
1917
+
1918
+
1919
+
1920
+
1921
+
1922
+
1923
+
1924
+
1925
+ const localizationBaseDir = path.join(__dirname, "..", "src", "js", "localization");
1926
+
1927
+ // ======================================================
1928
+ // 🌐 LOCALIZATION CHECK (FULLY DYNAMIC)
1929
+ // ======================================================
1930
+
1931
+
1932
+ const jsRootDir = path.join(__dirname, "..", "src", "js");
1933
+
1934
+ // 🔍 Detect OLD localization files in root js/
1935
+ const oldLocalizationFiles = fs.readdirSync(jsRootDir)
1936
+ .filter(name =>
1937
+ /^localization-\d+(\.\d+)*\.js$/.test(name) ||
1938
+ /^localization_settings-\d+(\.\d+)*\.js$/.test(name)
1939
+ );
1940
+
1941
+ // ❌ If old structure found → STOP
1942
+ if (oldLocalizationFiles.length > 0) {
1943
+
1944
+ console.error(`
1945
+ ❌ OLD LOCALIZATION STRUCTURE DETECTED
1946
+
1947
+ You are using outdated file structure:
1948
+ src/js/localization-x.x.js
1949
+ src/js/localization_settings-x.x.js
1950
+
1951
+ 🚨 This is no longer supported.
1952
+
1953
+ 📦 Found files:
1954
+ ${oldLocalizationFiles.map(f => " - " + f).join("\n")}
1955
+
1956
+ 👉 Please move them to new structure:
1957
+
1958
+ src/js/localization/localization_settings-x.x.js
1959
+ src/js/localization/localization-x.x/
1960
+
1961
+ ⚠️ Example:
1962
+
1963
+ OLD:
1964
+ src/js/localization-x.x.js
1965
+ src/js/localization_settings-x.x.js
1966
+
1967
+ NEW:
1968
+ src/js/localization/localization_settings-1.1.js
1969
+ src/js/localization/localization-x.x/localization-x.x.js
1970
+
1971
+ ❌ Build stopped.
1972
+ `);
1973
+
1974
+ process.exit(1);
1975
+ }
1976
+
1977
+
1978
+
1979
+
1980
+ if (fs.existsSync(localizationBaseDir)) {
1981
+
1982
+ // ❌ Block wrong files
1983
+ const invalidFiles = fs.readdirSync(localizationBaseDir)
1984
+ .filter(name => /^localization-\d+(\.\d+)*\.js$/.test(name));
1985
+
1986
+ if (invalidFiles.length > 0) {
1987
+ console.error(`
1988
+ ❌ INVALID LOCALIZATION FILE LOCATION
1989
+
1990
+ 🚫 localization-x.x.js must NOT be directly inside:
1991
+ src/js/localization/
1992
+
1993
+ 📦 Found:
1994
+ ${invalidFiles.map(f => " - " + f).join("\n")}
1995
+
1996
+ ❌ Build stopped.
1997
+ `);
1998
+ process.exit(1);
1999
+ }
2000
+
2001
+ // 🔍 Find localization-x.x folders
2002
+ const localizationVersions = fs.readdirSync(localizationBaseDir)
2003
+ .filter(name => /^localization-\d+(\.\d+)+$/.test(name));
2004
+
2005
+ if (localizationVersions.length === 0) {
2006
+ console.log("ℹ️ No localization-x.x folder found. Skipping...");
2007
+ } else {
2008
+
2009
+ // ✅ Get latest version (same logic as editor)
2010
+ const latestLocalizationDir = localizationVersions.sort((a, b) => {
2011
+ const vA = parseFloat(a.split('-')[1]);
2012
+ const vB = parseFloat(b.split('-')[1]);
2013
+ return vB - vA;
2014
+ })[0];
2015
+
2016
+ const localizationPath = path.join(localizationBaseDir, latestLocalizationDir);
2017
+
2018
+ // ======================================================
2019
+ // ✅ CHECK localization-x.x.js exists
2020
+ // ======================================================
2021
+
2022
+ const version = latestLocalizationDir.split('-')[1];
2023
+ const expectedFile = `localization-${version}.js`;
2024
+ const localizationFilePath = path.join(localizationPath, expectedFile);
2025
+
2026
+ if (!fs.existsSync(localizationFilePath)) {
2027
+ console.error(`
2028
+ ❌ localization file missing
2029
+
2030
+ Expected:
2031
+ ${localizationFilePath}
2032
+
2033
+ ❌ Build stopped.
2034
+ `);
2035
+ process.exit(1);
2036
+ }
2037
+
2038
+ // ======================================================
2039
+ // ✅ CHECK run.js exists
2040
+ // ======================================================
2041
+
2042
+ const runJsPath = path.join(localizationPath, "run.js");
2043
+
2044
+ if (!fs.existsSync(runJsPath)) {
2045
+ console.error(`❌ run.js not found in ${latestLocalizationDir}`);
2046
+ process.exit(1);
2047
+ }
2048
+
2049
+ // ======================================================
2050
+ // 🚀 EXECUTE run.js
2051
+ // ======================================================
2052
+
2053
+ console.log(`🌐 Localization detected: ${latestLocalizationDir}`);
2054
+ console.log(`🚀 Executing ${runJsPath}...`);
2055
+
2056
+ execSync(`node "${runJsPath}"`, { stdio: "inherit" });
2057
+ }
2058
+
2059
+ } else {
2060
+ console.log("ℹ️ Localization not used in this project. Skipping...");
2061
+ }
2062
+
2063
+
2064
+
2065
+
2066
+
2067
+
2068
+
2069
+
2070
+
2071
+
2072
+
2073
+
2074
+
2075
+
2076
+
2077
+
2078
+
2079
+
2080
+
2081
+ //editor-x.x import old style check and stop execution START
2082
+
2083
+
2084
+
2085
+ // Match: editor/editor-2.3, editor/editor-2.3.1, etc.
2086
+ const FORBIDDEN_REGEX = /editor\/editor-\d+(\.\d+)+/;
2087
+
2088
+ let hasError = false;
2089
+
2090
+ const ERROR_MESSAGE = `const ERROR_MESSAGE = ❌ Invalid import detected!
2091
+
2092
+ You are using a direct version-based path like: editor/editor-x.x/editor.js
2093
+
2094
+ 🚫 This is NOT allowed.
2095
+
2096
+ 👉 Please use the proper alias or updated import method.
2097
+ Example: import { ... } from '@editor'
2098
+
2099
+ ⚠️ Do not use version-based paths in imports.
2100
+ 👉 Please add this manually in vite.config.js:
2101
+
2102
+ alias: {
2103
+ '@editor': path.resolve(__dirname, './src/js/editor/editor-x.x')
2104
+ }`
2105
+
2106
+ function scanDir(dir) {
2107
+ const files = fs.readdirSync(dir);
2108
+
2109
+ for (const file of files) {
2110
+ const fullPath = path.join(dir, file);
2111
+ const stat = fs.statSync(fullPath);
2112
+
2113
+ if (stat.isDirectory()) {
2114
+ scanDir(fullPath);
2115
+ } else if (file.endsWith(".js") || file.endsWith(".ts") || file.endsWith(".f7")) {
2116
+ const content = fs.readFileSync(fullPath, "utf-8");
2117
+
2118
+ const lines = content.split("\n");
2119
+
2120
+ lines.forEach((line, index) => {
2121
+ if (FORBIDDEN_REGEX.test(line)) {
2122
+ console.error(
2123
+ `❌ Forbidden import found:\nFile: ${fullPath}\nLine: ${index + 1}\nCode: ${line.trim()}\n`,
2124
+ ERROR_MESSAGE
2125
+ );
2126
+ hasError = true;
2127
+ }
2128
+ });
2129
+ }
2130
+ }
2131
+ }
2132
+
2133
+ // Run scan
2134
+ scanDir(ROOT_DIR);
2135
+
2136
+ // Throw error (exit process)
2137
+ if (hasError) {
2138
+ console.error("🚫 Build failed due to forbidden editor imports.");
2139
+ process.exit(1);
2140
+ } else {
2141
+ console.log("✅ No forbidden imports found.");
2142
+ }
2143
+
2144
+
2145
+
2146
+
2147
+
2148
+
2149
+ //editor-x.x import old style check and stop execution START
2150
+
2151
+
2152
+
2153
+
2154
+
2155
+
2156
+
2157
+
2158
+
2159
+
2160
+ // Check all the codeplays plugins version START
2161
+
2162
+
2163
+
2164
+
2165
+ // ====================================================================
2166
+ // AUTO-ADD esbuild.drop: ['console','debugger'] to vite.config.js / mjs
2167
+ // ====================================================================
2168
+
2169
+
2170
+
2171
+ const checkAndupdateDropInViteConfig = () => {
2172
+
2173
+ const possibleFiles = [
2174
+ "vite.config.js",
2175
+ "vite.config.mjs"
2176
+ ];
2177
+
2178
+ // Detect existing config file
2179
+ const viteConfigPath = possibleFiles
2180
+ .map(file => path.join(process.cwd(), file))
2181
+ .find(filePath => fs.existsSync(filePath));
2182
+
2183
+ if (!viteConfigPath) {
2184
+ console.warn("⚠️ No vite config found. Skipping.");
2185
+ return;
2186
+ }
2187
+
2188
+ //console.log("📄 Using:", viteConfigPath.split("/").pop());
2189
+
2190
+ let viteContent = fs.readFileSync(viteConfigPath, "utf8");
2191
+
2192
+ // Skip if already exists
2193
+ if (/drop\s*:\s*\[.*['"]console['"].*\]/.test(viteContent)) {
2194
+ console.log("ℹ️ vite.config.(m)js already Updated. Skipping...");
2195
+ return;
2196
+ }
2197
+
2198
+ console.log("🔧 Adding esbuild.drop ...");
2199
+
2200
+ // If esbuild block exists
2201
+ if (/esbuild\s*:\s*{/.test(viteContent)) {
2202
+ viteContent = viteContent.replace(
2203
+ /esbuild\s*:\s*{([\s\S]*?)(^ {0,8})}/m,
2204
+ (full, inner, indent) => {
2205
+
2206
+ let lines = inner
2207
+ .split("\n")
2208
+ .map(l => l.trim())
2209
+ .filter(Boolean);
2210
+
2211
+ // Fix last comma
2212
+ if (lines.length > 0) {
2213
+ lines[lines.length - 1] =
2214
+ lines[lines.length - 1].replace(/,+$/, "") + ",";
2215
+ }
2216
+
2217
+ // Re-indent
2218
+ lines = lines.map(l => indent + " " + l);
2219
+
2220
+ // Add drop
2221
+ lines.push(`${indent} drop: ['console','debugger'],`);
2222
+
2223
+ return `esbuild: {\n${lines.join("\n")}\n${indent}}`;
2224
+ }
2225
+ );
2226
+ }
2227
+
2228
+ // If esbuild missing
2229
+ else {
2230
+ viteContent = viteContent.replace(
2231
+ /export default defineConfig\s*\(\s*{/,
2232
+ m => `${m}\n esbuild: {\n drop: ['console','debugger'],\n },`
2233
+ );
2234
+ }
2235
+
2236
+ fs.writeFileSync(viteConfigPath, viteContent, "utf8");
2237
+ console.log("✅ vite.config.(m)js Updated successfully.");
2238
+ };
2239
+
2240
+
2241
+
2242
+
2243
+
2244
+
2245
+
2246
+
2247
+
2248
+
2249
+ const compareVersion = (v1, v2) => {
2250
+ const a = v1.split(".").map(Number);
2251
+ const b = v2.split(".").map(Number);
2252
+
2253
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
2254
+ const num1 = a[i] || 0;
2255
+ const num2 = b[i] || 0;
2256
+ if (num1 > num2) return 1;
2257
+ if (num1 < num2) return -1;
2258
+ }
2259
+ return 0;
2260
+ };
2261
+
2262
+
2263
+
2264
+
2265
+
2266
+
2267
+
2268
+
2269
+
2270
+
2271
+ const admobConfigPath = path.join('src', 'js','Ads', 'admob-ad-configuration.json');
2272
+
2273
+ const checkAdmobConfigurationProperty=()=>{
2274
+
2275
+
2276
+ if (!_admobConfig.ADMOB_ENABLED)
2277
+ {
2278
+ console.log("ℹ️ Admob is not enabled so 'admob-ad-configuration.json' checking is skipping...");
2279
+ return;
2280
+ }
2281
+
2282
+
2283
+ const REQUIRED_CONFIG_KEYS = [
2284
+ "isKidsApp",
2285
+ "isTesting",
2286
+ "isConsoleLogEnabled",
2287
+ "bannerEnabled",
2288
+ "interstitialEnabled",
2289
+ "appOpenEnabled",
2290
+ "rewardVideoEnabled",
2291
+ "rewardInterstitialEnabled",
2292
+ "collapsibleEnabled",
2293
+ "isLandScape",
2294
+ "isOverlappingEnable",
2295
+ "bannerTypeAndroid",
2296
+ "bannerTypeiOS",
2297
+ "bannerTopSpaceColor",
2298
+ "interstitialLoadScreenTextColor",
2299
+ "interstitialLoadScreenBackgroundColor",
2300
+ "beforeBannerSpace",
2301
+ "whenShow",
2302
+ "minimumClick",
2303
+ "interstitialTimeOut",
2304
+ "interstitialFirstTimeOut",
2305
+ "appOpenAdsTimeOut",
2306
+ "maxRetryCount",
2307
+ "retrySecondsAr",
2308
+ "appOpenPerSession",
2309
+ "interstitialPerSession",
2310
+ "appOpenFirstTimeOut"
2311
+ ];
2312
+
2313
+
2314
+
2315
+
2316
+
2317
+ let admobConfigInJson;
2318
+
2319
+ try {
2320
+ admobConfigInJson = JSON.parse(readFileSync(admobConfigPath, "utf8"));
2321
+ } catch (err) {
2322
+ console.error("❌ Failed to read admob-ad-configuration.json", err);
2323
+ process.exit(1);
2324
+ }
2325
+
2326
+ // ✅ Validate config object exists
2327
+ if (!admobConfigInJson.config) {
2328
+ console.error('❌ "config" object is missing in admob-ad-configuration.json');
2329
+ process.exit(1);
2330
+ }
2331
+
2332
+
2333
+ const admobConfigMinVersion="1.5"
2334
+
2335
+ if (compareVersion(admobConfigInJson.VERSION, admobConfigMinVersion) < 0) {
2336
+ console.error(`❌ Please use at-least version ${admobConfigMinVersion} in "src/js/Ads/admob-ad-configuration.json"`);
2337
+ process.exit(1);
2338
+ }
2339
+
2340
+
2341
+ const config = admobConfigInJson.config;
2342
+
2343
+ // ✅ Find missing properties
2344
+ const missingKeys = REQUIRED_CONFIG_KEYS.filter(
2345
+ key => !(key in config)
2346
+ );
2347
+
2348
+
2349
+
2350
+ if (missingKeys.length > 0) {
2351
+ console.error("❌ Missing required configuration keys. Please check it in 'src/js/Ads/admob-ad-configuration.json'");
2352
+
2353
+ missingKeys.forEach(k => console.error(" - " + k));
2354
+ process.exit(1);
2355
+ }
2356
+
2357
+
2358
+ console.log('✅ All keys exist. in "admob-ad-configuration.json file" Configuration looks good.');
2359
+ }
2360
+
2361
+
2362
+
2363
+ function ensureGitignoreEntry(entry) {
2364
+ const gitignorePath = path.join(process.cwd(), '.gitignore');
2365
+
2366
+ // If .gitignore doesn't exist, create it
2367
+ if (!fs.existsSync(gitignorePath)) {
2368
+ fs.writeFileSync(gitignorePath, `${entry}\n`, 'utf8');
2369
+ console.log(`✅ .gitignore created and added: ${entry}`);
2370
+ return;
2371
+ }
2372
+
2373
+ const content = fs.readFileSync(gitignorePath, 'utf8');
2374
+
2375
+ // Normalize lines (trim + remove trailing slashes for comparison)
2376
+ const lines = content
2377
+ .split(/\r?\n/)
2378
+ .map(l => l.trim());
2379
+
2380
+ const normalizedEntry = entry.replace(/\/$/, '');
2381
+
2382
+ const exists = lines.some(
2383
+ line => line.replace(/\/$/, '') === normalizedEntry
2384
+ );
2385
+
2386
+ if (exists) {
2387
+ console.log(`ℹ️ .gitignore already contains: ${entry}`);
2388
+ return;
2389
+ }
2390
+
2391
+ // Ensure file ends with newline
2392
+ const separator = content.endsWith('\n') ? '' : '\n';
2393
+
2394
+ fs.appendFileSync(gitignorePath, `${separator}${entry}\n`, 'utf8');
2395
+ console.log(`✅ Added to .gitignore: ${entry}`);
2396
+ }
2397
+
2398
+
2399
+ ensureGitignoreEntry('buildCodeplay/');
2400
+
2401
+
2402
+ // Run the validation
2403
+ (async () => {
2404
+
2405
+ await loadPluginVersions(); // 🔥 NEW
2406
+
2407
+ await checkPlugins();
2408
+ checkAndupdateDropInViteConfig();
2409
+ checkAdmobConfigurationProperty()
2410
+ })();
2411
+
2412
+
2413
+ // ======================================================
2414
+ // Validate theme folder location (src/js/theme is NOT allowed)
2415
+ // ======================================================
2416
+
2417
+ function validateThemeFolderLocation() {
2418
+ const oldThemePath = path.join(process.cwd(), 'src', 'js', 'theme');
2419
+ const newThemePath = path.join(process.cwd(), 'src', 'theme');
2420
+
2421
+ // ❌ Block old structure
2422
+ if (fs.existsSync(oldThemePath)) {
2423
+ console.error(
2424
+ '\n❌ INVALID PROJECT STRUCTURE DETECTED\n' +
2425
+ '--------------------------------------------------\n' +
2426
+ 'The "theme" folder must NOT be inside:\n' +
2427
+ ' src/js/theme\n\n' +
2428
+ '✅ Correct location is:\n' +
2429
+ ' src/theme\n\n' +
2430
+ '🛑 Please move the folder and re-run the build.\n'
2431
+ );
2432
+ process.exit(1);
2433
+ }
2434
+
2435
+ // ⚠️ Optional warning if new theme folder is missing
2436
+ if (!fs.existsSync(newThemePath)) {
2437
+ console.warn(
2438
+ '\n⚠️ WARNING: "src/theme" folder not found.\n' +
2439
+ 'If your app uses themes, please ensure it exists.\n'
2440
+ );
2441
+ } else {
2442
+ console.log('✅ Theme folder structure validated (src/theme).');
2443
+ }
2444
+ }
2445
+ validateThemeFolderLocation()
2446
+
2447
+
2448
+
2449
+ const validateAndRestoreSignDetails=()=>{
2450
+
2451
+ // Read config file
2452
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
2453
+
2454
+ // Ensure android and buildOptions exist
2455
+ if (!config.android) config.android = {};
2456
+ if (!config.android.buildOptions) config.android.buildOptions = {};
2457
+
2458
+ // Update only if changed
2459
+ let updated = false;
2460
+
2461
+ if (config.android.buildOptions.releaseType !== 'AAB') {
2462
+ config.android.buildOptions.releaseType = 'AAB';
2463
+ updated = true;
2464
+ }
2465
+
2466
+ if (config.android.buildOptions.signingType !== 'jarsigner') {
2467
+ config.android.buildOptions.signingType = 'jarsigner';
2468
+ updated = true;
2469
+ }
2470
+
2471
+ // Write back only if modified
2472
+ if (updated) {
2473
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
2474
+ console.log('capacitor.config.json updated successfully.');
2475
+ } else {
2476
+ console.log('No changes needed.');
2477
+ }
2478
+
2479
+ }
2480
+
2481
+ validateAndRestoreSignDetails()
2482
+
2483
+
2484
+ execSync('node buildCodeplay/fix-onesignal-plugin.js', { stdio: 'inherit' });
2485
+
2486
+
2487
+
2488
+
2489
+
2490
+
2491
+
2492
+ //################################## SystemBars.java update for "@capacitor/android": "^8.3.0" plugin START ###############################
2493
+
2494
+
2495
+ const filePath = path.join(
2496
+ __dirname,
2497
+ "../node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/SystemBars.java"
2498
+ );
2499
+
2500
+ // 🔍 OLD BLOCK (anchor)
2501
+ const OLD_BLOCK = `if (shouldPassthroughInsets) {
2502
+ // We need to correct for a possible shown IME
2503
+ v.setPadding(0, 0, 0, keyboardVisible ? imeInsets.bottom : 0);
2504
+
2505
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM && hasViewportCover && insetHandlingEnabled) {
2506
+ Insets safeAreaInsets = calcSafeAreaInsets(insets);
2507
+ injectSafeAreaCSS(safeAreaInsets.top, safeAreaInsets.right, safeAreaInsets.bottom, safeAreaInsets.left);
2508
+ }
2509
+
2510
+ return new WindowInsetsCompat.Builder(insets)
2511
+ .setInsets(
2512
+ WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout(),
2513
+ Insets.of(
2514
+ systemBarsInsets.left,
2515
+ systemBarsInsets.top,
2516
+ systemBarsInsets.right,
2517
+ getBottomInset(systemBarsInsets, keyboardVisible)
2518
+ )
2519
+ )
2520
+ .build();
2521
+ }`;
2522
+
2523
+ // ✅ NEW BLOCK
2524
+ const NEW_BLOCK = `if (shouldPassthroughInsets) {
2525
+ /* 🔴 ORIGINAL CODE (COMMENTED FOR SAFETY)
2526
+ ${OLD_BLOCK.split("\n").map(line => " " + line).join("\n")}
2527
+ */
2528
+
2529
+ // ✅ NEW LOGIC (CUSTOM FIX)
2530
+ v.setPadding(0, 0, 0, 0);
2531
+
2532
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM && hasViewportCover && insetHandlingEnabled) {
2533
+ Insets safeAreaInsets = calcSafeAreaInsets(insets);
2534
+ injectSafeAreaCSS(safeAreaInsets.top, safeAreaInsets.right, safeAreaInsets.bottom, safeAreaInsets.left);
2535
+ }
2536
+
2537
+ return insets; // WebView handles everything
2538
+ }`;
2539
+
2540
+ // 🚨 ERROR MESSAGE
2541
+ const ERROR_MSG = `
2542
+ ❌ Capacitor SystemBars.java structure changed!
2543
+
2544
+ Plugin: @capacitor/android
2545
+ Path : node_modules\@capacitor\android\capacitor\src\main\java\com\getcapacitor\plugin\SystemBars.java
2546
+
2547
+ Check version of "@capacitor/android": in package.json
2548
+
2549
+ 👉 Expected code block not found.
2550
+
2551
+ This usually means Capacitor updated internally.
2552
+
2553
+ Please:
2554
+ 1. Open SystemBars.java
2555
+ 2. Update patch script
2556
+ 3. Re-run build
2557
+
2558
+ ⛔ Build stopped.
2559
+ `;
2560
+
2561
+ function patchFile() {
2562
+ if (!fs.existsSync(filePath)) {
2563
+ console.error("❌ SystemBars.java not found!");
2564
+ process.exit(1);
2565
+ }
2566
+
2567
+ let content = fs.readFileSync(filePath, "utf8");
2568
+
2569
+ // ✅ Already patched?
2570
+ if (content.includes("🔴 ORIGINAL CODE (COMMENTED FOR SAFETY)")) {
2571
+ console.log("✅ Already SystemBars.java patched. Skipping...");
2572
+ return;
2573
+ }
2574
+
2575
+ // 🔍 Check old block exists
2576
+ if (!content.includes(OLD_BLOCK)) {
2577
+ console.error(ERROR_MSG);
2578
+ process.exit(1);
2579
+ }
2580
+
2581
+ // 🔁 Replace
2582
+ const updated = content.replace(OLD_BLOCK, NEW_BLOCK);
2583
+
2584
+ fs.writeFileSync(filePath, updated, "utf8");
2585
+
2586
+ console.log("✅ SystemBars.java patched (comment + new logic)!");
2587
+ }
2588
+
2589
+ patchFile();
2590
+
2591
+ //################################## SystemBars.java update for "@capacitor/android": "^8.3.0" plugin END ###############################
2592
+
2593
+
2594
+
2595
+
2596
+ /*
2597
+ Release Notes
2598
+
2599
+ 5.1
2600
+ Kotlin version update is commented. Previously admob is not worked if not update the kotlin version to higher version
2601
+
2602
2602
  */