Initial Commit ...

This commit is contained in:
2026-11-10 15:59:29 +03:30
commit a46b556f64
40 changed files with 1355 additions and 0 deletions
+52
View File
@@ -0,0 +1,52 @@
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db
#
src/app/views/temp
#
# Electron ...
platforms/electron/dist
platforms/electron/www
platforms/electron/node_modules
#
package-lock.json
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env node
// bin/xcli.js
require('../dist/index.js');
+39
View File
@@ -0,0 +1,39 @@
{
"name": "@xframework/xcli",
"version": "0.0.1",
"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"
},
"private": true,
"files": [
"bin",
"dist",
"templates"
],
"engines": {
"node": ">=14.17.3 <17"
},
"dependencies": {
"chalk": "^4.1.2",
"commander": "^9.5.0",
"execa": "^5.1.1",
"fs-extra": "^10.1.0",
"handlebars": "^4.7.10",
"inquirer": "^8.2.7",
"ora": "^5.4.1"
},
"devDependencies": {
"@types/fs-extra": "^9.0.13",
"@types/inquirer": "^7.3.3",
"@types/node": "^14.18.63",
"ts-morph": "^13.0.3",
"typescript": "^4.2.4"
}
}
+49
View File
@@ -0,0 +1,49 @@
import ora from 'ora';
import execa from 'execa';
import { Command } from 'commander';
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);
}
});
}
+46
View File
@@ -0,0 +1,46 @@
import { join } from 'path';
import * as fs from 'fs-extra';
import inquirer from 'inquirer';
import { Command } from 'commander';
import { logger } from '../lib/logger';
import { findProjectRoot } from '../lib/project-utils';
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());
}
+56
View File
@@ -0,0 +1,56 @@
import chalk from 'chalk';
import execa from 'execa';
import { Command } from 'commander';
import { logger } from '../lib/logger';
const REQUIRED_IONIC = '6.6.0';
const REQUIRED_NODE = '14.17.3';
const REQUIRED_ANGULAR = '12.0.4';
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})`) : ''}`);
}
+66
View File
@@ -0,0 +1,66 @@
import { Command } from 'commander';
import { logger } from '../lib/logger';
import { generatePage } from '../generators/page';
import { generateView } from '../generators/view';
import { generateModule } from '../generators/module';
import { generateService } from '../generators/service';
import { generateProviderPage } from '../generators/provider-page';
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());
}
+14
View File
@@ -0,0 +1,14 @@
import { Command } from 'commander';
import { join } from 'path';
import * as fs from 'fs-extra';
import { logger } from '../lib/logger';
import { findManifestRoot, loadManifest, writeManifest } from '../manifest/manifest-store';
import { scanProject } from '../manifest/manifest-scanner';
export function registerManifestCommand(program: Command): void {
const manifest = program.command('manifest').description('Manage xFramework.json');
manifest.command('sync').description('Rescan and update the manifest').action(async () => {
const root = await findManifestRoot(process.cwd()); if (!root) throw new Error('Not an xFramework project. Required file xFramework.json was not found.');
const current = await loadManifest(root); const scanned = scanProject(root, current.project.name); scanned.project.createdAt = current.project.createdAt; await writeManifest(root, scanned); logger.success(`Manifest synchronized: ${join(root, 'xFramework.json')}`);
});
}
+50
View File
@@ -0,0 +1,50 @@
import ora from 'ora';
import { Command } from 'commander';
import { logger } from '../lib/logger';
import { generateNewProject } from '../generators/new-project';
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 inquirer = require('inquirer');
const ans = await inquirer.prompt([
{
type: 'input',
name: 'name',
message: 'Project name:',
default: 'my-x-app',
validate: (v: string) =>
/^[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: any) => (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);
}
});
}
+34
View File
@@ -0,0 +1,34 @@
import { Command } from 'commander';
import { join } from 'path';
import * as fs from 'fs-extra';
import { logger } from '../lib/logger';
import { findManifestRoot, loadManifest, writeManifest } from '../manifest/manifest-store';
import { scanProject } from '../manifest/manifest-scanner';
export function registerProjectCommand(program: Command): void {
const project = program.command('project').description('Inspect and initialize xFramework projects');
project.command('init').description('Create xFramework.json by scanning the current project').option('--force', 'Overwrite existing manifest').action(async (options) => {
const root = process.cwd(); const file = join(root, 'xFramework.json');
const hasProjectFiles = await fs.pathExists(join(root, 'package.json')) || await fs.pathExists(join(root, 'angular.json'));
if (!hasProjectFiles) throw new Error('The current directory is not an xFramework project root. package.json or angular.json is required.');
if (await fs.pathExists(file) && !options.force) throw new Error('xFramework.json already exists. Use --force to overwrite it.');
const pkg = await fs.readJson(join(root, 'package.json')).catch(() => ({}));
const manifest = scanProject(root, pkg.name || root.split(/[\\/]/).pop() || 'xFramework-project');
await writeManifest(root, manifest); logger.success(`Manifest created: ${file}`);
});
project.command('inspect').description('Show the project manifest summary').action(async () => {
const root = await requiredRoot(); const manifest = await loadManifest(root);
console.log(`Project: ${manifest.project.name}`); console.log(`Manifest: ${join(root, 'xFramework.json')}`);
Object.keys(manifest.components).forEach(key => console.log(`${key}: ${manifest.components[key].length}`));
});
project.command('validate').description('Validate xFramework.json and registered files').action(async () => {
const root = await requiredRoot(); const manifest = await loadManifest(root); const missing: string[] = [];
Object.values(manifest.components).flat().forEach(component => component.files.forEach(file => { if (!fs.pathExistsSync(join(root, file.path))) missing.push(file.path); }));
if (missing.length) throw new Error(`Manifest references missing files:\n${missing.join('\n')}`);
logger.success('xFramework project is valid');
});
}
async function requiredRoot(): Promise<string> {
const root = await findManifestRoot(process.cwd()); if (!root) throw new Error('Not an xFramework project. Required file xFramework.json was not found.'); return root;
}
+15
View File
@@ -0,0 +1,15 @@
import * as fs from 'fs-extra';
import { join } from 'path';
import { toKebab, toPascal } from '../lib/naming';
import { requireProjectRoot } from '../lib/project-utils';
import { copyTemplate } from '../lib/fs-utils';
import { logger } from '../lib/logger';
export async function generateModule(opts: { name: string }): Promise<void> {
const root = await requireProjectRoot(); const kebab = toKebab(opts.name); const pascal = toPascal(opts.name);
const file = join(root, 'src/app/pages', kebab, `${kebab}-page.module.ts`);
if (await fs.pathExists(file)) throw new Error(`Module '${kebab}' already exists`);
const templatesRoot = join(__dirname, '..', 'templates', 'module');
await copyTemplate(templatesRoot, 'module.ts.hbs', file, { __NAME__: kebab, __CLASS__: pascal });
logger.success(`Module '${pascal}' generated`);
}
+40
View File
@@ -0,0 +1,40 @@
import execa from 'execa';
import { join } from 'path';
import * as fs from 'fs-extra';
import { logger } from '../lib/logger';
import { copyTemplate } from '../lib/fs-utils';
import { scanProject } from '../manifest/manifest-scanner';
import { writeManifest } from '../manifest/manifest-store';
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);
await fs.ensureDir(directory);
onProgress?.('Creating directory structure...');
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);
onProgress?.('Running ionic init...');
await execa('npx', ['@ionic/cli@6.6.0', 'init', 'x-framework-app', 'angular', '--type=angular-standalone'], { cwd: projectRoot, stdio: 'inherit' });
onProgress?.('Copying xFramework templates...');
await copyTemplateTree(templatesRoot, projectRoot, { __APP_NAME__: name, __APP_INSTANCE__: name + 'Client' });
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 });
if (!skipInstall) { onProgress?.('npm install...'); await execa('npm', ['install', '--legacy-peer-deps'], { cwd: projectRoot, stdio: 'inherit' }); }
onProgress?.('Creating xFramework.json...');
await writeManifest(projectRoot, scanProject(projectRoot, name));
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);
}
}
+59
View File
@@ -0,0 +1,59 @@
import { join } from 'path';
import * as fs from 'fs-extra';
import { logger } from '../lib/logger';
import { copyTemplate } from '../lib/fs-utils';
import { requireProjectRoot, registerRoute } from '../lib/project-utils';
import { loadManifest, writeManifest, addComponent } from '../manifest/manifest-store';
export interface GenPageOptions {
name: string;
module?: string;
lazy?: boolean;
provider?: boolean;
}
export async function generatePage(opts: GenPageOptions) {
const projectRoot = await requireProjectRoot();
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));
await registerRoute(projectRoot, pascal, kebab);
const manifest = await loadManifest(projectRoot);
addComponent(manifest, 'pages', { id: kebab, name: pascal, type: 'page', path: join('src/app/pages', kebab), files: [
{ path: join('src/app/pages', kebab, `${kebab}.page.ts`).replace(/\\/g, '/') },
{ path: join('src/app/pages', kebab, `${kebab}.page.html`).replace(/\\/g, '/') },
{ path: join('src/app/pages', kebab, `${kebab}.page.scss`).replace(/\\/g, '/') }
], status: 'active' });
await writeManifest(projectRoot, manifest);
}
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());
}
+47
View File
@@ -0,0 +1,47 @@
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();
}
+18
View File
@@ -0,0 +1,18 @@
import * as fs from 'fs-extra';
import { join } from 'path';
import { toKebab, toPascal } from '../lib/naming';
import { requireProjectRoot } from '../lib/project-utils';
import { copyTemplate } from '../lib/fs-utils';
import { logger } from '../lib/logger';
export async function generateProviderPage(opts: { name: string; kind?: string }): Promise<void> {
const root = await requireProjectRoot(); const kebab = toKebab(opts.name); const pascal = toPascal(opts.name); const kind = opts.kind === 'management' ? 'management' : 'explorer';
const dir = join(root, 'src/app/pages', kebab, `${kebab}-${kind}`);
if (await fs.pathExists(dir)) throw new Error(`Provider page '${kebab}-${kind}' already exists`);
const templatesRoot = join(__dirname, '..', 'templates', 'provider-page');
await copyTemplate(templatesRoot, 'base.provider.page.ts.hbs', join(dir, `${kebab}-base.provider.page.ts`), { __NAME__: kebab, __CLASS__: pascal });
await fs.writeFile(join(dir, `${kebab}-${kind}.page.ts`), `// TODO: Implement ${pascal} ${kind} page\n`);
await fs.writeFile(join(dir, `${kebab}-${kind}.page.html`), '<!-- TODO: Add provider page content -->\n');
await fs.writeFile(join(dir, `${kebab}-${kind}.page.scss`), '/* TODO: Add provider page styles */\n');
logger.success(`Provider page '${pascal}-${kind}' generated`);
}
+15
View File
@@ -0,0 +1,15 @@
import * as fs from 'fs-extra';
import { join } from 'path';
import { toKebab, toPascal } from '../lib/naming';
import { requireProjectRoot } from '../lib/project-utils';
import { copyTemplate } from '../lib/fs-utils';
import { logger } from '../lib/logger';
export async function generateService(opts: { name: string }): Promise<void> {
const root = await requireProjectRoot(); const kebab = toKebab(opts.name); const pascal = toPascal(opts.name);
const file = join(root, 'src/app/shared/services', `${kebab}.service.ts`);
if (await fs.pathExists(file)) throw new Error(`Service '${kebab}' already exists`);
const templatesRoot = join(__dirname, '..', 'templates', 'service');
await copyTemplate(templatesRoot, 'service.ts.hbs', file, { __CLASS__: pascal });
logger.success(`Service '${pascal}' generated`);
}
+18
View File
@@ -0,0 +1,18 @@
import { join } from 'path';
import * as fs from 'fs-extra';
import { logger } from '../lib/logger';
import { copyTemplate } from '../lib/fs-utils';
import { toKebab, toPascal } from '../lib/naming';
import { requireProjectRoot } from '../lib/project-utils';
export async function generateView(opts: { name: string }): Promise<void> {
const root = await requireProjectRoot(); const kebab = toKebab(opts.name); const pascal = toPascal(opts.name);
const dir = join(root, 'src/app/views', kebab);
if (await fs.pathExists(dir)) throw new Error(`View '${kebab}' already exists`);
const data = { __NAME__: kebab, __CLASS__: pascal };
const templatesRoot = join(__dirname, '..', 'templates', 'view');
await copyTemplate(templatesRoot, 'view.component.ts.hbs', join(dir, `v-${kebab}.component.ts`), data);
await fs.writeFile(join(dir, `v-${kebab}.component.html`), '<!-- TODO: Add view content -->\n');
await fs.writeFile(join(dir, `v-${kebab}.component.scss`), '/* TODO: Add view styles */\n');
logger.success(`View '${pascal}' generated`);
}
+71
View File
@@ -0,0 +1,71 @@
// src/index.ts
import chalk from 'chalk';
import { join } from 'path';
import { readFileSync } from 'fs';
import { Command } from 'commander';
import { registerGenerateCommand } from './commands/generate';
import { registerProjectCommand } from './commands/project';
import { registerManifestCommand } from './commands/manifest';
import { registerAddCommand } from './commands/add';
import { registerConfigCommand } from './commands/config';
import { registerDoctorCommand } from './commands/doctor';
import { registerNewCommand } from './commands/new';
// import { registerAddCommand } from './commands/add';
// import { registerBuildCommand } from './commands/build';
// import { registerConfigCommand } from './commands/config';
// import { registerDoctorCommand } from './commands/doctor';
// import { registerGenerateCommand } from './commands/generate';
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');
// ثبت زیردستورات
registerGenerateCommand(program);
registerProjectCommand(program);
registerManifestCommand(program);
registerAddCommand(program);
registerConfigCommand(program);
registerNewCommand(program);
registerDoctorCommand(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);
});
+38
View File
@@ -0,0 +1,38 @@
import * as fs from 'fs-extra';
import Handlebars from 'handlebars';
import { join, dirname } from 'path';
export async function renderTemplate(
templateSource: string,
data: Record<string, any>
): Promise<any> {
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<string, any>,
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);
}
+13
View File
@@ -0,0 +1,13 @@
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)),
};
+11
View File
@@ -0,0 +1,11 @@
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, '_');
+39
View File
@@ -0,0 +1,39 @@
import * as fs from 'fs-extra';
import { join } from 'path';
import { Project, SyntaxKind } from 'ts-morph';
import { findManifestRoot, loadManifest } from '../manifest/manifest-store';
export async function findProjectRoot(start: string): Promise<string | null> {
return findManifestRoot(start);
}
export async function requireProjectRoot(start: string = process.cwd()): Promise<string> {
const root = await findManifestRoot(start);
if (!root) throw new Error('Not an xFramework project. Required file xFramework.json was not found. Run `xcli project init` first.');
await loadManifest(root);
return root;
}
export async function registerRoute(projectRoot: string, className: string, routePath: string, opts: { canDeactivate?: boolean } = { canDeactivate: true }): Promise<void> {
const routingFile = join(projectRoot, 'src', 'app', 'app-routing.module.ts');
if (!(await fs.pathExists(routingFile))) throw new Error(`Routing file not found: ${routingFile}`);
const project = new Project();
const source = project.addSourceFileAtPath(routingFile);
const routesVar = source.getVariableDeclaration('routes');
if (!routesVar) throw new Error('`routes` variable not found in app-routing.module.ts');
const init = routesVar.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression);
if (!init) throw new Error('`routes` is not an array literal');
if (init.getElements().some(el => el.getText().includes(`path: '${routePath}'`))) return;
if (opts.canDeactivate !== false) ensureImport(source, 'x-framework-core', 'XCanDeactivateGuard');
init.addElement(writer => {
writer.write('{').newLine(); writer.write(` component: ${className},`).newLine(); writer.write(` path: '${routePath}',`).newLine();
if (opts.canDeactivate !== false) writer.write(' canDeactivate: [XCanDeactivateGuard],').newLine(); writer.write('}');
});
await source.save();
}
function ensureImport(source: ReturnType<Project['addSourceFileAtPath']>, moduleSpecifier: string, namedImport: string): void {
const existing = source.getImportDeclaration(imp => imp.getModuleSpecifierValue() === moduleSpecifier);
if (existing) { if (!existing.getNamedImports().some(ni => ni.getName() === namedImport)) existing.addNamedImport(namedImport); }
else source.addImportDeclaration({ moduleSpecifier, namedImports: [namedImport] });
}
+38
View File
@@ -0,0 +1,38 @@
import { join } from 'path';
import {
XFrameworkManifest,
XFrameworkComponent,
} from './manifest-types';
import * as fs from 'fs-extra';
function files(root: string, directory: string): string[] {
const absolute = join(root, directory);
if (!fs.existsSync(absolute)) return [];
if (fs.statSync(absolute).isFile()) return [directory.replace(/\\/g, '/')];
return fs.readdirSync(absolute, { withFileTypes: true }).flatMap(entry => {
const child = join(directory, entry.name);
return entry.isDirectory() ? files(root, child) : [child.replace(/\\/g, '/')];
});
}
function component(root: string, type: XFrameworkComponent['type'], path: string, id: string, name: string): XFrameworkComponent {
return { id, name, type, path, files: files(root, path).map(file => ({ path: file })), status: 'active' };
}
export function scanProject(root: string, name: string): XFrameworkManifest {
const now = new Date().toISOString();
const pageRoot = 'src/app/pages'; const viewRoot = 'src/app/views'; const serviceRoot = 'src/app/shared/services';
const pageDirs = fs.existsSync(join(root, pageRoot)) ? fs.readdirSync(join(root, pageRoot), { withFileTypes: true }).filter(e => e.isDirectory()) : [];
const viewDirs = fs.existsSync(join(root, viewRoot)) ? fs.readdirSync(join(root, viewRoot), { withFileTypes: true }).filter(e => e.isDirectory()) : [];
const serviceFiles = files(root, serviceRoot).filter(file => file.endsWith('.service.ts'));
const pages = pageDirs.map(e => component(root, 'page', `${pageRoot}/${e.name}`, e.name, e.name));
const views = viewDirs.map(e => component(root, 'view', `${viewRoot}/${e.name}`, e.name, e.name));
const services = serviceFiles.map(file => component(root, 'service', file, file.split('/').pop()!.replace('.service.ts', ''), file));
return {
$schema: 'https://xframework.saherelm.ir/schemas/xFramework.schema.json', manifestVersion: '1.0',
project: { name, displayName: name, type: 'xFramework-client', framework: 'xFramework', language: 'typescript', createdAt: now, updatedAt: now },
paths: { source: 'src', app: 'src/app', pages: pageRoot, views: viewRoot, services: serviceRoot, config: 'src/app/config', assets: 'src/assets', routing: 'src/app/app-routing.module.ts', pageConfig: 'src/app/config/page.config.ts' },
dependencies: { xFramework: [] }, components: { pages, views, services, modules: [], routes: [], configs: [] },
settings: { autoRegisterRoutes: true, autoUpdatePageConfig: true, autoUpdateManifest: true, strictManifest: true }
};
}
+44
View File
@@ -0,0 +1,44 @@
import * as fs from 'fs-extra';
import {
MANIFEST_FILE,
XFrameworkManifest,
XFrameworkComponent,
} from './manifest-types';
import { dirname, join } from 'path';
export async function findManifestRoot(start: string): Promise<string | null> {
let current = start;
while (true) {
if (await fs.pathExists(join(current, MANIFEST_FILE))) return current;
const parent = dirname(current);
if (parent === current) return null;
current = parent;
}
}
export async function loadManifest(root: string): Promise<XFrameworkManifest> {
const file = join(root, MANIFEST_FILE);
if (!(await fs.pathExists(file))) throw new Error(`Not an xFramework project: ${MANIFEST_FILE} was not found in '${root}' or its parents.`);
let manifest: XFrameworkManifest;
try { manifest = await fs.readJson(file); } catch (error: any) { throw new Error(`Invalid ${MANIFEST_FILE}: ${error.message}`); }
validateManifest(manifest);
return manifest;
}
export function validateManifest(manifest: XFrameworkManifest): void {
if (!manifest || manifest.manifestVersion !== '1.0') throw new Error('Unsupported or missing xFramework manifestVersion. Expected "1.0".');
if (!manifest.project || !manifest.project.name || manifest.project.framework !== 'xFramework') throw new Error('Invalid xFramework.json project metadata.');
if (!manifest.paths || !manifest.components || !manifest.settings) throw new Error('Invalid xFramework.json: paths, components and settings are required.');
}
export async function writeManifest(root: string, manifest: XFrameworkManifest): Promise<void> {
manifest.project.updatedAt = new Date().toISOString();
validateManifest(manifest);
await fs.writeJson(join(root, MANIFEST_FILE), manifest, { spaces: 2 });
}
export function addComponent(manifest: XFrameworkManifest, collection: string, component: XFrameworkComponent): void {
manifest.components[collection] = manifest.components[collection] || [];
if (manifest.components[collection].some(item => item.id === component.id)) throw new Error(`Manifest component already exists: ${component.id}`);
manifest.components[collection].push(component);
}
+26
View File
@@ -0,0 +1,26 @@
export interface XFrameworkComponentFile {
path: string;
role?: string;
}
export interface XFrameworkComponent {
id: string;
name: string;
path: string;
[key: string]: any;
files: XFrameworkComponentFile[];
status: 'active' | 'missing' | 'unknown';
type: 'page' | 'provider-page' | 'view' | 'module' | 'service' | 'route' | 'config' | 'unknown';
}
export interface XFrameworkManifest {
$schema?: string;
manifestVersion: string;
paths: Record<string, string>;
components: Record<string, XFrameworkComponent[]>;
dependencies: { xFramework: string[]; angular?: Record<string, string>; ionic?: Record<string, string> };
settings: { autoRegisterRoutes: boolean; autoUpdatePageConfig: boolean; autoUpdateManifest: boolean; strictManifest: boolean };
project: { name: string; displayName?: string; type: string; framework: 'xFramework'; frameworkVersion?: string; language?: string; createdAt: string; updatedAt: string };
}
export const MANIFEST_FILE = 'xFramework.json';
+32
View File
@@ -0,0 +1,32 @@
{{! 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 {}
+17
View File
@@ -0,0 +1,17 @@
{{! 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>
+2
View File
@@ -0,0 +1,2 @@
// __NAME__.page.scss
// TODO: Add styles
+29
View File
@@ -0,0 +1,29 @@
{{! 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
}
@@ -0,0 +1,65 @@
{{! 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
}
}
+20
View File
@@ -0,0 +1,20 @@
{{! 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
}
+54
View File
@@ -0,0 +1,54 @@
{{! 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);
}
}
+32
View File
@@ -0,0 +1,32 @@
{{! 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 {}
+17
View File
@@ -0,0 +1,17 @@
{{! 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>
+2
View File
@@ -0,0 +1,2 @@
// __NAME__.page.scss
// TODO: Add styles
+29
View File
@@ -0,0 +1,29 @@
{{! 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
}
@@ -0,0 +1,65 @@
{{! 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
}
}
+20
View File
@@ -0,0 +1,20 @@
{{! 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
}
+54
View File
@@ -0,0 +1,54 @@
{{! 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);
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"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"]
}