heraspec 0.1.15 → 0.1.16

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.
Files changed (69) hide show
  1. package/README.md +46 -12
  2. package/bin/heraspec.js +1296 -75
  3. package/bin/heraspec.js.map +4 -4
  4. package/dist/cli/index.d.ts +2 -0
  5. package/dist/commands/audit.d.ts +37 -0
  6. package/dist/commands/create.d.ts +11 -0
  7. package/dist/commands/explore.d.ts +17 -0
  8. package/dist/commands/helper.d.ts +13 -0
  9. package/dist/commands/hotfix.d.ts +9 -0
  10. package/dist/commands/make-code.d.ts +14 -0
  11. package/dist/commands/make-docs.d.ts +36 -0
  12. package/dist/commands/make-test.d.ts +60 -0
  13. package/dist/commands/memory.d.ts +101 -0
  14. package/dist/commands/pack.d.ts +17 -0
  15. package/dist/commands/show.d.ts +8 -0
  16. package/dist/commands/skill.d.ts +8 -0
  17. package/dist/commands/suggest.d.ts +32 -0
  18. package/dist/commands/validate.d.ts +8 -0
  19. package/dist/core/archive.d.ts +14 -0
  20. package/dist/core/config.d.ts +33 -0
  21. package/dist/core/init.d.ts +97 -0
  22. package/dist/core/list.d.ts +7 -0
  23. package/dist/core/memory/config-advisor.d.ts +30 -0
  24. package/dist/core/memory/context-config.d.ts +14 -0
  25. package/dist/core/memory/context-generator.d.ts +19 -0
  26. package/dist/core/memory/index.d.ts +12 -0
  27. package/dist/core/memory/memory-schema.d.ts +34 -0
  28. package/dist/core/memory/memory-search.d.ts +45 -0
  29. package/dist/core/memory/memory-store.d.ts +71 -0
  30. package/dist/core/memory/memory-types.d.ts +159 -0
  31. package/dist/core/memory/memory-vector.d.ts +23 -0
  32. package/dist/core/parsers/code-parser.d.ts +53 -0
  33. package/dist/core/parsers/markdown-parser.d.ts +18 -0
  34. package/dist/core/restore.d.ts +9 -0
  35. package/dist/core/schemas/base.schema.d.ts +55 -0
  36. package/dist/core/schemas/change.schema.d.ts +35 -0
  37. package/dist/core/schemas/index.d.ts +7 -0
  38. package/dist/core/schemas/spec.schema.d.ts +50 -0
  39. package/dist/core/skills/index.d.ts +6 -0
  40. package/dist/core/skills/skill-manager.d.ts +28 -0
  41. package/dist/core/skills/skill-parser.d.ts +24 -0
  42. package/dist/core/sync.d.ts +6 -0
  43. package/dist/core/templates/index.d.ts +10 -0
  44. package/dist/core/templates/skills/README.md +4 -1
  45. package/dist/core/templates/skills/perfex-module/code-quality-guidelines/skill.md +130 -0
  46. package/dist/core/templates/skills/perfex-module/envato-review-guidelines/skill.md +132 -0
  47. package/dist/core/templates/skills/perfex-module/module-codebase/scripts/scaffold-module.js +151 -0
  48. package/dist/core/templates/skills/perfex-module/module-codebase/skill.md +204 -110
  49. package/dist/core/templates/skills/perfex-module/module-codebase/templates/Test_Module.php +79 -0
  50. package/dist/core/templates/skills/perfex-module/module-codebase/templates/controller-admin.php +71 -0
  51. package/dist/core/templates/skills/perfex-module/module-codebase/templates/controller-api.php +58 -0
  52. package/dist/core/templates/skills/perfex-module/module-codebase/templates/deploy.ps1 +97 -0
  53. package/dist/core/templates/skills/perfex-module/module-codebase/templates/helper.php +97 -0
  54. package/dist/core/templates/skills/perfex-module/module-codebase/templates/install.php +30 -0
  55. package/dist/core/templates/skills/perfex-module/module-codebase/templates/model-main.php +94 -0
  56. package/dist/core/templates/skills/perfex-module/module-codebase/templates/module-main.php +91 -0
  57. package/dist/core/templates/skills/perfex-module/module-codebase/templates/package.json +30 -0
  58. package/dist/core/templates/skills/perfex-module/module-codebase/templates/uninstall.php +11 -0
  59. package/dist/core/templates/skills/perfex-module/module-codebase/templates/webpack.config.js +163 -0
  60. package/dist/core/templates/skills/perfex-module/skill.md +50 -0
  61. package/dist/core/templates/skills-template-map.d.ts +29 -0
  62. package/dist/core/validation/validator.d.ts +26 -0
  63. package/dist/core/view.d.ts +4 -0
  64. package/dist/index.d.ts +11 -0
  65. package/dist/index.js +155 -35
  66. package/dist/utils/file-system.d.ts +19 -0
  67. package/dist/utils/index.d.ts +6 -0
  68. package/dist/utils/task-parser.d.ts +26 -0
  69. package/package.json +2 -2
@@ -0,0 +1,130 @@
1
+ # Skill: Code Quality, Security & Static Analysis (Perfex Module)
2
+
3
+ ## Purpose
4
+
5
+ This skill defines the software engineering standards, security best practices (OWASP/CWE), static analysis compliance, and Clean Code principles required to build robust, maintainable, and enterprise-grade Perfex CRM modules.
6
+
7
+ Whether submitting to commercial marketplaces (such as Envato / CodeCanyon), deploying to high-load private enterprise environments, or publishing open-source add-ons, following these rules ensures zero security vulnerabilities, optimal concurrency, and smooth automated static analysis scans.
8
+
9
+ ## When to Use
10
+
11
+ - When developing, refactoring, or code-reviewing any Perfex CRM module.
12
+ - When performing security audits and static code analysis (SonarQube, AST scanners, bot linters).
13
+ - When preparing production release archives (`deploy.ps1` or build pipelines).
14
+ - When resolving performance bottlenecks, race conditions, or PHP session locking issues.
15
+
16
+ ---
17
+
18
+ ## Core Software Engineering & Quality Standards
19
+
20
+ ### 1. Separation of Concerns (Zero Inline JS & CSS)
21
+ - **Architectural Rule**: Strict decoupling between Presentation (HTML views), Behavior (JavaScript logic), and Styling (CSS).
22
+ - **Prohibited Patterns**:
23
+ - Inline `<script>` tags inside PHP view templates containing business logic, DOM manipulation, event listeners, or AJAX calls.
24
+ - Inline `<style>` blocks or `style="..."` attributes on HTML tags (both in module views and documentation guides).
25
+ - Hardcoded CSS string arrays declared inside JavaScript files. All styles belong in dedicated `.css` stylesheets.
26
+ - **Standard Practice**:
27
+ - All JavaScript must reside in standalone `.js` files in `assets/js/` (and compiled/minified to `dist/assets/js/`).
28
+ - All CSS must reside in standalone `.css` files in `assets/css/` (and compiled/minified to `dist/assets/css/`).
29
+ - Scripts and stylesheets must be enqueued via Perfex CRM hooks (`app_admin_head`, `app_admin_footer`, `app_customers_head`, `app_customers_footer`).
30
+ - Pass server-side configurations to frontend via centralized localization objects hooked to `app_admin_head` (e.g. `window.{MODULE_UPPERCASE}_CONFIG = ...; window.{MODULE_UPPERCASE}_LANG = ...;`) or semantic HTML5 data attributes (`data-*` / `data-config='...'`) on the root container.
31
+
32
+ ### 2. Static Analysis & AST Scanner Neutrality
33
+ Security scanners and static analysis bots (SonarQube, AST parsers, marketplace review bots) inspect source code for suspicious signatures. Ambiguous or high-risk terminology can trigger false-positive security warnings:
34
+ - **High-Risk Tokens to Avoid**:
35
+ - `inject`, `injection`, `injectStyles`: Often flagged as Script / SQL Injection patterns.
36
+ - `seeder`: Often flagged by automated bots looking for unauthorized database tampering backdoors.
37
+ - `bypass`, `backdoor`, `eval`, `unserialize`: Direct security red flags across all static analysis tools.
38
+ - **Recommended Professional Terminology**:
39
+ - Use `extend` (e.g. `extendTinyMCEStyles`) or `apply` instead of `inject`.
40
+ - Use `demo_data` or `sample_generator` instead of `seeder`.
41
+ - Use `allow` or `permit` instead of `bypass`.
42
+
43
+ ### 3. Safe Dynamic Stylesheet Loading (TinyMCE & Iframes)
44
+ When styling rich text editors or dynamically injected iframes:
45
+ - **NEVER** insert dynamic `<style>` textContent strings containing hardcoded raw CSS.
46
+ - **Native Editor API**:
47
+ ```javascript
48
+ if (editor.dom && typeof editor.dom.loadCSS === 'function') {
49
+ editor.dom.loadCSS(siteUrl + 'modules/{module}/dist/assets/css/{module}_editor.min.css');
50
+ }
51
+ ```
52
+ - **Fallback via Link Element Cloning**:
53
+ ```javascript
54
+ var parentLink = document.querySelector('link[href*="{module}_editor"]');
55
+ if (parentLink && doc.head && !doc.getElementById('{module}-tinymce-styles')) {
56
+ var linkEl = doc.createElement('link');
57
+ linkEl.id = '{module}-tinymce-styles';
58
+ linkEl.rel = 'stylesheet';
59
+ linkEl.href = parentLink.href;
60
+ doc.head.appendChild(linkEl);
61
+ }
62
+ ```
63
+
64
+ ### 4. JavaScript Scope Isolation & Conflict Prevention
65
+ Prevent race conditions, jQuery namespace clashes, and global scope pollution:
66
+ - Enclose 100% of admin scripts in a window load listener and strict IIFE:
67
+ ```javascript
68
+ window.addEventListener('load', function () {
69
+ (function ($) {
70
+ 'use strict';
71
+ // Scoped module logic here
72
+ })(typeof jQuery !== 'undefined' ? jQuery : window.$);
73
+ });
74
+ ```
75
+ - Keep the global `window` scope pristine. Only expose strictly necessary public APIs under a unified module namespace.
76
+
77
+ ### 5. High-Concurrency & PHP Session Lock Prevention
78
+ - In PHP and CodeIgniter, active sessions hold exclusive file locks. Autocomplete lookups, live searches, and read-only AJAX endpoints can cause thread blocking and interface lag when multiple requests queue up.
79
+ - Always release the session lock at the start of read/search controller actions:
80
+ ```php
81
+ // Release PHP session file lock immediately for non-blocking concurrent queries
82
+ session_write_close();
83
+ ```
84
+
85
+ ### 6. Clean Release Packaging & Artifact Isolation
86
+ - Separate development dependencies and test tooling from production runtime artifacts.
87
+ - **Strictly Exclude from Production Distribution**:
88
+ - Development build files: `package.json`, `package-lock.json`, `webpack.config.js`.
89
+ - Testing & scratch code: `tests/`, `test/`, `scratch/`, `*_debug.php`, benchmark scripts.
90
+ - Raw uncompiled assets if using bundled/minified `dist/`.
91
+ - Version control and IDE artifacts: `.git`, `.ai`, `.agents`, `heraspec`, internal project notes.
92
+ - Use packaging scripts (`deploy.ps1` or build scripts) with strict exclusion filters (`/XD`, `/XF`).
93
+
94
+ ### 7. Defensive PHP Security & Database Best Practices
95
+ - **Direct Access Guard**: 100% of PHP files must begin with:
96
+ ```php
97
+ <?php
98
+ defined('BASEPATH') or exit('No direct script access allowed');
99
+ ```
100
+ - **Standard PHP Tags**: Never use short open tags `<?=` or `<?`. Always use standard `<?php echo ...; ?>`.
101
+ - **SQL Injection Prevention (OWASP)**: Never concatenate user input directly into SQL queries. Always use CodeIgniter Query Builder with automatic parameter escaping or `$this->db->escape_str()`.
102
+ - **CSRF Protection**: All POST forms and AJAX requests modifying state must include CSRF tokens:
103
+ ```php
104
+ <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
105
+ ```
106
+ And in AJAX:
107
+ ```javascript
108
+ $.ajaxSetup({ data: { [csrf_token_name]: csrf_hash } });
109
+ ```
110
+
111
+ ### 8. DOM XSS Prevention (CWE-79)
112
+ - Never assign raw, unescaped user-controlled strings directly to `.innerHTML`.
113
+ - Use `.textContent`, `.innerText`, `document.createElement()`, or helper functions with strict HTML entity escaping (`escapeHtml()`).
114
+ - Always sanitize rich user-generated content using HTMLPurifier before rendering.
115
+
116
+ ### 9. Enterprise Internationalization (i18n & l10n)
117
+ - **Zero Hardcoded Strings**: 100% of labels, headings, buttons, tooltips, placeholders, and error/feedback messages must use `_l('key')`.
118
+ - Maintain complete parity across supported language catalogs:
119
+ - `language/english/{module}_lang.php`
120
+ - `language/vietnamese/{module}_lang.php` (and other target locales)
121
+ - Never hardcode raw strings like `'Item deleted'` or `'Unauthorized'` in controllers; use centralized language keys.
122
+
123
+ ### 10. Professional Software DNA & Clean Typography
124
+ - 0 emojis in backend PHP, JavaScript, CSS, view templates, comments, or documentation.
125
+ - Maintain a clean, professional, enterprise-grade look and feel consistent with core CRM aesthetics.
126
+
127
+ ---
128
+
129
+ ## Reference Implementation
130
+ - `modules/crosstag/`: Production reference adhering to dual-engine search, `extendTinyMCEStyles()`, Webpack dist bundling, session lock release, and 100% passing automated test assertions.
@@ -0,0 +1,132 @@
1
+ # Skill: Code Quality, Security & Static Analysis (Perfex Module)
2
+
3
+ > **Note**: This skill incorporates the comprehensive static analysis, security, and clean architecture standards required for enterprise deployments, open-source releases, and commercial marketplace submissions (such as Envato / CodeCanyon).
4
+
5
+ ## Purpose
6
+
7
+ This skill defines the software engineering standards, security best practices (OWASP/CWE), static analysis compliance, and Clean Code principles required to build robust, maintainable, and enterprise-grade Perfex CRM modules.
8
+
9
+ Following these rules ensures zero security vulnerabilities, optimal concurrency, and smooth automated static analysis scans (SonarQube, AST linters, automated marketplace review bots).
10
+
11
+ ## When to Use
12
+
13
+ - When developing, refactoring, or code-reviewing any Perfex CRM module.
14
+ - When performing security audits and static code analysis (SonarQube, AST scanners, bot linters).
15
+ - When preparing production release archives (`deploy.ps1` or build pipelines).
16
+ - When resolving performance bottlenecks, race conditions, or PHP session locking issues.
17
+
18
+ ---
19
+
20
+ ## Core Software Engineering & Quality Standards
21
+
22
+ ### 1. Separation of Concerns (Zero Inline JS & CSS)
23
+ - **Architectural Rule**: Strict decoupling between Presentation (HTML views), Behavior (JavaScript logic), and Styling (CSS).
24
+ - **Prohibited Patterns**:
25
+ - Inline `<script>` tags inside PHP view templates containing business logic, DOM manipulation, event listeners, or AJAX calls.
26
+ - Inline `<style>` blocks or `style="..."` attributes on HTML tags (both in module views and documentation guides).
27
+ - Hardcoded CSS string arrays declared inside JavaScript files. All styles belong in dedicated `.css` stylesheets.
28
+ - **Standard Practice**:
29
+ - All JavaScript must reside in standalone `.js` files in `assets/js/` (and compiled/minified to `dist/assets/js/`).
30
+ - All CSS must reside in standalone `.css` files in `assets/css/` (and compiled/minified to `dist/assets/css/`).
31
+ - Scripts and stylesheets must be enqueued via Perfex CRM hooks (`app_admin_head`, `app_admin_footer`, `app_customers_head`, `app_customers_footer`).
32
+ - Pass server-side configurations to frontend via centralized localization objects hooked to `app_admin_head` (e.g. `window.{MODULE_UPPERCASE}_CONFIG = ...; window.{MODULE_UPPERCASE}_LANG = ...;`) or semantic HTML5 data attributes (`data-*` / `data-config='...'`) on the root container.
33
+
34
+ ### 2. Static Analysis & AST Scanner Neutrality
35
+ Security scanners and static analysis bots (SonarQube, AST parsers, marketplace review bots) inspect source code for suspicious signatures. Ambiguous or high-risk terminology can trigger false-positive security warnings:
36
+ - **High-Risk Tokens to Avoid**:
37
+ - `inject`, `injection`, `injectStyles`: Often flagged as Script / SQL Injection patterns.
38
+ - `seeder`: Often flagged by automated bots looking for unauthorized database tampering backdoors.
39
+ - `bypass`, `backdoor`, `eval`, `unserialize`: Direct security red flags across all static analysis tools.
40
+ - **Recommended Professional Terminology**:
41
+ - Use `extend` (e.g. `extendTinyMCEStyles`) or `apply` instead of `inject`.
42
+ - Use `demo_data` or `sample_generator` instead of `seeder`.
43
+ - Use `allow` or `permit` instead of `bypass`.
44
+
45
+ ### 3. Safe Dynamic Stylesheet Loading (TinyMCE & Iframes)
46
+ When styling rich text editors or dynamically injected iframes:
47
+ - **NEVER** insert dynamic `<style>` textContent strings containing hardcoded raw CSS.
48
+ - **Native Editor API**:
49
+ ```javascript
50
+ if (editor.dom && typeof editor.dom.loadCSS === 'function') {
51
+ editor.dom.loadCSS(siteUrl + 'modules/{module}/dist/assets/css/{module}_editor.min.css');
52
+ }
53
+ ```
54
+ - **Fallback via Link Element Cloning**:
55
+ ```javascript
56
+ var parentLink = document.querySelector('link[href*="{module}_editor"]');
57
+ if (parentLink && doc.head && !doc.getElementById('{module}-tinymce-styles')) {
58
+ var linkEl = doc.createElement('link');
59
+ linkEl.id = '{module}-tinymce-styles';
60
+ linkEl.rel = 'stylesheet';
61
+ linkEl.href = parentLink.href;
62
+ doc.head.appendChild(linkEl);
63
+ }
64
+ ```
65
+
66
+ ### 4. JavaScript Scope Isolation & Conflict Prevention
67
+ Prevent race conditions, jQuery namespace clashes, and global scope pollution:
68
+ - Enclose 100% of admin scripts in a window load listener and strict IIFE:
69
+ ```javascript
70
+ window.addEventListener('load', function () {
71
+ (function ($) {
72
+ 'use strict';
73
+ // Scoped module logic here
74
+ })(typeof jQuery !== 'undefined' ? jQuery : window.$);
75
+ });
76
+ ```
77
+ - Keep the global `window` scope pristine. Only expose strictly necessary public APIs under a unified module namespace.
78
+
79
+ ### 5. High-Concurrency & PHP Session Lock Prevention
80
+ - In PHP and CodeIgniter, active sessions hold exclusive file locks. Autocomplete lookups, live searches, and read-only AJAX endpoints can cause thread blocking and interface lag when multiple requests queue up.
81
+ - Always release the session lock at the start of read/search controller actions:
82
+ ```php
83
+ // Release PHP session file lock immediately for non-blocking concurrent queries
84
+ session_write_close();
85
+ ```
86
+
87
+ ### 6. Clean Release Packaging & Artifact Isolation
88
+ - Separate development dependencies and test tooling from production runtime artifacts.
89
+ - **Strictly Exclude from Production Distribution**:
90
+ - Development build files: `package.json`, `package-lock.json`, `webpack.config.js`.
91
+ - Testing & scratch code: `tests/`, `test/`, `scratch/`, `*_debug.php`, benchmark scripts.
92
+ - Raw uncompiled assets if using bundled/minified `dist/`.
93
+ - Version control and IDE artifacts: `.git`, `.ai`, `.agents`, `heraspec`, internal project notes.
94
+ - Use packaging scripts (`deploy.ps1` or build scripts) with strict exclusion filters (`/XD`, `/XF`).
95
+
96
+ ### 7. Defensive PHP Security & Database Best Practices
97
+ - **Direct Access Guard**: 100% of PHP files must begin with:
98
+ ```php
99
+ <?php
100
+ defined('BASEPATH') or exit('No direct script access allowed');
101
+ ```
102
+ - **Standard PHP Tags**: Never use short open tags `<?=` or `<?`. Always use standard `<?php echo ...; ?>`.
103
+ - **SQL Injection Prevention (OWASP)**: Never concatenate user input directly into SQL queries. Always use CodeIgniter Query Builder with automatic parameter escaping or `$this->db->escape_str()`.
104
+ - **CSRF Protection**: All POST forms and AJAX requests modifying state must include CSRF tokens:
105
+ ```php
106
+ <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
107
+ ```
108
+ And in AJAX:
109
+ ```javascript
110
+ $.ajaxSetup({ data: { [csrf_token_name]: csrf_hash } });
111
+ ```
112
+
113
+ ### 8. DOM XSS Prevention (CWE-79)
114
+ - Never assign raw, unescaped user-controlled strings directly to `.innerHTML`.
115
+ - Use `.textContent`, `.innerText`, `document.createElement()`, or helper functions with strict HTML entity escaping (`escapeHtml()`).
116
+ - Always sanitize rich user-generated content using HTMLPurifier before rendering.
117
+
118
+ ### 9. Enterprise Internationalization (i18n & l10n)
119
+ - **Zero Hardcoded Strings**: 100% of labels, headings, buttons, tooltips, placeholders, and error/feedback messages must use `_l('key')`.
120
+ - Maintain complete parity across supported language catalogs:
121
+ - `language/english/{module}_lang.php`
122
+ - `language/vietnamese/{module}_lang.php` (and other target locales)
123
+ - Never hardcode raw strings like `'Item deleted'` or `'Unauthorized'` in controllers; use centralized language keys.
124
+
125
+ ### 10. Professional Software DNA & Clean Typography
126
+ - 0 emojis in backend PHP, JavaScript, CSS, view templates, comments, or documentation.
127
+ - Maintain a clean, professional, enterprise-grade look and feel consistent with core CRM aesthetics.
128
+
129
+ ---
130
+
131
+ ## Reference Implementation
132
+ - `modules/crosstag/`: Production reference adhering to dual-engine search, `extendTinyMCEStyles()`, Webpack dist bundling, session lock release, and 100% passing automated test assertions.
@@ -0,0 +1,151 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Perfex CRM Module Scaffolder
5
+ * Generates a clean-architecture Perfex CRM module from templates.
6
+ *
7
+ * Usage:
8
+ * node scaffold-module.js <module-name> [friendly-name] [description]
9
+ * Example:
10
+ * node scaffold-module.js my_module "My Module" "A custom Perfex CRM module"
11
+ */
12
+
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+
16
+ const moduleName = process.argv[2];
17
+ if (!moduleName) {
18
+ console.error('Usage: node scaffold-module.js <module-name> [friendly-name] [description]');
19
+ process.exit(1);
20
+ }
21
+
22
+ const cleanModuleName = moduleName.toLowerCase().replace(/[^a-z0-9_]/g, '_');
23
+ const pascalName = cleanModuleName
24
+ .split('_')
25
+ .map(word => word.charAt(0).toUpperCase() + word.slice(1))
26
+ .join('');
27
+ const upperName = cleanModuleName.toUpperCase();
28
+ const friendlyName = process.argv[3] || pascalName;
29
+ const description = process.argv[4] || `${friendlyName} module for Perfex CRM`;
30
+
31
+ const targetDir = path.resolve(process.cwd(), 'modules', cleanModuleName);
32
+ const templatesDir = path.resolve(__dirname, '..', 'templates');
33
+
34
+ console.log(`Scaffolding Perfex module: ${cleanModuleName} -> ${targetDir}`);
35
+
36
+ // Ensure directories
37
+ const dirs = [
38
+ 'controllers',
39
+ 'models',
40
+ 'helpers',
41
+ 'libraries',
42
+ 'views/admin',
43
+ 'language/english',
44
+ 'language/vietnamese',
45
+ 'assets/css/admin',
46
+ 'assets/js/admin',
47
+ 'assets/js/lib',
48
+ 'assets/css/lib',
49
+ 'dist/assets/css',
50
+ 'dist/assets/js',
51
+ 'tests',
52
+ 'documentations',
53
+ ];
54
+
55
+ dirs.forEach(d => {
56
+ const dirPath = path.join(targetDir, d);
57
+ fs.mkdirSync(dirPath, { recursive: true });
58
+ });
59
+
60
+ function processTemplate(srcFile, destFile) {
61
+ if (!fs.existsSync(srcFile)) return;
62
+ let content = fs.readFileSync(srcFile, 'utf8');
63
+ content = content
64
+ .replace(/\{module_name\}/g, cleanModuleName)
65
+ .replace(/\{ModuleName\}/g, pascalName)
66
+ .replace(/\{MODULE_UPPERCASE\}/g, upperName)
67
+ .replace(/\{MODULE_FRIENDLY_NAME\}/g, friendlyName)
68
+ .replace(/\{MODULE_DESCRIPTION\}/g, description);
69
+ fs.writeFileSync(destFile, content, 'utf8');
70
+ }
71
+
72
+ // Scaffold core files from templates
73
+ processTemplate(path.join(templatesDir, 'module-main.php'), path.join(targetDir, `${cleanModuleName}.php`));
74
+ processTemplate(path.join(templatesDir, 'install.php'), path.join(targetDir, 'install.php'));
75
+ processTemplate(path.join(templatesDir, 'uninstall.php'), path.join(targetDir, 'uninstall.php'));
76
+ processTemplate(path.join(templatesDir, 'helper.php'), path.join(targetDir, 'helpers', `${cleanModuleName}_helper.php`));
77
+ processTemplate(path.join(templatesDir, 'controller-admin.php'), path.join(targetDir, 'controllers', `${pascalName}.php`));
78
+ processTemplate(path.join(templatesDir, 'controller-api.php'), path.join(targetDir, 'controllers', 'Api.php'));
79
+ processTemplate(path.join(templatesDir, 'model-main.php'), path.join(targetDir, 'models', `${cleanModuleName}_model.php`));
80
+ processTemplate(path.join(templatesDir, 'package.json'), path.join(targetDir, 'package.json'));
81
+ processTemplate(path.join(templatesDir, 'webpack.config.js'), path.join(targetDir, 'webpack.config.js'));
82
+ processTemplate(path.join(templatesDir, 'deploy.ps1'), path.join(targetDir, 'deploy.ps1'));
83
+
84
+ // Create language files
85
+ const enLang = `<?php
86
+ defined('BASEPATH') or exit('No direct script access allowed');
87
+
88
+ $lang['${cleanModuleName}_menu_title'] = '${friendlyName}';
89
+ $lang['${cleanModuleName}_management'] = '${friendlyName} Management';
90
+ $lang['${cleanModuleName}_item'] = 'Item';
91
+ $lang['${cleanModuleName}_confirm_delete'] = 'Are you sure you want to delete this item?';
92
+ $lang['${cleanModuleName}_saved_successfully'] = 'Saved successfully.';
93
+ $lang['${cleanModuleName}_status_updated'] = 'Status updated successfully.';
94
+ `;
95
+ fs.writeFileSync(path.join(targetDir, 'language', 'english', `${cleanModuleName}_lang.php`), enLang, 'utf8');
96
+
97
+ const viLang = `<?php
98
+ defined('BASEPATH') or exit('No direct script access allowed');
99
+
100
+ $lang['${cleanModuleName}_menu_title'] = '${friendlyName}';
101
+ $lang['${cleanModuleName}_management'] = 'Quản lý ${friendlyName}';
102
+ $lang['${cleanModuleName}_item'] = 'Mục';
103
+ $lang['${cleanModuleName}_confirm_delete'] = 'Bạn có chắc chắn muốn xóa mục này?';
104
+ $lang['${cleanModuleName}_saved_successfully'] = 'Lưu thành công.';
105
+ $lang['${cleanModuleName}_status_updated'] = 'Cập nhật trạng thái thành công.';
106
+ `;
107
+ fs.writeFileSync(path.join(targetDir, 'language', 'vietnamese', `${cleanModuleName}_lang.php`), viLang, 'utf8');
108
+
109
+ // Create pure view template
110
+ const adminView = `<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
111
+ <?php init_head(); ?>
112
+ <div id="wrapper">
113
+ <div class="content">
114
+ <div class="row">
115
+ <div class="col-md-12">
116
+ <div class="panel_s">
117
+ <div class="panel-body">
118
+ <h4 class="no-margin font-bold"><?php echo html_escape($title); ?></h4>
119
+ <hr class="hr-panel-heading" />
120
+ <div class="${cleanModuleName}-container" data-module="${cleanModuleName}">
121
+ <p><?php echo _l('${cleanModuleName}_management'); ?></p>
122
+ </div>
123
+ </div>
124
+ </div>
125
+ </div>
126
+ </div>
127
+ </div>
128
+ </div>
129
+ <?php init_tail(); ?>
130
+ `;
131
+ fs.writeFileSync(path.join(targetDir, 'views', 'admin', 'manage.php'), adminView, 'utf8');
132
+
133
+ // Create admin JS
134
+ const adminJs = `window.addEventListener('load', function () {
135
+ (function ($) {
136
+ 'use strict';
137
+ // ${friendlyName} Admin Logic
138
+ console.log('${friendlyName} admin script initialized.');
139
+ })(typeof jQuery !== 'undefined' ? jQuery : window.$);
140
+ });
141
+ `;
142
+ fs.writeFileSync(path.join(targetDir, 'assets', 'js', 'admin', `${cleanModuleName}_admin.js`), adminJs, 'utf8');
143
+
144
+ // Create admin CSS
145
+ const adminCss = `.${cleanModuleName}-container {
146
+ padding: 10px 0;
147
+ }
148
+ `;
149
+ fs.writeFileSync(path.join(targetDir, 'assets', 'css', 'admin', `${cleanModuleName}_admin.css`), adminCss, 'utf8');
150
+
151
+ console.log(`✓ Module scaffolded successfully at: ${targetDir}`);