From d6c666eb3c609beb376d1cd3c6d7582982d3e6cc Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Tue, 10 Nov 2026 10:40:34 +0330 Subject: [PATCH] last ... --- .../Developer/CLi Tool for xFramework 2.html | 1286 ++++++++ .../Cli Tool Development for xFramework.html | 2034 +++++++++++++ .../XClient Cli xFramework Tool .html | 2034 +++++++++++++ ...workComponents Overview 14050818 v1.0.html | 1534 ++++++++++ .../{SDKManager 1.html => SDK Manager 1.html} | 0 .../{SDKManager 2.html => SDK Manager 2.html} | 0 .../SDKManager/Versions/SDK Manager 3.html | 2594 ++++++++++++++++ .../SDKManager/Versions/SDK Manager 4.html | 2643 +++++++++++++++++ 8 files changed, 12125 insertions(+) create mode 100644 Documents/Docs/Developer/CLi Tool for xFramework 2.html create mode 100644 Documents/Docs/Developer/Cli Tool Development for xFramework.html create mode 100644 Documents/Docs/Developer/XClient Cli xFramework Tool .html create mode 100644 Documents/Docs/Developer/xFrameworkComponents Overview 14050818 v1.0.html rename Documents/Resources/SDKManager/Versions/{SDKManager 1.html => SDK Manager 1.html} (100%) rename Documents/Resources/SDKManager/Versions/{SDKManager 2.html => SDK Manager 2.html} (100%) create mode 100644 Documents/Resources/SDKManager/Versions/SDK Manager 3.html create mode 100644 Documents/Resources/SDKManager/Versions/SDK Manager 4.html diff --git a/Documents/Docs/Developer/CLi Tool for xFramework 2.html b/Documents/Docs/Developer/CLi Tool for xFramework 2.html new file mode 100644 index 0000000..e4e24c1 --- /dev/null +++ b/Documents/Docs/Developer/CLi Tool for xFramework 2.html @@ -0,0 +1,1286 @@ + + + + + +xcli – راهنمای کامل ساخت ابزار تولید برنامه‌های xFramework + + + +
+ + + +
+ +
+

راهنمای کامل ساخت xcli

+

+ ساخت گام‌به‌گام ابزار CLI برای تولید و مدیریت برنامه‌های مبتنی بر xFramework، + با الگوبرداری از xClient و سازگار با محدودیت‌های نسخه‌ای + @angular/cli@12.0.4 و @ionic/cli@6.6.0. +

+
+ Node ≥ 14 + Angular CLI 12.0.4 + Ionic CLI 6.6.0 + Commander.js + Handlebars + ts-morph + CommonJS +
+
+ + +

۱. مقدمه و اهداف

+ +

+ پروژه xClient یک اپلیکیشن کامل و بالغ بر پایه Ionic/Angular است که با + سه بسته اصلی x-framework-core، x-framework-services، + x-framework-components، x-framework-identity-sdk، + x-framework-push-service و x-saherelm-api-sdk ساخته شده است. + این پروژه الگوی کاملی از ساختار پوشه‌ها، الگوهای کدنویسی، + پیکربندی و مدیریت Localization/Routing/State را در خود دارد. +

+ +

+ هدف این سند طراحی و پیاده‌سازی ابزاری به نام xcli است که با الهام از + ساختار xClient، چرخه توسعه یک برنامه xFramework را خودکار کند: +

+ +
+
+

🎯 اهداف عملکردی

+
    +
  • ساخت پروژه جدید از صفر با یک دستور
  • +
  • افزودن موجودیت (DTO + 4 سرویس + Facade)
  • +
  • افزودن صفحه مدیریت و اکسپلورر
  • +
  • حذف صفحه با پاکسازی همه ارجاعات
  • +
  • مدیریت کلیدهای ترجمه
  • +
  • بررسی سلامت پروژه (doctor)
  • +
  • Build و تحلیل باندل
  • +
+
+
+

⚠️ محدودیت‌ها

+
    +
  • Angular CLI باید 12.0.4 باشد
  • +
  • Ionic CLI باید 6.6.0 باشد
  • +
  • پروژه‌های تولیدی باید با Angular 12 کار کنند
  • +
  • نمی‌توانیم از Standalone Components استفاده کنیم
  • +
  • tsconfig و tsconfig.app.json باید با ViewEngine یا Ivy سازگار باشد
  • +
  • ng-packagr نسخه 12
  • +
+
+
+

📦 خروجی نهایی

+
    +
  • پکیج npm به نام xcli
  • +
  • قابل نصب با npm i -g xcli
  • +
  • قابل استفاده به‌صورت npx xcli
  • +
  • مستندسازی شده
  • +
  • قابل توسعه با plugin
  • +
+
+
+ + +

۲. پیش‌نیازها و نسخه‌ها

+ +

نسخه‌های اجباری برای پروژه‌های تولیدی

+ + + + + + + + + + + + + + +
ابزارنسخهنقش
@angular/cli12.0.4تولید اسکلت پروژه، build و test
@ionic/cli6.6.0Ionic integration، Serve، Build
@angular/core~12.0.0هسته Angular
@ionic/angular^6.0.0کامپوننت‌های Ionic
typescript~4.2.3سازگار با Angular 12
rxjs~6.6.0سازگار با Angular 12
zone.js~0.11.4سازگار با Angular 12
ng-packagr^12.0.0برای build کتابخانه‌ها
+ +

نسخه‌های CLI خودمان (xcli)

+ + + + + + + + + + + + + + + +
پکیجنسخهدلیل انتخاب
commander^11.1.0CommonJS، پایدار
inquirer^8.2.6CommonJS (v9 ESM است)
chalk^4.1.2CommonJS (v5 ESM است)
ora^5.4.1CommonJS (v6 ESM است)
handlebars^4.7.8CommonJS
fs-extra^10.1.0CommonJS
ts-morph^15.1.0سازگار با TypeScript 4.3
globby^11.1.0CommonJS (v12+ ESM)
semver^7.5.4CommonJS
+ +
+ نکته حیاتی: Node.js ≥ 14 توصیه می‌شود. برای اطمینان از سازگاری، + در package.json مقدار "engines": {"node": ">=14.0.0"} قرار دهید. + همچنین تمام پکیج‌ها باید CommonJS باشند؛ اگر نسخه ESM انتخاب شود، باید از + "type": "module" در package.json و import syntax استفاده کنید که + برای سازگاری بیشتر توصیه نمی‌شود. +
+ + +

۳. تحلیل مرجع: xClient به‌عنوان الگو

+ +

برای ساخت xcli، ابتدا ساختار xClient را استخراج می‌کنیم تا بدانیم چه فایل‌هایی باید تولید شوند.

+ +

ساختار هدف پروژه

+

+my-app/
+├── angular.json
+├── ionic.config.json
+├── capacitor.config.json
+├── package.json
+├── tsconfig.json
+├── tsconfig.app.json
+├── tslint.json
+├── src/
+│   ├── index.html
+│   ├── main.ts
+│   ├── polyfills.ts
+│   ├── global.d.ts
+│   ├── styles.scss
+│   ├── manifest.webmanifest
+│   ├── environments/
+│   │   ├── environment.ts
+│   │   └── environment.prod.ts
+│   ├── theme/
+│   │   ├── variables.scss
+│   │   └── theme.scss
+│   └── app/
+│       ├── app.module.ts
+│       ├── app-routing.module.ts
+│       ├── app.component.ts/html/scss
+│       ├── config/
+│       │   ├── app.config.ts
+│       │   ├── x.config.ts
+│       │   ├── x-api.config.ts
+│       │   ├── page.config.ts
+│       │   └── localization.config.ts
+│       ├── shared/
+│       │   ├── shared.module.ts
+│       │   ├── public-api.ts
+│       │   └── services/
+│       │       └── shared.service.ts
+│       ├── pages/
+│       │   ├── startup/
+│       │   ├── landing/
+│       │   ├── home/
+│       │   ├── error/
+│       │   └── not-authorized/
+│       └── views/
+│           └── (از قبل با x-framework-components تأمین می‌شود)
+└── assets/
+    ├── icon/
+    ├── image/
+    └── audio/
+
+ +

فایل‌های حیاتی که باید patch شوند

+ + + + + + + + + + + + + + +
فایلمسئولیتکی patch می‌شود
package.jsonافزودن وابستگی‌هاxcli init
app.module.tsimport ماژول‌های xFrameworkxcli init
app-routing.module.tsافزودن route هاpage:add
page.config.tsافزودن PageIndex و Navpage:add
localization.config.tsافزودن کلیدهای ترجمهstring:add
public-api.ts (SDK)export های جدیدentity:add
x-endpoint.typings.tsافزودن Endpoint جدیدentity:add
+ +

الگوهای کلیدی قابل تعمیم

+ +
+
+

Base Page → Concrete

+

+ FilesBaseProviderPage ← FilesManagementPage / FilesExplorerPage. + xcli باید همین سه فایل را برای هر موجودیت جدید تولید کند. +

+
+
+

Entity → 5 Services

+

+ هر Entity شامل Dto، EntityService، ProviderService، EntityPushService و Facade است. +

+
+
+

Config غول‌آسا

+

+ همه config ها در XConfig مرکب از 7 نوع ذخیره و از طریق InjectionToken توزیع می‌شوند. +

+
+
+

Localization مرکب

+

+ AppResourceIDs + resource های هر دامنه + منابع Shared در یک آرایه ترکیب می‌شوند. +

+
+
+ + +

۴. معماری xcli

+ +

ساختار پکیج

+ +

+xcli/
+├── package.json                    # وابستگی‌ها + bin
+├── README.md
+├── bin/
+│   └── xcli.js                     # entry point با shebang
+├── lib/
+│   ├── cli.js                      # Commander bootstrap
+│   ├── commands/
+│   │   ├── init.js                 # xcli init
+│   │   ├── page-add.js             # xcli page:add
+│   │   ├── page-remove.js          # xcli page:remove
+│   │   ├── entity-add.js           # xcli entity:add
+│   │   ├── string-add.js           # xcli string:add
+│   │   ├── config.js               # xcli config:show
+│   │   ├── build.js                # xcli build
+│   │   └── doctor.js               # xcli doctor
+│   ├── generators/
+│   │   ├── project.js              # تولید پروژه کامل
+│   │   ├── page.js                 # تولید صفحه
+│   │   ├── entity.js               # تولید موجودیت
+│   │   └── string.js               # افزودن ترجمه
+│   ├── utils/
+│   │   ├── logger.js               # چاپ رنگی
+│   │   ├── paths.js                # کشف ریشه‌ها
+│   │   ├── fs-helper.js            # render + write
+│   │   ├── ast.js                  # ts-morph patch
+│   │   └── shell.js                # execSync wrapper
+│   └── templates/
+│       ├── project/                # قالب‌های پروژه
+│       ├── page/                   # قالب‌های صفحه
+│       ├── entity/                 # قالب‌های موجودیت
+│       └── string/                 # قالب‌های ترجمه
+└── .gitignore
+
+ +

نمودار جریان دستور `page:add`

+

+  [User]      [CLI]          [Generator]      [FS/AST]        [Project]
+    │           │                │                │                │
+    ├─page:add─►│                │                │                │
+    │           ├─parse opts────►│                │                │
+    │           │                ├─findProjectRoot►│                │
+    │           │                │◄───────path────┤                │
+    │           │                │                │                │
+    │           │                ├─render templates►│                │
+    │           │                │                ├─write files────►│
+    │           │                │                │                │
+    │           │                ├─patch routing──►│                │
+    │           │                │                ├─add route──────►│
+    │           │                │                │                │
+    │           │                ├─patch page config►│                │
+    │           │                │                ├─add nav────────►│
+    │           │                │                │                │
+    │◄──done────┤◄───────────────┤                │                │
+
+ +

تصمیمات کلیدی

+ + + + + + + + + + + + +
تصمیمدلیل
CommonJSسازگاری با Node 14+ و ابزارهایی مثل npx @angular/cli@12.0.4
Shell-out برای initجلوگیری از نوشتن دستی boilerplate Angular (نصب ng new راحت‌تر است)
ts-morph برای patchویرایش امن فایل‌های TypeScript با حفظ فرمت
Handlebars برای templatesساده، بدون وابستگی به runtime Angular
پیکربندی xcli.config.jsهر پروژه می‌تواند مسیرها و کنوانسیون‌های خود را داشته باشد
Dry-run modeاجازه پیش‌نمایش تغییرات قبل از اعمال
+ + +

فاز ۱ زیرساخت پروژه xcli

+ +
+
+

ایجاد پوشه پروژه

+

mkdir xcli && cd xcli

+
+
+

ایجاد package.json

+

در ادامه کد کامل ارائه می‌شود.

+
+
+

ساختار پوشه‌ها

+

mkdir -p bin lib/commands lib/generators lib/utils lib/templates

+
+
+

نصب وابستگی‌ها

+

npm install

+
+
+

پیوند محلی برای تست

+

npm link (بعد از پیاده‌سازی)

+
+
+ +

package.json

+
xcli/package.json
+
{
+  "name": "xcli",
+  "version": "1.0.0",
+  "description": "xFramework scaffolding CLI (Angular 12 + Ionic 6)",
+  "main": "./lib/cli.js",
+  "bin": { "xcli": "./bin/xcli.js" },
+  "engines": { "node": ">=14.0.0" },
+  "files": ["bin", "lib", "README.md"],
+  "keywords": ["xframework", "angular", "ionic", "scaffolding"],
+  "license": "MIT",
+  "dependencies": {
+    "chalk": "^4.1.2",
+    "commander": "^11.1.0",
+    "fs-extra": "^10.1.0",
+    "globby": "^11.1.0",
+    "handlebars": "^4.7.8",
+    "inquirer": "^8.2.6",
+    "ora": "^5.4.1",
+    "semver": "^7.5.4",
+    "ts-morph": "^15.1.0"
+  }
+}
+ +

bin/xcli.js

+
xcli/bin/xcli.js
+
#!/usr/bin/env node
+'use strict';
+
+require('../lib/cli').run(process.argv).catch((err) => {
+  const msg = err && err.message ? err.message : String(err);
+  console.error('\x1b[31m✖ ' + msg + '\x1b[0m');
+  if (process.env.XCLI_DEBUG) console.error(err);
+  process.exit(1);
+});
+ +
+ اجرای مجوز: پس از ایجاد، نیاز است فایل را با دستور + chmod +x bin/xcli.js (در Linux/Mac) قابل اجرا کنید. +
+ +

lib/cli.js

+
xcli/lib/cli.js
+
'use strict';
+
+const { Command } = require('commander');
+const pkg = require('../package.json');
+
+async function run(argv) {
+  const program = new Command();
+
+  program
+    .name('xcli')
+    .version(pkg.version, '-v, --version')
+    .description('xFramework scaffolding CLI (Angular 12 + Ionic 6)')
+    .option('--debug', 'Show debug output', false)
+    .hook('preAction', (cmd) => {
+      if (cmd.opts().debug) process.env.XCLI_DEBUG = '1';
+    })
+    .addHelpText('after', `
+Commands:
+  init <name>             Create a new xFramework project
+  page:add <name>         Add a new page
+  page:remove <name>      Remove an existing page
+  entity:add <Name>       Add a new entity (DTO + services)
+  string:add <key>        Add a localization key
+  config:show             Show effective configuration
+  build                   Build project with analysis
+  doctor                  Check project health
+
+Examples:
+  $ xcli init my-app
+  $ xcli page:add orders --type=management --entity=Order
+  $ xcli entity:add Order --key=string
+  $ xcli string:add orders_title --fa=سفارش‌ها --en=Orders
+  $ xcli doctor
+    `);
+
+  program.addCommand(require('./commands/init'));
+  program.addCommand(require('./commands/page-add'));
+  program.addCommand(require('./commands/page-remove'));
+  program.addCommand(require('./commands/entity-add'));
+  program.addCommand(require('./commands/string-add'));
+  program.addCommand(require('./commands/config'));
+  program.addCommand(require('./commands/build'));
+  program.addCommand(require('./commands/doctor'));
+
+  await program.parseAsync(argv);
+}
+
+module.exports = { run };
+ + +

فاز ۲ Utilities

+ +

lib/utils/logger.js

+
xcli/lib/utils/logger.js
+
'use strict';
+const chalk = require('chalk');
+
+module.exports = {
+  info:    (m) => console.log(chalk.blue('ℹ ') + m),
+  success: (m) => console.log(chalk.green('✔ ') + m),
+  warn:    (m) => console.log(chalk.yellow('⚠ ') + m),
+  error:   (m) => console.log(chalk.red('✖ ') + m),
+  step:    (m) => console.log(chalk.cyan('▶ ') + m),
+  dim:     (m) => console.log(chalk.gray(m)),
+  header:  (m) => console.log('\n' + chalk.bold.cyan('═══ ' + m + ' ═══')),
+};
+ +

lib/utils/paths.js

+
xcli/lib/utils/paths.js
+
'use strict';
+const fs = require('fs');
+const path = require('path');
+
+function findProjectRoot(start = process.cwd()) {
+  let dir = start;
+  for (let i = 0; i < 10; i++) {
+    const hasAngular = fs.existsSync(path.join(dir, 'angular.json'));
+    const hasModule = fs.existsSync(path.join(dir, 'src/app/app.module.ts'));
+    if (hasAngular && hasModule) return dir;
+    const parent = path.dirname(dir);
+    if (parent === dir) break;
+    dir = parent;
+  }
+  return null;
+}
+
+function findSdkRoot(start = process.cwd()) {
+  const candidates = [
+    'Modules/xApiSDKHolder/projects/x-saherelm-api-sdk',
+    'projects/x-saherelm-api-sdk',
+    'x-saherelm-api-sdk',
+    '../x-saherelm-api-sdk',
+  ];
+  let dir = start;
+  for (let i = 0; i < 10; i++) {
+    for (const c of candidates) {
+      const full = path.join(dir, c);
+      if (fs.existsSync(path.join(full, 'src/public-api.ts'))) return full;
+    }
+    const parent = path.dirname(dir);
+    if (parent === dir) break;
+    dir = parent;
+  }
+  return null;
+}
+
+function loadProjectConfig(root) {
+  const cfgPath = path.join(root, 'xcli.config.js');
+  if (!fs.existsSync(cfgPath)) {
+    return {
+      paths: {
+        app: 'src/app',
+        pages: 'src/app/pages',
+        config: 'src/app/config',
+      },
+      conventions: {
+        pageNamePattern: 'kebab-case',
+        entityNamePattern: 'PascalCase',
+        entityKeyDefault: 'string',
+      },
+    };
+  }
+  try {
+    return require(cfgPath);
+  } catch (e) {
+    return {};
+  }
+}
+
+module.exports = { findProjectRoot, findSdkRoot, loadProjectConfig };
+ +

lib/utils/fs-helper.js

+
xcli/lib/utils/fs-helper.js
+
'use strict';
+const fse = require('fs-extra');
+const path = require('path');
+const Handlebars = require('handlebars');
+
+// helpers
+Handlebars.registerHelper('lower', (s) => s ? String(s).toLowerCase() : '');
+Handlebars.registerHelper('upper', (s) => s ? String(s).toUpperCase() : '');
+Handlebars.registerHelper('camel', (s) => s ? s.charAt(0).toLowerCase() + s.slice(1) : '');
+Handlebars.registerHelper('pascal', (s) => s ? s.charAt(0).toUpperCase() + s.slice(1) : '');
+Handlebars.registerHelper('kebab', (s) => s ? String(s).replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase() : '');
+Handlebars.registerHelper('plural', (s) => s ? s + 's' : '');
+Handlebars.registerHelper('eq', (a, b) => a === b);
+Handlebars.registerHelper('not', (v) => !v);
+Handlebars.registerHelper('json', (v) => JSON.stringify(v, null, 2));
+Handlebars.registerHelper('date', () => new Date().toISOString().slice(0, 10));
+
+async function renderTemplateFile(tplPath, data) {
+  const src = await fse.readFile(tplPath, 'utf8');
+  const tpl = Handlebars.compile(src, { noEscape: true });
+  return tpl(data);
+}
+
+async function writeFromTemplate(tplPath, outPath, data) {
+  const content = await renderTemplateFile(tplPath, data);
+  await fse.ensureDir(path.dirname(outPath));
+  await fse.writeFile(outPath, content, 'utf8');
+  return outPath;
+}
+
+async function renderString(tplString, data) {
+  const tpl = Handlebars.compile(tplString, { noEscape: true });
+  return tpl(data);
+}
+
+module.exports = { renderTemplateFile, writeFromTemplate, renderString };
+ +

lib/utils/ast.js (با ts-morph)

+
xcli/lib/utils/ast.js
+
'use strict';
+const path = require('path');
+const { Project, SyntaxKind } = require('ts-morph');
+const fse = require('fs-extra');
+
+function toPascal(name) {
+  return name.split('-').map(p => p.charAt(0).toUpperCase() + p.slice(1)).join('');
+}
+
+// ─── app-routing.module.ts patch ───
+function patchAppRoutingModule({ root, name, type, route }) {
+  const file = path.join(root, 'src/app/app-routing.module.ts');
+  const project = new Project();
+  const source = project.addSourceFileAtPath(file);
+  const Name = toPascal(name);
+
+  if (type === 'management' || type === 'explorer') {
+    const routes = source.getVariableDeclaration('routes');
+    if (!routes) return;
+    const arr = routes.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression);
+    if (!arr) return;
+
+    const marker = `./pages/${name}`;
+    if (source.getFullText().includes(marker)) return;
+
+    arr.addElement(`{
+    path: '${route}',
+    loadChildren: () => import('./pages/${name}/${name}-page.module').then(
+      (m) => m.${Name}PageModule
+    ),
+  }`);
+  }
+  source.saveSync();
+}
+
+// ─── page.config.ts patch ───
+function patchPageConfig({ root, name, type, route }) {
+  const file = path.join(root, 'src/app/config/page.config.ts');
+  const project = new Project();
+  const source = project.addSourceFileAtPath(file);
+  const Name = toPascal(name);
+  const routeKey = name.replace(/-/g, '');
+
+  // 1) AppRoutes enum
+  const appRoutes = source.getEnum('AppRoutes');
+  if (appRoutes && !appRoutes.getMember(Name)) {
+    appRoutes.addMember({ name: Name, initializer: `'${route}'` });
+  }
+
+  // 2) PageIndex
+  const pageIndex = source.getVariableDeclaration('PageIndex');
+  if (pageIndex) {
+    const init = pageIndex.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
+    if (init && !init.getProperty(Name)) {
+      init.addPropertyAssignment({
+        name: Name,
+        initializer: `{
+    id: \`\${PageName.${Name}}\`,
+    name: \`\${PageName.${Name}}\`,
+    title: AppResourceIDs.${name}_page_title,
+    description: AppResourceIDs.${name}_page_description,
+    baseRoute: \`\${AppRoutes.${Name}}\`,
+    route: ['/', \`\${AppRoutes.${Name}}\`],
+    icon: XIconNames.posts,
+  }`,
+      });
+    }
+  }
+
+  // 3) Pages object
+  const pages = source.getVariableDeclaration('Pages');
+  if (pages) {
+    const init = pages.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
+    if (init && !init.getProperty(Name)) {
+      init.addPropertyAssignment({
+        name: Name,
+        initializer: `PageIndex.${Name}`,
+      });
+    }
+  }
+
+  source.saveSync();
+}
+
+// ─── localization patch ───
+function patchLocalization({ root, key, fa, en }) {
+  const file = path.join(root, 'src/app/config/localization.config.ts');
+  const project = new Project();
+  const source = project.addSourceFileAtPath(file);
+
+  // 1) AppResourceIDs enum
+  const enumDecl = source.getEnum('AppResourceIDs');
+  if (enumDecl && !enumDecl.getMember(key)) {
+    enumDecl.addMember({ name: key, initializer: `'${key}'` });
+  }
+
+  // 2) persian array resource entries
+  const persian = source.getVariableDeclaration('persianResources');
+  if (persian && fa) {
+    const arr = persian.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression);
+    if (arr && !source.getFullText().includes(`id: '${key}'`)) {
+      arr.addElement(`{ id: '${key}', value: '${fa}' }`);
+    }
+  }
+
+  const english = source.getVariableDeclaration('englishResources');
+  if (english && en) {
+    const arr = english.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression);
+    if (arr && !source.getFullText().includes(`id: '${key}'`)) {
+      arr.addElement(`{ id: '${key}', value: '${en}' }`);
+    }
+  }
+
+  source.saveSync();
+}
+
+// ─── x-endpoint patch ───
+function patchEndpoints({ sdkRoot, Name, pluralName }) {
+  const file = path.join(sdkRoot, 'src/lib/typings/x-endpoint.typings.ts');
+  const project = new Project();
+  const source = project.addSourceFileAtPath(file);
+
+  const apiEndPoint = source.getEnum('XApiEndPoint');
+  if (apiEndPoint) {
+    if (!apiEndPoint.getMember(`${Name}Entity`)) {
+      apiEndPoint.addMember({
+        name: `${Name}Entity`,
+        initializer: `'Entities/${pluralName}'`,
+      });
+    }
+    if (!apiEndPoint.getMember(`${Name}Service`)) {
+      apiEndPoint.addMember({
+        name: `${Name}Service`,
+        initializer: `'Services/${pluralName}'`,
+      });
+    }
+  }
+
+  source.saveSync();
+}
+
+// ─── public-api patch ───
+function patchPublicApi({ sdkRoot, Name }) {
+  const file = path.join(sdkRoot, 'src/public-api.ts');
+  const project = new Project();
+  const source = project.addSourceFileAtPath(file);
+  const lower = Name.charAt(0).toLowerCase() + Name.slice(1);
+
+  const exports = [
+    `export * from './lib/${lower}/models/x-${lower}.dto';`,
+    `export * from './lib/${lower}/services/x-${lower}.entity.service';`,
+    `export * from './lib/${lower}/services/x-${lower}.provider.service';`,
+    `export * from './lib/${lower}/services/x-${lower}.entity.push.service';`,
+    `export * from './lib/${lower}/x-${lower}.services';`,
+  ];
+
+  for (const line of exports) {
+    if (!source.getFullText().includes(line)) {
+      source.addStatements('\n' + line);
+    }
+  }
+  source.saveSync();
+}
+
+module.exports = {
+  patchAppRoutingModule,
+  patchPageConfig,
+  patchLocalization,
+  patchEndpoints,
+  patchPublicApi,
+  toPascal,
+};
+ +

lib/utils/shell.js

+
xcli/lib/utils/shell.js
+
'use strict';
+const { execSync } = require('child_process');
+
+function run(cmd, opts = {}) {
+  return execSync(cmd, {
+    stdio: opts.silent ? 'pipe' : 'inherit',
+    cwd: opts.cwd || process.cwd(),
+    encoding: 'utf8',
+    ...opts,
+  });
+}
+
+module.exports = { run };
+ + +

فاز ۳ Commands

+ +

lib/commands/init.js

+
xcli/lib/commands/init.js
+
'use strict';
+
+const { Command } = require('commander');
+const path = require('path');
+const fse = require('fs-extra');
+const ora = require('ora');
+const inquirer = require('inquirer');
+const logger = require('../utils/logger');
+const shell = require('../utils/shell');
+const { generateProject } = require('../generators/project');
+
+module.exports = new Command('init')
+  .description('Create a new xFramework project (Angular 12 + Ionic 6)')
+  .argument('<name>', 'Project name (kebab-case)')
+  .option('-d, --dir <dir>', 'Target directory', process.cwd())
+  .option('--skip-install', 'Skip npm install', false)
+  .option('--base-api <url>', 'Base API URL', 'https://localhost:5001/')
+  .option('--hub-url <url>', 'SignalR hub URL', 'https://localhost:5001/')
+  .option('--dry-run', 'Preview commands without executing', false)
+  .action(async (name, opts) => {
+    if (!/^[a-z][a-z0-9-]*$/.test(name)) {
+      logger.error('Project name must be kebab-case (e.g. my-app)');
+      process.exit(1);
+    }
+
+    const target = path.resolve(opts.dir, name);
+
+    // handle existing dir
+    if (await fse.pathExists(target)) {
+      if (opts.dryRun) {
+        logger.warn(`(dry-run) Would overwrite ${target}`);
+        return;
+      }
+      const { overwrite } = await inquirer.prompt([
+        {
+          type: 'confirm', name: 'overwrite',
+          message: `Directory "${name}" exists. Overwrite?`,
+          default: false,
+        },
+      ]);
+      if (!overwrite) { logger.warn('Aborted.'); return; }
+      await fse.remove(target);
+    }
+
+    // step 1: ng new (Angular 12.0.4)
+    logger.header('Step 1/3: Creating Angular 12 project');
+    const ngCmd = `npx -y @angular/cli@12.0.4 new ${name} --routing --style=scss --skip-git --skip-install --strict=false`;
+    logger.dim('$ ' + ngCmd);
+    if (!opts.dryRun) {
+      const sp = ora('Running ng new...').start();
+      try {
+        shell.run(ngCmd, { cwd: opts.dir });
+        sp.succeed('Angular project created');
+      } catch (e) {
+        sp.fail('ng new failed');
+        throw e;
+      }
+    }
+
+    // step 2: patch for xFramework
+    logger.header('Step 2/3: Patching for xFramework');
+    if (!opts.dryRun) {
+      const sp = ora('Applying xFramework patches...').start();
+      try {
+        await generateProject({ name, target, opts });
+        sp.succeed('xFramework patches applied');
+      } catch (e) {
+        sp.fail('Patch failed: ' + e.message);
+        throw e;
+      }
+    } else {
+      logger.warn(`(dry-run) Would patch ${target}`);
+    }
+
+    // step 3: install
+    if (!opts.skipInstall && !opts.dryRun) {
+      logger.header('Step 3/3: Installing dependencies');
+      const sp = ora('Running npm install (legacy-peer-deps)...').start();
+      try {
+        shell.run('npm install --legacy-peer-deps', { cwd: target });
+        sp.succeed('Dependencies installed');
+      } catch (e) {
+        sp.warn('npm install failed; try manually: cd ' + name + ' && npm install --legacy-peer-deps');
+      }
+    }
+
+    logger.header('✔ Done');
+    logger.info(`Project created at: ${target}`);
+    logger.info('Next steps:');
+    logger.dim(`  cd ${name}`);
+    logger.dim('  npm start');
+    logger.dim('  xcli page:add home');
+    logger.dim('  xcli entity:add Product');
+  });
+ +

lib/commands/page-add.js

+
xcli/lib/commands/page-add.js
+
'use strict';
+
+const { Command } = require('commander');
+const path = require('path');
+const ora = require('ora');
+const logger = require('../utils/logger');
+const { findProjectRoot, loadProjectConfig } = require('../utils/paths');
+const { generatePage } = require('../generators/page');
+
+module.exports = new Command('page:add')
+  .description('Add a new page to the project')
+  .argument('<name>', 'Page name (kebab-case)')
+  .option('-t, --type <type>', 'management | explorer | auth | custom', 'custom')
+  .option('-e, --entity <entity>', 'Associated entity (PascalCase)')
+  .option('--route <route>', 'Custom route (default: name)')
+  .option('--no-nav', 'Do not add to navigation')
+  .option('--dry-run', 'Preview without writing', false)
+  .action(async (name, opts) => {
+    if (!/^[a-z][a-z0-9-]*$/.test(name)) {
+      logger.error('Page name must be kebab-case');
+      process.exit(1);
+    }
+    const root = findProjectRoot();
+    if (!root) {
+      logger.error('Not in an xFramework project (missing angular.json or app.module.ts)');
+      process.exit(1);
+    }
+    const projectConfig = loadProjectConfig(root);
+
+    if (opts.dryRun) {
+      logger.header('Dry-run: changes preview');
+      logger.info(`Will create page "${name}" of type "${opts.type}"`);
+      if (opts.entity) logger.info(`Using entity: ${opts.entity}`);
+      logger.info(`Route: /${opts.route || name}`);
+      logger.info(`Add to navigation: ${opts.nav}`);
+      return;
+    }
+
+    const sp = ora(`Generating page "${name}"...`).start();
+    try {
+      const files = await generatePage({
+        root,
+        name,
+        type: opts.type,
+        entity: opts.entity,
+        route: opts.route || name,
+        addToNav: opts.nav,
+        config: projectConfig,
+      });
+      sp.succeed(`Page "${name}" generated`);
+      logger.header('Files created/modified:');
+      files.forEach((f) => logger.dim('  + ' + path.relative(root, f)));
+      logger.info('');
+      logger.success('Run "npm start" to test the page');
+    } catch (e) {
+      sp.fail('Failed: ' + e.message);
+      throw e;
+    }
+  });
+ +

lib/commands/entity-add.js

+
xcli/lib/commands/entity-add.js
+
'use strict';
+
+const { Command } = require('commander');
+const path = require('path');
+const ora = require('ora');
+const logger = require('../utils/logger');
+const { findSdkRoot } = require('../utils/paths');
+const { generateEntity } = require('../generators/entity');
+
+module.exports = new Command('entity:add')
+  .description('Add a new entity to the API SDK (DTO + services + push + facade)')
+  .argument('<Name>', 'Entity name (PascalCase, e.g. Order)')
+  .option('--key <type>', 'Key type: string | number', 'string')
+  .option('--plural <plural>', 'Plural name (default: Name + s)')
+  .option('--with-push', 'Include SignalR push service', true)
+  .option('--with-provider', 'Include provider service', true)
+  .option('--endpoint <path>', 'API endpoint base path')
+  .option('--dry-run', 'Preview without writing', false)
+  .action(async (Name, opts) => {
+    if (!/^[A-Z][A-Za-z0-9]*$/.test(Name)) {
+      logger.error('Entity name must be PascalCase (e.g. Order, OrderItem)');
+      process.exit(1);
+    }
+    const sdkRoot = findSdkRoot();
+    if (!sdkRoot) {
+      logger.error('Cannot find x-saherelm-api-sdk root');
+      process.exit(1);
+    }
+
+    if (opts.dryRun) {
+      logger.header('Dry-run: entity generation preview');
+      logger.info(`Entity: ${Name}`);
+      logger.info(`Key type: ${opts.key}`);
+      logger.info(`With push: ${opts.withPush}`);
+      logger.info(`With provider: ${opts.withProvider}`);
+      logger.info('Files:');
+      logger.dim(`  src/lib/${Name.toLowerCase()}/models/x-${Name.toLowerCase()}.dto.ts`);
+      logger.dim(`  src/lib/${Name.toLowerCase()}/services/x-${Name.toLowerCase()}.entity.service.ts`);
+      if (opts.withProvider) logger.dim(`  ...provider service`);
+      if (opts.withPush) logger.dim(`  ...push service`);
+      logger.dim(`  src/lib/${Name.toLowerCase()}/x-${Name.toLowerCase()}.services.ts`);
+      return;
+    }
+
+    const sp = ora(`Generating entity "${Name}"...`).start();
+    try {
+      const files = await generateEntity({
+        sdkRoot,
+        Name,
+        keyType: opts.key,
+        pluralName: opts.plural || (Name + 's'),
+        withPush: opts.withPush,
+        withProvider: opts.withProvider,
+        endpoint: opts.endpoint,
+      });
+      sp.succeed(`Entity "${Name}" generated`);
+      logger.header('Files created/modified:');
+      files.forEach((f) => logger.dim('  + ' + path.relative(sdkRoot, f)));
+    } catch (e) {
+      sp.fail('Failed: ' + e.message);
+      throw e;
+    }
+  });
+ +

lib/commands/string-add.js

+
xcli/lib/commands/string-add.js
+
'use strict';
+
+const { Command } = require('commander');
+const ora = require('ora');
+const logger = require('../utils/logger');
+const { findProjectRoot } = require('../utils/paths');
+const { addStringKey } = require('../generators/string');
+
+module.exports = new Command('string:add')
+  .description('Add a localization key to project languages')
+  .argument('<key>', 'Resource key (snake_case)')
+  .option('--fa <text>', 'Persian translation')
+  .option('--en <text>', 'English translation')
+  .option('--dry-run', 'Preview without writing', false)
+  .action(async (key, opts) => {
+    if (!/^[a-z][a-z0-9_]*$/.test(key)) {
+      logger.error('Key must be snake_case (e.g. orders_title)');
+      process.exit(1);
+    }
+    if (!opts.fa && !opts.en) {
+      logger.error('Provide at least --fa or --en');
+      process.exit(1);
+    }
+    const root = findProjectRoot();
+    if (!root) { logger.error('Not in xFramework project'); process.exit(1); }
+
+    if (opts.dryRun) {
+      logger.header('Dry-run: string add preview');
+      logger.info(`Key: ${key}`);
+      if (opts.fa) logger.info(`FA: ${opts.fa}`);
+      if (opts.en) logger.info(`EN: ${opts.en}`);
+      return;
+    }
+
+    const sp = ora(`Adding localization key "${key}"...`).start();
+    try {
+      await addStringKey({ root, key, fa: opts.fa, en: opts.en });
+      sp.succeed(`Key "${key}" added`);
+    } catch (e) {
+      sp.fail('Failed: ' + e.message);
+      throw e;
+    }
+  });
+ +

lib/commands/doctor.js

+
xcli/lib/commands/doctor.js
+
'use strict';
+
+const { Command } = require('commander');
+const fs = require('fs');
+const path = require('path');
+const chalk = require('chalk');
+const logger = require('../utils/logger');
+const { findProjectRoot } = require('../utils/paths');
+
+module.exports = new Command('doctor')
+  .description('Check project health')
+  .action(async () => {
+    const root = findProjectRoot();
+    if (!root) {
+      logger.error('Not in an xFramework project');
+      process.exit(1);
+    }
+
+    const checks = [];
+    const add = (name, ok, fix) => checks.push({ name, ok, fix });
+
+    // package.json
+    let pkg = {};
+    try { pkg = require(path.join(root, 'package.json')); } catch {}
+    add('package.json exists', !!pkg.name, 'Run xcli init');
+
+    // Angular + Ionic
+    add('@angular/core installed', !!pkg.dependencies?.['@angular/core'], 'npm i @angular/core@~12.0.0');
+    add('@ionic/angular installed', !!pkg.dependencies?.['@ionic/angular'], 'npm i @ionic/angular@^6.0.0');
+
+    // x-framework
+    ['x-framework-core', 'x-framework-services', 'x-framework-components',
+     'x-framework-identity-sdk', 'x-framework-push-service', 'x-saherelm-api-sdk']
+      .forEach(lib => {
+        add(
+          `${lib} installed`,
+          !!pkg.dependencies?.[lib] || !!pkg.devDependencies?.[lib],
+          `npm i ${lib}`
+        );
+      });
+
+    // key files
+    [
+      'src/app/app.module.ts',
+      'src/app/app-routing.module.ts',
+      'src/app/config/x.config.ts',
+      'src/app/config/x-api.config.ts',
+      'src/app/config/app.config.ts',
+      'src/app/config/page.config.ts',
+      'src/app/config/localization.config.ts',
+      'src/app/shared/shared.module.ts',
+      'src/environments/environment.ts',
+      'src/theme/variables.scss',
+      'src/theme/theme.scss',
+      'ionic.config.json',
+      'capacitor.config.json',
+    ].forEach(f => add(`${f} exists`, fs.existsSync(path.join(root, f)), 'Re-init project'));
+
+    // report
+    logger.header('Project Health Check');
+    let pass = 0, fail = 0;
+    checks.forEach((c) => {
+      if (c.ok) { logger.success(c.name); pass++; }
+      else {
+        logger.error(c.name + '  →  ' + (c.fix || ''));
+        fail++;
+      }
+    });
+    logger.info('');
+    console.log(
+      chalk.bold('Summary: ') +
+      chalk.green(`${pass} passed`) +
+      ', ' +
+      (fail > 0 ? chalk.red(`${fail} failed`) : chalk.gray('0 failed'))
+    );
+    process.exit(fail > 0 ? 1 : 0);
+  });
+ +

lib/commands/page-remove.js (خلاصه)

+
xcli/lib/commands/page-remove.js
+
'use strict';
+
+const { Command } = require('commander');
+const path = require('path');
+const fse = require('fs-extra');
+const inquirer = require('inquirer');
+const ora = require('ora');
+const logger = require('../utils/logger');
+const { findProjectRoot } = require('../utils/paths');
+const ast = require('../utils/ast');
+
+module.exports = new Command('page:remove')
+  .description('Remove an existing page and clean all references')
+  .argument('<name>', 'Page name (kebab-case)')
+  .option('--force', 'Skip confirmation', false)
+  .action(async (name, opts) => {
+    const root = findProjectRoot();
+    if (!root) { logger.error('Not in project'); process.exit(1); }
+
+    const pageDir = path.join(root, 'src/app/pages', name);
+    if (!(await fse.pathExists(pageDir))) {
+      logger.error(`Page "${name}" not found at ${pageDir}`);
+      process.exit(1);
+    }
+
+    if (!opts.force) {
+      const { confirm } = await inquirer.prompt([
+        { type: 'confirm', name: 'confirm', message: `Delete page "${name}" and clean all references?`, default: false },
+      ]);
+      if (!confirm) { logger.warn('Aborted'); return; }
+    }
+
+    const
+
+
+
+
+راهنمای جامع ساخت xCLI برای xFramework
+
+
+
+
+
+
+
+
📘 مستندات فنی و عملیاتی | نسخه ۱.۰
+

راهنمای جامع ساخت xCLI
ابزار تولید و مدیریت پروژه‌های xFramework

+

+ مستندی گام‌به‌گام برای طراحی و پیاده‌سازی ابزار خط فرمان (CLI) به‌منظور ساخت، تولید و مدیریت + برنامه‌های کاربردی مبتنی بر xFramework با الگوگیری کامل از پروژه مرجع xClient. +

+
+ 🅰️ @angular/cli@12.0.4 + ⚡ @ionic/cli@6.6.0 + 🟢 Node v14.17.3 + 📦 xFramework Workspace +
+
+
+ +
+ + + + + +
+ + +
+

#1. معرفی پروژه و ضرورت xCLI

+ +

1.1. xFramework چیست؟

+

+ xFramework مجموعه‌ای از کتابخانه‌های ماژولار انگولار است که برای ساخت اپلیکیشن‌های + سازمانی (Enterprise) روی پشته‌ی Angular + Ionic + Capacitor/Cordova توسعه یافته است. + این چارچوب در قالب چند بسته (Package) مستقل ارائه می‌شود که هر کدام یک لایه از نیازهای نرم‌افزاری را پوشش می‌دهند: +

+ +
+
+
🧩
+

x-framework-core

+

لایه پایه شامل Utilityها، Enumهای سراسری، Type Guardها، ساختار Exceptionها و ابزارهای عمومی.

+
+
+
🛠️
+

x-framework-services

+

سرویس‌های سراسری مثل XManagerService، TaskManager، SecureStorage، Localization و ThemeManager.

+
+
+
🎨
+

x-framework-components

+

مجموعه‌ی بزرگی از کامپوننت‌های UI: XCard، XForm، XList، XTabs، XChart، XDataPager، XIDE و...

+
+
+
🔐
+

x-framework-identity-sdk

+

SDK احراز هویت، مدیریت توکن، Guardها (AuthGuard)، پروفایل کاربر و سرویس‌های حساب کاربری.

+
+
+
🚀
+

x-framework-push-service

+

مدیریت SignalR Push، سوکت‌های بلادرنگ، WebRTC و زیرساخت ارتباطی پیام‌رسانی.

+
+
+
🗂️
+

xApiSDKHolder

+

تولید SDK از API (به‌صورت دستی یا Codegen) برای موجودیت‌های دامنه مثل Tags، Files، Webinars و Strings.

+
+
+ +

1.2. پروژه xClient چه می‌کند؟

+

+ xClient در واقع یک اپلیکیشن مرجع (Reference Application) است که تمام قابلیت‌های xFramework + را در قالب یک محصول واقعی (سامانه‌ی آموزشی/محتوایی «ساحر علم») پیاده‌سازی می‌کند. مهم‌ترین لایه‌های این پروژه: +

+
    +
  • Workspace چند ماژولی: پوشه‌ی Modules/ شامل xApiSDKHolder، xFrameworkComponentsHolder و دیگر Holderهاست که به‌صورت کتابخانه‌های قابل انتشار نگهداری می‌شوند.
  • +
  • پروژه اصلی کلاینت: در پوشه‌ی xClient/ که خود از ساختار استاندارد Angular CLI + Ionic استفاده می‌کند.
  • +
  • لایه View: پوشه‌ی src/app/views مجموعه‌ای از V* کامپوننت‌ها (VPage، VDto، VFile، VTag، VWebinar و ...) که به کامپوننت‌های xFramework وصل می‌شوند.
  • +
  • لایه Page: پوشه‌ی src/app/pages شامل صفحات با ساختار مشترک (Home، Landing، Files، Tags، Webinars، Account و ...).
  • +
  • پیکربندی متمرکز: src/app/config/app.config.ts و x.config.ts به‌عنوان Single Source of Truth برای کل تنظیمات.
  • +
  • Environmentها: src/environments با دو فایل environment.ts و environment.prod.ts.
  • +
  • Pluginهای Cordova: در پوشه‌ی plugins/ با type definitionهای TypeScript برای Device، Splashscreen و StatusBar.
  • +
+ +

1.3. چرا به xCLI نیاز داریم؟

+

+ هر بار که می‌خواهیم یک پروژه‌ی جدید بر پایه‌ی xFramework بسازیم، باید ده‌ها فایل پیکربندی، چندین ماژول، ساختار View/Page، + Environment، Theme و Plugin را به‌صورت دستی ایجاد کنیم. این کار: +

+
    +
  • زمان‌بر و مستعد خطا است.
  • +
  • باعث ناسازگاری بین پروژه‌ها می‌شود (عدم رعایت Convention).
  • +
  • به‌روزرسانی نسخه‌ی فریم‌ورک را در چندین پروژه دشوار می‌کند.
  • +
  • امکان ارائه‌ی «تجربه‌ی توسعه‌دهنده» یکپارچه و مستند را نمی‌دهد.
  • +
+ +
+
💡
+
+ هدف xCLI: با یک دستور مثل xcli new my-app، پروژه‌ای کاملاً آماده با همان ساختار xClient تولید شود؛ + و با دستوراتی مانند xcli g page یا xcli g view بتوان اجزای جدید را به شکل استاندارد اضافه کرد. +
+
+
+ + +
+

#2. پیش‌نیازها و محیط اجرا

+ +

+ با توجه به محدودیت‌های اعلام‌شده، کل فرآیند باید بر روی نسخه‌های زیر پایدار بماند. این نسخه‌ها «قفل‌شده» در نظر گرفته می‌شوند + و xCLI باید در همان بازه کار کند. +

+ + + + + + + + + + + + + +
ابزارنسخهنقش
Node.jsv14.17.3Runtime اصلی CLI و Angular
npmهمراه با Node 14 → 6.xمدیریت پکیج‌ها
@angular/cli12.0.4اسکلت‌بندی و Build
@ionic/cli6.6.0مدیریت پروژه‌های Ionic و Cordova
TypeScript~4.2.xهمراه Angular 12
RxJS~6.6.xهمراه Angular 12
+ +

2.1. نصب ابزارها

+
# نصب نسخه‌های دقیق و قفل‌شده (توصیه می‌شود)
+npm i -g @angular/cli@12.0.4
+npm i -g @ionic/cli@6.6.0
+
+# بررسی نسخه‌ها
+node -v      # v14.17.3
+ng version   # Angular CLI: 12.0.4
+ionic -v     # 6.6.0
+ +
+
⚠️
+
+ توجه: Angular 12 بر روی Node 14 و 16 تست شده است. استفاده از Node 18+ باعث خطاهای + ERR_OSSL_EVP_UNSUPPORTED در Webpack 5 می‌شود. بنابراین پیشنهاد می‌شود از nvm یا nvs + برای مدیریت نسخه‌ی Node استفاده شود. +
+
+ +

2.2. ساختار پوشه‌ی توسعه

+

ساختار پیشنهادی برای مخزن توسعه‌ی xCLI به شکل زیر است:

+ +
xFrameworkWorkspace/
+├── xCli/                           # ← پروژه‌ی CLI (محل ساخت ابزار)
+│   ├── package.json
+│   ├── src/
+│   │   ├── index.ts                # نقطه‌ی ورود CLI
+│   │   ├── commands/               # دستورات
+│   │   ├── generators/             # تولیدکننده‌ها
+│   │   ├── templates/              # قالب‌ها
+│   │   ├── lib/                    # ابزارهای مشترک
+│   │   └── config/                 # پیکربندی CLI
+│   └── bin/
+│       └── xcli.js                 # شیم اجرایی (Shebang)
+│
+├── xClient/                        # ← پروژه‌ی مرجع
+│   ├── plugins/
+│   ├── src/
+│   │   ├── app/
+│   │   ├── environments/
+│   │   ├── theme/
+│   │   └── ...
+│   └── ...
+│
+└── Modules/                        # ← Holderهای کتابخانه‌ای
+    ├── xApiSDKHolder/
+    └── xFrameworkComponentsHolder/
+
+ + +
+

#3. معماری پیشنهادی xCLI

+ +

+ xCLI باید از الگوی Command + Generator + Template پیروی کند. این معماری مشابه Angular CLI، Nest CLI، + یا Nx است، ولی سبک‌تر و متناسب با نیاز xFramework. +

+ +
+
+
⌨️
+

لایه Commands

+

پارس دستورات ورودی، مدیریت Flagها، نمایش Help و اجرای Generator مناسب.

+
+
+
⚙️
+

لایه Generators

+

منطق تولید کد: ساخت فایل، جایگزینی Placeholder، Merge با فایل‌های موجود.

+
+
+
📁
+

لایه Templates

+

قالب‌های متنی با Placeholderهایی مانند __NAME__، __CLASS__، __PATH__.

+
+
+
🧠
+

لایه Schematics

+

اختیاری: استفاده از Schematics برای اجرای دقیق‌تر تغییرات روی AST فایل‌های TypeScript.

+
+
+ +

3.1. جریان اجرا

+
+
+

ورود کاربر

+

xcli g page --name=files --module=files در ترمینال وارد می‌شود.

+
+
+

پارس دستور

+

لایه Commands با commander یا yargs دستور و Flagها را تجزیه می‌کند.

+
+
+

اعتبارسنجی

+

بررسی وجود پروژه، نام معتبر، عدم تکرار، تطابق با Convention.

+
+
+

اجرای Generator

+

Generator با استفاده از Template مناسب و جایگزینی Placeholderها، فایل‌ها را ایجاد می‌کند.

+
+
+

Merge و ثبت

+

ثبت فایل‌های جدید در app-routing.module.ts، page.config.ts یا app.config.ts.

+
+
+

گزارش

+

نمایش فایل‌های ایجاد/تغییرداده‌شده و دستور بعدی برای اجرا.

+
+
+ +

3.2. وابستگی‌های xCLI

+ + + + + + + + + + + + +
پکیجهدف
commanderپارس زیردستور و Flagها
inquirerپرسش تعاملی از کاربر (Interactive prompt)
chalkرنگ‌دهی به خروجی ترمینال
oraنمایش Spinner حین اجرا
fs-extraعملیات فایل (copy، ensureDir، writeJson)
handlebarsرندر قالب‌های متنی
execaاجرای دستورات Shell (npm, ng, ionic)
ts-morph (اختیاری)ویرایش AST فایل‌های TypeScript
+ +
+
📌
+
+ برای شروع سبک، فقط از commander، inquirer، chalk، ora، + fs-extra و handlebars استفاده کنید. تغییرات AST را به کمک ts-morph در فاز دوم اضافه نمایید. +
+
+
+ + +
+

#4. ساختار پروژه xClient (مرجع)

+ +

+ برای این‌که xCLI بتواند پروژه‌ی همسان xClient تولید کند، باید ساختار آن را دقیقاً بشناسیم. در ادامه، شاخه‌های مهم با + توضیح جایگاه و نقش آورده شده‌اند. +

+ +

4.1. نمای کلی

+
+xClient/ +├── plugins/ +│ ├── cordova-plugin-device/ +│ │ └── types/index.d.ts # interface Device +│ ├── cordova-plugin-splashscreen/ +│ │ ├── src/wp/ +│ │ │ ├── SplashScreen.cs +│ │ │ └── ResolutionHelper.cs +│ │ └── types/index.d.ts +│ └── cordova-plugin-statusbar/ +│ ├── src/wp/StatusBar.cs +│ └── types/index.d.ts +│ +├── src/ +│ ├── index.html +│ ├── main.ts +│ ├── polyfills.ts +│ ├── typings.d.ts +│ ├── global.d.ts +│ │ +│ ├── environments/ +│ │ ├── environment.ts +│ │ └── environment.prod.ts +│ │ +│ ├── theme/ +│ │ └── theme.scss # Design Tokens + Ionic + XFramework +│ │ +│ └── app/ +│ ├── config/ +│ │ ├── app.config.ts # xSharedConfig، XCONFIG +│ │ ├── x.config.ts # InjectionToken +│ │ ├── x-api.config.ts # XApiConfiguration +│ │ ├── localization.config.ts # AppResourceIDs +│ │ ├── page.config.ts # PageIndex، Pages، NavItems +│ │ └── audio.config.ts +│ │ +│ ├── pages/ +│ │ ├── home/ +│ │ ├── landing/ +│ │ ├── startup/ +│ │ ├── account/ +│ │ ├── files/ +│ │ ├── tags/ +│ │ ├── webinars/ +│ │ ├── error/ +│ │ └── not-authorized/ +│ │ +│ ├── views/ +│ │ ├── v-page/ +│ │ ├── v-page-presenter/ +│ │ ├── v-dto/ +│ │ ├── v-query-presenter/ +│ │ ├── v-paginator/ +│ │ ├── v-file/ +│ │ ├── v-media/ +│ │ ├── v-tag/ +│ │ ├── v-tags-presenter/ +│ │ ├── v-files-presenter/ +│ │ ├── v-webinar/ +│ │ ├── v-webinar-view/ +│ │ ├── v-webinar-connect/ +│ │ ├── v-person/ +│ │ ├── v-user/ +│ │ ├── v-friendship/ +│ │ ├── v-login/ +│ │ ├── v-register/ +│ │ ├── v-profile/ +│ │ ├── v-avatar/ +│ │ ├── v-video/ +│ │ ├── v-error/ +│ │ ├── v-lazy-view/ +│ │ ├── v-string/ +│ │ ├── v-resource/ +│ │ ├── v-locale/ +│ │ ├── v-reference/ +│ │ ├── v-tag-input/ +│ │ ├── v-file-input/ +│ │ ├── v-icons-presenter/ +│ │ ├── classes/ +│ │ │ └── v-base.component.ts # VBaseComponent +│ │ ├── constants/ +│ │ │ ├── fab.defaults.ts +│ │ │ ├── button.defaults.ts +│ │ │ ├── slide.options.defaults.ts +│ │ │ └── actionbar.defaults.ts +│ │ ├── directives/ +│ │ ├── typings/ +│ │ ├── tools/ +│ │ └── views.module.ts +│ │ +│ ├── shared/ +│ │ ├── services/ +│ │ │ ├── shared.service.ts # SharedService +│ │ │ ├── x-electron.service.ts +│ │ │ ├── x-media-devices.service.ts +│ │ │ ├── x-scrolling-provider.service.ts +│ │ │ └── x-content-share-service.ts +│ │ ├── typings/ +│ │ ├── shared.module.ts +│ │ └── public-api.ts +│ │ +│ ├── app-routing.module.ts +│ ├── app.component.ts +│ ├── app.component.html +│ ├── app.component.scss +│ └── app.module.ts +│ +└── angular.json / package.json / tsconfig.json +
+ +

4.2. نکات کلیدی ساختاری

+
    +
  • + الگوی Base Component در Views: تمام کامپوننت‌های View از VBaseComponent یا + VBaseDtoComponent ارث می‌برند. این باعث یکپارچگی مدیریت Task، Error و Loading می‌شود. +
  • +
  • + الگوی Page / Provider: صفحات پیچیده (مثل Files، Tags، Webinars) از یک BaseProviderPage + استفاده می‌کنند که منطق Query، Add، Update، Delete و Push را از پیش پیاده‌سازی کرده است. +
  • +
  • + الگوی Dto: کامپوننت v-dto به‌عنوان Presenter عمومی برای هر Dto عمل می‌کند + و با VModelFieldDescriptorها فیلدها را رندر می‌کند. +
  • +
  • + مرکز پیکربندی: تمام تنظیمات در environment.configurations جمع شده و از طریق + XCONFIG (که از app.config.ts می‌آید) در سراسر برنامه در دسترس است. +
  • +
  • + پوشه‌ی Plugins: تعریف‌های TypeScript پلاگین‌های Cordova برای Device، Splashscreen و StatusBar + به‌صورت محلی در پروژه نگهداری می‌شود تا از پکیج‌های @types مستقل باشد. +
  • +
+
+ + +
+

#5. پیاده‌سازی گام‌به‌گام xCLI

+ +

در این بخش، از صفر تا صد ابزار xCLI ساخته می‌شود. هر گام با دستور، فایل و قطعه‌کد همراه است.

+ +

گام ۱: ساخت پوشه و مقداردهی اولیه

+
mkdir xCli && cd xCli
+npm init -y
+npm i commander@9 inquirer@8 chalk@4 ora@5 fs-extra@10 handlebars@4 execa@5
+npm i -D typescript@4.2 @types/node@14 @types/fs-extra@9 @types/inquirer@7
+ +
+
🎯
+
+ چرا این نسخه‌ها؟ commander@9، inquirer@8، chalk@4 و ora@5 + با Node 14 سازگارند. نسخه‌های جدیدتر (مثلاً inquirer@9 یا chalk@5) به ESM منتقل شده‌اند و + با CommonJS پروژه‌های Angular 12 تضاد ایجاد می‌کنند. +
+
+ +

گام ۲: تنظیم package.json و tsconfig

+
{
+  "name": "@xframework/xcli",
+  "version": "1.0.0",
+  "description": "CLI for generating and managing xFramework applications",
+  "main": "dist/index.js",
+  "bin": {
+    "xcli": "bin/xcli.js"
+  },
+  "scripts": {
+    "build": "tsc -p tsconfig.json",
+    "dev": "ts-node src/index.ts",
+    "link": "npm run build && npm link"
+  },
+  "files": [
+    "bin",
+    "dist",
+    "templates"
+  ],
+  "engines": {
+    "node": ">=14.17.3 <17"
+  }
+}
+ +
{
+  "compilerOptions": {
+    "target": "ES2019",
+    "module": "CommonJS",
+    "moduleResolution": "node",
+    "outDir": "dist",
+    "rootDir": "src",
+    "strict": true,
+    "esModuleInterop": true,
+    "skipLibCheck": true,
+    "resolveJsonModule": true,
+    "declaration": true,
+    "sourceMap": true
+  },
+  "include": ["src/**/*.ts"]
+}
+ +

گام ۳: Shم اجرایی (bin)

+

فایل bin/xcli.js در واقع یک Loader است که نسخه‌ی کامپایل‌شده را اجرا می‌کند:

+
#!/usr/bin/env node
+// bin/xcli.js
+require('../dist/index.js');
+ +
+
🔐
+
+ روی Linux/macOS اجرای chmod +x bin/xcli.js لازم است. npm هنگام npm link این کار را خودکار انجام می‌دهد. +
+
+ +

گام ۴: نقطه‌ی ورود CLI

+

فایل src/index.ts با commander ساخته می‌شود:

+
// src/index.ts
+import { Command } from 'commander';
+import { registerNewCommand } from './commands/new';
+import { registerGenerateCommand } from './commands/generate';
+import { registerAddCommand } from './commands/add';
+import { registerConfigCommand } from './commands/config';
+import { registerBuildCommand } from './commands/build';
+import { registerDoctorCommand } from './commands/doctor';
+import chalk from 'chalk';
+import { readFileSync } from 'fs';
+import { join } from 'path';
+
+const pkg = JSON.parse(
+  readFileSync(join(__dirname, '..', 'package.json'), 'utf-8')
+);
+
+const program = new Command();
+
+program
+  .name('xcli')
+  .description('CLI for xFramework application scaffolding & management')
+  .version(pkg.version, '-v, --version', 'output the current version');
+
+// ثبت زیردستورات
+registerNewCommand(program);
+registerGenerateCommand(program);
+registerAddCommand(program);
+registerConfigCommand(program);
+registerBuildCommand(program);
+registerDoctorCommand(program);
+
+// دستور پیش‌فرض
+program
+  .command('help [command]')
+  .description('display help for xcli or a specific command')
+  .action((cmd) => {
+    if (cmd) {
+      const sub = program.commands.find((c) => c.name() === cmd);
+      if (sub) {
+        sub.help();
+      } else {
+        console.log(chalk.red(`Unknown command: ${cmd}`));
+        process.exit(1);
+      }
+    } else {
+      program.help();
+    }
+  });
+
+// مدیریت خطاها
+process.on('unhandledRejection', (err: any) => {
+  console.error(chalk.red('\n💥 Unexpected error:'), err?.message || err);
+  process.exit(1);
+});
+
+// پارس آرگومان‌ها
+program.parseAsync(process.argv).catch((err) => {
+  console.error(chalk.red(err.message));
+  process.exit(1);
+});
+ +

گام ۵: کتابخانه‌ی ابزارهای مشترک

+

یک فایل src/lib/logger.ts برای رنگ‌دهی یکنواخت:

+
// src/lib/logger.ts
+import chalk from 'chalk';
+
+export const logger = {
+  info: (msg: string) => console.log(chalk.cyan('ℹ '), msg),
+  success: (msg: string) => console.log(chalk.green('✔ '), msg),
+  warn: (msg: string) => console.log(chalk.yellow('⚠ '), msg),
+  error: (msg: string) => console.log(chalk.red('✖ '), msg),
+  title: (msg: string) =>
+    console.log('\n' + chalk.bold.blue(`◆ ${msg}`) + '\n'),
+  file: (path: string) => console.log(chalk.gray('  CREATE'), chalk.white(path)),
+  update: (path: string) =>
+    console.log(chalk.gray('  UPDATE'), chalk.yellow(path)),
+};
+ +

فایل src/lib/fs-utils.ts برای مدیریت فایل‌ها:

+
// src/lib/fs-utils.ts
+import * as fs from 'fs-extra';
+import { join, dirname } from 'path';
+import Handlebars from 'handlebars';
+
+export async function renderTemplate(
+  templateSource: string,
+  data: Record
+): Promise {
+  const template = Handlebars.compile(templateSource, { noEscape: true });
+  return template(data);
+}
+
+export async function writeRendered(
+  targetPath: string,
+  content: string,
+  overwrite = false
+) {
+  if (!overwrite && (await fs.pathExists(targetPath))) {
+    throw new Error(`File already exists: ${targetPath}`);
+  }
+  await fs.ensureDir(dirname(targetPath));
+  await fs.writeFile(targetPath, content, 'utf-8');
+}
+
+export async function copyTemplate(
+  templatesRoot: string,
+  relativePath: string,
+  targetPath: string,
+  data: Record,
+  extensionsToRender = ['.ts', '.html', '.scss', '.json', '.md', '.xml', '.js']
+) {
+  const source = await fs.readFile(join(templatesRoot, relativePath), 'utf-8');
+  const ext = '.' + relativePath.split('.').pop();
+  const content = extensionsToRender.includes(ext)
+    ? await renderTemplate(source, data)
+    : source;
+  await writeRendered(targetPath, content);
+}
+ +

گام ۶: دستور xcli new

+

این دستور پروژه‌ی جدید xFramework را از صفر ایجاد می‌کند.

+ +
+
+

الف) تعریف دستور

+
// src/commands/new.ts
+import { Command } from 'commander';
+import inquirer from 'inquirer';
+import ora from 'ora';
+import { generateNewProject } from '../generators/new-project';
+import { logger } from '../lib/logger';
+
+export function registerNewCommand(program: Command) {
+  program
+    .command('new [name]')
+    .description('Create a new xFramework application')
+    .option('-d, --directory <path>', 'Target directory')
+    .option('--skip-install', 'Skip npm install')
+    .option('--template <type>', 'Project template', 'default')
+    .action(async (name, options) => {
+      logger.title('Creating xFramework project');
+
+      // پرسش تعاملی اگر نام داده نشده باشد
+      if (!name) {
+        const ans = await inquirer.prompt([
+          {
+            type: 'input',
+            name: 'name',
+            message: 'Project name:',
+            default: 'my-x-app',
+            validate: (v) =>
+              /^[a-z][a-z0-9-]*$/.test(v) ||
+              'lowercase letters, numbers, dash only',
+          },
+        ]);
+        name = ans.name;
+      }
+
+      const spinner = ora('Scaffolding project...').start();
+      try {
+        await generateNewProject({
+          name,
+          directory: options.directory || `./${name}`,
+          template: options.template,
+          skipInstall: options.skipInstall,
+          onProgress: (msg) => (spinner.text = msg),
+        });
+        spinner.succeed('Project created successfully');
+        logger.info(`cd ${name}`);
+        logger.info('npm run start:dev');
+      } catch (err: any) {
+        spinner.fail(err.message);
+        process.exit(1);
+      }
+    });
+}
+
+
+

ب) منطق تولید پروژه

+
// src/generators/new-project.ts
+import { execa } from 'execa';
+import * as fs from 'fs-extra';
+import { join } from 'path';
+import { logger } from '../lib/logger';
+import { copyTemplate } from '../lib/fs-utils';
+
+export interface NewProjectOptions {
+  name: string;
+  directory: string;
+  template: string;
+  skipInstall?: boolean;
+  onProgress?: (msg: string) => void;
+}
+
+export async function generateNewProject(opts: NewProjectOptions) {
+  const { name, directory, onProgress, skipInstall } = opts;
+  const templatesRoot = join(__dirname, '..', '..', 'templates', opts.template);
+
+  // 1. ساخت پوشه
+  await fs.ensureDir(directory);
+  onProgress?.('Creating directory structure...');
+
+  // 2. تولید با Angular CLI
+  onProgress?.('Running ng new...');
+  await execa(
+    'npx',
+    [
+      '@angular/cli@12.0.4', 'new', name,
+      '--routing', '--style=scss', '--skip-git', '--skip-install',
+      '--skip-tests', '--package-manager=npm',
+    ],
+    { cwd: directory, stdio: 'inherit' }
+  );
+
+  const projectRoot = join(directory, name);
+
+  // 3. افزودن Ionic
+  onProgress?.('Running ionic init...');
+  await execa('npx', ['@ionic/cli@6.6.0', 'init', 'x-framework-app', 'angular', '--type=angular-standalone'], {
+    cwd: projectRoot,
+    stdio: 'inherit',
+  });
+
+  // 4. کپی قالب‌های سفارشی (app, views, config, plugins...)
+  onProgress?.('Copying xFramework templates...');
+  await copyTemplateTree(templatesRoot, projectRoot, {
+    __APP_NAME__: name,
+    __APP_INSTANCE__: name + 'Client',
+  });
+
+  // 5. نصب پکیج‌های xFramework
+  onProgress?.('Installing dependencies...');
+  const pkgPath = join(projectRoot, 'package.json');
+  const pkg = await fs.readJson(pkgPath);
+  pkg.dependencies = {
+    ...pkg.dependencies,
+    'x-framework-core': '^1.0.0',
+    'x-framework-services': '^1.0.0',
+    'x-framework-components': '^1.0.0',
+    'x-framework-identity-sdk': '^1.0.0',
+    'x-framework-push-service': '^1.0.0',
+    'x-saherelm-api-sdk': '^1.0.0',
+  };
+  await fs.writeJson(pkgPath, pkg, { spaces: 2 });
+
+  // 6. نصب نهایی
+  if (!skipInstall) {
+    onProgress?.('npm install...');
+    await execa('npm', ['install', '--legacy-peer-deps'], {
+      cwd: projectRoot,
+      stdio: 'inherit',
+    });
+  }
+
+  logger.success(`Project '${name}' generated at ${projectRoot}`);
+}
+
+async function copyTemplateTree(
+  src: string,
+  dest: string,
+  context: Record<string, any>
+) {
+  const entries = await fs.readdir(src, { withFileTypes: true });
+  for (const entry of entries) {
+    const srcPath = join(src, entry.name);
+    const destPath = join(dest, entry.name);
+    if (entry.isDirectory()) {
+      await copyTemplateTree(srcPath, destPath, context);
+    } else {
+      await copyTemplate(src, entry.name, destPath, context);
+    }
+  }
+}
+
+
+ +

گام ۷: دستور xcli g (Generate)

+

ساخت زیردستور برای تولید اجزای مختلف:

+
// src/commands/generate.ts
+import { Command } from 'commander';
+import { generatePage } from '../generators/page';
+import { generateView } from '../generators/view';
+import { generateService } from '../generators/service';
+import { generateModule } from '../generators/module';
+import { generateProviderPage } from '../generators/provider-page';
+import { logger } from '../lib/logger';
+
+export function registerGenerateCommand(program: Command) {
+  const g = program
+    .command('generate')
+    .alias('g')
+    .description('Generate xFramework artifacts');
+
+  // xcli g page
+  g.command('page <name>')
+    .description('Generate a Page (src/app/pages/<name>)')
+    .option('-m, --module <name>', 'Parent module', 'app')
+    .option('--lazy', 'Create lazy-loaded module')
+    .option('--provider', 'Extend VQueryPresenterBasePage')
+    .action(async (name, opts) => {
+      logger.title(`Generating page: ${name}`);
+      await generatePage({ name, ...opts });
+    });
+
+  // xcli g view
+  g.command('view <name>')
+    .description('Generate a View component (src/app/views/v-<name>)')
+    .option('--dto', 'Extend VBaseDtoComponent')
+    .option('--page', 'Extend VPageComponent')
+    .option('--plain', 'Plain Angular component')
+    .action(async (name, opts) => {
+      logger.title(`Generating view: ${name}`);
+      await generateView({ name, ...opts });
+    });
+
+  // xcli g service
+  g.command('service <name>')
+    .description('Generate a shared service')
+    .option('--singleton', 'providedIn: root', true)
+    .action(async (name, opts) => {
+      logger.title(`Generating service: ${name}`);
+      await generateService({ name, ...opts });
+    });
+
+  // xcli g module
+  g.command('module <name>')
+    .description('Generate an Angular module with routing')
+    .option('--lazy', 'Lazy-loaded module')
+    .action(async (name, opts) => {
+      logger.title(`Generating module: ${name}`);
+      await generateModule({ name, ...opts });
+    });
+
+  // xcli g provider-page
+  g.command('provider-page <name>')
+    .description('Generate a ProviderPage (Explorer/Management)')
+    .option('--kind <kind>', 'explorer | management', 'explorer')
+    .action(async (name, opts) => {
+      logger.title(`Generating provider page: ${name}`);
+      await generateProviderPage({ name, ...opts });
+    });
+
+  // اگر هیچ زیردستوری داده نشد، راهنما نشان بده
+  g.action(() => g.help());
+}
+ +

گام ۸: Generator برای Page

+
// src/generators/page.ts
+import { join } from 'path';
+import * as fs from 'fs-extra';
+import { logger } from '../lib/logger';
+import { copyTemplate } from '../lib/fs-utils';
+import { findProjectRoot, registerRoute } from '../lib/project-utils';
+
+export interface GenPageOptions {
+  name: string;
+  module?: string;
+  lazy?: boolean;
+  provider?: boolean;
+}
+
+export async function generatePage(opts: GenPageOptions) {
+  const projectRoot = await findProjectRoot(process.cwd());
+  if (!projectRoot) {
+    throw new Error('Not inside an xFramework project');
+  }
+
+  const templatesRoot = join(__dirname, '..', '..', 'templates', 'page');
+  const pagesRoot = join(projectRoot, 'src', 'app', 'pages');
+
+  const kebab = toKebab(opts.name);
+  const pascal = toPascal(opts.name);
+  const targetDir = join(pagesRoot, kebab);
+
+  if (await fs.pathExists(targetDir)) {
+    throw new Error(`Page '${kebab}' already exists`);
+  }
+
+  // فایل‌های اصلی
+  const data = {
+    __NAME__: kebab,
+    __CLASS__: pascal,
+    __TITLE_RES__: `${kebab}_page_title`,
+    __DESC_RES__: `${kebab}_page_description`,
+    __BASE_CLASS__: opts.provider ? 'VQueryPresenterBasePage' : 'VPageComponent',
+  };
+
+  await copyTemplate(templatesRoot, 'page.page.ts.hbs', join(targetDir, `${kebab}.page.ts`), data);
+  await copyTemplate(templatesRoot, 'page.page.html.hbs', join(targetDir, `${kebab}.page.html`), data);
+  await copyTemplate(templatesRoot, 'page.page.scss.hbs', join(targetDir, `${kebab}.page.scss`), data);
+
+  logger.file(join('src/app/pages', kebab));
+
+  // ثبت در routing
+  await registerRoute(projectRoot, pascal, kebab);
+  logger.success(`Page '${pascal}' generated`);
+}
+
+function toKebab(s: string) {
+  return s.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
+}
+function toPascal(s: string) {
+  return s.replace(/(^|-)([a-z])/g, (_, __, c) => c.toUpperCase());
+}
+ +

گام ۹: ثبت Route و اصلاح app-routing

+

با استفاده از ts-morph می‌توان آرایه‌ی routes را دستکاری کرد. برای شروع می‌توانید یک Placeholder ساده تعریف کنید:

+
// src/lib/project-utils.ts
+import { execa } from 'execa';
+import * as fs from 'fs-extra';
+import { join, dirname } from 'path';
+import { Project, SyntaxKind } from 'ts-morph';
+
+export async function findProjectRoot(start: string): Promise<string | null> {
+  let current = start;
+  for (let i = 0; i < 8; i++) {
+    const pkgPath = join(current, 'package.json');
+    if (await fs.pathExists(pkgPath)) {
+      const pkg = await fs.readJson(pkgPath);
+      if (pkg.dependencies?.['x-framework-core']) return current;
+    }
+    const parent = dirname(current);
+    if (parent === current) break;
+    current = parent;
+  }
+  return null;
+}
+
+export async function registerRoute(
+  projectRoot: string,
+  className: string,
+  routePath: string
+) {
+  const routingFile = join(projectRoot, 'src', 'app', 'app-routing.module.ts');
+  const project = new Project();
+  const source = project.addSourceFileAtPath(routingFile);
+
+  const routesArray = source.getVariableDeclaration('routes');
+  if (!routesArray) throw new Error('routes array not found');
+
+  const initializer = routesArray.getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);
+  initializer.addElement((writer) => {
+    writer
+      .write('{')
+      .newLine()
+      .write(`  component: ${className},`)
+      .newLine()
+      .write(`  path: '${routePath}',`)
+      .newLine()
+      .write(`  canDeactivate: [XCanDeactivateGuard],`)
+      .newLine()
+      .write('}');
+  });
+
+  source.saveSync();
+}
+
+ +

گام ۱۰: دستور xcli add (افزودن وابستگی و پلاگین)

+
// src/commands/add.ts
+import { Command } from 'commander';
+import { execa } from 'execa';
+import ora from 'ora';
+import { logger } from '../lib/logger';
+import { findProjectRoot } from '../lib/project-utils';
+
+export function registerAddCommand(program: Command) {
+  const add = program.command('add').description('Add dependencies / plugins');
+
+  // xcli add plugin <name>
+  add.command('plugin <name>')
+    .description('Add a Cordova plugin (device, splashscreen, statusbar)')
+    .action(async (name) => {
+      const root = await findProjectRoot(process.cwd());
+      if (!root) throw new Error('Not inside an xFramework project');
+
+      const spinner = ora(`Adding cordova plugin: ${name}`).start();
+      try {
+        await execa('ionic', ['cordova', 'plugin', 'add', `cordova-plugin-${name}`], {
+          cwd: root,
+          stdio: 'inherit',
+        });
+        // کپی type definitions به پوشه plugins
+        // (اختیاری، اگر نسخه‌ی محلی نگهداری می‌کنید)
+        spinner.succeed();
+      } catch (err: any) {
+        spinner.fail(err.message);
+      }
+    });
+
+  // xcli add x-framework-xxx
+  add.command('package <name>')
+    .description('Add an xFramework package to the project')
+    .action(async (name) => {
+      const root = await findProjectRoot(process.cwd());
+      if (!root) throw new Error('Not inside an xFramework project');
+
+      const spinner = ora(`Installing ${name}`).start();
+      try {
+        await execa('npm', ['install', name, '--legacy-peer-deps'], {
+          cwd: root,
+          stdio: 'inherit',
+        });
+        spinner.succeed();
+      } catch (err: any) {
+        spinner.fail(err.message);
+      }
+    });
+}
+ +

گام ۱۱: دستور xcli doctor

+

یک ابزار تشخیصی که محیط را بررسی می‌کند:

+
// src/commands/doctor.ts
+import { Command } from 'commander';
+import { execa } from 'execa';
+import { logger } from '../lib/logger';
+import chalk from 'chalk';
+
+const REQUIRED_NODE = '14.17.3';
+const REQUIRED_ANGULAR = '12.0.4';
+const REQUIRED_IONIC = '6.6.0';
+
+export function registerDoctorCommand(program: Command) {
+  program.command('doctor')
+    .description('Verify environment compatibility')
+    .action(async () => {
+      logger.title('Environment Check');
+
+      const checks = await Promise.all([
+        runVersion('node', ['-v']),
+        runVersion('npm', ['-v']),
+        runVersion('ng', ['version']),
+        runVersion('ionic', ['-v']),
+      ]);
+
+      const [node, npm, ng, ionic] = checks;
+
+      printCheck('Node.js', node, REQUIRED_NODE);
+      printCheck('npm', npm, null);
+      printCheck('@angular/cli', ng, REQUIRED_ANGULAR);
+      printCheck('@ionic/cli', ionic, REQUIRED_IONIC);
+
+      const nodeOk = node.startsWith('v14');
+      const ngOk = ng.startsWith('12');
+      const ionicOk = ionic.startsWith('6');
+
+      if (nodeOk && ngOk && ionicOk) {
+        logger.success('All checks passed ✅');
+      } else {
+        logger.warn('Some checks failed — see above');
+        process.exit(1);
+      }
+    });
+}
+
+async function runVersion(cmd: string, args: string[]) {
+  try {
+    const { stdout } = await execa(cmd, args);
+    return stdout.split('\n')[0].trim();
+  } catch {
+    return 'not installed';
+  }
+}
+
+function printCheck(name: string, found: string, expected: string | null) {
+  const ok = !expected || found.includes(expected);
+  const icon = ok ? chalk.green('✔') : chalk.red('✖');
+  console.log(`${icon} ${name.padEnd(20)} ${found}${expected ? chalk.gray(` (expected ${expected})`) : ''}`);
+}
+
+ + +
+

#6. تولیدکننده‌ها (Generators)

+ +

هر Generator باید بتواند مستقیم اجرا شود و همچنین توسط Command فراخوانی شود. جدول زیر لیست کامل Generatorها را نشان می‌دهد:

+ + + + + + + + + + + + + + + + + + + +
Generatorخروجیپایه
g new <app>پروژه‌ی کاملAngular + Ionic + xFramework
g page <name>صفحهVPageComponent
g page --providerصفحه با QueryVQueryPresenterBasePage
g provider-pageExplorer/ManagementBase
g view <name>کامپوننت ViewVBaseDtoComponent
g service <name>سرویسXBaseService
g module <name>ماژول RoutingRouterModule.forChild
g dto <name>Dto + type guardXBaseDto
g enum <name>Enum با isValueInEnum—
g config <name>Config با InjectionToken—
g pipe <name>Pure Pipe—
g directive <name>Attribute Directive—
+ +

6.1. کتابخانه‌ی کمکی برای Conventionها

+
// src/lib/naming.ts
+export const toKebab = (s: string) =>
+  s.replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/\s+/g, '-').toLowerCase();
+
+export const toPascal = (s: string) =>
+  toKebab(s).split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join('');
+
+export const toCamel = (s: string) =>
+  toPascal(s).replace(/^./, (c) => c.toLowerCase());
+
+export const toSnake = (s: string) =>
+  toKebab(s).replace(/-/g, '_');
+ +

6.2. الگوی Generator استاندارد

+

هر Generator جدید باید این الگو را رعایت کند:

+
    +
  1. یافتن ریشه‌ی پروژه با findProjectRoot.
  2. +
  3. اعتبارسنجی نام و عدم تکرار.
  4. +
  5. تولید فایل‌ها با copyTemplate.
  6. +
  7. Merge با فایل‌های موجود (Routing، Module، PageIndex).
  8. +
  9. نمایش گزارش با logger.
  10. +
  11. در صورت خطا، خروج با کد 1 و پیام روشن.
  12. +
+
+ + +
+

#7. سیستم قالب‌ها (Templates)

+ +

قالب‌ها فایل‌های .hbs هستند که با Handlebars رندر می‌شوند. نام‌گذاری متغیرها با __NAME__ انجام می‌شود (نه {{name}}) تا از تضاد با دستورات خود Handlebars جلوگیری شود.

+ +

7.1. قالب Page

+
{{! templates/page/page.page.ts.hbs }}
+import { ChangeDetectionStrategy, Component } from '@angular/core';
+import { XSideType } from 'x-framework-components';
+import { VPageComponent } from 'src/app/views/v-page/v-page.component';
+
+@Component({
+  selector: 'app-__NAME__',
+  templateUrl: './__NAME__.page.html',
+  styleUrls: ['./__NAME__.page.scss'],
+  changeDetection: ChangeDetectionStrategy.OnPush,
+})
+// tslint:disable-next-line:component-class-suffix
+export class __CLASS__Page extends VPageComponent {
+  //
+  //#region Props ...
+  hasSide = true;
+  toolbarShowSubTitle = true;
+  showToolbarEndSlot = true;
+  showToolbarContent = false;
+  titleRes = this.AppResourceIDs.__TITLE_RES__;
+  toolbarSubTitle = this.resourceProvider(this.titleRes);
+
+  /**
+   * use this for Menu always Visible ...
+   */
+  toggleMenuWhen = '';
+  sideType = XSideType.Overlay;
+  //#endregion
+}
+ +
{{! templates/page/page.page.html.hbs }}
+<!--                -->
+<!-- Page Presenter -->
+<!--                -->
+<v-page-presenter
+  [loading]="loading"
+  [containerBase]="this"
+  [uiDisabled]="uiDisabled"
+  [contentTemplate]="contentTemplate"
+></v-page-presenter>
+
+<!--              -->
+<!-- Page Content -->
+<!--              -->
+<ng-template #contentTemplate>
+  <!-- TODO: Add content -->
+</ng-template>
+ +

7.2. قالب View (VBaseDto)

+
{{! templates/view/view.component.ts.hbs }}
+import {
+  Component,
+  ChangeDetectionStrategy,
+} from '@angular/core';
+import {
+  getFieldNames,
+  XExceptionIDs,
+  isNullOrUndefined,
+  isNullOrEmptyString,
+} from 'x-framework-core';
+import {
+  X__CLASS__Dto,
+  default__CLASS__Dto,
+  prepare__CLASS__DtoFields,
+} from 'x-saherelm-api-sdk';
+import {
+  VBaseDtoComponent,
+  VModelFieldDescriptor,
+  VModelValidationResult,
+} from '../../v-dto/v-dto.typings';
+
+@Component({
+  selector: 'v-__NAME__',
+  templateUrl: './v-__NAME__.component.html',
+  styleUrls: ['./v-__NAME__.component.scss'],
+  changeDetection: ChangeDetectionStrategy.OnPush,
+})
+export class V__CLASS__Component extends VBaseDtoComponent<X__CLASS__Dto> {
+  readonly defaultModel: X__CLASS__Dto = { ...default__CLASS__Dto };
+  readonly FieldNames = getFieldNames(this.defaultModel);
+
+  defaultFieldDescriptors: VModelFieldDescriptor<any>[] = [
+    // TODO: Add field descriptors
+  ];
+
+  validate(
+    model?: Partial<X__CLASS__Dto>
+  ): VModelValidationResult<X__CLASS__Dto> {
+    // TODO: Implement validation
+    const normalized = this.normalize(model);
+    return {
+      isValid: true,
+      normalized,
+      isValidForAdd: true,
+      isValidForUpdate: true,
+      validationErrors: [],
+    };
+  }
+
+  prepare(model?: X__CLASS__Dto): X__CLASS__Dto {
+    return prepare__CLASS__DtoFields(model);
+  }
+}
+ +

7.3. قالب ProviderPage (Explorer / Management)

+

این قالب دقیقاً بازتاب ساختار FilesBaseProviderPage و TagsBaseProviderPage است که در xClient دیدیم:

+ +
{{! templates/provider-page/base.provider.page.ts.hbs }}
+import {
+  Component,
+  ViewChild,
+  TemplateRef,
+  ChangeDetectionStrategy,
+} from '@angular/core';
+import { Observable, Subject } from 'rxjs';
+import { nameof, getFieldNames, isNullOrUndefined } from 'x-framework-core';
+import { X__CLASS__Dto, default__CLASS__Dto } from 'x-saherelm-api-sdk';
+import { XQueryDto, XQueryResultDto } from 'x-framework-identity-sdk';
+import { VQueryPresenterBasePage } from 'src/app/views/v-query-presenter/v-query-presenter.base.page';
+import { VBaseDtoActionModel, VBaseDtoPresentType } from 'src/app/views/v-dto/v-dto.typings';
+import { XListItem } from 'x-framework-components';
+
+@Component({
+  template: '',
+  changeDetection: ChangeDetectionStrategy.OnPush,
+})
+export abstract class __CLASS__BaseProviderPage extends VQueryPresenterBasePage {
+  //
+  modelIdentifier: string = nameof<X__CLASS__Dto>('id');
+  listTabCardTitle = this.AppResourceIDs.__NAME__s;
+
+  //
+  queryPresenterActionProvider = new Subject<any>();
+  listItemActionProvider = new Subject<VBaseDtoActionModel>();
+
+  //
+  query: XQueryDto = {
+    page: 1,
+    filter: '',
+    pageSize: this.config.defaultPageSize,
+    sortBy: nameof<X__CLASS__Dto>('id'),
+  };
+  dtoQueryResult: XQueryResultDto<X__CLASS__Dto> = undefined;
+  hasQueryResultError = false;
+
+  // Templates
+  @ViewChild('itemTemplate') itemTemplate!: TemplateRef<any>;
+  @ViewChild('listItemTemplate') listItemTemplate!: TemplateRef<any>;
+  @ViewChild('addItemTemplate') addItemTemplate!: TemplateRef<any>;
+  @ViewChild('updateItemTemplate') updateItemTemplate!: TemplateRef<any>;
+  @ViewChild('detailsItemTemplate') detailsItemTemplate!: TemplateRef<any>;
+
+  abstract getModelTask(identifier: string): Observable<any>;
+  abstract queryModelTask(query: XQueryDto): Observable<XQueryResultDto<any>>;
+
+  async handleGetQueryResult(query: XQueryDto): Promise<XQueryResultDto<any>> {
+    // TODO: implement
+    return undefined as any;
+  }
+  async validateAndPrepareListItems(items: XListItem<any>[]) {
+    return items;
+  }
+  async requestFillingItems(exists: any[], recieved: any[]) {
+    return undefined as any;
+  }
+  async doItemActions(info: { id: string; data: any }) {
+    // TODO
+  }
+  async handleCustomError(error?: string) {
+    // TODO
+  }
+}
+ +

7.4. قالب Service

+
{{! templates/service/service.ts.hbs }}
+import { Inject, Injectable } from '@angular/core';
+import { XBaseService } from 'x-framework-core';
+import { XManagerService } from 'x-framework-services';
+import { X_CONFIG } from 'src/app/config/x.config';
+import { XConfig } from 'src/app/config/app.config';
+
+@Injectable({
+  providedIn: 'root',
+})
+export class X__CLASS__Service extends XBaseService {
+  constructor(
+    @Inject(X_CONFIG) public config: XConfig,
+    public managerService: XManagerService
+  ) {
+    super(config);
+  }
+
+  // TODO: Add methods
+}
+ +

7.5. قالب Module با Lazy Loading

+
{{! templates/module/module.ts.hbs }}
+import { NgModule } from '@angular/core';
+import { RouterModule } from '@angular/router';
+import { AuthGuard } from 'x-framework-identity-sdk';
+import { XCanDeactivateGuard } from 'x-framework-core';
+import { BaseRoutes } from 'src/app/config/page.config';
+import { ViewsModule } from 'src/app/views/views.module';
+
+@NgModule({
+  declarations: [],
+  imports: [
+    ViewsModule,
+    RouterModule.forChild([
+      {
+        pathMatch: 'full',
+        path: BaseRoutes.Default,
+        redirectTo: '__NAME__',
+      },
+      {
+        path: '__NAME__',
+        canActivate: [AuthGuard],
+        canDeactivate: [XCanDeactivateGuard],
+        loadChildren: () =>
+          import('./pages/__NAME__/__NAME__.module').then(
+            (m) => m.__CLASS__PageModule
+          ),
+      },
+    ]),
+  ],
+  exports: [ViewsModule, RouterModule],
+})
+export class __CLASS__PageModule {}
+ +
+
✅
+
+ قرارداد قالب‌ها: هر فایل قالب باید در پوشه‌ی مخصوص خود نگهداری شود (page، view، service، provider-page، module، …) + و نام فایل قالب با نام فایل خروجی یکسان باشد، فقط پسوند .hbs اضافه شده باشد. +
+
+
+ + +
+

#8. مدیریت پیکربندی و Environments

+ +

+ در xClient پیکربندی از طریق فایل‌های app.config.ts، x.config.ts و + environment.ts انجام می‌شود. xCLI باید بتواند این پیکربندی را در زمان ساخت پروژه و در زمان اجرا (با + دستور xcli config set) مدیریت کند. +

+ +

8.1. ساختار پیشنهادی پیکربندی

+
// src/app/config/app.config.ts (خلاصه)
+import { XFrameworkCoreConfig } from 'x-framework-core';
+import { XFrameworkServicesConfig } from 'x-framework-services';
+import { XFrameworkComponentsConfig } from 'x-framework-components';
+import { XFrameworkIdentitySDKConfig } from 'x-framework-identity-sdk';
+import { XFrameworkPushServiceConfig } from 'x-framework-push-service';
+import { XSaherElmApiSDKConfig } from 'x-saherelm-api-sdk';
+
+export type XConfig = XFrameworkCoreConfig
+  & XFrameworkServicesConfig
+  & XFrameworkComponentsConfig
+  & XFrameworkIdentitySDKConfig
+  & XFrameworkPushServiceConfig
+  & XSaherElmApiSDKConfig
+  & AppConfig;
+
+export const xFrameworkCoreSharedConfig = { /* ... */ };
+export const xFrameworkServicesSharedConfig = { /* ... */ };
+export const xFrameworkComponentsSharedConfig = { /* ... */ };
+export const xFrameworkIdentitySDKSharedConfig = { /* ... */ };
+export const xFrameworkPushServiceSharedConfig = { /* ... */ };
+export const xSaherElmApiSDKSharedConfig = { /* ... */ };
+export const xAppSharedConfig = { /* ... */ };
+
+export const xSharedConfig = {
+  ...xFrameworkCoreSharedConfig,
+  ...xFrameworkServicesSharedConfig,
+  ...xFrameworkComponentsSharedConfig,
+  ...xFrameworkIdentitySDKSharedConfig,
+  ...xFrameworkPushServiceSharedConfig,
+  ...xSaherElmApiSDKSharedConfig,
+  ...xAppSharedConfig,
+};
+ +

8.2. دستور xcli config

+
// src/commands/config.ts
+import { Command } from 'commander';
+import inquirer from 'inquirer';
+import * as fs from 'fs-extra';
+import { join } from 'path';
+import { findProjectRoot } from '../lib/project-utils';
+import { logger } from '../lib/logger';
+
+export function registerConfigCommand(program: Command) {
+  const cfg = program.command('config')
+    .description('Manage project configuration');
+
+  // xcli config show
+  cfg.command('show')
+    .description('Show current environment configuration')
+    .action(async () => {
+      const root = await findProjectRoot(process.cwd());
+      const envFile = join(root!, 'src', 'environments', 'environment.ts');
+      console.log(await fs.readFile(envFile, 'utf-8'));
+    });
+
+  // xcli config set <key> <value>
+  cfg.command('set <key> <value>')
+    .description('Set a configuration value (dot-notation)')
+    .option('--prod', 'Apply to production environment')
+    .action(async (key, value, opts) => {
+      const root = await findProjectRoot(process.cwd());
+      const envFile = join(
+        root!,
+        'src',
+        'environments',
+        opts.prod ? 'environment.prod.ts' : 'environment.ts'
+      );
+      // Update with ts-morph or simple regex
+      // ... (پیاده‌سازی با ts-morph ترجیح داده می‌شود)
+      logger.success(`Set ${key} = ${value} in ${envFile}`);
+    });
+
+  // xcli config locales
+  cfg.command('locales')
+    .description('List available locales')
+    .action(async () => {
+      // خواندن از localization.config.ts
+    });
+
+  cfg.action(() => cfg.help());
+}
+ +

8.3. دستور xcli env

+

مدیریت Environment:

+
xcli env add staging
+xcli env list
+xcli env remove staging
+xcli env switch staging
+

پیاده‌سازی این دستور به ایجاد فایل جدید environment.staging.ts و به‌روزرسانی angular.json در بخش fileReplacements منجر می‌شود.

+
+ + +
+

#9. مدیریت افزونه‌ها (Cordova Plugins)

+ +

+ در xClient سه پلاگین Cordova به‌صورت محلی نگهداری می‌شود: + cordova-plugin-device، cordova-plugin-splashscreen و cordova-plugin-statusbar. + xCLI باید بتواند این پلاگین‌ها را با Type Definitionهای آماده اضافه کند. +

+ +

9.1. ساختار پوشه‌ی پلاگین‌ها

+
plugins/
+└── cordova-plugin-<name>/
+    ├── types/
+    │   └── index.d.ts         ← Type Definitions
+    └── src/
+        └── wp/                ← پیاده‌سازی Windows Phone (اختیاری)
+ +

9.2. قالب Type Definition برای Device

+
// templates/plugins/device/index.d.ts.hbs
+// Type definitions for Apache Cordova Device plugin
+
+interface Device {
+  cordova: string;
+  available: boolean;
+  model: string;
+  platform: string;
+  uuid: string;
+  version: string;
+  manufacturer: string;
+  isVirtual: boolean;
+  serial: string;
+}
+
+declare var device: Device;
+ +

9.3. دستور xcli add plugin

+

این دستور باید سه کار انجام دهد:

+
    +
  1. اجرای ionic cordova plugin add cordova-plugin-<name>.
  2. +
  3. کپی پوشه‌ی types/ به plugins/cordova-plugin-<name>/types/.
  4. +
  5. افزودن ارجاع در tsconfig.json (بخش include یا files) اگر لازم شد.
  6. +
+
// src/commands/add-plugin.ts
+import { Command } from 'commander';
+import { execa } from 'execa';
+import * as fs from 'fs-extra';
+import { join } from 'path';
+import ora from 'ora';
+import { findProjectRoot } from '../lib/project-utils';
+
+export async function addCordovaPlugin(name: string) {
+  const root = await findProjectRoot(process.cwd());
+  if (!root) throw new Error('Not inside an xFramework project');
+
+  const spinner = ora(`Adding cordova plugin: ${name}`).start();
+  try {
+    // 1) اجرای ionic
+    await execa('ionic', ['cordova', 'plugin', 'add', `cordova-plugin-${name}`], {
+      cwd: root,
+      stdio: 'inherit',
+    });
+
+    // 2) کپی Type Definitions از قالب‌ها
+    const templateDir = join(__dirname, '..', '..', 'templates', 'plugins', name);
+    const targetDir = join(root, 'plugins', `cordova-plugin-${name}`);
+    if (await fs.pathExists(templateDir)) {
+      await fs.copy(templateDir, targetDir);
+    }
+
+    spinner.succeed(`Plugin ${name} added`);
+  } catch (err: any) {
+    spinner.fail(err.message);
+    throw err;
+  }
+}
+ +

9.4. قالب‌های پلاگین در xCLI

+
templates/plugins/
+├── device/
+│   └── types/index.d.ts
+├── splashscreen/
+│   └── types/index.d.ts
+└── statusbar/
+    └── types/index.d.ts
+ +
+
💡
+
+ اگر پروژه به Cordova وابسته نیست (مثلاً وب/الکترون)، دستور xcli add plugin باید هشدار دهد و از ادامه امتناع کند. + از فلگ --force برای عبور از این بررسی استفاده کنید. +
+
+
+ + +
+

#10. فرآیند ساخت، تست و انتشار

+ +

10.1. دستور xcli build

+

دستور Build پوششی روی ng build و ionic build است با گزینه‌های پرکاربرد:

+
// src/commands/build.ts
+import { Command } from 'commander';
+import { execa } from 'execa';
+import ora from 'ora';
+import { findProjectRoot } from '../lib/project-utils';
+
+export function registerBuildCommand(program: Command) {
+  program.command('build')
+    .description('Build the application')
+    .option('-c, --configuration <cfg>', 'Angular configuration', 'production')
+    .option('--prod', 'Shorthand for --configuration=production')
+    .option('--base-href <href>', 'Base href')
+    .option('--deploy-url <url>', 'Deploy URL')
+    .option('--source-map', 'Generate source maps')
+    .action(async (opts) => {
+      const root = await findProjectRoot(process.cwd());
+      if (!root) throw new Error('Not inside an xFramework project');
+
+      const cfg = opts.prod ? 'production' : opts.configuration;
+      const args = ['build', '--configuration', cfg];
+
+      if (opts.baseHref) args.push('--base-href', opts.baseHref);
+      if (opts.deployUrl) args.push('--deploy-url', opts.deployUrl);
+      if (opts.sourceMap) args.push('--source-map');
+
+      const spinner = ora(`Building (${cfg})...`).start();
+      try {
+        await execa('ng', args, { cwd: root, stdio: 'inherit' });
+        spinner.succeed('Build completed');
+      } catch (err: any) {
+        spinner.fail(err.message);
+      }
+    });
+
+  program.command('serve')
+    .description('Start dev server')
+    .option('--port <port>', 'Dev port', '4200')
+    .option('--host <host>', 'Dev host', 'localhost')
+    .action(async (opts) => {
+      const root = await findProjectRoot(process.cwd());
+      await execa(
+        'ng',
+        ['serve', '--port', opts.port, '--host', opts.host],
+        { cwd: root!, stdio: 'inherit' }
+      );
+    });
+}
+ +

10.2. تست

+

دستور xcli test پوشش نازکی روی ng test است با گزینه‌های Coverage و Watch:

+
xcli test --coverage
+xcli test --watch=false --browsers=ChromeHeadless
+ +

10.3. انتشار xCLI روی npm

+

پس از تست محلی با npm link، می‌توان پکیج را روی رجیستری شرکت یا npm عمومی منتشر کرد:

+
npm run build
+npm version patch
+npm publish --access public
+ +
+
⚠️
+
+ حتماً قبل از npm publish، فایل .npmignore بسازید تا src/، node_modules/ و + tsconfig.json منتشر نشوند. فقط bin/، dist/ و templates/ باید منتشر شوند. +
+
+ +

10.4. نمونه‌ی .npmignore

+
src/
+node_modules/
+*.log
+tsconfig.json
+*.tsbuildinfo
+.DS_Store
+.vscode/
+.idea/
+test/
+coverage/
+
+
+ + +
+

#11. مثال‌های عملی و سناریوها

+ +

11.1. ساخت پروژه‌ی جدید

+
xcli new my-x-app
+

خروجی مورد انتظار:

+
◆ Creating xFramework project
+
+✔ Project created successfully
+
+ℹ cd my-x-app
+ℹ npm run start:dev
+ +

11.2. افزودن صفحه به پروژه

+
cd my-x-app +xcli g page files --module=files --provider
+

فایل‌های تولیدشده:

+
src/app/pages/files/
+├── files.page.ts
+├── files.page.html
+└── files.page.scss
+
+✔ src/app/app-routing.module.ts updated
+ +

11.3. افزودن View با Dto

+
xcli g view article --dto
+

خروجی:

+
src/app/views/v-article/
+├── v-article.component.ts
+├── v-article.component.html
+└── v-article.component.scss
+
+✔ View 'VArticleComponent' generated
+ +

11.4. افزودن پلاگین StatusBar

+
xcli add plugin statusbar
+

نتیجه:

+
✔ Plugin statusbar added
+
+plugins/
+└── cordova-plugin-statusbar/
+    └── types/
+        └── index.d.ts
+ +

11.5. بررسی محیط

+
xcli doctor
+
◆ Environment Check
+
+✔ Node.js              v14.17.3   (expected 14.17.3)
+✔ npm                  6.14.13
+✔ @angular/cli         12.0.4     (expected 12.0.4)
+✔ @ionic/cli           6.6.0      (expected 6.6.0)
+
+✔ All checks passed ✅
+ +

11.6. Build پروژه

+
xcli build --prod --base-href=/app/
+ +

11.7. سناریوی کامل

+
+
+

ساخت پروژه

+ xcli new saherelm-admin +
+
+

افزودن پلاگین‌ها

+ xcli add plugin device + xcli add plugin splashscreen + xcli add plugin statusbar +
+
+

افزودن پکیج‌های xFramework

+ xcli add package x-saherelm-api-sdk +
+
+

تولید صفحات

+ xcli g page dashboard + xcli g page users --provider + xcli g page reports --provider +
+
+

تولید Viewها

+ xcli g view user --dto + xcli g view report --dto +
+
+

Build

+ xcli build --prod +
+
+
+ + +
+

#12. پیوست: جدول کامل دستورات

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
دستورتوضیح
xcli new [name]ساخت پروژه‌ی جدید
xcli g page <name>تولید صفحه
xcli g page <name> --providerتولید صفحه با منطق Query
xcli g provider-page <name>تولید Provider Page (Explorer/Management)
xcli g view <name>تولید View Component
xcli g service <name>تولید سرویس
xcli g module <name>تولید ماژول با Routing
xcli g dto <name>تولید Dto و Type Guard
xcli g enum <name>تولید Enum با Helper
xcli g config <name>تولید Config و Token
xcli g pipe <name>تولید Pipe
xcli g directive <name>تولید Directive
xcli add plugin <name>افزودن پلاگین Cordova
xcli add package <name>افزودن پکیج npm
xcli buildساخت پروژه
xcli serveاجرای سرور توسعه
xcli testاجرای تست‌ها
xcli config showنمایش پیکربندی فعلی
xcli config set <key> <value>تنظیم مقدار پیکربندی
xcli env add <name>افزودن Environment جدید
xcli env listلیست Environmentها
xcli env switch <name>تغییر Environment فعال
xcli doctorبررسی سلامت محیط
xcli help [cmd]نمایش راهنمای دستورات
+ +
+ +

12.1. ساختار نهایی پوشه‌ی xCLI

+
+xCli/ +├── bin/ +│ └── xcli.js +├── src/ +│ ├── index.ts +│ ├── commands/ +│ │ ├── new.ts +│ │ ├── generate.ts +│ │ ├── add.ts +│ │ ├── config.ts +│ │ ├── build.ts +│ │ └── doctor.ts +│ ├── generators/ +│ │ ├── new-project.ts +│ │ ├── page.ts +│ │ ├── provider-page.ts +│ │ ├── view.ts +│ │ ├── service.ts +│ │ ├── module.ts +│ │ ├── dto.ts +│ │ └── ... .ts +│ ├── lib/ +│ │ ├── logger.ts +│ │ ├── fs-utils.ts +│ │ ├── naming.ts +│ │ └── project-utils.ts +│ └── config/ +│ └── xcli.config.ts +├── templates/ +│ ├── default/ # قالب پیش‌فرض پروژه +│ ├── page/ +│ ├── view/ +│ ├── service/ +│ ├── module/ +│ ├── provider-page/ +│ └── plugins/ +│ ├── device/ +│ ├── splashscreen/ +│ └── statusbar/ +├── package.json +├── tsconfig.json +└── .npmignore +
+ +
+ +

12.2. راهنمای پیاده‌سازی سریع (Quick Start)

+
# 1) کلون / ساخت پروژه xCli
+mkdir xCli && cd xCli
+npm init -y
+
+# 2) نصب وابستگی‌ها
+npm i commander@9 inquirer@8 chalk@4 ora@5 fs-extra@10 handlebars@4 execa@5
+npm i -D typescript@4.2 @types/node@14 @types/fs-extra@9
+
+# 3) ساخت فایل‌های بالا (index, commands, generators, templates)
+# ...
+
+# 4) Build
+npm run build
+
+# 5) Link
+npm link
+
+# 6) تست
+xcli new demo-app
+cd demo-app
+xcli g page dashboard --provider
+xcli add plugin device
+xcli doctor
+xcli build --prod
+ +
+
🎉
+
+ در پایان این مستند، شما یک ابزار CLI کامل به‌نام xcli خواهید داشت که قادر است پروژه‌های xFramework را + با همان ساختار xClient بسازد، صفحات و Viewها و سرویس‌ها را استاندارد تولید کند، پلاگین‌های Cordova را اضافه کند، + پیکربندی را مدیریت کند و فرآیند Build/Test را پوشش دهد. +
+
+
+ +
+
+ +
+ 📘 مستندات فنی xCLI — تولید شده بر اساس تحلیل پروژه xClient و جستجو در منابع xFramework +
+ محدودیت نسخه‌ها: @angular/cli@12.0.4 · @ionic/cli@6.6.0 · Node v14.17.3 +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/XClient Cli xFramework Tool .html b/Documents/Docs/Developer/XClient Cli xFramework Tool .html new file mode 100644 index 0000000..be38024 --- /dev/null +++ b/Documents/Docs/Developer/XClient Cli xFramework Tool .html @@ -0,0 +1,2034 @@ + + + + + +راهنمای جامع ساخت xCLI برای xFramework + + + + + +
+
+
📘 مستندات فنی و عملیاتی | نسخه ۱.۰
+

راهنمای جامع ساخت xCLI
ابزار تولید و مدیریت پروژه‌های xFramework

+

+ مستندی گام‌به‌گام برای طراحی و پیاده‌سازی ابزار خط فرمان (CLI) به‌منظور ساخت، تولید و مدیریت + برنامه‌های کاربردی مبتنی بر xFramework با الگوگیری کامل از پروژه مرجع xClient. +

+
+ 🅰️ @angular/cli@12.0.4 + ⚡ @ionic/cli@6.6.0 + 🟢 Node v14.17.3 + 📦 xFramework Workspace +
+
+
+ +
+ + + + + +
+ + +
+

#1. معرفی پروژه و ضرورت xCLI

+ +

1.1. xFramework چیست؟

+

+ xFramework مجموعه‌ای از کتابخانه‌های ماژولار انگولار است که برای ساخت اپلیکیشن‌های + سازمانی (Enterprise) روی پشته‌ی Angular + Ionic + Capacitor/Cordova توسعه یافته است. + این چارچوب در قالب چند بسته (Package) مستقل ارائه می‌شود که هر کدام یک لایه از نیازهای نرم‌افزاری را پوشش می‌دهند: +

+ +
+
+
🧩
+

x-framework-core

+

لایه پایه شامل Utilityها، Enumهای سراسری، Type Guardها، ساختار Exceptionها و ابزارهای عمومی.

+
+
+
🛠️
+

x-framework-services

+

سرویس‌های سراسری مثل XManagerService، TaskManager، SecureStorage، Localization و ThemeManager.

+
+
+
🎨
+

x-framework-components

+

مجموعه‌ی بزرگی از کامپوننت‌های UI: XCard، XForm، XList، XTabs، XChart، XDataPager، XIDE و...

+
+
+
🔐
+

x-framework-identity-sdk

+

SDK احراز هویت، مدیریت توکن، Guardها (AuthGuard)، پروفایل کاربر و سرویس‌های حساب کاربری.

+
+
+
🚀
+

x-framework-push-service

+

مدیریت SignalR Push، سوکت‌های بلادرنگ، WebRTC و زیرساخت ارتباطی پیام‌رسانی.

+
+
+
🗂️
+

xApiSDKHolder

+

تولید SDK از API (به‌صورت دستی یا Codegen) برای موجودیت‌های دامنه مثل Tags، Files، Webinars و Strings.

+
+
+ +

1.2. پروژه xClient چه می‌کند؟

+

+ xClient در واقع یک اپلیکیشن مرجع (Reference Application) است که تمام قابلیت‌های xFramework + را در قالب یک محصول واقعی (سامانه‌ی آموزشی/محتوایی «ساحر علم») پیاده‌سازی می‌کند. مهم‌ترین لایه‌های این پروژه: +

+
    +
  • Workspace چند ماژولی: پوشه‌ی Modules/ شامل xApiSDKHolder، xFrameworkComponentsHolder و دیگر Holderهاست که به‌صورت کتابخانه‌های قابل انتشار نگهداری می‌شوند.
  • +
  • پروژه اصلی کلاینت: در پوشه‌ی xClient/ که خود از ساختار استاندارد Angular CLI + Ionic استفاده می‌کند.
  • +
  • لایه View: پوشه‌ی src/app/views مجموعه‌ای از V* کامپوننت‌ها (VPage، VDto، VFile، VTag، VWebinar و ...) که به کامپوننت‌های xFramework وصل می‌شوند.
  • +
  • لایه Page: پوشه‌ی src/app/pages شامل صفحات با ساختار مشترک (Home، Landing، Files، Tags، Webinars، Account و ...).
  • +
  • پیکربندی متمرکز: src/app/config/app.config.ts و x.config.ts به‌عنوان Single Source of Truth برای کل تنظیمات.
  • +
  • Environmentها: src/environments با دو فایل environment.ts و environment.prod.ts.
  • +
  • Pluginهای Cordova: در پوشه‌ی plugins/ با type definitionهای TypeScript برای Device، Splashscreen و StatusBar.
  • +
+ +

1.3. چرا به xCLI نیاز داریم؟

+

+ هر بار که می‌خواهیم یک پروژه‌ی جدید بر پایه‌ی xFramework بسازیم، باید ده‌ها فایل پیکربندی، چندین ماژول، ساختار View/Page، + Environment، Theme و Plugin را به‌صورت دستی ایجاد کنیم. این کار: +

+
    +
  • زمان‌بر و مستعد خطا است.
  • +
  • باعث ناسازگاری بین پروژه‌ها می‌شود (عدم رعایت Convention).
  • +
  • به‌روزرسانی نسخه‌ی فریم‌ورک را در چندین پروژه دشوار می‌کند.
  • +
  • امکان ارائه‌ی «تجربه‌ی توسعه‌دهنده» یکپارچه و مستند را نمی‌دهد.
  • +
+ +
+
💡
+
+ هدف xCLI: با یک دستور مثل xcli new my-app، پروژه‌ای کاملاً آماده با همان ساختار xClient تولید شود؛ + و با دستوراتی مانند xcli g page یا xcli g view بتوان اجزای جدید را به شکل استاندارد اضافه کرد. +
+
+
+ + +
+

#2. پیش‌نیازها و محیط اجرا

+ +

+ با توجه به محدودیت‌های اعلام‌شده، کل فرآیند باید بر روی نسخه‌های زیر پایدار بماند. این نسخه‌ها «قفل‌شده» در نظر گرفته می‌شوند + و xCLI باید در همان بازه کار کند. +

+ + + + + + + + + + + + + +
ابزارنسخهنقش
Node.jsv14.17.3Runtime اصلی CLI و Angular
npmهمراه با Node 14 → 6.xمدیریت پکیج‌ها
@angular/cli12.0.4اسکلت‌بندی و Build
@ionic/cli6.6.0مدیریت پروژه‌های Ionic و Cordova
TypeScript~4.2.xهمراه Angular 12
RxJS~6.6.xهمراه Angular 12
+ +

2.1. نصب ابزارها

+
# نصب نسخه‌های دقیق و قفل‌شده (توصیه می‌شود)
+npm i -g @angular/cli@12.0.4
+npm i -g @ionic/cli@6.6.0
+
+# بررسی نسخه‌ها
+node -v      # v14.17.3
+ng version   # Angular CLI: 12.0.4
+ionic -v     # 6.6.0
+ +
+
⚠️
+
+ توجه: Angular 12 بر روی Node 14 و 16 تست شده است. استفاده از Node 18+ باعث خطاهای + ERR_OSSL_EVP_UNSUPPORTED در Webpack 5 می‌شود. بنابراین پیشنهاد می‌شود از nvm یا nvs + برای مدیریت نسخه‌ی Node استفاده شود. +
+
+ +

2.2. ساختار پوشه‌ی توسعه

+

ساختار پیشنهادی برای مخزن توسعه‌ی xCLI به شکل زیر است:

+ +
xFrameworkWorkspace/
+├── xCli/                           # ← پروژه‌ی CLI (محل ساخت ابزار)
+│   ├── package.json
+│   ├── src/
+│   │   ├── index.ts                # نقطه‌ی ورود CLI
+│   │   ├── commands/               # دستورات
+│   │   ├── generators/             # تولیدکننده‌ها
+│   │   ├── templates/              # قالب‌ها
+│   │   ├── lib/                    # ابزارهای مشترک
+│   │   └── config/                 # پیکربندی CLI
+│   └── bin/
+│       └── xcli.js                 # شیم اجرایی (Shebang)
+│
+├── xClient/                        # ← پروژه‌ی مرجع
+│   ├── plugins/
+│   ├── src/
+│   │   ├── app/
+│   │   ├── environments/
+│   │   ├── theme/
+│   │   └── ...
+│   └── ...
+│
+└── Modules/                        # ← Holderهای کتابخانه‌ای
+    ├── xApiSDKHolder/
+    └── xFrameworkComponentsHolder/
+
+ + +
+

#3. معماری پیشنهادی xCLI

+ +

+ xCLI باید از الگوی Command + Generator + Template پیروی کند. این معماری مشابه Angular CLI، Nest CLI، + یا Nx است، ولی سبک‌تر و متناسب با نیاز xFramework. +

+ +
+
+
⌨️
+

لایه Commands

+

پارس دستورات ورودی، مدیریت Flagها، نمایش Help و اجرای Generator مناسب.

+
+
+
⚙️
+

لایه Generators

+

منطق تولید کد: ساخت فایل، جایگزینی Placeholder، Merge با فایل‌های موجود.

+
+
+
📁
+

لایه Templates

+

قالب‌های متنی با Placeholderهایی مانند __NAME__، __CLASS__، __PATH__.

+
+
+
🧠
+

لایه Schematics

+

اختیاری: استفاده از Schematics برای اجرای دقیق‌تر تغییرات روی AST فایل‌های TypeScript.

+
+
+ +

3.1. جریان اجرا

+
+
+

ورود کاربر

+

xcli g page --name=files --module=files در ترمینال وارد می‌شود.

+
+
+

پارس دستور

+

لایه Commands با commander یا yargs دستور و Flagها را تجزیه می‌کند.

+
+
+

اعتبارسنجی

+

بررسی وجود پروژه، نام معتبر، عدم تکرار، تطابق با Convention.

+
+
+

اجرای Generator

+

Generator با استفاده از Template مناسب و جایگزینی Placeholderها، فایل‌ها را ایجاد می‌کند.

+
+
+

Merge و ثبت

+

ثبت فایل‌های جدید در app-routing.module.ts، page.config.ts یا app.config.ts.

+
+
+

گزارش

+

نمایش فایل‌های ایجاد/تغییرداده‌شده و دستور بعدی برای اجرا.

+
+
+ +

3.2. وابستگی‌های xCLI

+ + + + + + + + + + + + +
پکیجهدف
commanderپارس زیردستور و Flagها
inquirerپرسش تعاملی از کاربر (Interactive prompt)
chalkرنگ‌دهی به خروجی ترمینال
oraنمایش Spinner حین اجرا
fs-extraعملیات فایل (copy، ensureDir، writeJson)
handlebarsرندر قالب‌های متنی
execaاجرای دستورات Shell (npm, ng, ionic)
ts-morph (اختیاری)ویرایش AST فایل‌های TypeScript
+ +
+
📌
+
+ برای شروع سبک، فقط از commander، inquirer، chalk، ora، + fs-extra و handlebars استفاده کنید. تغییرات AST را به کمک ts-morph در فاز دوم اضافه نمایید. +
+
+
+ + +
+

#4. ساختار پروژه xClient (مرجع)

+ +

+ برای این‌که xCLI بتواند پروژه‌ی همسان xClient تولید کند، باید ساختار آن را دقیقاً بشناسیم. در ادامه، شاخه‌های مهم با + توضیح جایگاه و نقش آورده شده‌اند. +

+ +

4.1. نمای کلی

+
+xClient/ +├── plugins/ +│ ├── cordova-plugin-device/ +│ │ └── types/index.d.ts # interface Device +│ ├── cordova-plugin-splashscreen/ +│ │ ├── src/wp/ +│ │ │ ├── SplashScreen.cs +│ │ │ └── ResolutionHelper.cs +│ │ └── types/index.d.ts +│ └── cordova-plugin-statusbar/ +│ ├── src/wp/StatusBar.cs +│ └── types/index.d.ts +│ +├── src/ +│ ├── index.html +│ ├── main.ts +│ ├── polyfills.ts +│ ├── typings.d.ts +│ ├── global.d.ts +│ │ +│ ├── environments/ +│ │ ├── environment.ts +│ │ └── environment.prod.ts +│ │ +│ ├── theme/ +│ │ └── theme.scss # Design Tokens + Ionic + XFramework +│ │ +│ └── app/ +│ ├── config/ +│ │ ├── app.config.ts # xSharedConfig، XCONFIG +│ │ ├── x.config.ts # InjectionToken +│ │ ├── x-api.config.ts # XApiConfiguration +│ │ ├── localization.config.ts # AppResourceIDs +│ │ ├── page.config.ts # PageIndex، Pages، NavItems +│ │ └── audio.config.ts +│ │ +│ ├── pages/ +│ │ ├── home/ +│ │ ├── landing/ +│ │ ├── startup/ +│ │ ├── account/ +│ │ ├── files/ +│ │ ├── tags/ +│ │ ├── webinars/ +│ │ ├── error/ +│ │ └── not-authorized/ +│ │ +│ ├── views/ +│ │ ├── v-page/ +│ │ ├── v-page-presenter/ +│ │ ├── v-dto/ +│ │ ├── v-query-presenter/ +│ │ ├── v-paginator/ +│ │ ├── v-file/ +│ │ ├── v-media/ +│ │ ├── v-tag/ +│ │ ├── v-tags-presenter/ +│ │ ├── v-files-presenter/ +│ │ ├── v-webinar/ +│ │ ├── v-webinar-view/ +│ │ ├── v-webinar-connect/ +│ │ ├── v-person/ +│ │ ├── v-user/ +│ │ ├── v-friendship/ +│ │ ├── v-login/ +│ │ ├── v-register/ +│ │ ├── v-profile/ +│ │ ├── v-avatar/ +│ │ ├── v-video/ +│ │ ├── v-error/ +│ │ ├── v-lazy-view/ +│ │ ├── v-string/ +│ │ ├── v-resource/ +│ │ ├── v-locale/ +│ │ ├── v-reference/ +│ │ ├── v-tag-input/ +│ │ ├── v-file-input/ +│ │ ├── v-icons-presenter/ +│ │ ├── classes/ +│ │ │ └── v-base.component.ts # VBaseComponent +│ │ ├── constants/ +│ │ │ ├── fab.defaults.ts +│ │ │ ├── button.defaults.ts +│ │ │ ├── slide.options.defaults.ts +│ │ │ └── actionbar.defaults.ts +│ │ ├── directives/ +│ │ ├── typings/ +│ │ ├── tools/ +│ │ └── views.module.ts +│ │ +│ ├── shared/ +│ │ ├── services/ +│ │ │ ├── shared.service.ts # SharedService +│ │ │ ├── x-electron.service.ts +│ │ │ ├── x-media-devices.service.ts +│ │ │ ├── x-scrolling-provider.service.ts +│ │ │ └── x-content-share-service.ts +│ │ ├── typings/ +│ │ ├── shared.module.ts +│ │ └── public-api.ts +│ │ +│ ├── app-routing.module.ts +│ ├── app.component.ts +│ ├── app.component.html +│ ├── app.component.scss +│ └── app.module.ts +│ +└── angular.json / package.json / tsconfig.json +
+ +

4.2. نکات کلیدی ساختاری

+
    +
  • + الگوی Base Component در Views: تمام کامپوننت‌های View از VBaseComponent یا + VBaseDtoComponent ارث می‌برند. این باعث یکپارچگی مدیریت Task، Error و Loading می‌شود. +
  • +
  • + الگوی Page / Provider: صفحات پیچیده (مثل Files، Tags، Webinars) از یک BaseProviderPage + استفاده می‌کنند که منطق Query، Add، Update، Delete و Push را از پیش پیاده‌سازی کرده است. +
  • +
  • + الگوی Dto: کامپوننت v-dto به‌عنوان Presenter عمومی برای هر Dto عمل می‌کند + و با VModelFieldDescriptorها فیلدها را رندر می‌کند. +
  • +
  • + مرکز پیکربندی: تمام تنظیمات در environment.configurations جمع شده و از طریق + XCONFIG (که از app.config.ts می‌آید) در سراسر برنامه در دسترس است. +
  • +
  • + پوشه‌ی Plugins: تعریف‌های TypeScript پلاگین‌های Cordova برای Device، Splashscreen و StatusBar + به‌صورت محلی در پروژه نگهداری می‌شود تا از پکیج‌های @types مستقل باشد. +
  • +
+
+ + +
+

#5. پیاده‌سازی گام‌به‌گام xCLI

+ +

در این بخش، از صفر تا صد ابزار xCLI ساخته می‌شود. هر گام با دستور، فایل و قطعه‌کد همراه است.

+ +

گام ۱: ساخت پوشه و مقداردهی اولیه

+
mkdir xCli && cd xCli
+npm init -y
+npm i commander@9 inquirer@8 chalk@4 ora@5 fs-extra@10 handlebars@4 execa@5
+npm i -D typescript@4.2 @types/node@14 @types/fs-extra@9 @types/inquirer@7
+ +
+
🎯
+
+ چرا این نسخه‌ها؟ commander@9، inquirer@8، chalk@4 و ora@5 + با Node 14 سازگارند. نسخه‌های جدیدتر (مثلاً inquirer@9 یا chalk@5) به ESM منتقل شده‌اند و + با CommonJS پروژه‌های Angular 12 تضاد ایجاد می‌کنند. +
+
+ +

گام ۲: تنظیم package.json و tsconfig

+
{
+  "name": "@xframework/xcli",
+  "version": "1.0.0",
+  "description": "CLI for generating and managing xFramework applications",
+  "main": "dist/index.js",
+  "bin": {
+    "xcli": "bin/xcli.js"
+  },
+  "scripts": {
+    "build": "tsc -p tsconfig.json",
+    "dev": "ts-node src/index.ts",
+    "link": "npm run build && npm link"
+  },
+  "files": [
+    "bin",
+    "dist",
+    "templates"
+  ],
+  "engines": {
+    "node": ">=14.17.3 <17"
+  }
+}
+ +
{
+  "compilerOptions": {
+    "target": "ES2019",
+    "module": "CommonJS",
+    "moduleResolution": "node",
+    "outDir": "dist",
+    "rootDir": "src",
+    "strict": true,
+    "esModuleInterop": true,
+    "skipLibCheck": true,
+    "resolveJsonModule": true,
+    "declaration": true,
+    "sourceMap": true
+  },
+  "include": ["src/**/*.ts"]
+}
+ +

گام ۳: Shم اجرایی (bin)

+

فایل bin/xcli.js در واقع یک Loader است که نسخه‌ی کامپایل‌شده را اجرا می‌کند:

+
#!/usr/bin/env node
+// bin/xcli.js
+require('../dist/index.js');
+ +
+
🔐
+
+ روی Linux/macOS اجرای chmod +x bin/xcli.js لازم است. npm هنگام npm link این کار را خودکار انجام می‌دهد. +
+
+ +

گام ۴: نقطه‌ی ورود CLI

+

فایل src/index.ts با commander ساخته می‌شود:

+
// src/index.ts
+import { Command } from 'commander';
+import { registerNewCommand } from './commands/new';
+import { registerGenerateCommand } from './commands/generate';
+import { registerAddCommand } from './commands/add';
+import { registerConfigCommand } from './commands/config';
+import { registerBuildCommand } from './commands/build';
+import { registerDoctorCommand } from './commands/doctor';
+import chalk from 'chalk';
+import { readFileSync } from 'fs';
+import { join } from 'path';
+
+const pkg = JSON.parse(
+  readFileSync(join(__dirname, '..', 'package.json'), 'utf-8')
+);
+
+const program = new Command();
+
+program
+  .name('xcli')
+  .description('CLI for xFramework application scaffolding & management')
+  .version(pkg.version, '-v, --version', 'output the current version');
+
+// ثبت زیردستورات
+registerNewCommand(program);
+registerGenerateCommand(program);
+registerAddCommand(program);
+registerConfigCommand(program);
+registerBuildCommand(program);
+registerDoctorCommand(program);
+
+// دستور پیش‌فرض
+program
+  .command('help [command]')
+  .description('display help for xcli or a specific command')
+  .action((cmd) => {
+    if (cmd) {
+      const sub = program.commands.find((c) => c.name() === cmd);
+      if (sub) {
+        sub.help();
+      } else {
+        console.log(chalk.red(`Unknown command: ${cmd}`));
+        process.exit(1);
+      }
+    } else {
+      program.help();
+    }
+  });
+
+// مدیریت خطاها
+process.on('unhandledRejection', (err: any) => {
+  console.error(chalk.red('\n💥 Unexpected error:'), err?.message || err);
+  process.exit(1);
+});
+
+// پارس آرگومان‌ها
+program.parseAsync(process.argv).catch((err) => {
+  console.error(chalk.red(err.message));
+  process.exit(1);
+});
+ +

گام ۵: کتابخانه‌ی ابزارهای مشترک

+

یک فایل src/lib/logger.ts برای رنگ‌دهی یکنواخت:

+
// src/lib/logger.ts
+import chalk from 'chalk';
+
+export const logger = {
+  info: (msg: string) => console.log(chalk.cyan('ℹ '), msg),
+  success: (msg: string) => console.log(chalk.green('✔ '), msg),
+  warn: (msg: string) => console.log(chalk.yellow('⚠ '), msg),
+  error: (msg: string) => console.log(chalk.red('✖ '), msg),
+  title: (msg: string) =>
+    console.log('\n' + chalk.bold.blue(`◆ ${msg}`) + '\n'),
+  file: (path: string) => console.log(chalk.gray('  CREATE'), chalk.white(path)),
+  update: (path: string) =>
+    console.log(chalk.gray('  UPDATE'), chalk.yellow(path)),
+};
+ +

فایل src/lib/fs-utils.ts برای مدیریت فایل‌ها:

+
// src/lib/fs-utils.ts
+import * as fs from 'fs-extra';
+import { join, dirname } from 'path';
+import Handlebars from 'handlebars';
+
+export async function renderTemplate(
+  templateSource: string,
+  data: Record
+): Promise {
+  const template = Handlebars.compile(templateSource, { noEscape: true });
+  return template(data);
+}
+
+export async function writeRendered(
+  targetPath: string,
+  content: string,
+  overwrite = false
+) {
+  if (!overwrite && (await fs.pathExists(targetPath))) {
+    throw new Error(`File already exists: ${targetPath}`);
+  }
+  await fs.ensureDir(dirname(targetPath));
+  await fs.writeFile(targetPath, content, 'utf-8');
+}
+
+export async function copyTemplate(
+  templatesRoot: string,
+  relativePath: string,
+  targetPath: string,
+  data: Record,
+  extensionsToRender = ['.ts', '.html', '.scss', '.json', '.md', '.xml', '.js']
+) {
+  const source = await fs.readFile(join(templatesRoot, relativePath), 'utf-8');
+  const ext = '.' + relativePath.split('.').pop();
+  const content = extensionsToRender.includes(ext)
+    ? await renderTemplate(source, data)
+    : source;
+  await writeRendered(targetPath, content);
+}
+ +

گام ۶: دستور xcli new

+

این دستور پروژه‌ی جدید xFramework را از صفر ایجاد می‌کند.

+ +
+
+

الف) تعریف دستور

+
// src/commands/new.ts
+import { Command } from 'commander';
+import inquirer from 'inquirer';
+import ora from 'ora';
+import { generateNewProject } from '../generators/new-project';
+import { logger } from '../lib/logger';
+
+export function registerNewCommand(program: Command) {
+  program
+    .command('new [name]')
+    .description('Create a new xFramework application')
+    .option('-d, --directory <path>', 'Target directory')
+    .option('--skip-install', 'Skip npm install')
+    .option('--template <type>', 'Project template', 'default')
+    .action(async (name, options) => {
+      logger.title('Creating xFramework project');
+
+      // پرسش تعاملی اگر نام داده نشده باشد
+      if (!name) {
+        const ans = await inquirer.prompt([
+          {
+            type: 'input',
+            name: 'name',
+            message: 'Project name:',
+            default: 'my-x-app',
+            validate: (v) =>
+              /^[a-z][a-z0-9-]*$/.test(v) ||
+              'lowercase letters, numbers, dash only',
+          },
+        ]);
+        name = ans.name;
+      }
+
+      const spinner = ora('Scaffolding project...').start();
+      try {
+        await generateNewProject({
+          name,
+          directory: options.directory || `./${name}`,
+          template: options.template,
+          skipInstall: options.skipInstall,
+          onProgress: (msg) => (spinner.text = msg),
+        });
+        spinner.succeed('Project created successfully');
+        logger.info(`cd ${name}`);
+        logger.info('npm run start:dev');
+      } catch (err: any) {
+        spinner.fail(err.message);
+        process.exit(1);
+      }
+    });
+}
+
+
+

ب) منطق تولید پروژه

+
// src/generators/new-project.ts
+import { execa } from 'execa';
+import * as fs from 'fs-extra';
+import { join } from 'path';
+import { logger } from '../lib/logger';
+import { copyTemplate } from '../lib/fs-utils';
+
+export interface NewProjectOptions {
+  name: string;
+  directory: string;
+  template: string;
+  skipInstall?: boolean;
+  onProgress?: (msg: string) => void;
+}
+
+export async function generateNewProject(opts: NewProjectOptions) {
+  const { name, directory, onProgress, skipInstall } = opts;
+  const templatesRoot = join(__dirname, '..', '..', 'templates', opts.template);
+
+  // 1. ساخت پوشه
+  await fs.ensureDir(directory);
+  onProgress?.('Creating directory structure...');
+
+  // 2. تولید با Angular CLI
+  onProgress?.('Running ng new...');
+  await execa(
+    'npx',
+    [
+      '@angular/cli@12.0.4', 'new', name,
+      '--routing', '--style=scss', '--skip-git', '--skip-install',
+      '--skip-tests', '--package-manager=npm',
+    ],
+    { cwd: directory, stdio: 'inherit' }
+  );
+
+  const projectRoot = join(directory, name);
+
+  // 3. افزودن Ionic
+  onProgress?.('Running ionic init...');
+  await execa('npx', ['@ionic/cli@6.6.0', 'init', 'x-framework-app', 'angular', '--type=angular-standalone'], {
+    cwd: projectRoot,
+    stdio: 'inherit',
+  });
+
+  // 4. کپی قالب‌های سفارشی (app, views, config, plugins...)
+  onProgress?.('Copying xFramework templates...');
+  await copyTemplateTree(templatesRoot, projectRoot, {
+    __APP_NAME__: name,
+    __APP_INSTANCE__: name + 'Client',
+  });
+
+  // 5. نصب پکیج‌های xFramework
+  onProgress?.('Installing dependencies...');
+  const pkgPath = join(projectRoot, 'package.json');
+  const pkg = await fs.readJson(pkgPath);
+  pkg.dependencies = {
+    ...pkg.dependencies,
+    'x-framework-core': '^1.0.0',
+    'x-framework-services': '^1.0.0',
+    'x-framework-components': '^1.0.0',
+    'x-framework-identity-sdk': '^1.0.0',
+    'x-framework-push-service': '^1.0.0',
+    'x-saherelm-api-sdk': '^1.0.0',
+  };
+  await fs.writeJson(pkgPath, pkg, { spaces: 2 });
+
+  // 6. نصب نهایی
+  if (!skipInstall) {
+    onProgress?.('npm install...');
+    await execa('npm', ['install', '--legacy-peer-deps'], {
+      cwd: projectRoot,
+      stdio: 'inherit',
+    });
+  }
+
+  logger.success(`Project '${name}' generated at ${projectRoot}`);
+}
+
+async function copyTemplateTree(
+  src: string,
+  dest: string,
+  context: Record<string, any>
+) {
+  const entries = await fs.readdir(src, { withFileTypes: true });
+  for (const entry of entries) {
+    const srcPath = join(src, entry.name);
+    const destPath = join(dest, entry.name);
+    if (entry.isDirectory()) {
+      await copyTemplateTree(srcPath, destPath, context);
+    } else {
+      await copyTemplate(src, entry.name, destPath, context);
+    }
+  }
+}
+
+
+ +

گام ۷: دستور xcli g (Generate)

+

ساخت زیردستور برای تولید اجزای مختلف:

+
// src/commands/generate.ts
+import { Command } from 'commander';
+import { generatePage } from '../generators/page';
+import { generateView } from '../generators/view';
+import { generateService } from '../generators/service';
+import { generateModule } from '../generators/module';
+import { generateProviderPage } from '../generators/provider-page';
+import { logger } from '../lib/logger';
+
+export function registerGenerateCommand(program: Command) {
+  const g = program
+    .command('generate')
+    .alias('g')
+    .description('Generate xFramework artifacts');
+
+  // xcli g page
+  g.command('page <name>')
+    .description('Generate a Page (src/app/pages/<name>)')
+    .option('-m, --module <name>', 'Parent module', 'app')
+    .option('--lazy', 'Create lazy-loaded module')
+    .option('--provider', 'Extend VQueryPresenterBasePage')
+    .action(async (name, opts) => {
+      logger.title(`Generating page: ${name}`);
+      await generatePage({ name, ...opts });
+    });
+
+  // xcli g view
+  g.command('view <name>')
+    .description('Generate a View component (src/app/views/v-<name>)')
+    .option('--dto', 'Extend VBaseDtoComponent')
+    .option('--page', 'Extend VPageComponent')
+    .option('--plain', 'Plain Angular component')
+    .action(async (name, opts) => {
+      logger.title(`Generating view: ${name}`);
+      await generateView({ name, ...opts });
+    });
+
+  // xcli g service
+  g.command('service <name>')
+    .description('Generate a shared service')
+    .option('--singleton', 'providedIn: root', true)
+    .action(async (name, opts) => {
+      logger.title(`Generating service: ${name}`);
+      await generateService({ name, ...opts });
+    });
+
+  // xcli g module
+  g.command('module <name>')
+    .description('Generate an Angular module with routing')
+    .option('--lazy', 'Lazy-loaded module')
+    .action(async (name, opts) => {
+      logger.title(`Generating module: ${name}`);
+      await generateModule({ name, ...opts });
+    });
+
+  // xcli g provider-page
+  g.command('provider-page <name>')
+    .description('Generate a ProviderPage (Explorer/Management)')
+    .option('--kind <kind>', 'explorer | management', 'explorer')
+    .action(async (name, opts) => {
+      logger.title(`Generating provider page: ${name}`);
+      await generateProviderPage({ name, ...opts });
+    });
+
+  // اگر هیچ زیردستوری داده نشد، راهنما نشان بده
+  g.action(() => g.help());
+}
+ +

گام ۸: Generator برای Page

+
// src/generators/page.ts
+import { join } from 'path';
+import * as fs from 'fs-extra';
+import { logger } from '../lib/logger';
+import { copyTemplate } from '../lib/fs-utils';
+import { findProjectRoot, registerRoute } from '../lib/project-utils';
+
+export interface GenPageOptions {
+  name: string;
+  module?: string;
+  lazy?: boolean;
+  provider?: boolean;
+}
+
+export async function generatePage(opts: GenPageOptions) {
+  const projectRoot = await findProjectRoot(process.cwd());
+  if (!projectRoot) {
+    throw new Error('Not inside an xFramework project');
+  }
+
+  const templatesRoot = join(__dirname, '..', '..', 'templates', 'page');
+  const pagesRoot = join(projectRoot, 'src', 'app', 'pages');
+
+  const kebab = toKebab(opts.name);
+  const pascal = toPascal(opts.name);
+  const targetDir = join(pagesRoot, kebab);
+
+  if (await fs.pathExists(targetDir)) {
+    throw new Error(`Page '${kebab}' already exists`);
+  }
+
+  // فایل‌های اصلی
+  const data = {
+    __NAME__: kebab,
+    __CLASS__: pascal,
+    __TITLE_RES__: `${kebab}_page_title`,
+    __DESC_RES__: `${kebab}_page_description`,
+    __BASE_CLASS__: opts.provider ? 'VQueryPresenterBasePage' : 'VPageComponent',
+  };
+
+  await copyTemplate(templatesRoot, 'page.page.ts.hbs', join(targetDir, `${kebab}.page.ts`), data);
+  await copyTemplate(templatesRoot, 'page.page.html.hbs', join(targetDir, `${kebab}.page.html`), data);
+  await copyTemplate(templatesRoot, 'page.page.scss.hbs', join(targetDir, `${kebab}.page.scss`), data);
+
+  logger.file(join('src/app/pages', kebab));
+
+  // ثبت در routing
+  await registerRoute(projectRoot, pascal, kebab);
+  logger.success(`Page '${pascal}' generated`);
+}
+
+function toKebab(s: string) {
+  return s.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
+}
+function toPascal(s: string) {
+  return s.replace(/(^|-)([a-z])/g, (_, __, c) => c.toUpperCase());
+}
+ +

گام ۹: ثبت Route و اصلاح app-routing

+

با استفاده از ts-morph می‌توان آرایه‌ی routes را دستکاری کرد. برای شروع می‌توانید یک Placeholder ساده تعریف کنید:

+
// src/lib/project-utils.ts
+import { execa } from 'execa';
+import * as fs from 'fs-extra';
+import { join, dirname } from 'path';
+import { Project, SyntaxKind } from 'ts-morph';
+
+export async function findProjectRoot(start: string): Promise<string | null> {
+  let current = start;
+  for (let i = 0; i < 8; i++) {
+    const pkgPath = join(current, 'package.json');
+    if (await fs.pathExists(pkgPath)) {
+      const pkg = await fs.readJson(pkgPath);
+      if (pkg.dependencies?.['x-framework-core']) return current;
+    }
+    const parent = dirname(current);
+    if (parent === current) break;
+    current = parent;
+  }
+  return null;
+}
+
+export async function registerRoute(
+  projectRoot: string,
+  className: string,
+  routePath: string
+) {
+  const routingFile = join(projectRoot, 'src', 'app', 'app-routing.module.ts');
+  const project = new Project();
+  const source = project.addSourceFileAtPath(routingFile);
+
+  const routesArray = source.getVariableDeclaration('routes');
+  if (!routesArray) throw new Error('routes array not found');
+
+  const initializer = routesArray.getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);
+  initializer.addElement((writer) => {
+    writer
+      .write('{')
+      .newLine()
+      .write(`  component: ${className},`)
+      .newLine()
+      .write(`  path: '${routePath}',`)
+      .newLine()
+      .write(`  canDeactivate: [XCanDeactivateGuard],`)
+      .newLine()
+      .write('}');
+  });
+
+  source.saveSync();
+}
+
+ +

گام ۱۰: دستور xcli add (افزودن وابستگی و پلاگین)

+
// src/commands/add.ts
+import { Command } from 'commander';
+import { execa } from 'execa';
+import ora from 'ora';
+import { logger } from '../lib/logger';
+import { findProjectRoot } from '../lib/project-utils';
+
+export function registerAddCommand(program: Command) {
+  const add = program.command('add').description('Add dependencies / plugins');
+
+  // xcli add plugin <name>
+  add.command('plugin <name>')
+    .description('Add a Cordova plugin (device, splashscreen, statusbar)')
+    .action(async (name) => {
+      const root = await findProjectRoot(process.cwd());
+      if (!root) throw new Error('Not inside an xFramework project');
+
+      const spinner = ora(`Adding cordova plugin: ${name}`).start();
+      try {
+        await execa('ionic', ['cordova', 'plugin', 'add', `cordova-plugin-${name}`], {
+          cwd: root,
+          stdio: 'inherit',
+        });
+        // کپی type definitions به پوشه plugins
+        // (اختیاری، اگر نسخه‌ی محلی نگهداری می‌کنید)
+        spinner.succeed();
+      } catch (err: any) {
+        spinner.fail(err.message);
+      }
+    });
+
+  // xcli add x-framework-xxx
+  add.command('package <name>')
+    .description('Add an xFramework package to the project')
+    .action(async (name) => {
+      const root = await findProjectRoot(process.cwd());
+      if (!root) throw new Error('Not inside an xFramework project');
+
+      const spinner = ora(`Installing ${name}`).start();
+      try {
+        await execa('npm', ['install', name, '--legacy-peer-deps'], {
+          cwd: root,
+          stdio: 'inherit',
+        });
+        spinner.succeed();
+      } catch (err: any) {
+        spinner.fail(err.message);
+      }
+    });
+}
+ +

گام ۱۱: دستور xcli doctor

+

یک ابزار تشخیصی که محیط را بررسی می‌کند:

+
// src/commands/doctor.ts
+import { Command } from 'commander';
+import { execa } from 'execa';
+import { logger } from '../lib/logger';
+import chalk from 'chalk';
+
+const REQUIRED_NODE = '14.17.3';
+const REQUIRED_ANGULAR = '12.0.4';
+const REQUIRED_IONIC = '6.6.0';
+
+export function registerDoctorCommand(program: Command) {
+  program.command('doctor')
+    .description('Verify environment compatibility')
+    .action(async () => {
+      logger.title('Environment Check');
+
+      const checks = await Promise.all([
+        runVersion('node', ['-v']),
+        runVersion('npm', ['-v']),
+        runVersion('ng', ['version']),
+        runVersion('ionic', ['-v']),
+      ]);
+
+      const [node, npm, ng, ionic] = checks;
+
+      printCheck('Node.js', node, REQUIRED_NODE);
+      printCheck('npm', npm, null);
+      printCheck('@angular/cli', ng, REQUIRED_ANGULAR);
+      printCheck('@ionic/cli', ionic, REQUIRED_IONIC);
+
+      const nodeOk = node.startsWith('v14');
+      const ngOk = ng.startsWith('12');
+      const ionicOk = ionic.startsWith('6');
+
+      if (nodeOk && ngOk && ionicOk) {
+        logger.success('All checks passed ✅');
+      } else {
+        logger.warn('Some checks failed — see above');
+        process.exit(1);
+      }
+    });
+}
+
+async function runVersion(cmd: string, args: string[]) {
+  try {
+    const { stdout } = await execa(cmd, args);
+    return stdout.split('\n')[0].trim();
+  } catch {
+    return 'not installed';
+  }
+}
+
+function printCheck(name: string, found: string, expected: string | null) {
+  const ok = !expected || found.includes(expected);
+  const icon = ok ? chalk.green('✔') : chalk.red('✖');
+  console.log(`${icon} ${name.padEnd(20)} ${found}${expected ? chalk.gray(` (expected ${expected})`) : ''}`);
+}
+
+ + +
+

#6. تولیدکننده‌ها (Generators)

+ +

هر Generator باید بتواند مستقیم اجرا شود و همچنین توسط Command فراخوانی شود. جدول زیر لیست کامل Generatorها را نشان می‌دهد:

+ + + + + + + + + + + + + + + + + + + +
Generatorخروجیپایه
g new <app>پروژه‌ی کاملAngular + Ionic + xFramework
g page <name>صفحهVPageComponent
g page --providerصفحه با QueryVQueryPresenterBasePage
g provider-pageExplorer/ManagementBase
g view <name>کامپوننت ViewVBaseDtoComponent
g service <name>سرویسXBaseService
g module <name>ماژول RoutingRouterModule.forChild
g dto <name>Dto + type guardXBaseDto
g enum <name>Enum با isValueInEnum—
g config <name>Config با InjectionToken—
g pipe <name>Pure Pipe—
g directive <name>Attribute Directive—
+ +

6.1. کتابخانه‌ی کمکی برای Conventionها

+
// src/lib/naming.ts
+export const toKebab = (s: string) =>
+  s.replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/\s+/g, '-').toLowerCase();
+
+export const toPascal = (s: string) =>
+  toKebab(s).split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join('');
+
+export const toCamel = (s: string) =>
+  toPascal(s).replace(/^./, (c) => c.toLowerCase());
+
+export const toSnake = (s: string) =>
+  toKebab(s).replace(/-/g, '_');
+ +

6.2. الگوی Generator استاندارد

+

هر Generator جدید باید این الگو را رعایت کند:

+
    +
  1. یافتن ریشه‌ی پروژه با findProjectRoot.
  2. +
  3. اعتبارسنجی نام و عدم تکرار.
  4. +
  5. تولید فایل‌ها با copyTemplate.
  6. +
  7. Merge با فایل‌های موجود (Routing، Module، PageIndex).
  8. +
  9. نمایش گزارش با logger.
  10. +
  11. در صورت خطا، خروج با کد 1 و پیام روشن.
  12. +
+
+ + +
+

#7. سیستم قالب‌ها (Templates)

+ +

قالب‌ها فایل‌های .hbs هستند که با Handlebars رندر می‌شوند. نام‌گذاری متغیرها با __NAME__ انجام می‌شود (نه {{name}}) تا از تضاد با دستورات خود Handlebars جلوگیری شود.

+ +

7.1. قالب Page

+
{{! templates/page/page.page.ts.hbs }}
+import { ChangeDetectionStrategy, Component } from '@angular/core';
+import { XSideType } from 'x-framework-components';
+import { VPageComponent } from 'src/app/views/v-page/v-page.component';
+
+@Component({
+  selector: 'app-__NAME__',
+  templateUrl: './__NAME__.page.html',
+  styleUrls: ['./__NAME__.page.scss'],
+  changeDetection: ChangeDetectionStrategy.OnPush,
+})
+// tslint:disable-next-line:component-class-suffix
+export class __CLASS__Page extends VPageComponent {
+  //
+  //#region Props ...
+  hasSide = true;
+  toolbarShowSubTitle = true;
+  showToolbarEndSlot = true;
+  showToolbarContent = false;
+  titleRes = this.AppResourceIDs.__TITLE_RES__;
+  toolbarSubTitle = this.resourceProvider(this.titleRes);
+
+  /**
+   * use this for Menu always Visible ...
+   */
+  toggleMenuWhen = '';
+  sideType = XSideType.Overlay;
+  //#endregion
+}
+ +
{{! templates/page/page.page.html.hbs }}
+<!--                -->
+<!-- Page Presenter -->
+<!--                -->
+<v-page-presenter
+  [loading]="loading"
+  [containerBase]="this"
+  [uiDisabled]="uiDisabled"
+  [contentTemplate]="contentTemplate"
+></v-page-presenter>
+
+<!--              -->
+<!-- Page Content -->
+<!--              -->
+<ng-template #contentTemplate>
+  <!-- TODO: Add content -->
+</ng-template>
+ +

7.2. قالب View (VBaseDto)

+
{{! templates/view/view.component.ts.hbs }}
+import {
+  Component,
+  ChangeDetectionStrategy,
+} from '@angular/core';
+import {
+  getFieldNames,
+  XExceptionIDs,
+  isNullOrUndefined,
+  isNullOrEmptyString,
+} from 'x-framework-core';
+import {
+  X__CLASS__Dto,
+  default__CLASS__Dto,
+  prepare__CLASS__DtoFields,
+} from 'x-saherelm-api-sdk';
+import {
+  VBaseDtoComponent,
+  VModelFieldDescriptor,
+  VModelValidationResult,
+} from '../../v-dto/v-dto.typings';
+
+@Component({
+  selector: 'v-__NAME__',
+  templateUrl: './v-__NAME__.component.html',
+  styleUrls: ['./v-__NAME__.component.scss'],
+  changeDetection: ChangeDetectionStrategy.OnPush,
+})
+export class V__CLASS__Component extends VBaseDtoComponent<X__CLASS__Dto> {
+  readonly defaultModel: X__CLASS__Dto = { ...default__CLASS__Dto };
+  readonly FieldNames = getFieldNames(this.defaultModel);
+
+  defaultFieldDescriptors: VModelFieldDescriptor<any>[] = [
+    // TODO: Add field descriptors
+  ];
+
+  validate(
+    model?: Partial<X__CLASS__Dto>
+  ): VModelValidationResult<X__CLASS__Dto> {
+    // TODO: Implement validation
+    const normalized = this.normalize(model);
+    return {
+      isValid: true,
+      normalized,
+      isValidForAdd: true,
+      isValidForUpdate: true,
+      validationErrors: [],
+    };
+  }
+
+  prepare(model?: X__CLASS__Dto): X__CLASS__Dto {
+    return prepare__CLASS__DtoFields(model);
+  }
+}
+ +

7.3. قالب ProviderPage (Explorer / Management)

+

این قالب دقیقاً بازتاب ساختار FilesBaseProviderPage و TagsBaseProviderPage است که در xClient دیدیم:

+ +
{{! templates/provider-page/base.provider.page.ts.hbs }}
+import {
+  Component,
+  ViewChild,
+  TemplateRef,
+  ChangeDetectionStrategy,
+} from '@angular/core';
+import { Observable, Subject } from 'rxjs';
+import { nameof, getFieldNames, isNullOrUndefined } from 'x-framework-core';
+import { X__CLASS__Dto, default__CLASS__Dto } from 'x-saherelm-api-sdk';
+import { XQueryDto, XQueryResultDto } from 'x-framework-identity-sdk';
+import { VQueryPresenterBasePage } from 'src/app/views/v-query-presenter/v-query-presenter.base.page';
+import { VBaseDtoActionModel, VBaseDtoPresentType } from 'src/app/views/v-dto/v-dto.typings';
+import { XListItem } from 'x-framework-components';
+
+@Component({
+  template: '',
+  changeDetection: ChangeDetectionStrategy.OnPush,
+})
+export abstract class __CLASS__BaseProviderPage extends VQueryPresenterBasePage {
+  //
+  modelIdentifier: string = nameof<X__CLASS__Dto>('id');
+  listTabCardTitle = this.AppResourceIDs.__NAME__s;
+
+  //
+  queryPresenterActionProvider = new Subject<any>();
+  listItemActionProvider = new Subject<VBaseDtoActionModel>();
+
+  //
+  query: XQueryDto = {
+    page: 1,
+    filter: '',
+    pageSize: this.config.defaultPageSize,
+    sortBy: nameof<X__CLASS__Dto>('id'),
+  };
+  dtoQueryResult: XQueryResultDto<X__CLASS__Dto> = undefined;
+  hasQueryResultError = false;
+
+  // Templates
+  @ViewChild('itemTemplate') itemTemplate!: TemplateRef<any>;
+  @ViewChild('listItemTemplate') listItemTemplate!: TemplateRef<any>;
+  @ViewChild('addItemTemplate') addItemTemplate!: TemplateRef<any>;
+  @ViewChild('updateItemTemplate') updateItemTemplate!: TemplateRef<any>;
+  @ViewChild('detailsItemTemplate') detailsItemTemplate!: TemplateRef<any>;
+
+  abstract getModelTask(identifier: string): Observable<any>;
+  abstract queryModelTask(query: XQueryDto): Observable<XQueryResultDto<any>>;
+
+  async handleGetQueryResult(query: XQueryDto): Promise<XQueryResultDto<any>> {
+    // TODO: implement
+    return undefined as any;
+  }
+  async validateAndPrepareListItems(items: XListItem<any>[]) {
+    return items;
+  }
+  async requestFillingItems(exists: any[], recieved: any[]) {
+    return undefined as any;
+  }
+  async doItemActions(info: { id: string; data: any }) {
+    // TODO
+  }
+  async handleCustomError(error?: string) {
+    // TODO
+  }
+}
+ +

7.4. قالب Service

+
{{! templates/service/service.ts.hbs }}
+import { Inject, Injectable } from '@angular/core';
+import { XBaseService } from 'x-framework-core';
+import { XManagerService } from 'x-framework-services';
+import { X_CONFIG } from 'src/app/config/x.config';
+import { XConfig } from 'src/app/config/app.config';
+
+@Injectable({
+  providedIn: 'root',
+})
+export class X__CLASS__Service extends XBaseService {
+  constructor(
+    @Inject(X_CONFIG) public config: XConfig,
+    public managerService: XManagerService
+  ) {
+    super(config);
+  }
+
+  // TODO: Add methods
+}
+ +

7.5. قالب Module با Lazy Loading

+
{{! templates/module/module.ts.hbs }}
+import { NgModule } from '@angular/core';
+import { RouterModule } from '@angular/router';
+import { AuthGuard } from 'x-framework-identity-sdk';
+import { XCanDeactivateGuard } from 'x-framework-core';
+import { BaseRoutes } from 'src/app/config/page.config';
+import { ViewsModule } from 'src/app/views/views.module';
+
+@NgModule({
+  declarations: [],
+  imports: [
+    ViewsModule,
+    RouterModule.forChild([
+      {
+        pathMatch: 'full',
+        path: BaseRoutes.Default,
+        redirectTo: '__NAME__',
+      },
+      {
+        path: '__NAME__',
+        canActivate: [AuthGuard],
+        canDeactivate: [XCanDeactivateGuard],
+        loadChildren: () =>
+          import('./pages/__NAME__/__NAME__.module').then(
+            (m) => m.__CLASS__PageModule
+          ),
+      },
+    ]),
+  ],
+  exports: [ViewsModule, RouterModule],
+})
+export class __CLASS__PageModule {}
+ +
+
✅
+
+ قرارداد قالب‌ها: هر فایل قالب باید در پوشه‌ی مخصوص خود نگهداری شود (page، view، service، provider-page، module، …) + و نام فایل قالب با نام فایل خروجی یکسان باشد، فقط پسوند .hbs اضافه شده باشد. +
+
+
+ + +
+

#8. مدیریت پیکربندی و Environments

+ +

+ در xClient پیکربندی از طریق فایل‌های app.config.ts، x.config.ts و + environment.ts انجام می‌شود. xCLI باید بتواند این پیکربندی را در زمان ساخت پروژه و در زمان اجرا (با + دستور xcli config set) مدیریت کند. +

+ +

8.1. ساختار پیشنهادی پیکربندی

+
// src/app/config/app.config.ts (خلاصه)
+import { XFrameworkCoreConfig } from 'x-framework-core';
+import { XFrameworkServicesConfig } from 'x-framework-services';
+import { XFrameworkComponentsConfig } from 'x-framework-components';
+import { XFrameworkIdentitySDKConfig } from 'x-framework-identity-sdk';
+import { XFrameworkPushServiceConfig } from 'x-framework-push-service';
+import { XSaherElmApiSDKConfig } from 'x-saherelm-api-sdk';
+
+export type XConfig = XFrameworkCoreConfig
+  & XFrameworkServicesConfig
+  & XFrameworkComponentsConfig
+  & XFrameworkIdentitySDKConfig
+  & XFrameworkPushServiceConfig
+  & XSaherElmApiSDKConfig
+  & AppConfig;
+
+export const xFrameworkCoreSharedConfig = { /* ... */ };
+export const xFrameworkServicesSharedConfig = { /* ... */ };
+export const xFrameworkComponentsSharedConfig = { /* ... */ };
+export const xFrameworkIdentitySDKSharedConfig = { /* ... */ };
+export const xFrameworkPushServiceSharedConfig = { /* ... */ };
+export const xSaherElmApiSDKSharedConfig = { /* ... */ };
+export const xAppSharedConfig = { /* ... */ };
+
+export const xSharedConfig = {
+  ...xFrameworkCoreSharedConfig,
+  ...xFrameworkServicesSharedConfig,
+  ...xFrameworkComponentsSharedConfig,
+  ...xFrameworkIdentitySDKSharedConfig,
+  ...xFrameworkPushServiceSharedConfig,
+  ...xSaherElmApiSDKSharedConfig,
+  ...xAppSharedConfig,
+};
+ +

8.2. دستور xcli config

+
// src/commands/config.ts
+import { Command } from 'commander';
+import inquirer from 'inquirer';
+import * as fs from 'fs-extra';
+import { join } from 'path';
+import { findProjectRoot } from '../lib/project-utils';
+import { logger } from '../lib/logger';
+
+export function registerConfigCommand(program: Command) {
+  const cfg = program.command('config')
+    .description('Manage project configuration');
+
+  // xcli config show
+  cfg.command('show')
+    .description('Show current environment configuration')
+    .action(async () => {
+      const root = await findProjectRoot(process.cwd());
+      const envFile = join(root!, 'src', 'environments', 'environment.ts');
+      console.log(await fs.readFile(envFile, 'utf-8'));
+    });
+
+  // xcli config set <key> <value>
+  cfg.command('set <key> <value>')
+    .description('Set a configuration value (dot-notation)')
+    .option('--prod', 'Apply to production environment')
+    .action(async (key, value, opts) => {
+      const root = await findProjectRoot(process.cwd());
+      const envFile = join(
+        root!,
+        'src',
+        'environments',
+        opts.prod ? 'environment.prod.ts' : 'environment.ts'
+      );
+      // Update with ts-morph or simple regex
+      // ... (پیاده‌سازی با ts-morph ترجیح داده می‌شود)
+      logger.success(`Set ${key} = ${value} in ${envFile}`);
+    });
+
+  // xcli config locales
+  cfg.command('locales')
+    .description('List available locales')
+    .action(async () => {
+      // خواندن از localization.config.ts
+    });
+
+  cfg.action(() => cfg.help());
+}
+ +

8.3. دستور xcli env

+

مدیریت Environment:

+
xcli env add staging
+xcli env list
+xcli env remove staging
+xcli env switch staging
+

پیاده‌سازی این دستور به ایجاد فایل جدید environment.staging.ts و به‌روزرسانی angular.json در بخش fileReplacements منجر می‌شود.

+
+ + +
+

#9. مدیریت افزونه‌ها (Cordova Plugins)

+ +

+ در xClient سه پلاگین Cordova به‌صورت محلی نگهداری می‌شود: + cordova-plugin-device، cordova-plugin-splashscreen و cordova-plugin-statusbar. + xCLI باید بتواند این پلاگین‌ها را با Type Definitionهای آماده اضافه کند. +

+ +

9.1. ساختار پوشه‌ی پلاگین‌ها

+
plugins/
+└── cordova-plugin-<name>/
+    ├── types/
+    │   └── index.d.ts         ← Type Definitions
+    └── src/
+        └── wp/                ← پیاده‌سازی Windows Phone (اختیاری)
+ +

9.2. قالب Type Definition برای Device

+
// templates/plugins/device/index.d.ts.hbs
+// Type definitions for Apache Cordova Device plugin
+
+interface Device {
+  cordova: string;
+  available: boolean;
+  model: string;
+  platform: string;
+  uuid: string;
+  version: string;
+  manufacturer: string;
+  isVirtual: boolean;
+  serial: string;
+}
+
+declare var device: Device;
+ +

9.3. دستور xcli add plugin

+

این دستور باید سه کار انجام دهد:

+
    +
  1. اجرای ionic cordova plugin add cordova-plugin-<name>.
  2. +
  3. کپی پوشه‌ی types/ به plugins/cordova-plugin-<name>/types/.
  4. +
  5. افزودن ارجاع در tsconfig.json (بخش include یا files) اگر لازم شد.
  6. +
+
// src/commands/add-plugin.ts
+import { Command } from 'commander';
+import { execa } from 'execa';
+import * as fs from 'fs-extra';
+import { join } from 'path';
+import ora from 'ora';
+import { findProjectRoot } from '../lib/project-utils';
+
+export async function addCordovaPlugin(name: string) {
+  const root = await findProjectRoot(process.cwd());
+  if (!root) throw new Error('Not inside an xFramework project');
+
+  const spinner = ora(`Adding cordova plugin: ${name}`).start();
+  try {
+    // 1) اجرای ionic
+    await execa('ionic', ['cordova', 'plugin', 'add', `cordova-plugin-${name}`], {
+      cwd: root,
+      stdio: 'inherit',
+    });
+
+    // 2) کپی Type Definitions از قالب‌ها
+    const templateDir = join(__dirname, '..', '..', 'templates', 'plugins', name);
+    const targetDir = join(root, 'plugins', `cordova-plugin-${name}`);
+    if (await fs.pathExists(templateDir)) {
+      await fs.copy(templateDir, targetDir);
+    }
+
+    spinner.succeed(`Plugin ${name} added`);
+  } catch (err: any) {
+    spinner.fail(err.message);
+    throw err;
+  }
+}
+ +

9.4. قالب‌های پلاگین در xCLI

+
templates/plugins/
+├── device/
+│   └── types/index.d.ts
+├── splashscreen/
+│   └── types/index.d.ts
+└── statusbar/
+    └── types/index.d.ts
+ +
+
💡
+
+ اگر پروژه به Cordova وابسته نیست (مثلاً وب/الکترون)، دستور xcli add plugin باید هشدار دهد و از ادامه امتناع کند. + از فلگ --force برای عبور از این بررسی استفاده کنید. +
+
+
+ + +
+

#10. فرآیند ساخت، تست و انتشار

+ +

10.1. دستور xcli build

+

دستور Build پوششی روی ng build و ionic build است با گزینه‌های پرکاربرد:

+
// src/commands/build.ts
+import { Command } from 'commander';
+import { execa } from 'execa';
+import ora from 'ora';
+import { findProjectRoot } from '../lib/project-utils';
+
+export function registerBuildCommand(program: Command) {
+  program.command('build')
+    .description('Build the application')
+    .option('-c, --configuration <cfg>', 'Angular configuration', 'production')
+    .option('--prod', 'Shorthand for --configuration=production')
+    .option('--base-href <href>', 'Base href')
+    .option('--deploy-url <url>', 'Deploy URL')
+    .option('--source-map', 'Generate source maps')
+    .action(async (opts) => {
+      const root = await findProjectRoot(process.cwd());
+      if (!root) throw new Error('Not inside an xFramework project');
+
+      const cfg = opts.prod ? 'production' : opts.configuration;
+      const args = ['build', '--configuration', cfg];
+
+      if (opts.baseHref) args.push('--base-href', opts.baseHref);
+      if (opts.deployUrl) args.push('--deploy-url', opts.deployUrl);
+      if (opts.sourceMap) args.push('--source-map');
+
+      const spinner = ora(`Building (${cfg})...`).start();
+      try {
+        await execa('ng', args, { cwd: root, stdio: 'inherit' });
+        spinner.succeed('Build completed');
+      } catch (err: any) {
+        spinner.fail(err.message);
+      }
+    });
+
+  program.command('serve')
+    .description('Start dev server')
+    .option('--port <port>', 'Dev port', '4200')
+    .option('--host <host>', 'Dev host', 'localhost')
+    .action(async (opts) => {
+      const root = await findProjectRoot(process.cwd());
+      await execa(
+        'ng',
+        ['serve', '--port', opts.port, '--host', opts.host],
+        { cwd: root!, stdio: 'inherit' }
+      );
+    });
+}
+ +

10.2. تست

+

دستور xcli test پوشش نازکی روی ng test است با گزینه‌های Coverage و Watch:

+
xcli test --coverage
+xcli test --watch=false --browsers=ChromeHeadless
+ +

10.3. انتشار xCLI روی npm

+

پس از تست محلی با npm link، می‌توان پکیج را روی رجیستری شرکت یا npm عمومی منتشر کرد:

+
npm run build
+npm version patch
+npm publish --access public
+ +
+
⚠️
+
+ حتماً قبل از npm publish، فایل .npmignore بسازید تا src/، node_modules/ و + tsconfig.json منتشر نشوند. فقط bin/، dist/ و templates/ باید منتشر شوند. +
+
+ +

10.4. نمونه‌ی .npmignore

+
src/
+node_modules/
+*.log
+tsconfig.json
+*.tsbuildinfo
+.DS_Store
+.vscode/
+.idea/
+test/
+coverage/
+
+
+ + +
+

#11. مثال‌های عملی و سناریوها

+ +

11.1. ساخت پروژه‌ی جدید

+
xcli new my-x-app
+

خروجی مورد انتظار:

+
◆ Creating xFramework project
+
+✔ Project created successfully
+
+ℹ cd my-x-app
+ℹ npm run start:dev
+ +

11.2. افزودن صفحه به پروژه

+
cd my-x-app +xcli g page files --module=files --provider
+

فایل‌های تولیدشده:

+
src/app/pages/files/
+├── files.page.ts
+├── files.page.html
+└── files.page.scss
+
+✔ src/app/app-routing.module.ts updated
+ +

11.3. افزودن View با Dto

+
xcli g view article --dto
+

خروجی:

+
src/app/views/v-article/
+├── v-article.component.ts
+├── v-article.component.html
+└── v-article.component.scss
+
+✔ View 'VArticleComponent' generated
+ +

11.4. افزودن پلاگین StatusBar

+
xcli add plugin statusbar
+

نتیجه:

+
✔ Plugin statusbar added
+
+plugins/
+└── cordova-plugin-statusbar/
+    └── types/
+        └── index.d.ts
+ +

11.5. بررسی محیط

+
xcli doctor
+
◆ Environment Check
+
+✔ Node.js              v14.17.3   (expected 14.17.3)
+✔ npm                  6.14.13
+✔ @angular/cli         12.0.4     (expected 12.0.4)
+✔ @ionic/cli           6.6.0      (expected 6.6.0)
+
+✔ All checks passed ✅
+ +

11.6. Build پروژه

+
xcli build --prod --base-href=/app/
+ +

11.7. سناریوی کامل

+
+
+

ساخت پروژه

+ xcli new saherelm-admin +
+
+

افزودن پلاگین‌ها

+ xcli add plugin device + xcli add plugin splashscreen + xcli add plugin statusbar +
+
+

افزودن پکیج‌های xFramework

+ xcli add package x-saherelm-api-sdk +
+
+

تولید صفحات

+ xcli g page dashboard + xcli g page users --provider + xcli g page reports --provider +
+
+

تولید Viewها

+ xcli g view user --dto + xcli g view report --dto +
+
+

Build

+ xcli build --prod +
+
+
+ + +
+

#12. پیوست: جدول کامل دستورات

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
دستورتوضیح
xcli new [name]ساخت پروژه‌ی جدید
xcli g page <name>تولید صفحه
xcli g page <name> --providerتولید صفحه با منطق Query
xcli g provider-page <name>تولید Provider Page (Explorer/Management)
xcli g view <name>تولید View Component
xcli g service <name>تولید سرویس
xcli g module <name>تولید ماژول با Routing
xcli g dto <name>تولید Dto و Type Guard
xcli g enum <name>تولید Enum با Helper
xcli g config <name>تولید Config و Token
xcli g pipe <name>تولید Pipe
xcli g directive <name>تولید Directive
xcli add plugin <name>افزودن پلاگین Cordova
xcli add package <name>افزودن پکیج npm
xcli buildساخت پروژه
xcli serveاجرای سرور توسعه
xcli testاجرای تست‌ها
xcli config showنمایش پیکربندی فعلی
xcli config set <key> <value>تنظیم مقدار پیکربندی
xcli env add <name>افزودن Environment جدید
xcli env listلیست Environmentها
xcli env switch <name>تغییر Environment فعال
xcli doctorبررسی سلامت محیط
xcli help [cmd]نمایش راهنمای دستورات
+ +
+ +

12.1. ساختار نهایی پوشه‌ی xCLI

+
+xCli/ +├── bin/ +│ └── xcli.js +├── src/ +│ ├── index.ts +│ ├── commands/ +│ │ ├── new.ts +│ │ ├── generate.ts +│ │ ├── add.ts +│ │ ├── config.ts +│ │ ├── build.ts +│ │ └── doctor.ts +│ ├── generators/ +│ │ ├── new-project.ts +│ │ ├── page.ts +│ │ ├── provider-page.ts +│ │ ├── view.ts +│ │ ├── service.ts +│ │ ├── module.ts +│ │ ├── dto.ts +│ │ └── ... .ts +│ ├── lib/ +│ │ ├── logger.ts +│ │ ├── fs-utils.ts +│ │ ├── naming.ts +│ │ └── project-utils.ts +│ └── config/ +│ └── xcli.config.ts +├── templates/ +│ ├── default/ # قالب پیش‌فرض پروژه +│ ├── page/ +│ ├── view/ +│ ├── service/ +│ ├── module/ +│ ├── provider-page/ +│ └── plugins/ +│ ├── device/ +│ ├── splashscreen/ +│ └── statusbar/ +├── package.json +├── tsconfig.json +└── .npmignore +
+ +
+ +

12.2. راهنمای پیاده‌سازی سریع (Quick Start)

+
# 1) کلون / ساخت پروژه xCli
+mkdir xCli && cd xCli
+npm init -y
+
+# 2) نصب وابستگی‌ها
+npm i commander@9 inquirer@8 chalk@4 ora@5 fs-extra@10 handlebars@4 execa@5
+npm i -D typescript@4.2 @types/node@14 @types/fs-extra@9
+
+# 3) ساخت فایل‌های بالا (index, commands, generators, templates)
+# ...
+
+# 4) Build
+npm run build
+
+# 5) Link
+npm link
+
+# 6) تست
+xcli new demo-app
+cd demo-app
+xcli g page dashboard --provider
+xcli add plugin device
+xcli doctor
+xcli build --prod
+ +
+
🎉
+
+ در پایان این مستند، شما یک ابزار CLI کامل به‌نام xcli خواهید داشت که قادر است پروژه‌های xFramework را + با همان ساختار xClient بسازد، صفحات و Viewها و سرویس‌ها را استاندارد تولید کند، پلاگین‌های Cordova را اضافه کند، + پیکربندی را مدیریت کند و فرآیند Build/Test را پوشش دهد. +
+
+
+ +
+
+ +
+ 📘 مستندات فنی xCLI — تولید شده بر اساس تحلیل پروژه xClient و جستجو در منابع xFramework +
+ محدودیت نسخه‌ها: @angular/cli@12.0.4 · @ionic/cli@6.6.0 · Node v14.17.3 +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/xFrameworkComponents Overview 14050818 v1.0.html b/Documents/Docs/Developer/xFrameworkComponents Overview 14050818 v1.0.html new file mode 100644 index 0000000..ef5d1ea --- /dev/null +++ b/Documents/Docs/Developer/xFrameworkComponents Overview 14050818 v1.0.html @@ -0,0 +1,1534 @@ + + + + + +xFrameworkComponents – راهنمای کامل کامپوننت‌ها + + + +
+ + + + + +
+ + +
+

راهنمای کامل کامپوننت‌های xFrameworkComponents

+

+ تحلیل جامع ۴۲ ماژول و بیش از ۵۵ کامپوننت کتابخانه UI چندسکویی xFramework، + بر اساس الگوی Container / Component و Property Provider. +

+
+ Angular + Ionic + Container Pattern + ActionProvider + OnPush + Observable-first + ApexCharts + Monaco / IDE +
+
+ + +

مرور کلی

+ +

+ x-framework-components بزرگ‌ترین کتابخانه UI در اکوسیستم xFramework است. + در فایل public-api.ts این کتابخانه، ۴۲ ماژول و بیش از + ۵۵ کامپوننت به‌همراه ده‌ها کلاس پایه، typings، tools و container export شده‌اند. +

+ +
+
+ ۴۲ + ماژول +

هر ماژول یک یا چند کامپوننت را bundle می‌کند

+
+
+ ۵۵+ + کامپوننت +

از Icon ساده تا IDE و Chart پیشرفته

+
+
+ ۸ + کلاس پایه +

XBaseComponent، XBasePage، XBaseDialogService و ...

+
+
+ ۱۲ + Container Interface +

ترکیب‌پذیر مثل Card+File+FileDrop

+
+
+ +

فلسفه طراحی

+
    +
  • Reactive-by-Default: همه پراپرتی‌ها می‌توانند XStandardType<T> = T | Observable<T> | Subject<T> باشند
  • +
  • ChangeDetection.OnPush: در تمام کامپوننت‌های واقعی
  • +
  • ActionProvider: به‌جای Input/Output پراکنده، یک Subject<XActionModel> مرکزی
  • +
  • Property Provider: مقادیر پیش‌فرض قابل inject شدن
  • +
  • Container Interface Mixins: ترکیب قابلیت‌ها (مثلاً Card + File + FileDrop = Avatar Upload)
  • +
+ + +

معماری سه‌لایه

+ +

هر کامپوننت در این کتابخانه از یک الگوی یکسان پیروی می‌کند:

+ +

+┌─────────────────────────────────────────────────────────────┐
+│  لایه ۱ – Property Provider (Injectable)                    │
+│  مثال: XCardContainer                                       │
+│  - مقادیر پیش‌فرض readonly                                  │
+│  - در root ثبت می‌شود                                       │
+└─────────────────────┬───────────────────────────────────────┘
+                      │ inject
+                      ▼
+┌─────────────────────────────────────────────────────────────┐
+│  لایه ۲ – Container Component (Abstract)                    │
+│  مثال: XCardContainerComponent                              │
+│  - @Input() های عمومی                                       │
+│  - متد extractProps() برای تست‌پذیری                         │
+│  - منطق مشترک                                               │
+└─────────────────────┬───────────────────────────────────────┘
+                      │ extends
+                      ▼
+┌─────────────────────────────────────────────────────────────┐
+│  لایه ۳ – Real Component                                    │
+│  مثال: XCardComponent                                       │
+│  - Template و SCSS                                          │
+│  - منطق اختصاصی                                             │
+│  - changeDetection: OnPush                                  │
+└─────────────────────────────────────────────────────────────┘
+
+ +

مثال کامل: XCardComponent

+ +
// ─── لایه ۱: Property Provider ───
+@Injectable({ providedIn: 'root' })
+export class XCardContainer extends XBaseContainer {
+  readonly actionProvider = new Subject<XCardActionModel>();
+  readonly color: XStandardType<XColorIdentifier> = XColorWithBrightness.Light;
+  readonly showHeader: XStandardType<boolean> = false;
+  readonly showActions: XStandardType<boolean> = false;
+  readonly title: XStandardType<XResourceIdentifier>;
+  // ...
+}
+
+// ─── لایه ۲: Container Component ───
+@Injectable()
+@Component({ template: `` })
+export abstract class XCardContainerComponent
+  extends XBaseContainerComponent implements IXCardContainer {
+
+  @Input() color = this.propertyProvider.color;
+  @Input() showHeader = this.propertyProvider.showHeader;
+  // ...
+
+  public extractProps(container?: IXCardContainer): Observable<IXCardContainer> {
+    return forkJoin({
+      color: this.getValue(container ? container.color : this.color),
+      // ...
+    }).pipe(map(data => ({ ...data, actionProvider: ... })));
+  }
+}
+
+// ─── لایه ۳: Real Component ───
+@Component({
+  selector: 'x-card',
+  templateUrl: './x-card.component.html',
+  changeDetection: ChangeDetectionStrategy.OnPush,
+})
+export class XCardComponent extends XCardContainerComponent {
+  // business logic only
+}
+ +
+ مزیت: با extractProps() می‌توان کامپوننت‌ها را به‌صورت + headless تست کرد و بدون رندر واقعی، خروجی همه پراپرتی‌ها را به‌صورت Observable دریافت نمود. +
+ + +

کلاس‌های پایه (Foundation)

+ +
+
+

XBaseComponent lib/classes/x-base-component.ts

+ Base +
+

+ ستون فقرات تمام کامپوننت‌ها و حتی XBasePage و XBaseDialogComponent. + از XRenderer (در x-framework-core) ارث می‌برد و شامل: +

+
    +
  • Task Manager – addOrUpdateTask, dispatchTask, onTaskStart/Finished/Failed
  • +
  • State Management – loading, uiDisabled, error, lock با EventEmitter برای همگام‌سازی
  • +
  • Observable Helpers – getValue, getArrayValue, getResourceValue, notEmptyValue, ...
  • +
  • Async Helpers – getValueAsync, mustBeValueAsync, ...
  • +
  • Subscription Cleanup – applyTakeUntilWrapper
  • +
  • Reload – reloadComponent() با visibility toggle
  • +
  • UUID – شناسه یکتا برای هر کامپوننت
  • +
  • Lifecycle Hooks – onInit, afterViewInit, onChange, onDestroy, ...
  • +
+
+ +
+
+

XBaseContainer / XBaseContainerComponent lib/classes/i-x-base.container.ts

+ Base +
+

+ دو کلاس که پایه الگوی Property Provider و Container Component هستند. + XBaseContainer برای نگه‌داشتن مقادیر، XBaseContainerComponent + برای تعریف @Input/Output ها و extractProps. +

+
+ +
+
+

XBasePage lib/classes/x-base-page.ts

+ Base +
+

+ پایه تمام Page ها. از XBaseComponent ارث می‌برد و قابلیت‌های زیر را اضافه می‌کند: +

+
    +
  • XCanDeactivate – گارد خروج از صفحه
  • +
  • preventBack – جلوگیری از back مرورگر با historyService.pushEmptyState
  • +
  • confirmUnlock – پرسش هنگام ترک صفحه Locked
  • +
  • Hook های داخلی برای پارامترهای route/query
  • +
  • scrollEventSimulator – شبیه‌سازی scroll برای زیرکامپوننت‌ها
  • +
  • presentDeactiveGuardDialog – دیالوگ خروج از Lock
  • +
+
+ +
+
+

XBaseDialogComponent lib/classes/x-base.dialog.component.ts

+ Base +
+

+ پایه کامپوننت‌های Dialog با MatDialog. مدیریت Toolbar، Back، Title، + ProgressBar و Task های داخل دیالوگ. +

+
+ +
+
+

XBaseDialogService lib/classes/x-base-dialog.service.ts

+ Base +
+

+ پایه سرویس‌های باز کردن Dialog. مدیریت MatDialogRef، backdrop click، + نتیجه (XDialogResult) و کلاس mobile. +

+
+ +
+
+

XBaseObservableTools lib/classes/x-base.observable.tools.ts

+ Base +
+

+ اینترفیس + پیاده‌سازی مجموعه‌ای از توابع کمکی Observable. این کلاس پایه‌ی رفتار + getValue و خانواده‌اش است. +

+
+ +
+
+

XBaseActionModel lib/classes/x-base-action.model.ts

+ Base +
+

+ اینترفیس ساده { action: T; payload?: any } که پایه تمام + ActionModel ها (Card, Button, Chart, Dto, ...) است. +

+
+ +
+
+

XDialogComponent lib/dialogs/x-dialog/x-dialog.component.ts

+ Base +
+

+ کلاس پایه برای همه Dialog Componentهایی که از XDialogConfig استفاده می‌کنند. + پشتیبانی از Modal و PopOver از طریق context.type. +

+
+ + +

Container Interfaces (ترکیب‌پذیری)

+ +

+ یکی از قوی‌ترین ویژگی‌های این کتابخانه، امکان ترکیب Container Interface ها است. + برای مثال: +

+ + + + + + + + + + + + + + + + + +
Containerترکیبکاربرد
IXBaseContainer—پایه
IXFileContainer—مدیریت اعتبارسنجی فایل
IXCardContainer—پایه Card
IXCardEmptyContainerCard + EmptyCard با حالت خالی
IXCardFileContainerCard + FileCard برای Upload
IXCardFileFileDropContainerCard + File + FileDropپایه Avatar Upload
IXCardActionBarContainerCard + ActionBarCard با ActionBar
IXCardEmptyActionSearchBarContainerCard + Empty + ActionBar + SearchBarپایه List/Table
IXToolbarFooterContainerToolbar + Footerپایه Page
IXNextPrevResetContainerNext + Prev + Resetپایه Stepper
+ +
+ قدرت این الگو: برای ساخت یک کامپوننت جدید فقط کافی است Container Interface + مناسب را ترکیب کنید و از XBaseContainerComponent ارث ببرید. تمام منطق + Card/Empty/File/ActionBar به‌صورت خودکار در دسترس است. +
+ + +

۱. کامپوننت‌های Layout

+ +
+
+

x-page lib/x-page/x-page.component.ts

+ Layout +
+

+ قلب هر صفحه در xFramework. ترکیبی از Side Menu، Toolbar، + Content، Footer و Infinity Scroller. از XBasePage ارث می‌برد + و به‌عنوان والد VPageComponent در xClient استفاده می‌شود. +

+
+
+ Inputs مهم +
    +
  • hasSide, sideSlot, sideType
  • +
  • toolbarShow* (Title, Menu, Logo, Back, SubTitle)
  • +
  • toolbarColor, sideColor
  • +
  • showPageRefresher, showPageInfinityScroller
  • +
  • enableCaptureMode, actions
  • +
+
+
+ Outputs +
    +
  • refreshPage, loadMore
  • +
  • scrolledEvent, menuStateChange
  • +
  • imageCaptured, splitterStateChanged
  • +
+
+
+
+ +
+
+

x-toolbar lib/x-page/x-toolbar

+ Layout +
+

+ نوار بالای صفحه با Slots کامل (Start/Center/End). از XToolbarContainerComponent + استفاده می‌کند و درونی XPageComponent است. +

+
+ +
+
+

x-footer lib/x-page/x-footer

+ Layout +
+

+ نوار پایین صفحه. معمولاً یک contentTemplate نمایش می‌دهد + (در xClient: نام شرکت). +

+
+ +
+
+

x-navigator lib/x-page/x-navigator

+ Layout +
+

+ منوی کناری سلسله‌مراتبی با قابلیت Collapse/Expand، paging خودکار و پشتیبانی از + startupState (ExpandAll, CollapseAll, ExpandActivePath). در xClient + به‌عنوان side menu استفاده می‌شود. +

+
+
+ Inputs +
    +
  • items: XNavigatorListItem[]
  • +
  • childColor, parentColor, dividerColor
  • +
  • startupState, closeSiblings
  • +
  • showChildIcon, showParentDetailIcon
  • +
  • disableParentRouting, supportRouting
  • +
+
+
+ Outputs +
    +
  • itemSelected
  • +
  • actionProvider (برای کنترل بیرونی)
  • +
+
+
+
+ +
+
+

x-card lib/x-card/x-card.component.ts

+ Layout +
+

+ Card کامل با Header (Avatar/Title/Subtitle)، Image، Content، Actions و Footer. + قابلیت Fullscreen با XCardAction.ToggleFullScreen از طریق actionProvider. +

+
+
+ Inputs +
    +
  • title, subTitle, avatarUrl
  • +
  • imageUrl, imageDescription
  • +
  • color, foregroundColor, isInPage
  • +
  • showHeader/Content/Actions/Footer
  • +
+
+
+ Actions +
    +
  • Refresh, EnterFullScreen
  • +
  • ExitFullScreen, ToggleFullScreen
  • +
  • FullScreenToggled (event)
  • +
+
+
+
+ +
+
+

x-frame lib/x-frame

+ Layout +
+

قاب ساده برای تقسیم‌بندی محتوا در طرح‌های پیچیده (split layouts).

+
+ + +

۲. کامپوننت‌های Form و ورودی

+ +
+
+

x-form lib/x-form/x-form.component.ts

+ Form +
+

+ موتور اصلی رندر فرم‌ها. یک XSimpleFormConfig<T> می‌گیرد و + از روی controls[]، فرم را می‌سازد و با Reactive Forms کار می‌کند. +

+
+
+ Inputs +
    +
  • formConfig: XSimpleFormConfig<T>
  • +
  • colorها: regular, accent, valid, invalid, pending, fill
  • +
  • applyStatusOnControls
  • +
+
+
+ Outputs +
    +
  • valueChanged, statusChanged
  • +
  • controlValueChanged, controlStatusChanged
  • +
  • controlFocused, controlBlured
  • +
+
+
+
+ +
+
+

x-ide lib/x-ide

+ Form/Editor +
+

+ ویرایشگر کد پیشرفته (Ace/Monaco wrapper) با toolbar، خط‌شماره، Tab، highlight، + word wrapping و action bar قابل تنظیم. +

+
+ +
+
+

x-markdown lib/x-markdown

+ Editor +
+

+ ویرایشگر Markdown با Toolbar (Bold, Italic, Heading, Link, Image, List, Quote, Code, Preview) + و پیش‌نمایش هم‌زمان. برای توضیحات غنی در فرم‌ها استفاده می‌شود. +

+
+ +
+
+

x-color-picker lib/x-color-picker

+ Input +
+

+ انتخاب رنگ با Saturation/Brightness پالت، Hue، Alpha Slider، Preset Colors، + Output Format (Hex/RGBA/HSLA) و Copy-to-Clipboard. +

+
+ +
+
+

x-color lib/x-color

+ Display +
+

+ نمایش یک رنگ به‌صورت دایره‌ای با اندازه، Border و Label. کلیک روی آن مقدار را در + clipboard کپی می‌کند. +

+
+ +
+
+

x-file-upload lib/x-file-upload

+ Upload +
+

+ کامپوزیت کامل FileDropArea + ActionBar + List + SearchBar + Empty. + تمام تنظیمات: maxAllowedFiles، minAllowedFileSize، + maxAllowedFileSize، allowedExtensions، exception handler ها. +

+
+ +
+
+

x-file-drop-area lib/x-file-drop-area

+ Upload +
+

+ Drag & Drop zone با پشتیبانی از multiple files، content template سفارشی، + حالت preview و رنگ‌های success/error/accent. +

+
+ +
+
+

x-avatar-upload lib/x-avatar-upload

+ Upload +
+

+ ترکیب Card + File + FileDrop + Thumbnail + Crop + Clear + Select. + برای آپلود تصویر پروفایل در فرم Register استفاده می‌شود. +

+
+ +
+
+

x-image-cropper lib/x-image-cropper

+ Editor +
+

+ برش تصویر با ngx-image-cropper. قابلیت aspectRatio، roundCropper، + format (png/jpeg) و outputType (base64/file). +

+
+ +
+
+

x-slider lib/x-slider + x-slide

+ Layout +
+

+ Slider/Carousel با x-slide برای هر اسلاید، animation و options. +

+
+ +
+
+

x-stepper lib/x-stepper + x-step

+ Wizard +
+

+ Wizard چندمرحله‌ای با Next/Prev/Reset، validators، confirmer و custom actions + در هر x-step. در RegisterPage استفاده می‌شود. +

+
+ +
+
+

x-search-bar lib/x-search-bar

+ Input +
+

+ Search با debounce، clear/cancel/search icon، keyboard type و enterKeyHint. + در تمام صفحه‌های مدیریت استفاده می‌شود. +

+
+ + +

۳. کامپوننت‌های Display

+ +
+
+

x-icon lib/x-icon

+ Display +
+

+ نمایش Material Icon با کنترل کامل روی color، clickable، applyDirection (RTL/LTR)، + foreground و tooltip. +

+
+ +
+
+

x-list lib/x-list

+ List +
+

+ لیست پیشرفته با Toolbar، SearchBar، ActionBar، Empty State، Slide Options + (swipe actions)، Reordering، Selection (single/multi) و custom templates. +

+
+
+ Inputs +
    +
  • items, itemTemplate, slidingOptionTemplate
  • +
  • showToolbar, showSearchBar, showActionBar
  • +
  • enableReordering, selectableItems
  • +
  • showOptionsAsSlide, showOptionsAsMenu
  • +
  • confirmRemove, clickableItems
  • +
+
+
+ Outputs +
    +
  • itemSelected, selectionChanged
  • +
  • optionSelected, removeItems
  • +
  • itemsChanged, orderChanged
  • +
+
+
+
+ +
+
+

x-grid lib/x-grid

+ Grid +
+

+ نمایش گرید از items با cols، gap، layout، + selectableItems. مناسب آیکون‌ها، thumbnail ها و کارت‌های کوتاه. +

+
+ +
+
+

x-table lib/x-table

+ Table +
+

+ جدول داده‌محور با ستون‌های تعریف‌شده، Sort، Paginator، SearchBar، Selection، + Sticky Header و custom cellTemplate. مناسب صفحه‌های مدیریت. +

+
+ +
+
+

x-chart lib/x-chart

+ Chart +
+

+ پوشش کامل ApexCharts با پشتیبانی از تمام انواع (line, bar, pie, radar, treemap, ...) + و ده‌ها event. ActionBar خودکار برای print، export (PNG/SVG/CSV)، zoom، pan، + fullscreen و reset. +

+
+
+ Inputs +
    +
  • type: XChartTypeIdentifier
  • +
  • series, options, stroke, colors
  • +
  • xAxis, yAxis, tooltip, annotations
  • +
  • gridColor, titleColor, backgroundColor
  • +
  • availableActionBarItems
  • +
+
+
+ Events +
    +
  • click, mounted, updated
  • +
  • zoomed, scrolled, selection
  • +
  • drillDownStart/End, drillUp
  • +
  • legendClick, markerClick
  • +
  • annotation*, dataPointSelection
  • +
+
+
+
+ +
+
+

x-thumbnail lib/x-thumbnail

+ Display +
+

+ نمایش thumbnail از یک identifier (URL یا data). با circular، + clickable، selectable و CUSTOM type. +

+
+ +
+
+

x-counter lib/x-counter

+ Display +
+

+ انیمیشن شمارش عددی از startValue به stopValue با + delay و displayPattern (مثلاً با کاما یا پیشوند). +

+
+ +
+
+

x-tree lib/x-tree

+ Tree +
+

+ نمایش داده‌های سلسله‌مراتبی به‌صورت درخت با expand/collapse. مناسب نمایش ساختارهای + پیچیده. +

+
+ +
+
+

x-empty lib/x-empty

+ State +
+

+ نمایش حالت خالی با message، refresh icon، رنگ‌های customizable، foreground و + actionProvider برای کنترل بیرونی. +

+
+ +
+
+

x-description-list lib/x-description-list + x-description-list-item

+ Display +
+

+ لیست Key/Value از یک model با modelKeyProvider، modelValueProvider، + hiddenModelKeys، sortOrderModelKeys و propertyActionTemplate. + برای نمایش جزئیات یک entity استفاده می‌شود. +

+
+ +
+
+

x-model-presenter lib/x-model-presenter + x-model-presenter-item

+ Display +
+

+ نمایش یک model به‌صورت accordion (panel به panel). قابلیت multiExpanded، + startupState و property actions مشابه DescriptionList. +

+
+ + + + +
+
+

x-tabs lib/x-tabs + x-tab

+ Navigation +
+

+ Tabs کامل با header position، animation، disable ripple، pagination خودکار، + loop، swipable، activeTabColor و tabIndicatorColor. قلب + VQueryPresenterComponent (چهار تب List/Details/Add/Update). +

+
+
+ Inputs +
    +
  • selectedIndex, loopTabs, swipable
  • +
  • alignTabs, showHeader, headerPosition
  • +
  • disablePagination, animationDuration
  • +
  • colorها: header/active/indicator/paginator
  • +
+
+
+ Outputs +
    +
  • selectedIndexChange
  • +
  • selectedTabChange
  • +
  • animationDone
  • +
+
+
+
+ +
+
+

x-tab-navigator lib/x-tab-navigator

+ Navigation +
+

+ نویگیتور پایین صفحه (bottom tab bar) با items، badge، selectedColor، + hideTabLabelsOnSmallScreens. مناسب اپلیکیشن‌های موبایل. +

+
+ +
+
+

x-expandable-list lib/x-expandable-list

+ Navigation +
+

+ لیست سلسله‌مراتبی با expand/collapse، custom child/parent template، routing + و startupState. استفاده در Side Menu (x-navigator درونی از آن استفاده می‌کند). +

+
+ +
+
+

x-expandable-panel lib/x-expandable-panel + x-panel

+ Navigation +
+

+ Accordion چندبخشی با multiExpanded، isAccordion، + applyColors و هر x-panel با title/description. +

+
+ +
+
+

x-fab lib/x-fab

+ Navigation +
+

+ Floating Action Button با child actions (mini/regular)، positioning + (vertical/horizontal)، routerLink/handler. در تمام صفحه‌های مدیریت برای + Add/Edit/Remove/Options استفاده می‌شود. +

+
+ + +

۵. کامپوننت‌های Dialog و Overlay

+ +
+
+

x-popover lib/dialogs/x-popover

+ Dialog +
+

+ Context Menu / Popover با XPopoverOption[] یا XPopoverItem[] + (با زیرمنو). در همه جای xClient (منوی More در Toolbar، انتخاب Playback Rate، ...) + استفاده می‌شود. +

+
+
+ Props +
    +
  • items, options
  • +
  • height, dividerColor, backgroundColor
  • +
+
+
+ نتیجه +
    +
  • XPopoverResult شامل item/option و نتیجه handler
  • +
+
+
+
+ +
+
+

x-selector-dialog lib/dialogs/x-selector-dialog

+ Dialog +
+

+ دیالوگ انتخابگر چندکاره با Search + DataPager + List. برای انتخاب یک یا چند آیتم + از یک لیست بزرگ. با queryFetcher قابل تنظیم است. +

+
+
+ Config +
    +
  • queryFetcher(query): Observable<Result>
  • +
  • itemTemplate: TemplateRef
  • +
  • canMultipleSelect
  • +
  • onItemSelect, onQueryChanged, onPageLoad
  • +
  • showPaginator, paginatorColor, paginatorPosition
  • +
+
+
+ نتیجه +
    +
  • XDialogResult.Ok با payload: selectedItems
  • +
+
+
+
+ +
+
+

x-color-picker-dialog lib/x-color-picker/x-color-picker-dialog

+ Dialog +
+

+ Color Picker داخل Dialog. برای انتخاب رنگ در فرم‌ها استفاده می‌شود. +

+
+ +
+
+

x-dialog lib/dialogs/x-dialog

+ Base +
+

+ کلاس پایه XDialogComponent با XDialogConfig. مدیریت + Toolbar، Back، Title، Select و ProgressBar. +

+
+ + +

۶. کامپوننت‌های Media

+ +
+
+

x-map lib/x-map + x-map-dialog

+ Map +
+

+ نقشه تعاملی (Leaflet/OL wrapper) با SearchBar، Marker، Zoom، Rotate، Locator، + ProgressBar. حالت canSelect برای انتخاب موقعیت. همراه + x-map-dialog برای انتخاب از Dialog. +

+
+ +
+
+

x-screen-capture lib/x-screen-capture

+ Capture +
+

+ ضبط تصویر از صفحه (html2canvas) با topOffset, bottomOffset + و downloadCapturedImage. در صفحه Error برای گرفتن snapshot از خطا استفاده می‌شود. +

+
+ +
+
+

x-thumbnail lib/x-thumbnail

+ Display +
+

توضیح در بخش Display.

+
+ +
+ توجه: کامپوننت‌های VFileComponent و VMediaComponent + که در xClient استفاده می‌شوند، در لایه Application هستند نه در این کتابخانه. + کتابخانه فقط primitive ها را فراهم می‌کند. +
+ + +

۷. کامپوننت‌های Utility

+ +
+
+

x-slotter lib/x-slotter + x-slot

+ Utility +
+

+ چیدمان Slot ها با Layout HORIZONTAL یا VERTICAL. چهار slot: + START, CENTER, END (افقی) یا TOP, CENTER, BOTTOM (عمودی). در تمام کامپوننت‌های + Card، User، File و ... استفاده می‌شود. +

+
+ +
+
+

x-action-bar lib/x-action-bar

+ Utility +
+

+ نوار Action در بالا/پایین یک بخش با دو slot (start/end). هر action با + icon/title/color/handler. قابلیت fire/show/hide/enable/disable از طریق actionProvider. +

+
+ +
+
+

x-search-bar lib/x-search-bar

+ Utility +
+

در بخش Form توضیح داده شد.

+
+ +
+
+

x-data-pager lib/x-data-pager

+ Data +
+

+ Pager کامل با query/result/paginator. خودش task را مدیریت می‌کند و آیتم‌ها را + با itemTemplate رندر می‌کند. حالت empty و refresh داخلی. +

+
+ +
+
+

x-data-scroller lib/x-data-scroller

+ Data +
+

+ نسخه Infinity Scroll از DataPager. با showPageInfinityScroller + و infinityScrollThreshold. +

+
+ +
+
+

x-spinner lib/x-spinner

+ Feedback +
+

+ Spinner با انواع مختلف (lines, circles, dots, bubbles, ...) از + XSpinner enum در core. +

+
+ +
+
+

x-progress-bar lib/x-progress-bar

+ Feedback +
+

+ نوار پیشرفت با type (determinate/indeterminate)، color و buffer. +

+
+ +
+
+

x-theme-manager lib/x-theme/x-theme-manager

+ Theme +
+

+ مدیریت Theme ها (ساخت، ویرایش، حذف، ذخیره) با پیش‌نمایش، انتخاب رنگ با + colorViewBorderColor، پشتیبانی از restartAfterSetTheme. +

+
+ + +

۸. کامپوننت‌های Specialized

+ +
+
+

x-fab lib/x-fab

+ Special +
+

در بخش Navigation توضیح داده شد.

+
+ +
+
+

x-chart lib/x-chart

+ Special +
+

در بخش Display توضیح داده شد.

+
+ +
+
+

x-ide lib/x-ide

+ Special +
+

در بخش Form توضیح داده شد.

+
+ +
+
+

x-screen-capture lib/x-screen-capture

+ Special +
+

در بخش Media توضیح داده شد.

+
+ +
+
+

x-color-picker lib/x-color-picker

+ Special +
+

در بخش Form توضیح داده شد.

+
+ + +

جدول کامل کامپوننت‌ها

+ +
+ + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#کامپوننتSelectorماژولدسته
1XPageComponentx-pageXPageModuleLayout
2XToolbarComponentx-toolbarXPageModuleLayout
3XFooterComponentx-footerXPageModuleLayout
4XNavigatorComponentx-navigatorXPageModuleLayout
5XCardComponentx-cardXCardModuleLayout
6XFrameComponentx-frameXFrameModuleLayout
7XFormComponentx-formXFormModuleForm
8XIDEComponentx-ideXIDEModuleForm
9XMarkdownComponentx-markdownXMarkdownModuleForm
10XColorPickerComponentx-color-pickerXColorPickerModuleForm
11XColorComponentx-colorXColorModuleForm
12XFileUploadComponentx-file-uploadXFileUploadModuleForm
13XFileDropAreaComponentx-file-drop-areaXFileDropAreaModuleForm
14XAvatarUploadComponentx-avatar-uploadXAvatarUploadModuleForm
15XImageCropperComponentx-image-cropperXImageCropperModuleForm
16XSliderComponentx-sliderXSliderModuleForm
17XSlideComponentx-slideXSliderModuleForm
18XStepperComponentx-stepperXStepperModuleForm
19XStepComponentx-stepXStepperModuleForm
20XIconComponentx-iconXIconModuleDisplay
21XListComponentx-listXListModuleDisplay
22XGridComponentx-gridXGridModuleDisplay
23XTableComponentx-tableXTableModuleDisplay
24XChartComponentx-chartXChartModuleDisplay
25XThumbnailComponentx-thumbnailXThumbnailModuleDisplay
26XCounterComponentx-counterXCounterModuleDisplay
27XTreeComponentx-treeXTreeModuleDisplay
28XEmptyComponentx-emptyXEmptyModuleDisplay
29XDescriptionListComponentx-description-listXDescriptionListModuleDisplay
30XDescriptionListItemComponentx-description-list-itemXDescriptionListModuleDisplay
31XModelPresenterComponentx-model-presenterXModelPresenterModuleDisplay
32XModelPresenterItemComponentx-model-presenter-itemXModelPresenterModuleDisplay
33XTabsComponentx-tabsXTabsModuleNavigation
34XTabComponentx-tabXTabsModuleNavigation
35XTabNavigatorComponentx-tab-navigatorXTabNavigatorModuleNavigation
36XExpandableListComponentx-expandable-listXExpandableListModuleNavigation
37XExpandablePanelComponentx-expandable-panelXExpandablePanelModuleNavigation
38XPanelComponentx-panelXExpandablePanelModuleNavigation
39XFabComponentx-fabXFabModuleNavigation
40XPopoverComponentx-popoverXDialogsModuleDialog
41XSelectorDialogComponentx-selector-dialogXDialogsModuleDialog
42XColorPickerDialogComponentx-color-picker-dialogXColorPickerModuleDialog
43XMapComponentx-mapXMapModuleMedia
44XMapDialogComponentx-map-dialogXMapModuleMedia
45XScreenCaptureComponentx-screen-captureXScreenCaptureModuleMedia
46XSlotterComponentx-slotterXSlotterModuleUtility
47XSlotComponentx-slotXSlotterModuleUtility
48XActionBarComponentx-action-barXActionBarModuleUtility
49XSearchBarComponentx-search-barXSearchBarModuleUtility
50XDataPagerComponentx-data-pagerXDataPagerModuleUtility
51XDataScrollerComponentx-data-scrollerXDataScrollerModuleUtility
52XSpinnerComponentx-spinnerXSpinnerModuleUtility
53XProgressBarComponentx-progress-barXProgressBarModuleUtility
54XThemeManagerComponentx-theme-managerXThemeModuleUtility
55XButtonComponentx-buttonXButtonModuleUtility
+ + +

الگوهای مشترک

+ +

۱. الگوی ActionProvider

+

هر کامپوننت یک Subject<XActionModel> می‌گیرد و از بیرون با .next({action, payload}) کنترل می‌شود.

+ +
// در Component
+this.applyTakeUntilWrapper(this.actionProvider.asObservable()).subscribe(model => {
+  switch (model.action) {
+    case XCardAction.Refresh: this.detectChanges(); break;
+    case XCardAction.ToggleFullScreen: this.toggleFullscreen(); break;
+  }
+});
+
+// در Consumer
+this.cardActionProvider.next({ action: XCardAction.ToggleFullScreen });
+ +

۲. الگوی XStandardType

+

+ تمام پراپرتی‌ها می‌توانند XStandardType<T> = T | Observable<T> | Subject<T> باشند. + این باعث می‌شود بتوانید reactive یا sync استفاده کنید: +

+ +
@Input() title: XStandardType<XResourceIdentifier>;
+
+// در Template، همیشه با async pipe:
+{{ getResourceValue(title) | async }}
+
+// اگر Observable باشد:
+[xColor]="getValue(color) | async"
+ +

۳. الگوی Slot + Slotter

+

+ Slotter برای چیدمان محتوای قابل جابجایی (start/center/end یا top/center/bottom). + هر Slot یک name و یک cssClass دارد: +

+ +
<x-slotter [layout]="SlotLayouts.HORIZONTAL">
+  <x-slot [name]="SlotNames.START">
+    <x-icon name="menu"></x-icon>
+  </x-slot>
+  <x-slot [name]="SlotNames.END">
+    <x-button title="save"></x-button>
+  </x-slot>
+</x-slotter>
+ +

۴. الگوی Container Interface Mixin

+ +
// نوع ترکیبی
+type TXCardFileContainer = IXComponentCardContainer & IXFileContainer;
+export interface IXCardFileContainer extends TXCardFileContainer {}
+
+// سرویس Provider
+@Injectable({ providedIn: 'root' })
+export class XCardFileContainer
+  extends XBaseContainer
+  implements IXCardFileContainer {
+  constructor(
+    protected cardPropertyProvider: XComponentCardContainer,
+    protected filePropertyProvider: XFileContainer
+  ) { super(); }
+}
+
+// کلاس پایه کامپوننت
+@Injectable()
+@Component({ template: `` })
+export class XCardFileContainerComponent
+  extends XBaseContainerComponent
+  implements IXCardFileContainer {
+  public extractProps(container?): Observable<IXCardFileContainer> {
+    // ترکیب props Card + File
+  }
+}
+ +

۵. الگوی XDialogService

+ +
export class XSelectorDialogService
+  extends XBaseDialogService<...> {
+
+  defaultTitleResourceIdentifier: XResourceIdentifier;
+
+  openDialogAndReturnRef(config: MatDialogConfig) {
+    return this.dialog.open(XSelectorDialogComponent, config);
+  }
+}
+
+// در Component:
+this.selectorDialogService.openDialog({
+  queryFetcher: (q) => this.api.files.fileProviderService.query(q),
+  itemTemplate: this.listItemRef,
+  canMultipleSelect: true,
+});
+
+// نتیجه:
+this.selectorDialogService.onResult.subscribe(res => {
+  if (res.result === XDialogResult.Ok) { /* res.payload = items[] */ }
+});
+ + +

پیشنهادها

+ +
+
+

✅ نقاط قوت

+
    +
  • الگوی Container/Component کاملاً یکپارچه
  • +
  • XStandardType پشتیبانی از sync/async
  • +
  • ActionProvider مرکزی برای همه
  • +
  • Container Interface Mixin عالی برای ترکیب
  • +
  • OnPush در همه کامپوننت‌ها
  • +
  • تعداد بالای کامپوننت‌های آماده (۵۵+)
  • +
+
+
+

⚠️ نقاط ضعف

+
    +
  • تعداد بسیار بالای Input در بعضی کامپوننت‌ها (XPage بیش از ۴۰)
  • +
  • همه کامپوننت‌ها در یک ماژول غول‌آسا (XFrameworkComponentsModule)
  • +
  • فقدان Storybook برای مستندسازی تعاملی
  • +
  • الگوهای مشترک در کلاس‌های جداگانه تکرار می‌شوند
  • +
  • وابستگی مستقیم به XManagerService
  • +
  • عدم استفاده از Signals (Angular 17+)
  • +
+
+
+

🔴 ریسک‌ها

+
    +
  • حجم باندل بالا به دلیل وابستگی همه کامپوننت‌ها به XFrameworkComponentsModule
  • +
  • Karma در برابر Jest – تست‌های async ناپایدار
  • +
  • عدم type-safe بودن XStandardType در بعضی جاها
  • +
  • Circular dependency در ماژول‌ها
  • +
+
+
+ +

پیشنهادهای عملی

+
    +
  1. مهاجرت به Standalone Components – Angular 14+ از این پشتیبانی می‌کند. هر کامپوننت را standalone کنید تا tree-shaking بهتر شود.
  2. +
  3. افزودن Storybook – نمایش تعاملی همه کامپوننت‌ها با props قابل تنظیم
  4. +
  5. جدا کردن XFrameworkComponentsModule – هر کامپوننت را به ماژول مستقل خودش منتقل کنید تا فقط کامپوننت‌های مصرف‌شده در باندل باشند.
  6. +
  7. جایگزینی XStandardType با Signal – در کنار هم نگه داشتن، مهاجرت تدریجی به Signals.
  8. +
  9. تست contract با extractProps – تست‌های snapshot از خروجی extractProps برای هر کامپوننت.
  10. +
  11. افزودن peer dependency validation – بررسی نسخه‌های Angular/Ionic قبل از نصب.
  12. +
  13. Design Tokens – جایگزینی رنگ‌های مستقیم با CSS Variables برای تم‌پذیری آسان‌تر.
  14. +
  15. مستندسازی Input ها با TSDoc – برای هر Input یک توضیح و مثال.
  16. +
  17. RTL-aware primitives – اطمینان از پشتیبانی کامل RTL در همه کامپوننت‌ها (بسیاری از آن‌ها جهت‌آگاه هستند).
  18. +
  19. Bundle analyzer – افزودن source-map-explorer برای بررسی سهم هر کامپوننت در باندل.
  20. +
+ +
+ +
+ خلاصه: x-framework-components یک کتابخانه بالغ با بیش از + ۵۵ کامپوننت آماده برای ساخت اپ‌های سازمانی است. با الگوی سه‌لایه‌ای (Provider/Container/Component) + و ActionProvider مرکزی، یکپارچگی بالایی در کد وجود دارد. اما برای مقیاس‌پذیری بیشتر، + مهاجرت تدریجی به Standalone، افزودن Storybook و جدا کردن ماژول‌ها ضروری است. +
+ +

+ راهنمای کامپوننت‌های xFramework – نسخه ۱.۰ – بر اساس کدهای ارسالی +

+ +
+
+ + + + \ No newline at end of file diff --git a/Documents/Resources/SDKManager/Versions/SDKManager 1.html b/Documents/Resources/SDKManager/Versions/SDK Manager 1.html similarity index 100% rename from Documents/Resources/SDKManager/Versions/SDKManager 1.html rename to Documents/Resources/SDKManager/Versions/SDK Manager 1.html diff --git a/Documents/Resources/SDKManager/Versions/SDKManager 2.html b/Documents/Resources/SDKManager/Versions/SDK Manager 2.html similarity index 100% rename from Documents/Resources/SDKManager/Versions/SDKManager 2.html rename to Documents/Resources/SDKManager/Versions/SDK Manager 2.html diff --git a/Documents/Resources/SDKManager/Versions/SDK Manager 3.html b/Documents/Resources/SDKManager/Versions/SDK Manager 3.html new file mode 100644 index 0000000..5f9a070 --- /dev/null +++ b/Documents/Resources/SDKManager/Versions/SDK Manager 3.html @@ -0,0 +1,2594 @@ + + + + + +XFramework Backend SDK Manager + + + + + +
+
+ +
+
XFramework Backend SDK Manager
+
تولید سرویس های فراخوانی سرویس دهنده
+
+
+
+ + +
+
+ + +
+ + + + +
+ +
+
📄
+

فایل Swagger JSON را بارگذاری کنید

+

فایل را اینجا بکشید و رها کنید یا روی این ناحیه کلیک کنید

+ +
+ + + +
+
+ + +
+
+ طراح و توسعه‌دهنده: هادی خزاعی اصل + | + شرکت: فن آوران ساحر علم +
+
+ نسخه: 1.2.0 +
+
+ + + + + + + + + + + +
+ + + + \ No newline at end of file diff --git a/Documents/Resources/SDKManager/Versions/SDK Manager 4.html b/Documents/Resources/SDKManager/Versions/SDK Manager 4.html new file mode 100644 index 0000000..a5f590a --- /dev/null +++ b/Documents/Resources/SDKManager/Versions/SDK Manager 4.html @@ -0,0 +1,2643 @@ + + + + + +XFramework Backend SDK Manager + + + + + +
+
+ +
+
XFramework Backend SDK Manager
+
تولید سرویس های فراخوانی سرویس دهنده
+
+
+
+ + +
+
+ + +
+ + + + +
+ +
+
📄
+

فایل Swagger JSON را بارگذاری کنید

+

فایل را اینجا بکشید و رها کنید یا روی این ناحیه کلیک کنید

+ +
+ + + +
+
+ + +
+
+ طراح و توسعه‌دهنده: هادی خزاعی اصل + | + شرکت: فن آوران ساحر علم +
+
+ نسخه: 1.3.0 +
+
+ + + + + + + + + + + +
+ + + + \ No newline at end of file